Merge "Bug 8153: Enforce check-style rules for netconf - mdsal-netconf-notification"
authorTomas Cere <tcere@cisco.com>
Fri, 28 Apr 2017 12:32:08 +0000 (12:32 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Fri, 28 Apr 2017 12:32:08 +0000 (12:32 +0000)
156 files changed:
netconf/aaa-authn-odl-plugin/pom.xml
netconf/aaa-authn-odl-plugin/src/main/java/org/opendaylight/aaa/odl/CredentialServiceAuthProvider.java
netconf/aaa-authn-odl-plugin/src/test/java/org/opendaylight/aaa/odl/CredentialServiceAuthProviderTest.java
netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/BaseCallHomeTopology.java
netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeMountDispatcher.java
netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeTopology.java
netconf/callhome-provider/src/main/resources/org/opendaylight/blueprint/callhome-topology.xml
netconf/callhome-provider/src/test/java/org/opendaylight/netconf/callhome/mount/CallHomeMountDispatcherTest.java
netconf/config-netconf-connector/pom.xml
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/DiscardChanges.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/Lock.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/UnLock.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/Validate.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/editconfig/EditConfig.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/editconfig/EditConfigXmlParser.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/getconfig/GetConfig.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/operations/runtimerpc/RuntimeRpc.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/osgi/Activator.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/osgi/NetconfOperationProvider.java
netconf/config-netconf-connector/src/main/java/org/opendaylight/netconf/confignetconfconnector/osgi/NetconfOperationServiceFactoryImpl.java
netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/NetconfMappingTest.java
netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/operations/editconfig/EditConfigTest.java
netconf/config-netconf-connector/src/test/java/org/opendaylight/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategyTest.java
netconf/mdsal-netconf-yang-library/pom.xml
netconf/mdsal-netconf-yang-library/src/main/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriter.java
netconf/mdsal-netconf-yang-library/src/test/java/org/opendaylight/netconf/mdsal/yang/library/SchemaServiceToMdsalWriterTest.java
netconf/netconf-api/pom.xml
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfClientSessionPreferences.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDeserializerException.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDocumentedException.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfExiSession.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfServerSessionPreferences.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfSessionListener.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfSessionPreferences.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/messages/NetconfHelloMessage.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageAdditionalHeader.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/NetconfMonitoringService.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/SessionEvent.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/monitoring/SessionListener.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/xml/XmlNetconfConstants.java
netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/NetconfDocumentedExceptionTest.java
netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageAdditionalHeaderTest.java
netconf/netconf-api/src/test/java/org/opendaylight/netconf/api/messages/NetconfHelloMessageTest.java
netconf/netconf-console/pom.xml
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/api/NetconfCommands.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfCommandUtils.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfListDevicesCommand.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfShowDeviceCommand.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/impl/NetconfCommandsImpl.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfConsoleUtils.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/utils/NetconfIidFactory.java
netconf/netconf-console/src/test/java/org/opendaylight/netconf/console/commands/NetconfCommandsImplCallsTest.java
netconf/netconf-console/src/test/java/org/opendaylight/netconf/console/impl/NetconfCommandsImplTest.java
netconf/netconf-impl/pom.xml
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerDispatcherImpl.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSession.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionListener.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiator.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiatorFactory.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiatorFactoryBuilder.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSession.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultNetconfOperation.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultStartExi.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/mapping/operations/DefaultStopExi.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/AggregatedNetconfOperationServiceFactory.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringService.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfImplActivator.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationRouterImpl.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfOperationServiceFactoryTracker.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfSessionMonitoringService.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/AdditionalHeaderParserTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/ConcurrentClientsTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/ExiEncodeDecodeTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/MessageParserTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfDispatcherImplTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/NetconfServerSessionListenerTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/mapping/operations/DefaultCloseSessionTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/mapping/operations/DefaultStopExiTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringServiceTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfImplActivatorTest.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/osgi/NetconfOperationRouterImplTest.java
netconf/netconf-notifications-api/pom.xml
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/BaseNetconfNotificationListener.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/BaseNotificationPublisherRegistration.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotification.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotificationCollector.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotificationListener.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotificationRegistry.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NotificationListenerRegistration.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NotificationRegistration.java
netconf/netconf-notifications-impl/pom.xml
netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/NetconfNotificationManager.java
netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/CreateSubscription.java
netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/Get.java
netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtil.java
netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/osgi/Activator.java
netconf/netconf-notifications-impl/src/test/java/org/opendaylight/netconf/notifications/impl/NetconfNotificationManagerTest.java
netconf/netconf-notifications-impl/src/test/java/org/opendaylight/netconf/notifications/impl/ops/CreateSubscriptionTest.java
netconf/netconf-notifications-impl/src/test/java/org/opendaylight/netconf/notifications/impl/ops/GetTest.java
netconf/netconf-notifications-impl/src/test/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtilTest.java
netconf/netconf-notifications-impl/src/test/java/org/opendaylight/netconf/notifications/impl/osgi/ActivatorTest.java
netconf/netconf-tcp/pom.xml
netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/NetconfNorthboundTcpServer.java
netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/netty/ProxyClientHandler.java [new file with mode: 0644]
netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/netty/ProxyServerHandler.java
netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/osgi/NetconfTCPActivator.java
netconf/netconf-topology-config/src/main/resources/org/opendaylight/blueprint/netconf-topology.xml
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/MasterSalFacade.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfNodeManager.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyContext.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/ProxyDOMDataBroker.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImpl.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/SlaveSalFacade.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadTransactionActor.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteAdapter.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteTransactionActor.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadAdapter.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadTransaction.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransaction.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteAdapter.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteTransaction.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/utils/NetconfTopologySetup.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/CancelRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/DeleteRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/ExistsRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/MergeRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionRequest.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/PutRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/ReadActorMessage.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/ReadRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/SubmitRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/WriteActorMessage.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/main/resources/org/opendaylight/blueprint/netconf-topology-singleton.xml
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-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImplTest.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/TestingRemoteDeviceConnectorImpl.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadOnlyTransactionTest.java
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java [new file with mode: 0644]
netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/WriteOnlyTransactionTest.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/impl/NetconfTopologyImpl.java
netconf/netconf-topology/src/test/java/org/opendaylight/netconf/topology/impl/NetconfTopologyImplTest.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacade.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacadeTest.java
netconf/sal-netconf-connector/src/test/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProviderTest.java

index 6dc5676e9df7adb5800b383537678dea4a64a3c2..115e048ff8fdb3e35b4554b367b8ad400047e573 100644 (file)
             <scope>test</scope>
         </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 67ad6ebc572475dce506bc4aee96bdbf6b00254d..19e72dfe08bf9aec4d1397b085a3271e8e1de2df 100644 (file)
@@ -25,10 +25,10 @@ import org.slf4j.LoggerFactory;
  * AuthProvider implementation delegating to AAA CredentialAuth&lt;PasswordCredentials&gt; instance.
  */
 public final class CredentialServiceAuthProvider implements AuthProvider, AutoCloseable {
-    private static final Logger logger = LoggerFactory.getLogger(CredentialServiceAuthProvider.class);
+    private static final Logger LOG = LoggerFactory.getLogger(CredentialServiceAuthProvider.class);
 
     /**
-     * Singleton instance with delayed instantiation
+     * Singleton instance with delayed instantiation.
      */
     public static volatile Map.Entry<BundleContext, CredentialServiceAuthProvider> INSTANCE;
 
@@ -39,23 +39,26 @@ public final class CredentialServiceAuthProvider implements AuthProvider, AutoCl
 
     public CredentialServiceAuthProvider(final BundleContext bundleContext) {
 
-        final ServiceTrackerCustomizer<CredentialAuth, CredentialAuth> customizer = new ServiceTrackerCustomizer<CredentialAuth, CredentialAuth>() {
+        final ServiceTrackerCustomizer<CredentialAuth, CredentialAuth> customizer =
+                new ServiceTrackerCustomizer<CredentialAuth, CredentialAuth>() {
             @Override
             public CredentialAuth addingService(final ServiceReference<CredentialAuth> reference) {
-                logger.trace("Credential service {} added", reference);
+                LOG.trace("Credential service {} added", reference);
                 nullableCredService = bundleContext.getService(reference);
                 return nullableCredService;
             }
 
             @Override
-            public void modifiedService(final ServiceReference<CredentialAuth> reference, final CredentialAuth service) {
-                logger.trace("Replacing modified Credential service {}", reference);
+            public void modifiedService(final ServiceReference<CredentialAuth> reference,
+                                        final CredentialAuth service) {
+                LOG.trace("Replacing modified Credential service {}", reference);
                 nullableCredService = service;
             }
 
             @Override
             public void removedService(final ServiceReference<CredentialAuth> reference, final CredentialAuth service) {
-                logger.trace("Removing Credential service {}. This AuthProvider will fail to authenticate every time", reference);
+                LOG.trace("Removing Credential service {}. "
+                        + "This AuthProvider will fail to authenticate every time", reference);
                 synchronized (CredentialServiceAuthProvider.this) {
                     nullableCredService = null;
                 }
@@ -66,13 +69,13 @@ public final class CredentialServiceAuthProvider implements AuthProvider, AutoCl
     }
 
     /**
-     * Authenticate user. This implementation tracks CredentialAuth&lt;PasswordCredentials&gt; and delegates the decision to it. If the service is not
-     * available, IllegalStateException is thrown.
+     * Authenticate user. This implementation tracks CredentialAuth&lt;PasswordCredentials&gt;
+     * and delegates the decision to it. If the service is not available, IllegalStateException is thrown.
      */
     @Override
     public synchronized boolean authenticated(final String username, final String password) {
         if (nullableCredService == null) {
-            logger.warn("Cannot authenticate user '{}', Credential service is missing", username);
+            LOG.warn("Cannot authenticate user '{}', Credential service is missing", username);
             throw new IllegalStateException("Credential service is not available");
         }
 
@@ -80,16 +83,16 @@ public final class CredentialServiceAuthProvider implements AuthProvider, AutoCl
         try {
             claim = nullableCredService.authenticate(new PasswordCredentialsWrapper(username, password));
         } catch (AuthenticationException e) {
-            logger.debug("Authentication failed for user '{}' : {}", username, e);
+            LOG.debug("Authentication failed for user '{}' : {}", username, e);
             return false;
         }
 
-        logger.debug("Authentication result for user '{}' : {}", username, claim.domain());
+        LOG.debug("Authentication result for user '{}' : {}", username, claim.domain());
         return true;
     }
 
     /**
-     * Invoke by blueprint
+     * Invoked by blueprint.
      */
     @Override
     public void close() {
@@ -101,7 +104,7 @@ public final class CredentialServiceAuthProvider implements AuthProvider, AutoCl
         private final String username;
         private final String password;
 
-        public PasswordCredentialsWrapper(final String username, final String password) {
+        PasswordCredentialsWrapper(final String username, final String password) {
             this.username = username;
             this.password = password;
         }
index 4962256717fb3bc0b7b59fb3a377a4051a465e5f..08456118c3bc2fe95604df3cc161749392c35110 100644 (file)
@@ -5,7 +5,6 @@
  * 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.aaa.odl;
 
 import static org.junit.Assert.assertFalse;
index 0b1972a3ef559bdbcd504886a81618c2f6f60125..f2d01b753ef4f3e3aa08f3f39b2d87ee051edbaf 100644 (file)
@@ -13,8 +13,6 @@ import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.topology.AbstractNetconfTopology;
 import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
@@ -23,17 +21,15 @@ abstract class BaseCallHomeTopology extends AbstractNetconfTopology {
 
     protected DOMMountPointService mountPointService = null;
 
-    BaseCallHomeTopology(String topologyId, NetconfClientDispatcher clientDispatcher,
-                         BindingAwareBroker bindingAwareBroker,
-                         Broker domBroker,
-                         EventExecutor eventExecutor,
-                         ScheduledThreadPool keepaliveExecutor,
-                         ThreadPool processingExecutor,
-                         SchemaRepositoryProvider schemaRepositoryProvider,
-                         DataBroker dataBroker,
-                         DOMMountPointService mountPointService) {
-        super(topologyId, clientDispatcher, bindingAwareBroker, domBroker, eventExecutor, keepaliveExecutor,
-                processingExecutor, schemaRepositoryProvider, dataBroker);
+    BaseCallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
+                         final EventExecutor eventExecutor,
+                         final ScheduledThreadPool keepaliveExecutor,
+                         final ThreadPool processingExecutor,
+                         final SchemaRepositoryProvider schemaRepositoryProvider,
+                         final DataBroker dataBroker,
+                         final DOMMountPointService mountPointService) {
+        super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
+                processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService);
         this.mountPointService = mountPointService;
     }
 }
index ee1790ce4514166372743c25787759335652b1fb..2241d6995ae2b93c7fe90df7b13e5a2740b602fe 100644 (file)
@@ -16,8 +16,6 @@ import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.callhome.mount.CallHomeMountSessionContext.CloseCallback;
 import org.opendaylight.netconf.callhome.protocol.CallHomeChannelActivator;
 import org.opendaylight.netconf.callhome.protocol.CallHomeNetconfSubsystemListener;
@@ -38,12 +36,10 @@ public class CallHomeMountDispatcher implements NetconfClientDispatcher, CallHom
     private final static Logger LOG = LoggerFactory.getLogger(CallHomeMountDispatcher.class);
 
     private final String topologyId;
-    private final BindingAwareBroker bindingAwareBroker;
     private final EventExecutor eventExecutor;
     private final ScheduledThreadPool keepaliveExecutor;
     private final ThreadPool processingExecutor;
     private final SchemaRepositoryProvider schemaRepositoryProvider;
-    private final org.opendaylight.controller.sal.core.api.Broker domBroker;
     private final CallHomeMountSessionManager sessionManager;
     private final DataBroker dataBroker;
     private final DOMMountPointService mountService;
@@ -52,44 +48,42 @@ public class CallHomeMountDispatcher implements NetconfClientDispatcher, CallHom
 
     private final CloseCallback onCloseHandler = new CloseCallback() {
         @Override
-        public void onClosed(CallHomeMountSessionContext deviceContext) {
+        public void onClosed(final CallHomeMountSessionContext deviceContext) {
             LOG.info("Removing {} from Netconf Topology.", deviceContext.getId());
             topology.disconnectNode(deviceContext.getId());
         }
     };
 
-    public CallHomeMountDispatcher(String topologyId, BindingAwareBroker bindingAwareBroker,
-                                   EventExecutor eventExecutor,
-                                   ScheduledThreadPool keepaliveExecutor,
-                                   ThreadPool processingExecutor,
-                                   SchemaRepositoryProvider schemaRepositoryProvider,
-                                   Broker domBroker, DataBroker dataBroker,
-                                   DOMMountPointService mountService) {
+    public CallHomeMountDispatcher(final String topologyId,
+                                   final EventExecutor eventExecutor,
+                                   final ScheduledThreadPool keepaliveExecutor,
+                                   final ThreadPool processingExecutor,
+                                   final SchemaRepositoryProvider schemaRepositoryProvider,
+                                   final DataBroker dataBroker,
+                                   final DOMMountPointService mountService) {
         this.topologyId = topologyId;
-        this.bindingAwareBroker = bindingAwareBroker;
         this.eventExecutor = eventExecutor;
         this.keepaliveExecutor = keepaliveExecutor;
         this.processingExecutor = processingExecutor;
         this.schemaRepositoryProvider = schemaRepositoryProvider;
-        this.domBroker = domBroker;
         this.sessionManager = new CallHomeMountSessionManager();
         this.dataBroker = dataBroker;
         this.mountService = mountService;
     }
 
     @Override
-    public Future<NetconfClientSession> createClient(NetconfClientConfiguration clientConfiguration) {
+    public Future<NetconfClientSession> createClient(final NetconfClientConfiguration clientConfiguration) {
         return activateChannel(clientConfiguration);
     }
 
     @Override
-    public Future<Void> createReconnectingClient(NetconfReconnectingClientConfiguration clientConfiguration) {
+    public Future<Void> createReconnectingClient(final NetconfReconnectingClientConfiguration clientConfiguration) {
         return activateChannel(clientConfiguration);
     }
 
-    private <V> Future<V> activateChannel(NetconfClientConfiguration conf) {
-        InetSocketAddress remoteAddr = conf.getAddress();
-        CallHomeMountSessionContext context = getSessionManager().getByAddress(remoteAddr);
+    private <V> Future<V> activateChannel(final NetconfClientConfiguration conf) {
+        final InetSocketAddress remoteAddr = conf.getAddress();
+        final CallHomeMountSessionContext context = getSessionManager().getByAddress(remoteAddr);
         LOG.info("Activating NETCONF channel for ip {} device context {}", remoteAddr, context);
         if (context == null) {
             return new FailedFuture<>(eventExecutor, new NullPointerException());
@@ -98,16 +92,16 @@ public class CallHomeMountDispatcher implements NetconfClientDispatcher, CallHom
     }
 
     void createTopology() {
-        this.topology = new CallHomeTopology(topologyId, this, bindingAwareBroker, domBroker, eventExecutor,
+        this.topology = new CallHomeTopology(topologyId, this, eventExecutor,
                 keepaliveExecutor, processingExecutor, schemaRepositoryProvider, dataBroker, mountService);
     }
 
     @Override
-    public void onNetconfSubsystemOpened(CallHomeProtocolSessionContext session,
-                                         CallHomeChannelActivator activator) {
-        CallHomeMountSessionContext deviceContext = getSessionManager().createSession(session, activator, onCloseHandler);
-        NodeId nodeId = deviceContext.getId();
-        Node configNode = deviceContext.getConfigNode();
+    public void onNetconfSubsystemOpened(final CallHomeProtocolSessionContext session,
+                                         final CallHomeChannelActivator activator) {
+        final CallHomeMountSessionContext deviceContext = getSessionManager().createSession(session, activator, onCloseHandler);
+        final NodeId nodeId = deviceContext.getId();
+        final Node configNode = deviceContext.getConfigNode();
         LOG.info("Provisioning fake config {}", configNode);
         topology.connectNode(nodeId, configNode);
     }
index fc774b0a81eac29bdd57c837a51c4d29a8a81e42..71a7af1340fe6a82d1f878cfa232543baa60b64a 100644 (file)
@@ -13,8 +13,6 @@ import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
@@ -25,21 +23,18 @@ import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider;
 
 public class CallHomeTopology extends BaseCallHomeTopology {
 
-    public CallHomeTopology(String topologyId, NetconfClientDispatcher clientDispatcher,
-                            BindingAwareBroker bindingAwareBroker,
-                            Broker domBroker, EventExecutor eventExecutor,
-                            ScheduledThreadPool keepaliveExecutor, ThreadPool processingExecutor,
-                            SchemaRepositoryProvider schemaRepositoryProvider,
-                            DataBroker dataBroker, DOMMountPointService mountPointService) {
-        super(topologyId, clientDispatcher, bindingAwareBroker, domBroker, eventExecutor,
+    public CallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
+                            final EventExecutor eventExecutor,
+                            final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor,
+                            final SchemaRepositoryProvider schemaRepositoryProvider,
+                            final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+        super(topologyId, clientDispatcher, eventExecutor,
                 keepaliveExecutor, processingExecutor, schemaRepositoryProvider,
                 dataBroker, mountPointService);
     }
 
     @Override
-    protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(RemoteDeviceId id,
-                                                                             Broker domBroker,
-                                                                             BindingAwareBroker bindingBroker) {
-        return new NetconfDeviceSalFacade(id, domBroker, bindingAwareBroker);
+    protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id) {
+        return new NetconfDeviceSalFacade(id, mountPointService, dataBroker);
     }
 }
index 831980c33ebf3f3c726a113fec855d6ea968ec8f..d97360476ee12d7dc746e53c2c0b6650699eafa3 100755 (executable)
            xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
            odl:use-default-for-reference-types="true">
 
-    <reference id="bindingAwareBroker"
-               interface="org.opendaylight.controller.sal.binding.api.BindingAwareBroker"/>
     <reference id="keepAliveExecutor"
                interface="org.opendaylight.controller.config.threadpool.ScheduledThreadPool"
                odl:type="global-netconf-ssh-scheduled-executor"/>
     <reference id="processingExecutor"
                interface="org.opendaylight.controller.config.threadpool.ThreadPool"
                odl:type="global-netconf-processing-executor"/>
-    <reference id="domBroker"
-               interface="org.opendaylight.controller.sal.core.api.Broker"/>
     <reference id="eventExecutor"
                interface="io.netty.util.concurrent.EventExecutor"
                odl:type="global-event-executor"/>
 
     <bean id="callhomeDispatcher" class="org.opendaylight.netconf.callhome.mount.CallHomeMountDispatcher">
         <argument value="topology-netconf"/>
-        <argument ref="bindingAwareBroker"/>
         <argument ref="eventExecutor"/>
         <argument ref="keepAliveExecutor"/>
         <argument ref="processingExecutor"/>
         <argument ref="schemaRepository"/>
-        <argument ref="domBroker"/>
         <argument ref="dataBroker"/>
         <argument ref="domMountPointService"/>
     </bean>
index c426471997de110d270cc0e2c6f5d33d428bcb50..cca8f5de3d56e1352e776333433abacaa518a526 100644 (file)
@@ -11,8 +11,8 @@ package org.opendaylight.netconf.callhome.mount;
 import static org.junit.Assert.assertFalse;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
@@ -20,15 +20,12 @@ import io.netty.util.concurrent.EventExecutor;
 import io.netty.util.concurrent.Future;
 import java.net.InetSocketAddress;
 import java.net.UnknownHostException;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.api.messages.NetconfHelloMessageAdditionalHeader;
 import org.opendaylight.netconf.callhome.protocol.CallHomeChannelActivator;
 import org.opendaylight.netconf.callhome.protocol.CallHomeProtocolSessionContext;
@@ -44,12 +41,10 @@ import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.
 
 public class CallHomeMountDispatcherTest {
     private String topologyId;
-    private BindingAwareBroker mockBroker;
     private EventExecutor mockExecutor;
     private ScheduledThreadPool mockKeepAlive;
     private ThreadPool mockProcessingExecutor;
     private SchemaRepositoryProvider mockSchemaRepoProvider;
-    private Broker mockDomBroker;
 
     private CallHomeMountDispatcher instance;
     private DataBroker mockDataBroker;
@@ -62,20 +57,18 @@ public class CallHomeMountDispatcherTest {
     @Before
     public void setup() {
         topologyId = "";
-        mockBroker = mock(BindingAwareBroker.class);
         mockExecutor = mock(EventExecutor.class);
         mockKeepAlive = mock(ScheduledThreadPool.class);
         mockProcessingExecutor = mock(ThreadPool.class);
         mockSchemaRepoProvider = mock(SchemaRepositoryProvider.class);
-        mockDomBroker = mock(Broker.class);
         mockDataBroker = mock(DataBroker.class);
         mockMount = mock(DOMMountPointService.class);
         mockSessMgr = mock(CallHomeMountSessionManager.class);
         mockTopology = mock(CallHomeTopology.class);
         mockProtoSess = mock(CallHomeProtocolSessionContext.class);
 
-        instance = new CallHomeMountDispatcher(topologyId, mockBroker, mockExecutor, mockKeepAlive,
-                mockProcessingExecutor, mockSchemaRepoProvider, mockDomBroker, mockDataBroker, mockMount) {
+        instance = new CallHomeMountDispatcher(topologyId, mockExecutor, mockKeepAlive,
+                mockProcessingExecutor, mockSchemaRepoProvider, mockDataBroker, mockMount) {
             @Override
             public CallHomeMountSessionManager getSessionManager() {
                 return mockSessMgr;
@@ -87,15 +80,15 @@ public class CallHomeMountDispatcherTest {
         };
     }
 
-    NetconfClientConfiguration someConfiguration(InetSocketAddress address) {
+    NetconfClientConfiguration someConfiguration(final InetSocketAddress address) {
         // NetconfClientConfiguration has mostly final methods, making it un-mock-able
 
-        NetconfClientConfiguration.NetconfClientProtocol protocol =
+        final NetconfClientConfiguration.NetconfClientProtocol protocol =
                 NetconfClientConfiguration.NetconfClientProtocol.SSH;
-        NetconfHelloMessageAdditionalHeader additionalHeader = mock(NetconfHelloMessageAdditionalHeader.class);
-        NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
-        ReconnectStrategy reconnectStrategy = mock(ReconnectStrategy.class);
-        AuthenticationHandler authHandler = mock(AuthenticationHandler.class);
+        final NetconfHelloMessageAdditionalHeader additionalHeader = mock(NetconfHelloMessageAdditionalHeader.class);
+        final NetconfClientSessionListener sessionListener = mock(NetconfClientSessionListener.class);
+        final ReconnectStrategy reconnectStrategy = mock(ReconnectStrategy.class);
+        final AuthenticationHandler authHandler = mock(AuthenticationHandler.class);
 
         return NetconfClientConfigurationBuilder.create().withProtocol(protocol).withAddress(address)
                 .withConnectionTimeoutMillis(0).withAdditionalHeader(additionalHeader)
@@ -106,11 +99,11 @@ public class CallHomeMountDispatcherTest {
     @Test
     public void canCreateASessionFromAConfiguration() {
         // given
-        CallHomeMountSessionContext mockContext = mock(CallHomeMountSessionContext.class);
-        InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
+        final CallHomeMountSessionContext mockContext = mock(CallHomeMountSessionContext.class);
+        final InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
         doReturn(mockContext).when(mockSessMgr).getByAddress(eq(someAddress));
 
-        NetconfClientConfiguration someCfg = someConfiguration(someAddress);
+        final NetconfClientConfiguration someCfg = someConfiguration(someAddress);
         // when
         instance.createClient(someCfg);
         // then
@@ -120,10 +113,10 @@ public class CallHomeMountDispatcherTest {
     @Test
     public void noSessionIsCreatedWithoutAContextAvailableForAGivenAddress() {
         // given
-        InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
-        NetconfClientConfiguration someCfg = someConfiguration(someAddress);
+        final InetSocketAddress someAddress = InetSocketAddress.createUnresolved("1.2.3.4", 123);
+        final NetconfClientConfiguration someCfg = someConfiguration(someAddress);
         // when
-        Future<NetconfClientSession> future = instance.createClient(someCfg);
+        final Future<NetconfClientSession> future = instance.createClient(someCfg);
         // then
         assertFalse(future.isSuccess());
     }
@@ -131,14 +124,14 @@ public class CallHomeMountDispatcherTest {
     @Test
     public void nodeIsInsertedIntoTopologyWhenSubsystemIsOpened() throws UnknownHostException {
         // given
-        NodeId mockNodeId = mock(NodeId.class);
-        Node mockNode = mock(Node.class);
-        CallHomeMountSessionContext mockDevCtxt = mock(CallHomeMountSessionContext.class);
+        final NodeId mockNodeId = mock(NodeId.class);
+        final Node mockNode = mock(Node.class);
+        final CallHomeMountSessionContext mockDevCtxt = mock(CallHomeMountSessionContext.class);
         doReturn(mockNodeId).when(mockDevCtxt).getId();
         doReturn(mockNode).when(mockDevCtxt).getConfigNode();
         doReturn(mockDevCtxt).when(mockSessMgr).createSession(any(CallHomeProtocolSessionContext.class),
                 any(CallHomeChannelActivator.class), any(CallHomeMountSessionContext.CloseCallback.class));
-        CallHomeChannelActivator activator = mock(CallHomeChannelActivator.class);
+        final CallHomeChannelActivator activator = mock(CallHomeChannelActivator.class);
         instance.createTopology();
         // when
         instance.onNetconfSubsystemOpened(mockProtoSess, activator);
index 8a63f3c8998941f29cdba56033c5190d8d003c6e..85593ce6be17eb72a9b86187120e45e2cb07644c 100644 (file)
           </instructions>
         </configuration>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index 52d97fb950264fe6a8b67fcf8de4fc87b77361e7..f3cc24494cbb98284cb06e9557ad5fb2fec6a838 100644 (file)
@@ -32,7 +32,8 @@ public class DiscardChanges extends AbstractConfigNetconfOperation {
 
     private static final Logger LOG = LoggerFactory.getLogger(DiscardChanges.class);
 
-    public DiscardChanges(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+    public DiscardChanges(final ConfigSubsystemFacade configSubsystemFacade,
+                          final String netconfSessionIdForReporting) {
         super(configSubsystemFacade, netconfSessionIdForReporting);
     }
 
@@ -46,8 +47,10 @@ public class DiscardChanges extends AbstractConfigNetconfOperation {
         return DISCARD;
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement xml) throws DocumentedException {
         fromXml(xml);
         try {
             getConfigSubsystemFacade().abortConfiguration();
index cb5e99feeb74f5f984d6f245392dc26c600b9551..9cca810ec98133ff54e818807ac282bbd761df49 100644 (file)
@@ -22,7 +22,8 @@ import org.w3c.dom.Element;
 
 /**
  * Simple Lock implementation that pretends to lock candidate datastore.
- * Candidate datastore is allocated per session and is private so no real locking is needed (JMX is the only possible interference)
+ * Candidate datastore is allocated per session and is private so no real locking is needed
+ * (JMX is the only possible interference)
  */
 public class Lock extends AbstractLastNetconfOperation {
 
@@ -36,17 +37,20 @@ public class Lock extends AbstractLastNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement operationElement) throws DocumentedException {
         final Datastore targetDatastore = extractTargetParameter(operationElement);
-        if(targetDatastore == Datastore.candidate) {
-            // Since candidate datastore instances are allocated per session and not accessible anywhere else, no need to lock
+        if (targetDatastore == Datastore.candidate) {
+            // Since candidate datastore instances are allocated per session and not accessible anywhere else,
+            // no need to lock
             LOG.debug("Locking {} datastore on session: {}", targetDatastore, getNetconfSessionIdForReporting());
             // TODO should this fail if we are already locked ?
             return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
         }
 
         // Not supported running lock
-        throw new DocumentedException("Unable to lock " + Datastore.running + " datastore", DocumentedException.ErrorType.APPLICATION,
+        throw new DocumentedException("Unable to lock " + Datastore.running + " datastore",
+                DocumentedException.ErrorType.APPLICATION,
                 DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
     }
 
index a20426b6d4e1af39c6fe9a7ab8d97cd4b6af4d37..17fff3d2185c74163142beb0671cf4e60f527ff8 100644 (file)
@@ -22,7 +22,8 @@ import org.w3c.dom.Element;
 
 /**
  * Simple unlock implementation that pretends to unlock candidate datastore.
- * Candidate datastore is allocated per session and is private so no real locking is needed (JMX is the only possible interference)
+ * Candidate datastore is allocated per session and is private so no real locking is needed
+ * (JMX is the only possible interference)
  */
 public class UnLock extends AbstractLastNetconfOperation {
 
@@ -35,17 +36,20 @@ public class UnLock extends AbstractLastNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement operationElement) throws DocumentedException {
         final Datastore targetDatastore = Lock.extractTargetParameter(operationElement);
-        if(targetDatastore == Datastore.candidate) {
-            // Since candidate datastore instances are allocated per session and not accessible anywhere else, no need to lock
+        if (targetDatastore == Datastore.candidate) {
+            // Since candidate datastore instances are allocated per session and not accessible anywhere else,
+            // no need to lock
             LOG.debug("Unlocking {} datastore on session: {}", targetDatastore, getNetconfSessionIdForReporting());
             // TODO this should fail if we are not locked
             return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
         }
 
         // Not supported running lock
-        throw new DocumentedException("Unable to unlock " + Datastore.running + " datastore", DocumentedException.ErrorType.APPLICATION,
+        throw new DocumentedException("Unable to unlock " + Datastore.running + " datastore",
+                DocumentedException.ErrorType.APPLICATION,
                 DocumentedException.ErrorTag.OPERATION_NOT_SUPPORTED, DocumentedException.ErrorSeverity.ERROR);
     }
 
index 61d05bc9f8119992d1fb7ab3c188b1ce7352b00b..7c4e823e389829a5f496c09d5e38d105b7dbdf51 100644 (file)
@@ -48,9 +48,10 @@ public class Validate extends AbstractConfigNetconfOperation {
         final String datastoreValue = sourceChildNode.getName();
         final Datastore sourceDatastore = Datastore.valueOf(datastoreValue);
 
-        if (sourceDatastore != Datastore.candidate){
-            throw new DocumentedException( "Only " + Datastore.candidate
-                    + " is supported as source for " + VALIDATE + " but was " + datastoreValue, ErrorType.APPLICATION, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
+        if (sourceDatastore != Datastore.candidate) {
+            throw new DocumentedException("Only " + Datastore.candidate
+                    + " is supported as source for " + VALIDATE + " but was " + datastoreValue, ErrorType.APPLICATION,
+                    ErrorTag.DATA_MISSING, ErrorSeverity.ERROR);
         }
     }
 
@@ -60,7 +61,8 @@ public class Validate extends AbstractConfigNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement xml) throws DocumentedException {
         checkXml(xml);
         try {
             getConfigSubsystemFacade().validateConfiguration();
@@ -72,7 +74,8 @@ public class Validate extends AbstractConfigNetconfOperation {
             final Map<String, String> errorInfo = new HashMap<>();
             errorInfo
                     .put(ErrorTag.OPERATION_FAILED.name(),
-                            "Datastore is not present. Use 'get-config' or 'edit-config' before triggering 'operations' operation");
+                            "Datastore is not present. "
+                                    + "Use 'get-config' or 'edit-config' before triggering 'operations' operation");
             throw new DocumentedException(e.getMessage(), e, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
                     ErrorSeverity.ERROR, errorInfo);
 
index eb01a57c11138396eb177571e75bf382ebc1dd49..e247928033564c095afa65b40f60b8edab7e37bb 100644 (file)
@@ -65,8 +65,10 @@ public class EditConfig extends AbstractConfigNetconfOperation {
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement xml) throws DocumentedException {
-        // FIXME config mapping getter works on dynamic yang store service and so does later executeConfigExecution method
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement xml) throws DocumentedException {
+        // FIXME config mapping getter works on dynamic yang store service
+        // and so does later executeConfigExecution method
         // They might have different view of current yangs in ODL and might cause race conditions
         final Config cfg = getConfigSubsystemFacade().getConfigMapping();
         final ConfigExecution configExecution = editConfigXmlParser.fromXml(xml, cfg);
index c317d1dd971eb90005b187f63f756a8baa8807be..ddba4ae81397a1d0695db8f58ccfbff2027f2625 100644 (file)
@@ -45,8 +45,8 @@ public class EditConfigXmlParser {
         xml.checkNamespace(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
 
 
-        XmlElement targetElement = null;
-        XmlElement targetChildNode = null;
+        XmlElement targetElement;
+        XmlElement targetChildNode;
         targetElement  = xml.getOnlyChildElementWithSameNamespace(EditConfigXmlParser.TARGET_KEY);
         targetChildNode = targetElement.getOnlyChildElementWithSameNamespace();
 
@@ -55,7 +55,7 @@ public class EditConfigXmlParser {
         LOG.debug("Setting {} to '{}'", EditConfigXmlParser.TARGET_KEY, targetDatastore);
 
         // check target
-        if (targetDatastore != Datastore.candidate){
+        if (targetDatastore != Datastore.candidate) {
             throw new DocumentedException(String.format(
                     "Only %s datastore supported for edit config but was: %s",
                     Datastore.candidate,
@@ -82,7 +82,7 @@ public class EditConfigXmlParser {
                 .getOnlyChildElementWithSameNamespaceOptionally(EditConfigXmlParser.ERROR_OPTION_KEY);
         if (errorOptionElement.isPresent()) {
             final String errorOptionParsed = errorOptionElement.get().getTextContent();
-            if (!errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION)){
+            if (!errorOptionParsed.equals(EditConfigXmlParser.DEFAULT_ERROR_OPTION)) {
                 throw new UnsupportedOperationException("Only " + EditConfigXmlParser.DEFAULT_ERROR_OPTION
                         + " supported for " + EditConfigXmlParser.ERROR_OPTION_KEY + ", was " + errorOptionParsed);
             }
@@ -97,7 +97,7 @@ public class EditConfigXmlParser {
             editStrategyType = EditStrategyType.valueOf(mergeStrategyString);
         }
 
-        XmlElement configElement = null;
+        XmlElement configElement;
         configElement = xml.getOnlyChildElementWithSameNamespace(XmlNetconfConstants.CONFIG_KEY);
 
         return new ConfigExecution(cfgMapping, configElement, testOption, editStrategyType);
index d7e3061cc37da0406b240fdd186cc7cdb0745381..dc1c31d19886c925c53306134faba33a34323e13 100644 (file)
@@ -28,7 +28,8 @@ public class GetConfig extends AbstractConfigNetconfOperation {
 
     private static final Logger LOG = LoggerFactory.getLogger(GetConfig.class);
 
-    public GetConfig(final ConfigSubsystemFacade configSubsystemFacade, final Optional<String> maybeNamespace, final String netconfSessionIdForReporting) {
+    public GetConfig(final ConfigSubsystemFacade configSubsystemFacade, final Optional<String> maybeNamespace,
+                     final String netconfSessionIdForReporting) {
         super(configSubsystemFacade, netconfSessionIdForReporting);
         this.maybeNamespace = maybeNamespace;
     }
index b8d5b58a2d4f55f7b4de8504a77fa2f72fd969bb..bbcdf28b6517277c1144570a1ca986144c631ad8 100644 (file)
@@ -53,7 +53,7 @@ public class RuntimeRpc extends AbstractConfigNetconfOperation {
         final Optional<XmlElement> contextInstanceElement = operationElement
                 .getOnlyChildElementOptionally(RpcFacade.CONTEXT_INSTANCE);
 
-        if (!contextInstanceElement.isPresent()){
+        if (!contextInstanceElement.isPresent()) {
             return HandlingPriority.CANNOT_HANDLE;
         }
 
@@ -97,8 +97,8 @@ public class RuntimeRpc extends AbstractConfigNetconfOperation {
                 execution.getAttributes());
         final Object result = getConfigSubsystemFacade().getRpcFacade().executeOperation(execution);
 
-        LOG.trace("Operation {} called successfully on {} with arguments {} with result {}", execution.getOperationName(),
-                execution.getOn(), execution.getAttributes(), result);
+        LOG.trace("Operation {} called successfully on {} with arguments {} with result {}",
+                execution.getOperationName(), execution.getOn(), execution.getAttributes(), result);
 
         if (execution.isVoid()) {
             return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.absent());
index 336c03a59b5b7b0eb48af22e0f2db0c18dcf2e29..40edbec2134b07934d98f10c3b973c4e75df5c36 100644 (file)
@@ -30,24 +30,30 @@ public class Activator implements BundleActivator {
 
     @Override
     public void start(final BundleContext context) throws Exception {
-        ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer = new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
+        ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory,
+                ConfigSubsystemFacadeFactory> schemaServiceTrackerCustomizer =
+                new ServiceTrackerCustomizer<ConfigSubsystemFacadeFactory, ConfigSubsystemFacadeFactory>() {
 
             @Override
-            public ConfigSubsystemFacadeFactory addingService(ServiceReference<ConfigSubsystemFacadeFactory> reference) {
+            public ConfigSubsystemFacadeFactory addingService(
+                    ServiceReference<ConfigSubsystemFacadeFactory> reference) {
                 LOG.debug("Got addingService(SchemaContextProvider) event");
                 // Yang store service should not be registered multiple times
-                ConfigSubsystemFacadeFactory configSubsystemFacade = reference.getBundle().getBundleContext().getService(reference);
+                ConfigSubsystemFacadeFactory configSubsystemFacade =
+                        reference.getBundle().getBundleContext().getService(reference);
                 osgiRegistration = startNetconfServiceFactory(configSubsystemFacade, context);
                 return configSubsystemFacade;
             }
 
             @Override
-            public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+            public void modifiedService(ServiceReference<ConfigSubsystemFacadeFactory> reference,
+                                        ConfigSubsystemFacadeFactory service) {
                 LOG.warn("Config manager facade was modified unexpectedly");
             }
 
             @Override
-            public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference, ConfigSubsystemFacadeFactory service) {
+            public void removedService(ServiceReference<ConfigSubsystemFacadeFactory> reference,
+                                       ConfigSubsystemFacadeFactory service) {
                 LOG.warn("Config manager facade was removed unexpectedly");
             }
         };
@@ -64,12 +70,15 @@ public class Activator implements BundleActivator {
         }
     }
 
-    private ServiceRegistration<NetconfOperationServiceFactory> startNetconfServiceFactory(final ConfigSubsystemFacadeFactory configSubsystemFacade, final BundleContext context) {
-        final NetconfOperationServiceFactoryImpl netconfOperationServiceFactory = new NetconfOperationServiceFactoryImpl(configSubsystemFacade);
+    private ServiceRegistration<NetconfOperationServiceFactory> startNetconfServiceFactory(
+            final ConfigSubsystemFacadeFactory configSubsystemFacade, final BundleContext context) {
+        final NetconfOperationServiceFactoryImpl netconfOperationServiceFactory =
+                new NetconfOperationServiceFactoryImpl(configSubsystemFacade);
         // Add properties to autowire with netconf-impl instance for cfg subsystem
         final Dictionary<String, String> properties = new Hashtable<>();
         properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.CONFIG_NETCONF_CONNECTOR);
-        return context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
+        return context.registerService(NetconfOperationServiceFactory.class,
+                netconfOperationServiceFactory, properties);
     }
 
 }
index 6f0a448dd213168e8a253ca833a30700c9c03514..30064685db637c588db33506041339139454be66 100644 (file)
@@ -26,7 +26,8 @@ import org.opendaylight.netconf.mapping.api.NetconfOperation;
 final class NetconfOperationProvider {
     private final Set<NetconfOperation> operations;
 
-    NetconfOperationProvider(final ConfigSubsystemFacade configSubsystemFacade, final String netconfSessionIdForReporting) {
+    NetconfOperationProvider(final ConfigSubsystemFacade configSubsystemFacade,
+                             final String netconfSessionIdForReporting) {
 
         operations = setUpOperations(configSubsystemFacade, netconfSessionIdForReporting);
     }
index 01405d447ea046997753ea0df61507c8ed6b7557..370e59e83e0d445f2e46857e935f7b183893bd9b 100644 (file)
@@ -24,7 +24,8 @@ public class NetconfOperationServiceFactoryImpl implements NetconfOperationServi
 
     @Override
     public NetconfOperationServiceImpl createService(String netconfSessionIdForReporting) {
-        return new NetconfOperationServiceImpl(configFacadeFactory.createFacade(netconfSessionIdForReporting), netconfSessionIdForReporting);
+        return new NetconfOperationServiceImpl(configFacadeFactory.createFacade(netconfSessionIdForReporting),
+                netconfSessionIdForReporting);
     }
 
     @Override
index c935801ddad79921f632ecfd8dc42d9c52691609..f4059a6438fa4434623ee3a180262021e4f08163 100644 (file)
@@ -140,7 +140,7 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
     private static final String INSTANCE_NAME = "instance-from-code";
     private static final String NETCONF_SESSION_ID = "foo";
-    private static final String TEST_NAMESPACE= "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
+    private static final String TEST_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test:impl";
     private NetconfTestImplModuleFactory factory;
     private DepTestImplModuleFactory factory2;
     private IdentityTestModuleFactory factory3;
@@ -176,13 +176,15 @@ public class NetconfMappingTest extends AbstractConfigTest {
             @Override
             public String fromYang(final String enumType, final String enumYangValue) {
                 return Preconditions.checkNotNull(getEnumMapping().get(enumYangValue),
-                        "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping());
+                        "Unable to resolve enum value %s, for enum %s with mappings %s",
+                        enumYangValue, enumType, getEnumMapping());
             }
 
             @Override
             public String toYang(final String enumType, final String enumYangValue) {
                 return Preconditions.checkNotNull(getEnumMapping().inverse().get(enumYangValue),
-                        "Unable to resolve enum value %s, for enum %s with mappings %s", enumYangValue, enumType, getEnumMapping().inverse());
+                        "Unable to resolve enum value %s, for enum %s with mappings %s",
+                        enumYangValue, enumType, getEnumMapping().inverse());
             }
         }).when(this.yangStoreSnapshot).getEnumResolver();
 
@@ -192,27 +194,31 @@ public class NetconfMappingTest extends AbstractConfigTest {
         factory4 = new TestImplModuleFactory();
         doNothing().when(sessionCloseable).close();
 
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory, this.factory2,
-                this.factory3, factory4));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, this.factory,
+                this.factory2, this.factory3, factory4));
 
         transactionProvider = new TransactionProvider(this.configRegistryClient, NETCONF_SESSION_ID);
 
-        configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot, "mapping-test");
+        configSubsystemFacade = new ConfigSubsystemFacade(configRegistryClient, configRegistryClient, yangStoreSnapshot,
+                "mapping-test");
     }
 
-    private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException, InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
+    private ObjectName createModule(final String instanceName) throws InstanceAlreadyExistsException,
+            InstanceNotFoundException, URISyntaxException, ValidationException, ConflictingVersionException {
         final ConfigTransactionJMXClient transaction = this.configRegistryClient.createTransaction();
 
         final ObjectName on = transaction.createModule(this.factory.getImplementationName(), instanceName);
         final NetconfTestImplModuleMXBean mxBean = transaction.newMXBeanProxy(on, NetconfTestImplModuleMXBean.class);
         setModule(mxBean, transaction, instanceName + "_dep");
 
-        int i = 1;
-        for (final Class<? extends AbstractServiceInterface> sInterface : factory.getImplementedServiceIntefaces()) {
-            final ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
+        int index = 1;
+        for (final Class<? extends AbstractServiceInterface> serviceInterface :
+                factory.getImplementedServiceIntefaces()) {
+            final ServiceInterfaceAnnotation annotation =
+                    serviceInterface.getAnnotation(ServiceInterfaceAnnotation.class);
             transaction.saveServiceReference(
-                    transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + instanceName + "_" + i++,
-                    on);
+                    transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()),
+                    "ref_from_code_to_" + instanceName + "_" + index++, on);
 
         }
         transaction.commit();
@@ -339,9 +345,9 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
             @Override
             public void testText(final Text text) throws NodeTestException {
-                if(text.getData().equals("ref_dep2")) {
+                if (text.getData().equals("ref_dep2")) {
                     defaultRefNameCount++;
-                } else if(text.getData().equals("ref_dep_user_two")) {
+                } else if (text.getData().equals("ref_dep_user_two")) {
                     userRefNameCount++;
                 }
             }
@@ -355,7 +361,8 @@ public class NetconfMappingTest extends AbstractConfigTest {
         nt.performTest(tester, Node.TEXT_NODE);
     }
 
-    private static void assertCorrectServiceNames(final Document configCandidate, final Set<String> refNames) throws NodeTestException {
+    private static void assertCorrectServiceNames(final Document configCandidate,
+                                                  final Set<String> refNames) throws NodeTestException {
         final Set<String> refNames2 = new HashSet<>(refNames);
         final NodeList servicesNodes = configCandidate.getElementsByTagName("services");
         assertEquals(1, servicesNodes.getLength());
@@ -365,10 +372,10 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
             @Override
             public void testElement(final Element element) throws NodeTestException {
-                if(element.getNodeName() != null) {
-                    if(element.getNodeName().equals("name")) {
+                if (element.getNodeName() != null) {
+                    if (element.getNodeName().equals("name")) {
                         final String elmText = element.getTextContent();
-                        if(refNames2.contains(elmText)) {
+                        if (refNames2.contains(elmText)) {
                             refNames2.remove(elmText);
                         } else {
                             throw new NodeTestException("Unexpected services defined: " + elmText);
@@ -394,17 +401,23 @@ public class NetconfMappingTest extends AbstractConfigTest {
         edit("netconfMessages/editConfig.xml");
         commit();
         Document response = getConfigRunning();
-        final Element ipElement = readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
-        assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
+        final Element ipElement = readXmlToElement(
+                "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>");
+        assertContainsElement(response, readXmlToElement(
+                "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">0:0:0:0:0:0:0:1</ip>"));
 
-        assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
+        assertContainsElement(response, readXmlToElement("<union-test-attr xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">456</union-test-attr>"));
 
 
         edit("netconfMessages/editConfig_setUnions.xml");
         commit();
         response = getConfigRunning();
-        assertContainsElement(response, readXmlToElement("<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
-        assertContainsElement(response, readXmlToElement("<union-test-attr xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">randomStringForUnion</union-test-attr>"));
+        assertContainsElement(response, readXmlToElement(
+                "<ip xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">127.1.2.3</ip>"));
+        assertContainsElement(response, readXmlToElement("<union-test-attr xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">"
+                + "randomStringForUnion</union-test-attr>"));
 
     }
 
@@ -438,7 +451,8 @@ public class NetconfMappingTest extends AbstractConfigTest {
         commit();
         assertXMLEqual(getConfigCandidate(), getConfigRunning());
 
-        final Document expectedResult = XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
+        final Document expectedResult =
+                XmlFileLoader.xmlFileToDocument("netconfMessages/editConfig_expectedResult.xml");
         XMLUnit.setIgnoreWhitespace(true);
         assertXMLEqual(expectedResult, getConfigRunning());
         assertXMLEqual(expectedResult, getConfigCandidate());
@@ -451,9 +465,11 @@ public class NetconfMappingTest extends AbstractConfigTest {
     }
 
     private static void checkBigDecimal(final Document response) throws NodeTestException, SAXException, IOException {
-        assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
+        assertContainsElement(response, readXmlToElement("<sleep-factor xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.58</sleep-factor>"));
         // Default
-        assertContainsElement(response, readXmlToElement("<sleep-factor xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
+        assertContainsElement(response, readXmlToElement("<sleep-factor xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2.00</sleep-factor>"));
     }
 
     private void closeSession() throws ParserConfigurationException, SAXException,
@@ -480,25 +496,29 @@ public class NetconfMappingTest extends AbstractConfigTest {
         executeOp(commitOp, "netconfMessages/commit.xml");
     }
 
-    private static Document lockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+    private static Document lockCandidate() throws ParserConfigurationException, SAXException, IOException,
+            DocumentedException {
         final Lock commitOp = new Lock(NETCONF_SESSION_ID);
         return executeOp(commitOp, "netconfMessages/lock.xml");
     }
 
-    private static Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException, DocumentedException {
+    private static Document unlockCandidate() throws ParserConfigurationException, SAXException, IOException,
+            DocumentedException {
         final UnLock commitOp = new UnLock(NETCONF_SESSION_ID);
         return executeOp(commitOp, "netconfMessages/unlock.xml");
     }
 
     private Document getConfigCandidate() throws ParserConfigurationException, SAXException, IOException,
             DocumentedException {
-        final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(), NETCONF_SESSION_ID);
+        final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(),
+                NETCONF_SESSION_ID);
         return executeOp(getConfigOp, "netconfMessages/getConfig_candidate.xml");
     }
 
     private Document getConfigRunning() throws ParserConfigurationException, SAXException, IOException,
             DocumentedException {
-        final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(), NETCONF_SESSION_ID);
+        final GetConfig getConfigOp = new GetConfig(configSubsystemFacade, Optional.<String>absent(),
+                NETCONF_SESSION_ID);
         return executeOp(getConfigOp, "netconfMessages/getConfig.xml");
     }
 
@@ -596,9 +616,9 @@ public class NetconfMappingTest extends AbstractConfigTest {
     public void testUnrecognisedConfigElements() throws Exception {
 
         final String format = "netconfMessages/unrecognised/editConfig_unrecognised%d.xml";
-        final int TESTS_COUNT = 8;
+        final int testsCount = 8;
 
-        for (int i = 0; i < TESTS_COUNT; i++) {
+        for (int i = 0; i < testsCount; i++) {
             final String file = String.format(format, i + 1);
             LOG.info("Reading {}", file);
             try {
@@ -666,24 +686,33 @@ public class NetconfMappingTest extends AbstractConfigTest {
         return executeOp(discardOp, "netconfMessages/discardChanges.xml");
     }
 
-    private static void checkBinaryLeafEdited(final Document response) throws NodeTestException, SAXException, IOException {
-        assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
-        assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
+    private static void checkBinaryLeafEdited(final Document response)
+            throws NodeTestException, SAXException, IOException {
+        assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">YmluYXJ5</binaryLeaf>"));
+        assertContainsElement(response, readXmlToElement("<binaryLeaf xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">ZGVmYXVsdEJpbg==</binaryLeaf>"));
     }
 
     private static void checkTypedefs(final Document response) throws NodeTestException, SAXException, IOException {
 
-        assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
+        assertContainsElement(response, readXmlToElement(
+                "<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">10</extended>"));
         // Default
-        assertContainsElement(response, readXmlToElement("<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
+        assertContainsElement(response, readXmlToElement(
+                "<extended xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">1</extended>"));
 
-        assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
+        assertContainsElement(response, readXmlToElement("<extended-twice xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">20</extended-twice>"));
         // Default
-        assertContainsElement(response, readXmlToElement("<extended-twice xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
+        assertContainsElement(response, readXmlToElement("<extended-twice xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">2</extended-twice>"));
 
-        assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
+        assertContainsElement(response, readXmlToElement("<extended-enum xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">two</extended-enum>"));
         // Default
-        assertContainsElement(response, readXmlToElement("<extended-enum xmlns=\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
+        assertContainsElement(response, readXmlToElement("<extended-enum xmlns="
+                + "\"urn:opendaylight:params:xml:ns:yang:controller:test:impl\">one</extended-enum>"));
     }
 
     private static void assertContainsString(final String string, final String substring) {
@@ -705,13 +734,13 @@ public class NetconfMappingTest extends AbstractConfigTest {
     }
 
     private static String getXpathForNetconfImplSubnode(final String instanceName, final String subnode) {
-        return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply" +
-                "/urn:ietf:params:xml:ns:netconf:base:1.0:data" +
-                "/urn:opendaylight:params:xml:ns:yang:controller:config:modules" +
-                "/urn:opendaylight:params:xml:ns:yang:controller:config:module" +
-                "[urn:opendaylight:params:xml:ns:yang:controller:config:name='" + instanceName + "']" +
-                "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf" +
-                "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:" + subnode;
+        return "/urn:ietf:params:xml:ns:netconf:base:1.0:rpc-reply"
+                + "/urn:ietf:params:xml:ns:netconf:base:1.0:data"
+                + "/urn:opendaylight:params:xml:ns:yang:controller:config:modules"
+                + "/urn:opendaylight:params:xml:ns:yang:controller:config:module"
+                + "[urn:opendaylight:params:xml:ns:yang:controller:config:name='" + instanceName + "']"
+                + "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:impl-netconf"
+                "/urn:opendaylight:params:xml:ns:yang:controller:test:impl:" + subnode;
     }
 
     private static void checkTypeConfigAttribute(final Document response) throws Exception {
@@ -720,7 +749,7 @@ public class NetconfMappingTest extends AbstractConfigTest {
                 "test2", "default-string");
         for (final Entry<String, String> nameToExpectedValue : namesToTypeValues.entrySet()) {
             XMLAssert.assertXpathEvaluatesTo(nameToExpectedValue.getValue(),
-                    getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(),"type"),
+                    getXpathForNetconfImplSubnode(nameToExpectedValue.getKey(), "type"),
                     response);
         }
     }
@@ -732,7 +761,8 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
         final SchemaContext schemaContext = YangParserTestUtils.parseYangStreams(yangDependencies);
         final YangStoreService yangStoreService = new YangStoreService(new SchemaContextProvider() {
-            @Override public SchemaContext getSchemaContext() {
+            @Override
+            public SchemaContext getSchemaContext() {
                 return schemaContext;
             }
         }, mock(SchemaSourceProvider.class));
@@ -783,7 +813,8 @@ public class NetconfMappingTest extends AbstractConfigTest {
         assertEquals(8 * 4, getElementsSize(response, "inner-inner-running-data"));
         assertEquals(8 * 4, getElementsSize(response, "deep3"));
         assertEquals(8 * 4 * 2, getElementsSize(response, "list-of-strings"));
-        assertEquals(8, getElementsSize(response, "inner-running-data-additional", "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
+        assertEquals(8, getElementsSize(response, "inner-running-data-additional",
+                "urn:opendaylight:params:xml:ns:yang:controller:test:impl"));
         assertEquals(8, getElementsSize(response, "deep4"));
         // TODO assert keys
 
@@ -818,7 +849,8 @@ public class NetconfMappingTest extends AbstractConfigTest {
         return response.getElementsByTagNameNS(namespace, elementName).getLength();
     }
 
-    private static Document executeOp(final NetconfOperation op, final String filename) throws ParserConfigurationException,
+    private static Document executeOp(final NetconfOperation op,
+                                      final String filename) throws ParserConfigurationException,
             SAXException, IOException, DocumentedException {
 
         final Document request = XmlFileLoader.xmlFileToDocument(filename);
@@ -835,8 +867,9 @@ public class NetconfMappingTest extends AbstractConfigTest {
 
     private List<InputStream> getYangs() {
         final List<String> paths = Arrays.asList("/META-INF/yang/config.yang", "/META-INF/yang/rpc-context.yang",
-                "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang", "/META-INF/yang/test-types.yang",
-                "/META-INF/yang/test-groups.yang", "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
+                "/META-INF/yang/config-test.yang", "/META-INF/yang/config-test-impl.yang",
+                "/META-INF/yang/test-types.yang", "/META-INF/yang/test-groups.yang",
+                "/META-INF/yang/ietf-inet-types@2013-07-15.yang");
         final Collection<InputStream> yangDependencies = new ArrayList<>();
         for (final String path : paths) {
             final InputStream is = Preconditions
@@ -846,10 +879,11 @@ public class NetconfMappingTest extends AbstractConfigTest {
         return Lists.newArrayList(yangDependencies);
     }
 
-    private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction, final String depName)
+    private void setModule(final NetconfTestImplModuleMXBean mxBean, final ConfigTransactionJMXClient transaction,
+                           final String depName)
             throws InstanceAlreadyExistsException, InstanceNotFoundException {
         mxBean.setSimpleInt((long) 44);
-        mxBean.setBinaryLeaf(new byte[] { 8, 7, 9 });
+        mxBean.setBinaryLeaf(new byte[]{8, 7, 9});
         final DtoD dtob = getDtoD();
         mxBean.setDtoD(dtob);
         //
@@ -865,7 +899,7 @@ public class NetconfMappingTest extends AbstractConfigTest {
         p2.setCoreSize(44L);
         p2.setPort("port23");
         p2.setSimpleInt3(456);
-        mxBean.setPeers(Lists.<Peers> newArrayList(p1, p2));
+        mxBean.setPeers(Lists.<Peers>newArrayList(p1, p2));
         // //
         mxBean.setSimpleLong(454545L);
         mxBean.setSimpleLong2(44L);
@@ -874,16 +908,18 @@ public class NetconfMappingTest extends AbstractConfigTest {
         mxBean.setSimpleShort(new Short((short) 4));
         mxBean.setSimpleTest(545);
 
-        mxBean.setComplexList(Lists.<ComplexList> newArrayList());
-        mxBean.setSimpleList(Lists.<Integer> newArrayList());
+        mxBean.setComplexList(Lists.<ComplexList>newArrayList());
+        mxBean.setSimpleList(Lists.<Integer>newArrayList());
 
         final ObjectName testingDepOn = transaction.createModule(this.factory2.getImplementationName(), depName);
-        int i = 1;
-        for (final Class<? extends AbstractServiceInterface> sInterface : factory2.getImplementedServiceIntefaces()) {
-            final ServiceInterfaceAnnotation annotation = sInterface.getAnnotation(ServiceInterfaceAnnotation.class);
+        int index = 1;
+        for (final Class<? extends AbstractServiceInterface> serviceInterface :
+                factory2.getImplementedServiceIntefaces()) {
+            final ServiceInterfaceAnnotation annotation =
+                    serviceInterface.getAnnotation(ServiceInterfaceAnnotation.class);
             transaction.saveServiceReference(
-                    transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()), "ref_from_code_to_" + depName + "_" + i++,
-                    testingDepOn);
+                    transaction.getServiceInterfaceName(annotation.namespace(), annotation.localName()),
+                    "ref_from_code_to_" + depName + "_" + index++, testingDepOn);
 
         }
         mxBean.setTestingDep(testingDepOn);
index e04f0c731fab0c86d4aaa6702d31914119b69eaa..39a3ee1e3b872edfeff6ec97b8de19ddd06871e8 100644 (file)
@@ -89,7 +89,8 @@ public class EditConfigTest {
         EditConfig edit = new EditConfig(cfgFacade, ValidateTest.NETCONF_SESSION_ID_FOR_REPORTING);
         EditConfigStrategy editStrat = mock(EditConfigStrategy.class);
 
-        doNothing().when(editStrat).executeConfiguration(anyString(), anyString(), anyMapOf(String.class, AttributeConfigElement.class),
+        doNothing().when(editStrat).executeConfiguration(anyString(), anyString(), anyMapOf(String.class,
+                AttributeConfigElement.class),
                 any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
 
         ConfigExecution editConfigExecution = mockExecution(editStrat);
@@ -103,7 +104,8 @@ public class EditConfigTest {
         verify(provider).getOrCreateTransaction();
 
         // For every instance execute strat
-        verify(editStrat, times(2/* Test */+ 2/* Set */ + 2/*Handle missing instance Test*/ + 2 /*Handle missing instance Set*/)).executeConfiguration(anyString(),
+        verify(editStrat, times(2/* Test */ + 2/* Set */ + 2/*Handle missing instance Test*/
+                + 2 /*Handle missing instance Set*/)).executeConfiguration(anyString(),
                 anyString(), anyMapOf(String.class, AttributeConfigElement.class),
                 any(ConfigTransactionClient.class), any(ServiceRegistryWrapper.class));
     }
@@ -122,7 +124,7 @@ public class EditConfigTest {
     }
 
     private Object getMappingDefinition(EditConfigStrategy editStrat) {
-        Map<String, Multimap<String, ModuleElementDefinition>> result = Maps.newHashMap();
+        final Map<String, Multimap<String, ModuleElementDefinition>> result = Maps.newHashMap();
 
         Multimap<String, ModuleElementDefinition> innerMultimap = HashMultimap.create();
         Map<String, AttributeConfigElement> attributes = getSimpleAttributes();
@@ -157,7 +159,7 @@ public class EditConfigTest {
     }
 
     private Map<String, Multimap<String, ModuleElementResolved>> getMapping(EditConfigStrategy editStrat) {
-        Map<String, Multimap<String, ModuleElementResolved>> result = Maps.newHashMap();
+        final Map<String, Multimap<String, ModuleElementResolved>> result = Maps.newHashMap();
 
         Multimap<String, ModuleElementResolved> innerMultimap = HashMultimap.create();
         Map<String, AttributeConfigElement> attributes = getSimpleAttributes();
@@ -178,10 +180,10 @@ public class EditConfigTest {
     }
 
     static Map<String, AttributeConfigElement> getSimpleAttributes() {
-        Map<String, AttributeConfigElement> attributes = Maps.newHashMap();
+        final Map<String, AttributeConfigElement> attributes = Maps.newHashMap();
         AttributeConfigElement ace1 = mock(AttributeConfigElement.class);
         doReturn("abcd").when(ace1).getResolvedDefaultValue();
-        doReturn(Optional.<String> of("abc")).when(ace1).getResolvedValue();
+        doReturn(Optional.<String>of("abc")).when(ace1).getResolvedValue();
         doReturn("mockedAce1").when(ace1).toString();
         doReturn("jmxNameAce1").when(ace1).getJmxName();
         attributes.put("a1", ace1);
index 7cc0288fe871b68d9b99abd3866eade10b3f1eae..12b6bf4d622fe60f8ffae65b32ae1e2220b98d81 100644 (file)
@@ -32,38 +32,38 @@ import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesMod
 import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
 
 public class MergeEditConfigStrategyTest extends AbstractConfigTest {
-    private static final MultipleDependenciesModuleFactory factory = new MultipleDependenciesModuleFactory();
+    private static final MultipleDependenciesModuleFactory FACTORY = new MultipleDependenciesModuleFactory();
+    private static final String FACTORY_NAME = FACTORY.getImplementationName();
     public static final String PARENT = "parent";
     public static final String D1 = "d1";
     public static final String D2 = "d2";
     public static final String D3 = "d3";
 
-    private static final String factoryName = factory.getImplementationName();
-
     @Before
     public void setUp() throws Exception {
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, FACTORY));
 
         ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
-        ObjectName d1 = transaction.createModule(factoryName, D1);
-        ObjectName d2 = transaction.createModule(factoryName, D2);
-        ObjectName parent = transaction.createModule(factoryName, PARENT);
+        ObjectName d1 = transaction.createModule(FACTORY_NAME, D1);
+        ObjectName d2 = transaction.createModule(FACTORY_NAME, D2);
+        ObjectName parent = transaction.createModule(FACTORY_NAME, PARENT);
         MultipleDependenciesModuleMXBean multipleDependenciesModuleMXBean = transaction.newMXBeanProxy(parent,
                 MultipleDependenciesModuleMXBean.class);
         multipleDependenciesModuleMXBean.setTestingDeps(asList(d1, d2));
-        transaction.createModule(factoryName, D3);
+        transaction.createModule(FACTORY_NAME, D3);
         transaction.commit();
     }
 
     @Test
     public void testMergingOfObjectNames() throws Exception {
-        MergeEditConfigStrategy strategy = new MergeEditConfigStrategy();
-        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        final MergeEditConfigStrategy strategy = new MergeEditConfigStrategy();
+        final ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
 
         // add D3
 
         AttributeConfigElement attributeConfigElement = mock(AttributeConfigElement.class);
-        doReturn(Optional.of(new ObjectName[] {createReadOnlyModuleON(factoryName, D3)})).when(attributeConfigElement).getResolvedValue();
+        doReturn(Optional.of(new ObjectName[] {createReadOnlyModuleON(FACTORY_NAME, D3)}))
+                .when(attributeConfigElement).getResolvedValue();
         doReturn("mocked").when(attributeConfigElement).toString();
         String attributeName = MultipleDependenciesModule.testingDepsJmxAttribute.getAttributeName();
         doReturn(attributeName).when(attributeConfigElement).getJmxName();
@@ -71,18 +71,18 @@ public class MergeEditConfigStrategyTest extends AbstractConfigTest {
                 attributeName,
                 attributeConfigElement);
 
-        strategy.executeConfiguration(factoryName, PARENT, configuration, transaction,
+        strategy.executeConfiguration(FACTORY_NAME, PARENT, configuration, transaction,
                 mock(ServiceRegistryWrapper.class));
         transaction.commit();
 
         // parent's attribute should contain d1,d2,d3
         MultipleDependenciesModuleMXBean proxy = configRegistryClient.newMXBeanProxy(
-                createReadOnlyModuleON(factoryName, PARENT),
+                createReadOnlyModuleON(FACTORY_NAME, PARENT),
                 MultipleDependenciesModuleMXBean.class);
         List<ObjectName> testingDeps = proxy.getTestingDeps();
-        List<ObjectName> expected = asList(createReadOnlyModuleON(factoryName, D1),
-                createReadOnlyModuleON(factoryName, D2),
-                createReadOnlyModuleON(factoryName, D3));
+        List<ObjectName> expected = asList(createReadOnlyModuleON(FACTORY_NAME, D1),
+                createReadOnlyModuleON(FACTORY_NAME, D2),
+                createReadOnlyModuleON(FACTORY_NAME, D3));
         assertEquals(expected, testingDeps);
     }
 }
index b8170ec8c41b5038ec2ff5a59aafcc9b05673f1b..145481a1eaf6e5a9ad898435584cd8a6f860b7bb 100644 (file)
             <artifactId>yang-test-util</artifactId>
         </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>
\ No newline at end of file
index d8fd148aadc659475782b904d39a9ba616f073b4..9690ad3e243354ec7294d2c494b417845857186f 100644 (file)
@@ -39,7 +39,7 @@ import org.slf4j.LoggerFactory;
 
 /**
  * Listens for updates on global schema context, transforms context to ietf-yang-library:modules-state and
- * writes this state to operational data store
+ * writes this state to operational data store.
  */
 // TODO Implement also yang-library-change notfication
 public class SchemaServiceToMdsalWriter implements SchemaContextListener, AutoCloseable {
@@ -66,7 +66,7 @@ public class SchemaServiceToMdsalWriter implements SchemaContextListener, AutoCl
     }
 
     /**
-     * Invoke by blueprint
+     * Invoked by blueprint.
      */
     public void start() {
         schemaService.registerSchemaContextListener(this);
@@ -88,25 +88,28 @@ public class SchemaServiceToMdsalWriter implements SchemaContextListener, AutoCl
             }
 
             @Override
-            public void onFailure(final Throwable t) {
-                LOG.warn("Failed to update modules state", t);
+            public void onFailure(final Throwable throwable) {
+                LOG.warn("Failed to update modules state", throwable);
             }
         });
     }
 
     private ModulesState createModuleStateFromModules(final Set<Module> modules) {
         final ModulesStateBuilder modulesStateBuilder = new ModulesStateBuilder();
-        final List<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module> moduleList =
+        final List<org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list
+                .Module> moduleList =
                 Lists.newArrayList();
 
         for (final Module module : modules) {
             moduleList.add(createModuleEntryFromModule(module));
         }
 
-        return modulesStateBuilder.setModule(moduleList).setModuleSetId(String.valueOf(moduleSetId.getAndIncrement())).build();
+        return modulesStateBuilder.setModule(moduleList).setModuleSetId(String.valueOf(moduleSetId.getAndIncrement()))
+                .build();
     }
 
-    private org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module createModuleEntryFromModule(final Module module) {
+    private org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409.module.list.Module
+        createModuleEntryFromModule(final Module module) {
         final ModuleBuilder moduleBuilder = new ModuleBuilder();
 
         // TODO Conformance type is always set to Implement value, but it should it really be like this?
@@ -129,6 +132,6 @@ public class SchemaServiceToMdsalWriter implements SchemaContextListener, AutoCl
             submodulesList.add(subModuleEntryBuilder.build());
         }
 
-        return  new SubmodulesBuilder().setSubmodule(submodulesList).build();
+        return new SubmodulesBuilder().setSubmodule(submodulesList).build();
     }
 }
index 3dd04fc4e09d9addf06ff678ff2080e5de48fc52..5e6457ac8e2d0b7f406b269a63f9483e0381b2e7 100644 (file)
@@ -67,17 +67,18 @@ public class SchemaServiceToMdsalWriterTest {
         when(dataBroker.newWriteOnlyTransaction()).thenReturn(writeTransaction);
         doNothing().when(writeTransaction).put(eq(LogicalDatastoreType.OPERATIONAL), any(), any());
         when(writeTransaction.submit()).thenReturn(Futures.immediateCheckedFuture(null));
-        when(schemaService.registerSchemaContextListener(any())).thenReturn(new ListenerRegistration<SchemaContextListener>() {
-            @Override
-            public void close() {
-
-            }
-
-            @Override
-            public SchemaContextListener getInstance() {
-                return null;
-            }
-        });
+        when(schemaService.registerSchemaContextListener(any())).thenReturn(
+                new ListenerRegistration<SchemaContextListener>() {
+                    @Override
+                    public void close() {
+
+                    }
+
+                    @Override
+                    public SchemaContextListener getInstance() {
+                        return null;
+                    }
+                });
         schemaServiceToMdsalWriter = new SchemaServiceToMdsalWriter(schemaService, dataBroker);
     }
 
@@ -86,7 +87,8 @@ public class SchemaServiceToMdsalWriterTest {
         schemaServiceToMdsalWriter.start();
 
         schemaServiceToMdsalWriter.onGlobalContextUpdated(getSchema());
-        verify(writeTransaction).put(eq(LogicalDatastoreType.OPERATIONAL), eq(MODULES_STATE_INSTANCE_IDENTIFIER), eq(createTestModuleState()));
+        verify(writeTransaction).put(eq(LogicalDatastoreType.OPERATIONAL),
+                eq(MODULES_STATE_INSTANCE_IDENTIFIER), eq(createTestModuleState()));
     }
 
     private SchemaContext getSchema() throws Exception {
@@ -108,7 +110,7 @@ public class SchemaServiceToMdsalWriterTest {
                 .setSubmodules(new SubmodulesBuilder().setSubmodule(Lists.newArrayList(sub)).build())
                 .setConformanceType(Module.ConformanceType.Implement)
                 .build();
-        return  new ModulesStateBuilder().setModuleSetId("0")
+        return new ModulesStateBuilder().setModuleSetId("0")
                 .setModule(Lists.newArrayList(module)).build();
     }
 }
\ No newline at end of file
index 1c88866d07598a7322916cdbd1dfc64208698f58..11f44453c7e2f4c3d53280319dc562f074dde349 100644 (file)
       <artifactId>mockito-configuration</artifactId>
     </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 3f63db448020093892d398d66ae266d24f74b04b..0c444a1fed94154f78f4731b140821412ea43522 100644 (file)
@@ -18,12 +18,14 @@ public final class NetconfClientSessionPreferences extends NetconfSessionPrefere
     private final NetconfMessage startExiMessage;
 
     public NetconfClientSessionPreferences(final NetconfHelloMessage helloMessage,
-                                     final NetconfMessage startExiMessage) {
+                                           final NetconfMessage startExiMessage) {
         super(helloMessage);
         this.startExiMessage = startExiMessage;
     }
 
     /**
+     * Getter for {@code NetconfMessage}.
+     *
      * @return the startExiMessage
      */
     public NetconfMessage getStartExiMessage() {
index 4eb5be39d1e60f21d7acebfb49dcdaf41f5d058d..9e93f8fb26b16a0e45bce19c459c04c134f6618f 100644 (file)
@@ -20,7 +20,7 @@ public class NetconfDeserializerException extends Exception {
         super(message);
     }
 
-    public NetconfDeserializerException(final String message, final Exception e) {
-        super(message, e);
+    public NetconfDeserializerException(final String message, final Exception exception) {
+        super(message, exception);
     }
 }
index 10f1020bde55be5a20d6cc021a5390834d1ad1ed..94735b07249e9a3acad2fcfc50bc713f498c0b19 100644 (file)
@@ -22,27 +22,33 @@ public class NetconfDocumentedException extends DocumentedException {
         super(message);
     }
 
-    public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+    public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+                                      final ErrorSeverity errorSeverity) {
         super(message, errorType, errorTag, errorSeverity);
     }
 
-    public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+    public NetconfDocumentedException(final String message, final ErrorType errorType, final ErrorTag errorTag,
+                                      final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
         super(message, errorType, errorTag, errorSeverity, errorInfo);
     }
 
-    public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
+    public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType,
+                                      final ErrorTag errorTag, final ErrorSeverity errorSeverity) {
         super(message, cause, errorType, errorTag, errorSeverity);
     }
 
-    public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType, final ErrorTag errorTag, final ErrorSeverity errorSeverity, final Map<String, String> errorInfo) {
+    public NetconfDocumentedException(final String message, final Exception cause, final ErrorType errorType,
+                                      final ErrorTag errorTag, final ErrorSeverity errorSeverity,
+                                      final Map<String, String> errorInfo) {
         super(message, cause, errorType, errorTag, errorSeverity, errorInfo);
     }
 
-    public NetconfDocumentedException(DocumentedException e) {
-        super(e.getMessage(), (Exception) e.getCause(), e.getErrorType(), e.getErrorTag(), e.getErrorSeverity(), e.getErrorInfo());
+    public NetconfDocumentedException(DocumentedException exception) {
+        super(exception.getMessage(), (Exception) exception.getCause(), exception.getErrorType(),
+                exception.getErrorTag(), exception.getErrorSeverity(), exception.getErrorInfo());
     }
 
-    public static NetconfDocumentedException fromXMLDocument( Document fromDoc) {
+    public static NetconfDocumentedException fromXMLDocument(Document fromDoc) {
         return new NetconfDocumentedException(DocumentedException.fromXMLDocument(fromDoc));
     }
 }
index 66fcc8723748d982f9c05735e6ca6fe0509dbebc..11b3012a8d86dc181e2bef78683819a1ea97cd52 100644 (file)
@@ -8,18 +8,19 @@
 package org.opendaylight.netconf.api;
 
 /**
- * Session capable of exi communication according to http://tools.ietf.org/html/draft-varga-netconf-exi-capability-02
+ * Session capable of exi communication according to http://tools.ietf.org/html/draft-varga-netconf-exi-capability-02.
  */
 public interface NetconfExiSession {
 
     /**
-     * Start exi communication with parameters included in start-exi message
+     * Start exi communication with parameters included in start-exi message.
+     *
      * @param startExiMessage start exi message
      */
     void startExiCommunication(NetconfMessage startExiMessage);
 
     /**
-     * Stop exi communication, initiated by stop-exi message
+     * Stop exi communication, initiated by stop-exi message.
      */
     void stopExiCommunication();
 }
index 348c273750e596a9e2abfb419f5a06140e274e53..72f9813f03cd1a46537fcf41ae96b6f720c35f00 100644 (file)
@@ -17,8 +17,7 @@ public final class NetconfServerSessionPreferences extends NetconfSessionPrefere
 
     private final long sessionId;
 
-    public NetconfServerSessionPreferences(final NetconfHelloMessage helloMessage,
-                                           long sessionId) {
+    public NetconfServerSessionPreferences(final NetconfHelloMessage helloMessage, long sessionId) {
         super(helloMessage);
         this.sessionId = sessionId;
     }
index 6b6af960f0864dbeb330ee5f03e8b342a3be872b..bfd1dbf0af210457e7baf357dc279aa5ccd8346d 100644 (file)
@@ -10,5 +10,6 @@ package org.opendaylight.netconf.api;
 
 import org.opendaylight.protocol.framework.SessionListener;
 
-public interface NetconfSessionListener<S extends NetconfSession> extends SessionListener<NetconfMessage, S, NetconfTerminationReason> {
+public interface NetconfSessionListener
+        <S extends NetconfSession> extends SessionListener<NetconfMessage, S, NetconfTerminationReason> {
 }
index 26c612840a6b9fba9bbdea7aba22cb4bf4df003f..4360fbfde6c6d8f3c5b54a6a5ad151b42eeb97f7 100644 (file)
@@ -19,6 +19,8 @@ public class NetconfSessionPreferences {
     }
 
     /**
+     * Getter for {@code NetconfHelloMessage}.
+     *
      * @return the helloMessage
      */
     public NetconfHelloMessage getHelloMessage() {
index a1ad34673b71e399ea6699d960480553a1fe9610..34c20e6f4373d434d3281fe9054bd281cc409ee0 100644 (file)
@@ -22,7 +22,8 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 /**
- * NetconfMessage that can carry additional header with session metadata. See {@link NetconfHelloMessageAdditionalHeader}
+ * NetconfMessage that can carry additional header with session metadata.
+ * See {@link NetconfHelloMessageAdditionalHeader}
  */
 public final class NetconfHelloMessage extends NetconfMessage {
 
@@ -30,7 +31,8 @@ public final class NetconfHelloMessage extends NetconfMessage {
 
     private final NetconfHelloMessageAdditionalHeader additionalHeader;
 
-    public NetconfHelloMessage(Document doc, NetconfHelloMessageAdditionalHeader additionalHeader) throws NetconfDocumentedException {
+    public NetconfHelloMessage(Document doc, NetconfHelloMessageAdditionalHeader additionalHeader)
+            throws NetconfDocumentedException {
         super(doc);
         checkHelloMessage(doc);
         this.additionalHeader = additionalHeader;
@@ -41,7 +43,8 @@ public final class NetconfHelloMessage extends NetconfMessage {
     }
 
     public Optional<NetconfHelloMessageAdditionalHeader> getAdditionalHeader() {
-        return additionalHeader== null ? Optional.<NetconfHelloMessageAdditionalHeader>absent() : Optional.of(additionalHeader);
+        return additionalHeader == null ? Optional.<NetconfHelloMessageAdditionalHeader>absent()
+                : Optional.of(additionalHeader);
     }
 
     private static void checkHelloMessage(Document doc) {
@@ -51,7 +54,7 @@ public final class NetconfHelloMessage extends NetconfMessage {
     }
 
     public static NetconfHelloMessage createClientHello(Iterable<String> capabilities,
-                                                        Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) throws NetconfDocumentedException {
+            Optional<NetconfHelloMessageAdditionalHeader> additionalHeaderOptional) throws NetconfDocumentedException {
         Document doc = createHelloMessageDoc(capabilities);
         return additionalHeaderOptional.isPresent() ? new NetconfHelloMessage(doc, additionalHeaderOptional.get())
                 : new NetconfHelloMessage(doc);
@@ -77,7 +80,8 @@ public final class NetconfHelloMessage extends NetconfMessage {
         return doc;
     }
 
-    public static NetconfHelloMessage createServerHello(Set<String> capabilities, long sessionId) throws NetconfDocumentedException {
+    public static NetconfHelloMessage createServerHello(Set<String> capabilities, long sessionId)
+            throws NetconfDocumentedException {
         Document doc = createHelloMessageDoc(capabilities);
         Element sessionIdElement = doc.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
                 XmlNetconfConstants.SESSION_ID);
@@ -95,8 +99,9 @@ public final class NetconfHelloMessage extends NetconfMessage {
         XmlElement element = XmlElement.fromDomElement(document.getDocumentElement());
         try {
             // accept even if hello has no namespace
-            return element.getName().equals(HELLO_TAG) &&
-                    (!element.hasNamespace() || element.getNamespace().equals(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
+            return element.getName().equals(HELLO_TAG)
+                    && (!element.hasNamespace()
+                    || element.getNamespace().equals(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0));
         } catch (DocumentedException e) {
             // Cannot happen, since we check for hasNamespace
             throw new IllegalStateException(e);
index 32557653c0e5913621cac2f6ba7b7c60a05fe328..2dbc49fe83ddee6ada9035a4ff10b70cf514d43d 100644 (file)
@@ -38,7 +38,8 @@ public class NetconfHelloMessageAdditionalHeader {
     private final String transport;
     private final String sessionIdentifier;
 
-    public NetconfHelloMessageAdditionalHeader(String userName, String hostAddress, String port, String transport, String sessionIdentifier) {
+    public NetconfHelloMessageAdditionalHeader(String userName, String hostAddress, String port,
+                                               String transport, String sessionIdentifier) {
         this.userName = userName;
         this.hostAddress = hostAddress;
         this.port = port;
@@ -67,7 +68,7 @@ public class NetconfHelloMessageAdditionalHeader {
     }
 
     /**
-     * Format additional header into a string suitable as a prefix for netconf hello message
+     * Format additional header into a string suitable as a prefix for netconf hello message.
      */
     public String toFormattedString() {
         Preconditions.checkNotNull(userName);
@@ -94,10 +95,11 @@ public class NetconfHelloMessageAdditionalHeader {
     private static final Pattern PATTERN = Pattern
             .compile("\\[(?<username>[^;]+);(?<address>.+)[:/](?<port>[0-9]+);(?<transport>[a-z]+)[^\\]]+\\]");
     private static final Pattern CUSTOM_HEADER_PATTERN = Pattern
-            .compile("\\[(?<username>[^;]+);(?<address>.+)[:/](?<port>[0-9]+);(?<transport>[a-z]+);(?<sessionIdentifier>[a-z]+)[^\\]]+\\]");
+            .compile("\\[(?<username>[^;]+);"
+                    + "(?<address>.+)[:/](?<port>[0-9]+);(?<transport>[a-z]+);(?<sessionIdentifier>[a-z]+)[^\\]]+\\]");
 
     /**
-     * Parse additional header from a formatted string
+     * Parse additional header from a formatted string.
      */
     public static NetconfHelloMessageAdditionalHeader fromString(String additionalHeader) {
         String additionalHeaderTrimmed = additionalHeader.trim();
index e60b71eb1f2dcdd0a7476fc0e20744da55605def..03d1d36e1b77b586e6b707d75f050f6827f29612 100644 (file)
@@ -19,7 +19,9 @@ public interface NetconfMonitoringService {
     Sessions getSessions();
 
     /**
-     * Returns session monitoring service session listener, which is used to notify monitoring service about state of session.
+     * Returns session monitoring service session listener, which is used to notify monitoring service about state of
+     * session.
+     *
      * @return session listener
      */
     SessionListener getSessionListener();
@@ -31,7 +33,9 @@ public interface NetconfMonitoringService {
     Capabilities getCapabilities();
 
     /**
-     * Allows push based capabilities information transfer. After the listener is registered, current state is pushed to the listener.
+     * Allows push based capabilities information transfer. After the listener is registered, current state is pushed
+     * to the listener.
+     *
      * @param listener Monitoring listener
      * @return listener registration
      */
@@ -39,6 +43,7 @@ public interface NetconfMonitoringService {
 
     /**
      * Allows push based sessions information transfer.
+     *
      * @param listener Monitoring listener
      * @return listener registration
      */
@@ -47,13 +52,15 @@ public interface NetconfMonitoringService {
     interface CapabilitiesListener {
 
         /**
-         * Callback used to notify about a change in used capabilities
+         * Callback used to notify about a change in used capabilities.
+         *
          * @param capabilities resulting capabilities
          */
         void onCapabilitiesChanged(Capabilities capabilities);
 
         /**
-         * Callback used to notify about a change in used schemas
+         * Callback used to notify about a change in used schemas.
+         *
          * @param schemas resulting schemas
          */
         void onSchemasChanged(Schemas schemas);
@@ -61,13 +68,15 @@ public interface NetconfMonitoringService {
 
     interface SessionsListener {
         /**
-         * Callback used to notify about netconf session start
+         * Callback used to notify about netconf session start.
+         *
          * @param session started session
          */
         void onSessionStarted(Session session);
 
         /**
-         * Callback used to notify about netconf session end
+         * Callback used to notify about netconf session end.
+         *
          * @param session ended session
          */
         void onSessionEnded(Session session);
@@ -76,6 +85,7 @@ public interface NetconfMonitoringService {
          * Callback used to notify about activity in netconf session, like
          * rpc or notification. It is triggered at regular time interval. Session parameter
          * contains only sessions which state was changed.
+         *
          * @param sessions updated sessions
          */
         void onSessionsUpdated(Collection<Session> sessions);
index bd30c22ea2d395ccfc16e5b242943587d71cc9de..d6c87c3ed82c81c329712fc8a5730cdfa4abc30e 100644 (file)
@@ -20,7 +20,8 @@ public class SessionEvent {
     }
 
     /**
-     * Returns session, where event occurred
+     * Returns session, where event occurred.
+     *
      * @return session
      */
     public NetconfManagementSession getSession() {
@@ -28,7 +29,8 @@ public class SessionEvent {
     }
 
     /**
-     * Returns event type
+     * Returns event type.
+     *
      * @return type
      */
     public Type getType() {
@@ -52,17 +54,17 @@ public class SessionEvent {
     }
 
     /**
-     * Session event type
+     * Session event type.
      */
     public enum Type {
 
         /**
-         * Correct rpc message received
+         * Correct rpc message received.
          */
         IN_RPC_SUCCESS,
 
         /**
-         * Incorrect rpc message received
+         * Incorrect rpc message received.
          */
         IN_RPC_FAIL,
 
@@ -72,7 +74,7 @@ public class SessionEvent {
         OUT_RPC_ERROR,
 
         /**
-         *  Notification message sent
+         * Notification message sent.
          */
         NOTIFICATION
     }
index 74df29cc789b0c977ad4eccd9b3fa910cf4df74e..1bfd3c976da16eb65fd2215569a2b6f3351189d5 100644 (file)
@@ -14,20 +14,23 @@ package org.opendaylight.netconf.api.monitoring;
 public interface SessionListener {
 
     /**
-     * Callback used to notify about netconf session start
+     * Callback used to notify about netconf session start.
+     *
      * @param session started session
      */
     void onSessionUp(NetconfManagementSession session);
 
     /**
-     * Callback used to notify about netconf session end
+     * Callback used to notify about netconf session end.
+     *
      * @param session ended session
      */
     void onSessionDown(NetconfManagementSession session);
 
     /**
      * Callback used to notify about activity in netconf session, like
-     * rpc or notification
+     * rpc or notification.
+     *
      * @param event session event, contains session and type of event
      */
     void onSessionEvent(SessionEvent event);
index 36b1b128eb397bbbcc0c99084d56fef9b22ab4e9..e3ffdd0ae5e213ad7919489d44b50896c261fc99 100644 (file)
@@ -13,7 +13,7 @@ import java.util.Set;
 
 /**
  * These constants mark operation service factories that are auto wired with netconf endpoint
- * for config subsystem
+ * for config subsystem.
  */
 public final class NetconfConstants {
     /*
@@ -25,5 +25,6 @@ public final class NetconfConstants {
     public static final String NETCONF_MONITORING = "ietf-netconf-monitoring";
     public static final String NETCONF_NOTIFICATION = "ietf-netconf-notifications";
 
-    public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR, NETCONF_MONITORING, NETCONF_NOTIFICATION);
+    public static final Set<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
+            NETCONF_MONITORING, NETCONF_NOTIFICATION);
 }
index 33bbef5cd5523cba29567db02e56d5c59b5a7033..955127c938352095ecabf838ef55d74b3937d6ec 100644 (file)
@@ -32,12 +32,16 @@ public final class XmlNetconfConstants {
     public static final String GET = "get";
     public static final String GET_CONFIG = "get-config";
 
-    public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 = XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+    public static final String URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0 =
+            XmlMappingConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
     public static final String URN_IETF_PARAMS_NETCONF_BASE_1_0 = "urn:ietf:params:netconf:base:1.0";
     public static final String URN_IETF_PARAMS_NETCONF_BASE_1_1 = "urn:ietf:params:netconf:base:1.1";
     public static final String URN_IETF_PARAMS_XML_NS_NETCONF_EXI_1_0 = "urn:ietf:params:xml:ns:netconf:exi:1.0";
-    public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0 = "urn:ietf:params:netconf:capability:notification:1.0";
+    public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0 =
+            "urn:ietf:params:netconf:capability:notification:1.0";
 
-    public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0 = "urn:ietf:params:netconf:capability:exi:1.0";
-    public static final String URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING = "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
+    public static final String URN_IETF_PARAMS_NETCONF_CAPABILITY_EXI_1_0 =
+            "urn:ietf:params:netconf:capability:exi:1.0";
+    public static final String URN_IETF_PARAMS_XML_NS_YANG_IETF_NETCONF_MONITORING =
+            "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring";
 }
index 777186b0587ad5473c52d938df89ab49dbf65bee..7876a5cadb67324f05df84255d5f0b1fcd5a639c 100644 (file)
@@ -40,10 +40,10 @@ public class NetconfDocumentedExceptionTest {
     public void setUp() throws Exception {
         final XPathFactory xPathfactory = XPathFactory.newInstance();
         xpath = xPathfactory.newXPath();
-        xpath.setNamespaceContext( new NamespaceContext() {
+        xpath.setNamespaceContext(new NamespaceContext() {
             @Override
             public Iterator<?> getPrefixes(final String namespaceURI) {
-                return Collections.singletonList( "netconf" ).iterator();
+                return Collections.singletonList("netconf").iterator();
             }
 
             @Override
@@ -55,67 +55,67 @@ public class NetconfDocumentedExceptionTest {
             public String getNamespaceURI(final String prefix) {
                 return XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
             }
-        } );
+        });
     }
 
     @Test
     public void testToAndFromXMLDocument() throws XPathExpressionException {
         final String errorMessage = "mock error message";
-        DocumentedException ex = new NetconfDocumentedException( errorMessage, null,
+        DocumentedException ex = new NetconfDocumentedException(errorMessage, null,
                 DocumentedException.ErrorType.PROTOCOL,
                 DocumentedException.ErrorTag.DATA_EXISTS,
                 DocumentedException.ErrorSeverity.WARNING,
-                ImmutableMap.of( "foo", "bar" ) );
+                ImmutableMap.of("foo", "bar"));
 
         final Document doc = ex.toXMLDocument();
-        assertNotNull( "Document is null", doc );
+        assertNotNull("Document is null", doc);
 
         final Node rootNode = doc.getDocumentElement();
 
-        assertEquals( "getNamespaceURI", "urn:ietf:params:xml:ns:netconf:base:1.0", rootNode.getNamespaceURI() );
-        assertEquals( "getLocalName", "rpc-reply", rootNode.getLocalName() );
+        assertEquals("getNamespaceURI", "urn:ietf:params:xml:ns:netconf:base:1.0", rootNode.getNamespaceURI());
+        assertEquals("getLocalName", "rpc-reply", rootNode.getLocalName());
 
         final Node rpcErrorNode = getNode("/netconf:rpc-reply/netconf:rpc-error", rootNode);
-        assertNotNull( "rpc-error not found", rpcErrorNode );
+        assertNotNull("rpc-error not found", rpcErrorNode);
 
         final Node errorTypeNode = getNode("netconf:error-type", rpcErrorNode);
-        assertNotNull( "error-type not found", errorTypeNode );
+        assertNotNull("error-type not found", errorTypeNode);
         assertEquals("error-type", DocumentedException.ErrorType.PROTOCOL.getTypeValue(),
-                      errorTypeNode.getTextContent() );
+                errorTypeNode.getTextContent());
 
         final Node errorTagNode = getNode("netconf:error-tag", rpcErrorNode);
-        assertNotNull( "error-tag not found", errorTagNode );
+        assertNotNull("error-tag not found", errorTagNode);
         assertEquals("error-tag", DocumentedException.ErrorTag.DATA_EXISTS.getTagValue(),
-                      errorTagNode.getTextContent() );
+                errorTagNode.getTextContent());
 
         final Node errorSeverityNode = getNode("netconf:error-severity", rpcErrorNode);
-        assertNotNull( "error-severity not found", errorSeverityNode );
+        assertNotNull("error-severity not found", errorSeverityNode);
         assertEquals("error-severity", DocumentedException.ErrorSeverity.WARNING.getSeverityValue(),
-                      errorSeverityNode.getTextContent() );
+                errorSeverityNode.getTextContent());
 
         final Node errorInfoNode = getNode("netconf:error-info/netconf:foo", rpcErrorNode);
-        assertNotNull( "foo not found", errorInfoNode );
-        assertEquals( "foo", "bar", errorInfoNode.getTextContent() );
+        assertNotNull("foo not found", errorInfoNode);
+        assertEquals("foo", "bar", errorInfoNode.getTextContent());
 
         final Node errorMsgNode = getNode("netconf:error-message", rpcErrorNode);
-        assertNotNull( "error-message not found", errorMsgNode );
-        assertEquals( "error-message", errorMessage, errorMsgNode.getTextContent() );
+        assertNotNull("error-message not found", errorMsgNode);
+        assertEquals("error-message", errorMessage, errorMsgNode.getTextContent());
 
         // Test fromXMLDocument
 
-        ex = DocumentedException.fromXMLDocument( doc );
+        ex = DocumentedException.fromXMLDocument(doc);
 
-        assertNotNull( "NetconfDocumentedException is null", ex );
+        assertNotNull("NetconfDocumentedException is null", ex);
         assertEquals("getErrorSeverity", DocumentedException.ErrorSeverity.WARNING, ex.getErrorSeverity());
         assertEquals("getErrorTag", DocumentedException.ErrorTag.DATA_EXISTS, ex.getErrorTag());
         assertEquals("getErrorType", DocumentedException.ErrorType.PROTOCOL, ex.getErrorType());
-        assertEquals( "getLocalizedMessage", errorMessage, ex.getLocalizedMessage() );
-        assertEquals( "getErrorInfo", ImmutableMap.of( "foo", "bar" ), ex.getErrorInfo() );
+        assertEquals("getLocalizedMessage", errorMessage, ex.getLocalizedMessage());
+        assertEquals("getErrorInfo", ImmutableMap.of("foo", "bar"), ex.getErrorInfo());
     }
 
     @SuppressWarnings("unchecked")
     <T> T getNode(final String xpathExp, final Node node) throws XPathExpressionException {
-        return (T)xpath.compile( xpathExp ).evaluate( node, XPathConstants.NODE );
+        return (T) xpath.compile(xpathExp).evaluate(node, XPathConstants.NODE);
     }
 }
 
index 4e2fbf086ddce48899cdc401eea5719d7f39be0e..b7b2b2db209530dd9c111ecdf6ca67a7cbaf6b8a 100644 (file)
@@ -35,8 +35,8 @@ public class NetconfHelloMessageAdditionalHeaderTest {
 
     @Test
     public void testStaticConstructor() throws Exception {
-        NetconfHelloMessageAdditionalHeader h = NetconfHelloMessageAdditionalHeader.fromString(customHeader);
-        assertEquals(h.toString(), header.toString());
-        assertEquals(h.toFormattedString(), header.toFormattedString());
+        NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(customHeader);
+        assertEquals(header.toString(), this.header.toString());
+        assertEquals(header.toFormattedString(), this.header.toFormattedString());
     }
 }
index 0384808743e7a8745f8b6b2ea738b27f33b0e739..8d5107dc5f65efe7b708208773d7f00d1c312938 100644 (file)
@@ -8,7 +8,6 @@
 
 package org.opendaylight.netconf.api.messages;
 
-
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
@@ -30,7 +29,8 @@ public class NetconfHelloMessageTest {
 
     @Test
     public void testConstructor() throws NetconfDocumentedException {
-        NetconfHelloMessageAdditionalHeader additionalHeader = new NetconfHelloMessageAdditionalHeader("name","host","1","transp","id");
+        NetconfHelloMessageAdditionalHeader additionalHeader = new NetconfHelloMessageAdditionalHeader("name",
+                "host", "1", "transp", "id");
         NetconfHelloMessage message = NetconfHelloMessage.createClientHello(caps, Optional.of(additionalHeader));
         assertTrue(NetconfHelloMessage.isHelloMessage(message));
         assertEquals(Optional.of(additionalHeader), message.getAdditionalHeader());
index 5b7d13865198513a81658c235478080b26d132b1..19bcb1aeddd3569dd87622820301e3286dcb6322 100644 (file)
@@ -90,6 +90,13 @@ and is available at http://www.eclipse.org/legal/epl-v10.html INTERNAL
             </instructions>
           </configuration>
         </plugin>
+        <plugin>
+            <groupId>org.apache.maven.plugins</groupId>
+            <artifactId>maven-checkstyle-plugin</artifactId>
+            <configuration>
+                <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+            </configuration>
+        </plugin>
     </plugins>
   </build>
 </project>
index 78fc0a1d9cb2ed1bd42c18734347f8b4f68bfbb8..f9b8ec5f3558ea76864663a1293a1ad04d6b6400 100644 (file)
@@ -16,7 +16,7 @@ public interface NetconfCommands {
 
     /**
      * Returns a Hashmap with NETCONF ID as outer key and
-     * inner keys representing attributes of a NETCONF device
+     * inner keys representing attributes of a NETCONF device.
      * @return :Hashmap with two keys for all NETCONF devices in topology
      */
     Map<String, Map<String, String>> listDevices();
@@ -40,15 +40,15 @@ public interface NetconfCommands {
     Map<String, Map<String, List<String>>> showDevice(String deviceId);
 
     /**
-     * Add a NETCONF connector
+     * Add a NETCONF connector.
      * @param netconfNode :An instance of {@link NetconfNode} containing
-     * all required information
+     *     all required information
      * @param deviceId :NETCONF node ID
      */
     void connectDevice(NetconfNode netconfNode, String deviceId);
 
     /**
-     * Disconnect a NETCONF connector
+     * Disconnect a NETCONF connector.
      * @param deviceIp :IP address of NETCONF device
      * @param devicePort :Port of NETCONF device
      * @return :Status of disconnect NETCONF connector
@@ -56,14 +56,14 @@ public interface NetconfCommands {
     boolean disconnectDevice(String deviceIp, String devicePort);
 
     /**
-     * Disconnect a NETCONF connector
+     * Disconnect a NETCONF connector.
      * @param deviceId :Node id of NETCONF device
      * @return :Status of disconnect NETCONF connector
      */
     boolean disconnectDevice(String deviceId);
 
     /**
-     * Update the NETCONF device for requested values
+     * Update the NETCONF device for requested values.
      * @param deviceId :NETCONF node ID
      * @param username :Username for NETCONF device
      * @param password :Password for NETCONF device
index 96715193b5a2928e0dc3ecf8acfe38368ff7d22b..e7c9eda71f697b784f3ae4c5c8ab94cd3cca7f54 100644 (file)
@@ -15,10 +15,10 @@ import java.util.regex.Pattern;
 public class NetconfCommandUtils {
 
     private static final Pattern IP_PATTERN = Pattern.compile(
-            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
-                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
-                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
-                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
+            "^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+                    + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+                    + "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
+                    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
 
     public static boolean isPortValid(final String devicePort) {
         if (Strings.isNullOrEmpty(devicePort)) {
@@ -28,7 +28,7 @@ public class NetconfCommandUtils {
         try {
             port = Integer.parseInt(devicePort);
         } catch (NumberFormatException e) {
-          return false;
+            return false;
         }
         return port >= 0 && port <= 65535;
     }
index 7a1ec73f45ec67a99d77a7b04621fe968b98ab7a..874dbc3c1b0db4ffcf8c6e59c295408cc3d769da 100644 (file)
@@ -32,6 +32,7 @@ public class NetconfListDevicesCommand extends AbstractAction {
         return null;
     }
 
+    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
     private void printDevicesList(@Nonnull final Map<String, Map<String, String>> allDevices) {
         final ShellTable table = new ShellTable();
         table.column(NetconfConsoleConstants.NETCONF_ID).alignLeft();
index 46d36dceb53e39a5d078bacafd8aa3a60f7f1caf..a6e76350a02299f8fbca45789d3ae81e5ead71ad 100644 (file)
@@ -84,6 +84,7 @@ public class NetconfShowDeviceCommand extends AbstractAction {
         return null;
     }
 
+    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
     private void printDeviceData(@Nonnull final Map<String, Map<String, List<String>>> devices) {
         final ShellTable table = new ShellTable();
         table.column(NetconfConsoleConstants.NETCONF_ID).alignLeft();
@@ -98,13 +99,15 @@ public class NetconfShowDeviceCommand extends AbstractAction {
                     device.get(NetconfConsoleConstants.NETCONF_IP).get(NetconfConsoleConstants.DEFAULT_INDEX),
                     device.get(NetconfConsoleConstants.NETCONF_PORT).get(NetconfConsoleConstants.DEFAULT_INDEX),
                     device.get(NetconfConsoleConstants.STATUS).get(NetconfConsoleConstants.DEFAULT_INDEX),
-                    device.get(NetconfConsoleConstants.AVAILABLE_CAPABILITIES).get(NetconfConsoleConstants.DEFAULT_INDEX));
+                    device.get(NetconfConsoleConstants.AVAILABLE_CAPABILITIES)
+                            .get(NetconfConsoleConstants.DEFAULT_INDEX));
             formatCapabilities(device, table, NetconfConsoleConstants.AVAILABLE_CAPABILITIES);
         }
         table.print(System.out);
     }
 
-    private void formatCapabilities(final Map<String, List<String>> device, final ShellTable table, final String capabilityName) {
+    private void formatCapabilities(final Map<String, List<String>> device, final ShellTable table,
+                                    final String capabilityName) {
         for (final String availableCapability : device.get(capabilityName)) {
             // First row is already added to table with the first available capability
             // Process rows other than the first to only have remaining available capabilities
index 95f0917dc92e9dc432c997c444a41a0f4cb0823c..810a4389d6a1f72a2e980e2a120dc9e2491200c7 100644 (file)
@@ -57,7 +57,8 @@ public class NetconfCommandsImpl implements NetconfCommands {
 
     @Override
     public Map<String, Map<String, String>> listDevices() {
-        final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
+        final Topology topology = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL,
+                NetconfIidFactory.NETCONF_TOPOLOGY_IID, dataBroker);
         if (topology == null) {
             return new HashMap<>();
         }
@@ -66,7 +67,8 @@ public class NetconfCommandsImpl implements NetconfCommands {
             final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
             final Map<String, String> attributes = new HashMap<>();
             attributes.put(NetconfConsoleConstants.NETCONF_ID, node.getNodeId().getValue());
-            attributes.put(NetconfConsoleConstants.NETCONF_IP, netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
+            attributes.put(NetconfConsoleConstants.NETCONF_IP,
+                    netconfNode.getHost().getIpAddress().getIpv4Address().getValue());
             attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString());
             attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase());
             netconfNodes.put(node.getNodeId().getValue(), attributes);
@@ -89,11 +91,15 @@ public class NetconfCommandsImpl implements NetconfCommands {
                     final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
                     final Map<String, List<String>> attributes = new HashMap<>();
                     attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
-                    attributes.put(NetconfConsoleConstants.NETCONF_IP, ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
-                    attributes.put(NetconfConsoleConstants.NETCONF_PORT, ImmutableList.of(netconfNode.getPort().getValue().toString()));
-                    attributes.put(NetconfConsoleConstants.STATUS, ImmutableList.of(netconfNode.getConnectionStatus().name()));
+                    attributes.put(NetconfConsoleConstants.NETCONF_IP,
+                            ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
+                    attributes.put(NetconfConsoleConstants.NETCONF_PORT,
+                            ImmutableList.of(netconfNode.getPort().getValue().toString()));
+                    attributes.put(NetconfConsoleConstants.STATUS,
+                            ImmutableList.of(netconfNode.getConnectionStatus().name()));
                     attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES,
-                            netconfNode.getAvailableCapabilities().getAvailableCapability().stream().map(AvailableCapability::getCapability).collect(Collectors.toList()));
+                            netconfNode.getAvailableCapabilities().getAvailableCapability().stream()
+                                    .map(AvailableCapability::getCapability).collect(Collectors.toList()));
                     device.put(node.getNodeId().getValue(), attributes);
                 }
             }
@@ -110,11 +116,15 @@ public class NetconfCommandsImpl implements NetconfCommands {
                 final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
                 final Map<String, List<String>> attributes = new HashMap<>();
                 attributes.put(NetconfConsoleConstants.NETCONF_ID, ImmutableList.of(node.getNodeId().getValue()));
-                attributes.put(NetconfConsoleConstants.NETCONF_IP, ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
-                attributes.put(NetconfConsoleConstants.NETCONF_PORT, ImmutableList.of(netconfNode.getPort().getValue().toString()));
-                attributes.put(NetconfConsoleConstants.STATUS, ImmutableList.of(netconfNode.getConnectionStatus().name()));
+                attributes.put(NetconfConsoleConstants.NETCONF_IP,
+                        ImmutableList.of(netconfNode.getHost().getIpAddress().getIpv4Address().getValue()));
+                attributes.put(NetconfConsoleConstants.NETCONF_PORT,
+                        ImmutableList.of(netconfNode.getPort().getValue().toString()));
+                attributes.put(NetconfConsoleConstants.STATUS,
+                        ImmutableList.of(netconfNode.getConnectionStatus().name()));
                 attributes.put(NetconfConsoleConstants.AVAILABLE_CAPABILITIES,
-                        netconfNode.getAvailableCapabilities().getAvailableCapability().stream().map(AvailableCapability::getCapability).collect(Collectors.toList()));
+                        netconfNode.getAvailableCapabilities().getAvailableCapability().stream()
+                                .map(AvailableCapability::getCapability).collect(Collectors.toList()));
                 device.put(node.getNodeId().getValue(), attributes);
             }
         }
@@ -146,9 +156,9 @@ public class NetconfCommandsImpl implements NetconfCommands {
             }
 
             @Override
-            public void onFailure(Throwable t) {
+            public void onFailure(Throwable throwable) {
                 LOG.error("Failed to created NetconfNode={}", netconfNode);
-                throw new RuntimeException(t);
+                throw new RuntimeException(throwable);
             }
         });
     }
@@ -172,28 +182,36 @@ public class NetconfCommandsImpl implements NetconfCommands {
 
     @Override
     public boolean disconnectDevice(final String deviceIp, final String devicePort) {
-        final String netconfNodeId = NetconfConsoleUtils.getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker).getNodeId().getValue();
+        final String netconfNodeId = NetconfConsoleUtils
+                .getNetconfNodeFromIpAndPort(deviceIp, devicePort, dataBroker).getNodeId().getValue();
         return disconnectDevice(netconfNodeId);
     }
 
     @Override
-    public String updateDevice(final String netconfNodeId, String username, String password, Map<String, String> updated) {
-        final Node node = NetconfConsoleUtils.read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.netconfNodeIid(netconfNodeId), dataBroker);
+    public String updateDevice(final String netconfNodeId, String username, String password,
+                               Map<String, String> updated) {
+        final Node node = NetconfConsoleUtils
+                .read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.netconfNodeIid(netconfNodeId), dataBroker);
 
         if (node != null && node.getAugmentation(NetconfNode.class) != null) {
             final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
 
             // Get NETCONF attributes to update if present else get their original values from NetconfNode instance
-            final String deviceIp = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_IP)) ?
-                    netconfNode.getHost().getIpAddress().getIpv4Address().getValue() : updated.get(NetconfConsoleConstants.NETCONF_IP);
-            final String devicePort = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_PORT)) ?
-                    netconfNode.getPort().getValue().toString() : updated.get(NetconfConsoleConstants.NETCONF_PORT);
+            final String deviceIp = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_IP))
+                    ? netconfNode.getHost().getIpAddress().getIpv4Address().getValue()
+                    : updated.get(NetconfConsoleConstants.NETCONF_IP);
+            final String devicePort = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.NETCONF_PORT))
+                    ? netconfNode.getPort().getValue().toString() : updated.get(NetconfConsoleConstants.NETCONF_PORT);
             final Boolean tcpOnly = (updated.get(NetconfConsoleConstants.TCP_ONLY).equals("true")) ? true : false;
-            final Boolean isSchemaless = (updated.get(NetconfConsoleConstants.SCHEMALESS).equals("true")) ? true : false;
-            final String newUsername = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.USERNAME)) ? updated.get(NetconfConsoleConstants.USERNAME) : username;
-            final String newPassword = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.PASSWORD)) ? updated.get(NetconfConsoleConstants.PASSWORD) : password;
-
-            final Credentials credentials = new LoginPasswordBuilder().setPassword(newPassword).setUsername(newUsername).build();
+            final Boolean isSchemaless =
+                    (updated.get(NetconfConsoleConstants.SCHEMALESS).equals("true")) ? true : false;
+            final String newUsername = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.USERNAME))
+                    ? updated.get(NetconfConsoleConstants.USERNAME) : username;
+            final String newPassword = Strings.isNullOrEmpty(updated.get(NetconfConsoleConstants.PASSWORD))
+                    ? updated.get(NetconfConsoleConstants.PASSWORD) : password;
+
+            final Credentials credentials =
+                    new LoginPasswordBuilder().setPassword(newPassword).setUsername(newUsername).build();
             final NetconfNode updatedNetconfNode = new NetconfNodeBuilder()
                     .setHost(new Host(new IpAddress(new Ipv4Address(deviceIp))))
                     .setPort(new PortNumber(Integer.decode(devicePort)))
@@ -209,7 +227,8 @@ public class NetconfCommandsImpl implements NetconfCommands {
                     .build();
 
             final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
-            transaction.put(LogicalDatastoreType.CONFIGURATION, NetconfIidFactory.netconfNodeIid(updatedNode.getNodeId().getValue()), updatedNode);
+            transaction.put(LogicalDatastoreType.CONFIGURATION,
+                    NetconfIidFactory.netconfNodeIid(updatedNode.getNodeId().getValue()), updatedNode);
 
             Futures.addCallback(transaction.submit(), new FutureCallback<Void>() {
 
@@ -219,9 +238,9 @@ public class NetconfCommandsImpl implements NetconfCommands {
                 }
 
                 @Override
-                public void onFailure(Throwable t) {
+                public void onFailure(Throwable throwable) {
                     LOG.error("Failed to updated NetconfNode={}", netconfNode);
-                    throw new RuntimeException(t);
+                    throw new RuntimeException(throwable);
                 }
             });
 
index 1ce147a5c7f0e8716606c6c5a80e7d229f059b1a..0845764f21ce81cf4ee7a3e9ba7b518c5fa9b0a9 100644 (file)
@@ -32,7 +32,7 @@ public class NetconfConsoleUtils {
     }
 
     /**
-     * Returns a list of NETCONF nodes for the IP
+     * Returns a list of NETCONF nodes for the IP.
      * @param deviceIp :IP address of NETCONF device
      * @param db :An instance of the {@link DataBroker}
      * @return :list on NETCONF nodes
@@ -67,28 +67,30 @@ public class NetconfConsoleUtils {
     }
 
     /**
-     * Returns a list with one NETCONF node for the IP and Port
+     * Returns a list with one NETCONF node for the IP and Port.
      * @param deviceIp :IP address of NETCONF device
      * @param devicePort :Port of NETCONF device
      * @param db :An instance of the {@link DataBroker}
      * @return :NETCONF node instance
      */
-    public static Node getNetconfNodeFromIpAndPort(final String deviceIp, final String devicePort, final DataBroker db) {
+    public static Node getNetconfNodeFromIpAndPort(final String deviceIp, final String devicePort,
+                                                   final DataBroker db) {
         final Topology topology = read(LogicalDatastoreType.OPERATIONAL, NetconfIidFactory.NETCONF_TOPOLOGY_IID, db);
         if (isNetconfNodesPresent(topology)) {
             for (Node node : topology.getNode()) {
                 final NetconfNode netconfNode = node.getAugmentation(NetconfNode.class);
                 if (netconfNode != null
                         && netconfNode.getHost().getIpAddress().getIpv4Address().getValue().equals(deviceIp)
-                        && devicePort.equals(netconfNode.getPort().getValue().toString()))
+                        && devicePort.equals(netconfNode.getPort().getValue().toString())) {
                     return node;
+                }
             }
         }
         return null;
     }
 
     /**
-     * Checks if the NETCONF topology contains nodes
+     * Checks if the NETCONF topology contains nodes.
      * @param topology :NETCONF topology instance
      * @return :<code>true</code> if not empty, else, <code>false</code>
      */
@@ -100,7 +102,7 @@ public class NetconfConsoleUtils {
     }
 
     /**
-     * Wait for datastore to populate NETCONF data
+     * Wait for datastore to populate NETCONF data.
      * @param deviceIp :IP address of NETCONF device
      */
     public static void waitForUpdate(final String deviceIp) {
@@ -112,14 +114,14 @@ public class NetconfConsoleUtils {
     }
 
     /**
-     * Blocking read transaction
+     * Blocking read transaction.
      * @param store :DatastoreType
      * @param path :InstanceIdentifier
      * @param db :An instance of the {@link DataBroker}
      * @return :data read from path
      */
-    public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(final LogicalDatastoreType store,
-            final InstanceIdentifier<D> path, final DataBroker db) {
+    public static <D extends org.opendaylight.yangtools.yang.binding.DataObject> D read(
+            final LogicalDatastoreType store, final InstanceIdentifier<D> path, final DataBroker db) {
         D result = null;
         final ReadOnlyTransaction transaction = db.newReadOnlyTransaction();
         Optional<D> optionalData;
index 37631acf6dccf633d83b67d424933fa201f1ba94..8df16c66420cf22ce05c5c7cf5163ddcb6a049de 100644 (file)
@@ -24,7 +24,8 @@ public class NetconfIidFactory {
         throw new IllegalStateException("Instantiating utility class.");
     }
 
-    public static final InstanceIdentifier<Topology> NETCONF_TOPOLOGY_IID = InstanceIdentifier.builder(NetworkTopology.class)
+    public static final InstanceIdentifier<Topology> NETCONF_TOPOLOGY_IID =
+            InstanceIdentifier.builder(NetworkTopology.class)
             .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())))
             .build();
 
index a0a7290d3d28adcb1a1c6dbb75af63b27738d552..c037c33fe5c8d94ce54f02ec060af9abe39b20e1 100644 (file)
@@ -35,7 +35,7 @@ public class NetconfCommandsImplCallsTest {
     private NetconfCommands netconfCommands;
 
     @Before
-    public void setUp(){
+    public void setUp() {
         initMocks(this);
     }
 
@@ -55,7 +55,8 @@ public class NetconfCommandsImplCallsTest {
 
     @Test
     public void testDisconnectDeviceCommand() throws Exception {
-        NetconfDisconnectDeviceCommand netconfDisconnectDeviceCommand = new NetconfDisconnectDeviceCommand(netconfCommands);
+        NetconfDisconnectDeviceCommand netconfDisconnectDeviceCommand =
+                new NetconfDisconnectDeviceCommand(netconfCommands);
         netconfDisconnectDeviceCommand.doExecute();
 
         verify(netconfCommands, times(0)).connectDevice(any(), any());
@@ -120,7 +121,8 @@ public class NetconfCommandsImplCallsTest {
 
         netconfUpdateDeviceCommand.doExecute();
 
-        verify(netconfCommands, times(1)).updateDevice(anyString(), anyString(), anyString(), hashMapArgumentCaptor.capture());
+        verify(netconfCommands, times(1)).updateDevice(anyString(), anyString(), anyString(),
+                hashMapArgumentCaptor.capture());
 
         assertTrue(hashMapArgumentCaptor.getValue().containsKey(NetconfConsoleConstants.NETCONF_IP));
         assertEquals("192.168.1.1", hashMapArgumentCaptor.getValue().get(NetconfConsoleConstants.NETCONF_IP));
index ddff3a6f9f0741b767adea57e24b0f17d2ee3345..e15d3753389285c046c4978a9d69403c00295486 100644 (file)
@@ -104,16 +104,19 @@ public class NetconfCommandsImplTest {
         final ExecutorService listenableFutureExecutor = SpecialExecutors.newBlockingBoundedCachedThreadPool(
                 16, 16, "CommitFutures");
 
-        final ConcurrentDOMDataBroker cDOMDataBroker = new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
+        final ConcurrentDOMDataBroker cDOMDataBroker =
+                new ConcurrentDOMDataBroker(datastores, listenableFutureExecutor);
 
         final ClassPool pool = ClassPool.getDefault();
         final DataObjectSerializerGenerator generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(pool));
         final BindingNormalizedNodeCodecRegistry codecRegistry = new BindingNormalizedNodeCodecRegistry(generator);
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
-        codecRegistry.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
+        codecRegistry
+                .onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, schemaContext));
 
         final GeneratedClassLoadingStrategy loading = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
-        final BindingToNormalizedNodeCodec bindingToNormalized = new BindingToNormalizedNodeCodec(loading, codecRegistry);
+        final BindingToNormalizedNodeCodec bindingToNormalized =
+                new BindingToNormalizedNodeCodec(loading, codecRegistry);
         bindingToNormalized.onGlobalContextUpdated(schemaContext);
         dataBroker = new BindingDOMDataBrokerAdapter(cDOMDataBroker, bindingToNormalized);
 
@@ -154,9 +157,10 @@ public class NetconfCommandsImplTest {
     }
 
     @Test
-    public void testConnectDisconnectDevice() throws InterruptedException, TimeoutException, TransactionCommitFailedException {
-        final NetconfNode netconfNode = new NetconfNodeBuilder().setPort(new PortNumber(7777)).
-                setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
+    public void testConnectDisconnectDevice()
+            throws InterruptedException, TimeoutException, TransactionCommitFailedException {
+        final NetconfNode netconfNode = new NetconfNodeBuilder()
+                .setPort(new PortNumber(7777)).setHost(HostBuilder.getDefaultInstance("10.10.1.1")).build();
 
         createTopology(LogicalDatastoreType.CONFIGURATION);
         netconfCommands.connectDevice(netconfNode, "netconf-ID");
@@ -226,22 +230,23 @@ public class NetconfCommandsImplTest {
         assertEquals(1, nodes.size());
     }
 
-    private void createTopology(LogicalDatastoreType dataStoreType) throws TransactionCommitFailedException, TimeoutException {
+    private void createTopology(LogicalDatastoreType dataStoreType)
+            throws TransactionCommitFailedException, TimeoutException {
         final List<Node> nodes = new ArrayList<>();
         final Node node = getNetconfNode(NODE_ID, IP, PORT, CONN_STATUS, CAP_PREFIX);
         nodes.add(node);
 
-        final Topology topology = new TopologyBuilder().
-                setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))).
-                setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
+        final Topology topology = new TopologyBuilder()
+                .setKey(new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName())))
+                .setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).setNode(nodes).build();
 
         final WriteTransaction writeTransaction = dataBroker.newWriteOnlyTransaction();
         writeTransaction.put(dataStoreType, NetconfIidFactory.NETCONF_TOPOLOGY_IID, topology);
         writeTransaction.submit().checkedGet(2, TimeUnit.SECONDS);
     }
 
-    private Node getNetconfNode(String nodeIdent, String ip, int portNumber, NetconfNodeConnectionStatus.ConnectionStatus cs,
-                                String notificationCapabilityPrefix) {
+    private Node getNetconfNode(String nodeIdent, String ip, int portNumber,
+                                NetconfNodeConnectionStatus.ConnectionStatus cs, String notificationCapabilityPrefix) {
 
         final Host host = HostBuilder.getDefaultInstance(ip);
         final PortNumber port = new PortNumber(portNumber);
@@ -250,10 +255,11 @@ public class NetconfCommandsImplTest {
         avCapList.add(new AvailableCapabilityBuilder()
                 .setCapabilityOrigin(AvailableCapability.CapabilityOrigin.UserDefined)
                 .setCapability(notificationCapabilityPrefix + "_availableCapabilityString1").build());
-        final AvailableCapabilities avCaps = new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
+        final AvailableCapabilities avCaps =
+                new AvailableCapabilitiesBuilder().setAvailableCapability(avCapList).build();
 
-        final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port).
-                setAvailableCapabilities(avCaps).build();
+        final NetconfNode nn = new NetconfNodeBuilder().setConnectionStatus(cs).setHost(host).setPort(port)
+                .setAvailableCapabilities(avCaps).build();
         final NodeId nodeId = new NodeId(nodeIdent);
         final NodeKey nk = new NodeKey(nodeId);
         final NodeBuilder nb = new NodeBuilder();
@@ -324,7 +330,8 @@ public class NetconfCommandsImplTest {
             }
 
             @Override
-            public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
+            public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+                    final SchemaContextListener listener) {
                 listener.onGlobalContextUpdated(getGlobalContext());
                 return new ListenerRegistration<SchemaContextListener>() {
                     @Override
index 76588defc839e889d0c6a4d9ee6869af941354ca..dde977b82aafb32104c5df3990ab6b867625ccff 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 b7b6f2791fc5ae227b9885144bfafcafafb1daf3..7db8db4f09abcae7d37f6f96d3c887c039d18103 100644 (file)
@@ -22,7 +22,8 @@ import org.opendaylight.netconf.impl.util.DeserializerExceptionHandler;
 import org.opendaylight.netconf.nettyutil.AbstractChannelInitializer;
 import org.opendaylight.protocol.framework.AbstractDispatcher;
 
-public class NetconfServerDispatcherImpl extends AbstractDispatcher<NetconfServerSession, NetconfServerSessionListener> implements NetconfServerDispatcher {
+public class NetconfServerDispatcherImpl extends AbstractDispatcher<NetconfServerSession,
+        NetconfServerSessionListener> implements NetconfServerDispatcher {
 
     private final ServerChannelInitializer initializer;
 
@@ -44,7 +45,8 @@ public class NetconfServerDispatcherImpl extends AbstractDispatcher<NetconfServe
 
     @Override
     public ChannelFuture createLocalServer(LocalAddress address) {
-        return super.createServer(address, LocalServerChannel.class, new ChannelPipelineInitializer<LocalChannel, NetconfServerSession>() {
+        return super.createServer(address, LocalServerChannel.class, new ChannelPipelineInitializer<LocalChannel,
+                NetconfServerSession>() {
             @Override
             public void initializeChannel(final LocalChannel ch, final Promise<NetconfServerSession> promise) {
                 initializer.initialize(ch, promise);
index d023be2f0d41a8a751529a762ff170e29d3c3d8f..dc314c05e0fe49a198ce33cce94925faa305af44 100644 (file)
@@ -47,20 +47,26 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public final class NetconfServerSession extends AbstractNetconfSession<NetconfServerSession, NetconfServerSessionListener> implements NetconfManagementSession {
+public final class NetconfServerSession extends AbstractNetconfSession<NetconfServerSession,
+        NetconfServerSessionListener> implements NetconfManagementSession {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSession.class);
-    private static final DateTimeFormatter dateFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
+    private static final String DATE_TIME_PATTERN_STRING = DateAndTime.PATTERN_CONSTANTS.get(0);
+    private static final Pattern DATE_TIME_PATTERN = Pattern.compile(DATE_TIME_PATTERN_STRING);
 
     private final NetconfHelloMessageAdditionalHeader header;
     private final NetconfServerSessionListener sessionListener;
 
     private ZonedDateTime loginTime;
-    private long inRpcSuccess, inRpcFail, outRpcError, outNotification;
+    private long inRpcSuccess;
+    private long inRpcFail;
+    private long outRpcError;
+    private long outNotification;
     private volatile boolean delayedClose;
 
-    public NetconfServerSession(final NetconfServerSessionListener sessionListener, final Channel channel, final long sessionId,
-            final NetconfHelloMessageAdditionalHeader header) {
+    public NetconfServerSession(final NetconfServerSessionListener sessionListener, final Channel channel,
+                                final long sessionId, final NetconfHelloMessageAdditionalHeader header) {
         super(sessionListener, channel, sessionId);
         this.header = header;
         this.sessionListener = sessionListener;
@@ -90,7 +96,7 @@ public final class NetconfServerSession extends AbstractNetconfSession<NetconfSe
             sessionListener.onNotification(this, (NetconfNotification) netconfMessage);
         }
         // delayed close was set, close after the message was sent
-        if(delayedClose) {
+        if (delayedClose) {
             channelFuture.addListener(new ChannelFutureListener() {
                 @Override
                 public void operationComplete(final ChannelFuture future) throws Exception {
@@ -113,9 +119,6 @@ public final class NetconfServerSession extends AbstractNetconfSession<NetconfSe
         outRpcError++;
     }
 
-    private static final String dateTimePatternString = DateAndTime.PATTERN_CONSTANTS.get(0);
-    private static final Pattern dateTimePattern = Pattern.compile(dateTimePatternString);
-
     @Override
     public Session toManagementSession() {
         SessionBuilder builder = new SessionBuilder();
@@ -131,10 +134,11 @@ public final class NetconfServerSession extends AbstractNetconfSession<NetconfSe
         builder.setSourceHost(new Host(address));
 
         Preconditions.checkState(DateAndTime.PATTERN_CONSTANTS.size() == 1);
-        String formattedDateTime = dateFormatter.format(loginTime);
+        String formattedDateTime = DATE_FORMATTER.format(loginTime);
 
-        Matcher matcher = dateTimePattern.matcher(formattedDateTime);
-        Preconditions.checkState(matcher.matches(), "Formatted datetime %s does not match pattern %s", formattedDateTime, dateTimePattern);
+        Matcher matcher = DATE_TIME_PATTERN.matcher(formattedDateTime);
+        Preconditions.checkState(matcher.matches(), "Formatted datetime %s does not match pattern %s",
+                formattedDateTime, DATE_TIME_PATTERN);
         builder.setLoginTime(new DateAndTime(formattedDateTime));
 
         builder.setInBadRpcs(new ZeroBasedCounter32(inRpcFail));
@@ -156,13 +160,13 @@ public final class NetconfServerSession extends AbstractNetconfSession<NetconfSe
     }
 
     private static Class<? extends Transport> getTransportForString(final String transport) {
-        switch(transport) {
-        case "ssh" :
-            return NetconfSsh.class;
-        case "tcp" :
-            return NetconfTcp.class;
-        default:
-            throw new IllegalArgumentException("Unknown transport type " + transport);
+        switch (transport) {
+            case "ssh":
+                return NetconfSsh.class;
+            case "tcp":
+                return NetconfTcp.class;
+            default:
+                throw new IllegalArgumentException("Unknown transport type " + transport);
         }
     }
 
@@ -172,7 +176,8 @@ public final class NetconfServerSession extends AbstractNetconfSession<NetconfSe
     }
 
     @Override
-    protected void addExiHandlers(final ByteToMessageDecoder decoder, final MessageToByteEncoder<NetconfMessage> encoder) {
+    protected void addExiHandlers(final ByteToMessageDecoder decoder,
+                                  final MessageToByteEncoder<NetconfMessage> encoder) {
         replaceMessageDecoder(decoder);
         replaceMessageEncoderAfterNextMessage(encoder);
     }
index b6c8d11a95afaf85da9285b55829ad04adcf8c3a..943edd7365a0b8b0a739d37c74b9d0a64fc8e801 100644 (file)
@@ -8,7 +8,6 @@
 
 package org.opendaylight.netconf.impl;
 
-
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import org.opendaylight.controller.config.util.xml.DocumentedException;
@@ -37,7 +36,8 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
     private final NetconfOperationRouter operationRouter;
     private final AutoCloseable onSessionDownCloseable;
 
-    public NetconfServerSessionListener(final NetconfOperationRouter operationRouter, final NetconfMonitoringService monitoringService,
+    public NetconfServerSessionListener(final NetconfOperationRouter operationRouter,
+                                        final NetconfMonitoringService monitoringService,
                                         final AutoCloseable onSessionDownCloseable) {
         this.operationRouter = operationRouter;
         this.monitoringSessionListener = monitoringService.getSessionListener();
@@ -55,6 +55,7 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
         onDown(netconfNetconfServerSession);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public void onDown(final NetconfServerSession netconfNetconfServerSession) {
         monitoringSessionListener.onSessionDown(netconfNetconfServerSession);
 
@@ -72,12 +73,13 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
 
     @Override
     public void onSessionTerminated(final NetconfServerSession netconfNetconfServerSession,
-            final NetconfTerminationReason netconfTerminationReason) {
+                                    final NetconfTerminationReason netconfTerminationReason) {
         LOG.debug("Session {} terminated, reason: {}", netconfNetconfServerSession,
                 netconfTerminationReason.getErrorMessage());
         onDown(netconfNetconfServerSession);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public void onMessage(final NetconfServerSession session, final NetconfMessage netconfMessage) {
         try {
@@ -96,7 +98,7 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
             monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
             throw new IllegalStateException("Unable to process incoming message " + netconfMessage, e);
         } catch (final DocumentedException e) {
-            LOG.trace("Error occurred while processing message",e);
+            LOG.trace("Error occurred while processing message", e);
             session.onOutgoingRpcError();
             session.onIncommingRpcFail();
             monitoringSessionListener.onSessionEvent(SessionEvent.inRpcFail(session));
@@ -137,7 +139,7 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
             throw new DocumentedException("Unknown tag " + rootNode.getNodeName() + " in message:\n" + netconfMessage,
                     DocumentedException.ErrorType.PROTOCOL, DocumentedException.ErrorTag.UNKNOWN_ELEMENT,
                     DocumentedException.ErrorSeverity.ERROR, ImmutableMap.of("bad-element",
-                            rootNode.getNodeName()));
+                    rootNode.getNodeName()));
         }
     }
 
@@ -145,11 +147,12 @@ public class NetconfServerSessionListener implements NetconfSessionListener<Netc
 
         final NamedNodeMap attributes = rootNode.getAttributes();
 
-        if(attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.MESSAGE_ID)!=null) {
+        if (attributes.getNamedItemNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0,
+                XmlNetconfConstants.MESSAGE_ID) != null) {
             return;
         }
 
-        if(attributes.getNamedItem(XmlNetconfConstants.MESSAGE_ID)!=null) {
+        if (attributes.getNamedItem(XmlNetconfConstants.MESSAGE_ID) != null) {
             return;
         }
 
index e3fd704663afa7a3d591dee80a3b6b2a8bc14aaf..b3e263a92beadc5f17597abc0eb46340556f3ff2 100644 (file)
@@ -26,8 +26,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class NetconfServerSessionNegotiator
-        extends
-        AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession, NetconfServerSessionListener> {
+        extends AbstractNetconfSessionNegotiator<NetconfServerSessionPreferences, NetconfServerSession,
+                NetconfServerSessionListener> {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiator.class);
 
@@ -78,9 +78,10 @@ public class NetconfServerSessionNegotiator
     }
 
     /**
-     * @param socketAddress
-     *            type of socket address LocalAddress, or
-     *            InetSocketAddress, for others returns unknown
+     * Get a name of the host.
+     *
+     * @param socketAddress type of socket address LocalAddress, or
+     *                      InetSocketAddress, for others returns unknown
      * @return Two values - port and host of socket address
      */
     protected static Map.Entry<String, String> getHostName(
index 44e2d4e8145e6a0124271da2af1635d6f94e20da..3d37f8ec13ddeb0401c0e5c82b17956ba6141b1c 100644 (file)
@@ -35,7 +35,8 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.mon
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfHelloMessage, NetconfServerSession, NetconfServerSessionListener> {
+public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorFactory<NetconfHelloMessage,
+        NetconfServerSession, NetconfServerSessionListener> {
 
     public static final Set<String> DEFAULT_BASE_CAPABILITIES = ImmutableSet.of(
             XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
@@ -52,15 +53,18 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
     private static final Logger LOG = LoggerFactory.getLogger(NetconfServerSessionNegotiatorFactory.class);
     private final Set<String> baseCapabilities;
 
-    public NetconfServerSessionNegotiatorFactory(final Timer timer, final NetconfOperationServiceFactory netconfOperationProvider,
+    public NetconfServerSessionNegotiatorFactory(final Timer timer,
+                                                 final NetconfOperationServiceFactory netconfOperationProvider,
                                                  final SessionIdProvider idProvider, final long connectionTimeoutMillis,
-                                                 final NetconfMonitoringService monitoringService, final Set<String> baseCapabilities) {
+                                                 final NetconfMonitoringService monitoringService,
+                                                 final Set<String> baseCapabilities) {
         this.timer = timer;
         this.aggregatedOpService = netconfOperationProvider;
         this.idProvider = idProvider;
         this.connectionTimeoutMillis = connectionTimeoutMillis;
         this.monitoringService = monitoringService;
-        this.baseCapabilities = validateBaseCapabilities(baseCapabilities == null ? DEFAULT_BASE_CAPABILITIES : baseCapabilities);
+        this.baseCapabilities = validateBaseCapabilities(baseCapabilities == null ? DEFAULT_BASE_CAPABILITIES :
+                baseCapabilities);
     }
 
 
@@ -68,7 +72,8 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
         // Check base capabilities to be supported by the server
         final Sets.SetView<String> unknownBaseCaps = Sets.difference(baseCapabilities, DEFAULT_BASE_CAPABILITIES);
         Preconditions.checkArgument(unknownBaseCaps.isEmpty(),
-                "Base capabilities that will be supported by netconf server have to be subset of %s, unknown base capabilities: %s",
+                "Base capabilities that will be supported by netconf server have to be subset of %s, "
+                        + "unknown base capabilities: %s",
                 DEFAULT_BASE_CAPABILITIES, unknownBaseCaps);
 
         final ImmutableSet.Builder<String> b = ImmutableSet.builder();
@@ -79,16 +84,19 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
     }
 
     /**
+     * Get session negotiator.
+     *
      * @param defunctSessionListenerFactory will not be taken into account as session listener factory can
      *                                      only be created after snapshot is opened, thus this method constructs
      *                                      proper session listener factory.
-     * @param channel Underlying channel
-     * @param promise Promise to be notified
+     * @param channel                       Underlying channel
+     * @param promise                       Promise to be notified
      * @return session negotiator
      */
     @Override
-    public SessionNegotiator<NetconfServerSession> getSessionNegotiator(final SessionListenerFactory<NetconfServerSessionListener> defunctSessionListenerFactory,
-                                                                        final Channel channel, final Promise<NetconfServerSession> promise) {
+    public SessionNegotiator<NetconfServerSession> getSessionNegotiator(
+            final SessionListenerFactory<NetconfServerSessionListener> defunctSessionListenerFactory,
+            final Channel channel, final Promise<NetconfServerSession> promise) {
         final long sessionId = idProvider.getNextSessionId();
 
         NetconfServerSessionPreferences proposal;
@@ -103,15 +111,18 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
                 getListener(Long.toString(sessionId), channel.localAddress()), connectionTimeoutMillis);
     }
 
-    private NetconfServerSessionListener getListener(final String netconfSessionIdForReporting, final SocketAddress socketAddress) {
-        final NetconfOperationService service = getOperationServiceForAddress(netconfSessionIdForReporting, socketAddress);
+    private NetconfServerSessionListener getListener(final String netconfSessionIdForReporting,
+                                                     final SocketAddress socketAddress) {
+        final NetconfOperationService service = getOperationServiceForAddress(netconfSessionIdForReporting,
+                socketAddress);
         final NetconfOperationRouter operationRouter =
                 new NetconfOperationRouterImpl(service, monitoringService, netconfSessionIdForReporting);
         return new NetconfServerSessionListener(operationRouter, monitoringService, service);
 
     }
 
-    protected NetconfOperationService getOperationServiceForAddress(final String netconfSessionIdForReporting, final SocketAddress socketAddress) {
+    protected NetconfOperationService getOperationServiceForAddress(final String netconfSessionIdForReporting,
+                                                                    final SocketAddress socketAddress) {
         return this.aggregatedOpService.createService(netconfSessionIdForReporting);
     }
 
@@ -119,8 +130,10 @@ public class NetconfServerSessionNegotiatorFactory implements SessionNegotiatorF
         return aggregatedOpService;
     }
 
-    private NetconfHelloMessage createHelloMessage(final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
-        return NetconfHelloMessage.createServerHello(Sets.union(transformCapabilities(capabilityProvider.getCapabilities()), baseCapabilities), sessionId);
+    private NetconfHelloMessage createHelloMessage(
+            final long sessionId, final NetconfMonitoringService capabilityProvider) throws NetconfDocumentedException {
+        return NetconfHelloMessage.createServerHello(Sets.union(transformCapabilities(capabilityProvider
+                .getCapabilities()), baseCapabilities), sessionId);
     }
 
     public static Set<String> transformCapabilities(final Capabilities capabilities) {
index 1f83e1559e8b7ae255fb24caa84698855e7fe646..a46ed9a4bf373870118a50228f87630a22ebce46 100644 (file)
@@ -35,7 +35,8 @@ public class NetconfServerSessionNegotiatorFactoryBuilder {
         return this;
     }
 
-    public NetconfServerSessionNegotiatorFactoryBuilder setAggregatedOpService(final NetconfOperationServiceFactory aggregatedOpService) {
+    public NetconfServerSessionNegotiatorFactoryBuilder setAggregatedOpService(
+            final NetconfOperationServiceFactory aggregatedOpService) {
         this.aggregatedOpService = aggregatedOpService;
         return this;
     }
@@ -45,7 +46,8 @@ public class NetconfServerSessionNegotiatorFactoryBuilder {
         return this;
     }
 
-    public NetconfServerSessionNegotiatorFactoryBuilder setMonitoringService(final NetconfMonitoringService monitoringService) {
+    public NetconfServerSessionNegotiatorFactoryBuilder setMonitoringService(
+            final NetconfMonitoringService monitoringService) {
         this.monitoringService = monitoringService;
         return this;
     }
@@ -58,7 +60,8 @@ public class NetconfServerSessionNegotiatorFactoryBuilder {
 
     public NetconfServerSessionNegotiatorFactory build() {
         validate();
-        return new NetconfServerSessionNegotiatorFactory(timer, aggregatedOpService, idProvider, connectionTimeoutMillis, monitoringService, baseCapabilities);
+        return new NetconfServerSessionNegotiatorFactory(timer, aggregatedOpService, idProvider,
+                connectionTimeoutMillis, monitoringService, baseCapabilities);
     }
 
 
@@ -69,6 +72,7 @@ public class NetconfServerSessionNegotiatorFactoryBuilder {
         Preconditions.checkArgument(connectionTimeoutMillis > 0, "connection time out <=0");
         Preconditions.checkNotNull(monitoringService, "NetconfMonitoringService not initialized");
 
-        baseCapabilities = (baseCapabilities == null) ? NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES : baseCapabilities;
+        baseCapabilities = (baseCapabilities == null) ? NetconfServerSessionNegotiatorFactory
+                .DEFAULT_BASE_CAPABILITIES : baseCapabilities;
     }
 }
index 78cc99d94368bdeb045c3a7d30b81b97f8be2765..d98f07b069560c3eb4e1394e0d13613f268c9af8 100644 (file)
@@ -43,8 +43,9 @@ public class DefaultCloseSession extends AbstractSingletonNetconfOperation imple
     /**
      * Close netconf operation router associated to this session, which in turn
      * closes NetconfOperationServiceSnapshot with all NetconfOperationService
-     * instances
+     * instances.
      */
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement)
             throws DocumentedException {
@@ -63,7 +64,7 @@ public class DefaultCloseSession extends AbstractSingletonNetconfOperation imple
     }
 
     @Override
-    public void setNetconfSession(final NetconfServerSession s) {
-        this.session = s;
+    public void setNetconfSession(final NetconfServerSession netconfServerSession) {
+        this.session = netconfServerSession;
     }
 }
index c0988fd05fc8343d2cadd087087f9a0419684d60..56b2c11e59f93be439c120086a513c173f2494a3 100644 (file)
@@ -10,5 +10,5 @@ package org.opendaylight.netconf.impl.mapping.operations;
 import org.opendaylight.netconf.impl.NetconfServerSession;
 
 public interface DefaultNetconfOperation {
-    void setNetconfSession(NetconfServerSession s);
+    void setNetconfSession(NetconfServerSession netconfServerSession);
 }
index c204dad8f24e33b4788d67bf1523effc53efe816..db75e6e0f53e18b21fc19024026d5e78ec337e2f 100644 (file)
@@ -51,8 +51,10 @@ public class DefaultStartExi extends AbstractSingletonNetconfOperation implement
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
-        final Element getSchemaResult = document.createElementNS(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement operationElement) throws DocumentedException {
+        final Element getSchemaResult = document.createElementNS(
+                XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
         LOG.trace("{} operation successful", START_EXI);
         return getSchemaResult;
     }
@@ -68,7 +70,7 @@ public class DefaultStartExi extends AbstractSingletonNetconfOperation implement
     }
 
     @Override
-    public void setNetconfSession(final NetconfServerSession s) {
-        netconfSession = s;
+    public void setNetconfSession(final NetconfServerSession netconfServerSession) {
+        netconfSession = netconfServerSession;
     }
 }
index 8f298f836767dfd39d6927ecb10cd4f7659f5706..600f63743d07cd41413d7af727da53bd2ebe9abe 100644 (file)
@@ -31,12 +31,14 @@ public class DefaultStopExi extends AbstractSingletonNetconfOperation implements
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(Document document,
+                                                       XmlElement operationElement) throws DocumentedException {
         LOG.debug("Received stop-exi message {} ", XmlUtil.toString(operationElement));
 
         netconfSession.stopExiCommunication();
 
-        Element getSchemaResult = document.createElementNS( XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
+        Element getSchemaResult = document.createElementNS(
+                XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0, XmlNetconfConstants.OK);
         LOG.trace("{} operation successful", STOP_EXI);
         return getSchemaResult;
     }
@@ -52,7 +54,7 @@ public class DefaultStopExi extends AbstractSingletonNetconfOperation implements
     }
 
     @Override
-    public void setNetconfSession(NetconfServerSession s) {
-        this.netconfSession = s;
+    public void setNetconfSession(NetconfServerSession netconfServerSession) {
+        this.netconfSession = netconfServerSession;
     }
 }
index 140a5d06362d2e901bfff190e44ac060989fc84c..5c292b1f6e5b9f70a7cca773554166c845db1339 100644 (file)
@@ -33,12 +33,14 @@ import org.slf4j.LoggerFactory;
 /**
  * NetconfOperationService aggregator. Makes a collection of operation services accessible as one.
  */
-public class AggregatedNetconfOperationServiceFactory implements NetconfOperationServiceFactory, NetconfOperationServiceFactoryListener, AutoCloseable {
+public class AggregatedNetconfOperationServiceFactory
+        implements NetconfOperationServiceFactory, NetconfOperationServiceFactoryListener, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(AggregatedNetconfOperationServiceFactory.class);
 
     private final Set<NetconfOperationServiceFactory> factories = new ConcurrentSet<>();
-    private final Multimap<NetconfOperationServiceFactory, AutoCloseable> registrations = Multimaps.synchronizedMultimap(HashMultimap.create());
+    private final Multimap<NetconfOperationServiceFactory, AutoCloseable> registrations =
+            Multimaps.synchronizedMultimap(HashMultimap.create());
     private final Set<CapabilityListener> listeners = new ConcurrentSet<>();
 
     public AggregatedNetconfOperationServiceFactory() {
@@ -58,6 +60,7 @@ public class AggregatedNetconfOperationServiceFactory implements NetconfOperatio
         }
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public synchronized void onRemoveNetconfOperationServiceFactory(NetconfOperationServiceFactory service) {
         factories.remove(service);
@@ -125,7 +128,8 @@ public class AggregatedNetconfOperationServiceFactory implements NetconfOperatio
 
         private final Set<NetconfOperationService> services;
 
-        public AggregatedNetconfOperation(final Set<NetconfOperationServiceFactory> factories, final String netconfSessionIdForReporting) {
+        AggregatedNetconfOperation(final Set<NetconfOperationServiceFactory> factories,
+                                   final String netconfSessionIdForReporting) {
             final Builder<NetconfOperationService> b = ImmutableSet.builder();
             for (final NetconfOperationServiceFactory factory : factories) {
                 b.add(factory.createService(netconfSessionIdForReporting));
@@ -142,6 +146,7 @@ public class AggregatedNetconfOperationServiceFactory implements NetconfOperatio
             return operations;
         }
 
+        @SuppressWarnings("checkstyle:IllegalCatch")
         @Override
         public void close() {
             try {
index c31531d052fee92b71120122046c749e209a20dc..489d984a52ae37f28b292dd7e08bea5f8413f24b 100644 (file)
@@ -47,7 +47,8 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
 
     private static final Schema.Location NETCONF_LOCATION = new Schema.Location(Schema.Location.Enumeration.NETCONF);
     private static final List<Schema.Location> NETCONF_LOCATIONS = ImmutableList.of(NETCONF_LOCATION);
-    private static final BasicCapability CANDIDATE_CAPABILITY = new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0");
+    private static final BasicCapability CANDIDATE_CAPABILITY =
+            new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0");
     private static final Function<Capability, Uri> CAPABILITY_TO_URI = new Function<Capability, Uri>() {
         @Override
         public Uri apply(final Capability input) {
@@ -68,6 +69,7 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
         netconfOperationProvider.registerCapabilityListener(this);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     synchronized Schemas getSchemas() {
         try {
             return transformSchemas(netconfOperationProvider.getCapabilities());
@@ -81,8 +83,9 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
     synchronized String getSchemaForModuleRevision(final String moduleName, final Optional<String> revision) {
 
         Map<String, String> revisionMapRequest = mappedModulesToRevisionToSchema.get(moduleName);
-        Preconditions.checkState(revisionMapRequest != null, "Capability for module %s not present, " + ""
-                + "available modules : %s", moduleName, Collections2.transform(capabilities.values(), CAPABILITY_TO_URI));
+        Preconditions.checkState(revisionMapRequest != null,
+                "Capability for module %s not present, available modules : %s",
+                moduleName, Collections2.transform(capabilities.values(), CAPABILITY_TO_URI));
 
         if (revision.isPresent()) {
             String schema = revisionMapRequest.get(revision.get());
@@ -103,7 +106,7 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
 
     private void updateCapabilityToSchemaMap(final Set<Capability> added, final Set<Capability> removed) {
         for (final Capability cap : added) {
-            if (!isValidModuleCapability(cap)){
+            if (!isValidModuleCapability(cap)) {
                 continue;
             }
 
@@ -118,7 +121,7 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
             revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
         }
         for (final Capability cap : removed) {
-            if (!isValidModuleCapability(cap)){
+            if (!isValidModuleCapability(cap)) {
                 continue;
             }
             final Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(cap.getModuleName().get());
@@ -238,9 +241,13 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
 
     private static NetconfCapabilityChange computeDiff(final Set<Capability> added, final Set<Capability> removed) {
         final NetconfCapabilityChangeBuilder netconfCapabilityChangeBuilder = new NetconfCapabilityChangeBuilder();
-        netconfCapabilityChangeBuilder.setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build()).build());
-        netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2.transform(removed, CAPABILITY_TO_URI)));
-        netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2.transform(added, CAPABILITY_TO_URI)));
+        netconfCapabilityChangeBuilder
+                .setChangedBy(new ChangedByBuilder().setServerOrUser(new ServerBuilder().setServer(true).build())
+                        .build());
+        netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(Collections2
+                .transform(removed, CAPABILITY_TO_URI)));
+        netconfCapabilityChangeBuilder.setAddedCapability(Lists.newArrayList(Collections2
+                .transform(added, CAPABILITY_TO_URI)));
         // TODO modified should be computed ... but why ?
         netconfCapabilityChangeBuilder.setModifiedCapability(Collections.<Uri>emptyList());
         return netconfCapabilityChangeBuilder.build();
index 0ae2b92e0620faf5f0f05ba26eaa17e3a278b197..df45459e1efc75c0c85d84da711b1c47dd252a2f 100644 (file)
@@ -44,6 +44,7 @@ public class NetconfImplActivator implements BundleActivator {
 
     private BaseNotificationPublisherRegistration listenerReg;
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public void start(final BundleContext context) {
         try {
@@ -57,58 +58,68 @@ public class NetconfImplActivator implements BundleActivator {
 
             final NetconfMonitoringServiceImpl monitoringService = startMonitoringService(context, factoriesListener);
 
-            NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
-                    .setAggregatedOpService(factoriesListener)
-                    .setTimer(timer)
-                    .setIdProvider(idProvider)
-                    .setMonitoringService(monitoringService)
-                    .setConnectionTimeoutMillis(connectionTimeoutMillis)
-                    .build();
+            NetconfServerSessionNegotiatorFactory serverNegotiatorFactory =
+                    new NetconfServerSessionNegotiatorFactoryBuilder()
+                            .setAggregatedOpService(factoriesListener)
+                            .setTimer(timer)
+                            .setIdProvider(idProvider)
+                            .setMonitoringService(monitoringService)
+                            .setConnectionTimeoutMillis(connectionTimeoutMillis)
+                            .build();
 
             eventLoopGroup = new NioEventLoopGroup();
 
             ServerChannelInitializer serverChannelInitializer = new ServerChannelInitializer(
                     serverNegotiatorFactory);
-            NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, eventLoopGroup, eventLoopGroup);
+            NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer,
+                    eventLoopGroup, eventLoopGroup);
 
             LocalAddress address = NetconfConfiguration.NETCONF_LOCAL_ADDRESS;
             LOG.trace("Starting local netconf server at {}", address);
             dispatch.createLocalServer(address);
 
-            final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector> notificationServiceTracker =
-                    new ServiceTracker<>(context, NetconfNotificationCollector.class, new ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>() {
-                        @Override
-                        public NetconfNotificationCollector addingService(ServiceReference<NetconfNotificationCollector> reference) {
-                            Preconditions.checkState(listenerReg == null, "Notification collector service was already added");
-                            listenerReg = context.getService(reference).registerBaseNotificationPublisher();
-                            monitoringService.setNotificationPublisher(listenerReg);
-                            return null;
-                        }
-
-                        @Override
-                        public void modifiedService(ServiceReference<NetconfNotificationCollector> reference, NetconfNotificationCollector service) {
-
-                        }
-
-                        @Override
-                        public void removedService(ServiceReference<NetconfNotificationCollector> reference, NetconfNotificationCollector service) {
-                            listenerReg.close();
-                            listenerReg = null;
-                            monitoringService.setNotificationPublisher(listenerReg);
-                        }
-                    });
+            final ServiceTracker<NetconfNotificationCollector, NetconfNotificationCollector>
+                    notificationServiceTracker = new ServiceTracker<>(context, NetconfNotificationCollector.class,
+                    new ServiceTrackerCustomizer<NetconfNotificationCollector, NetconfNotificationCollector>() {
+                            @Override
+                            public NetconfNotificationCollector addingService(ServiceReference<
+                                    NetconfNotificationCollector> reference) {
+                                Preconditions.checkState(listenerReg == null,
+                                        "Notification collector service was already added");
+                                listenerReg = context.getService(reference).registerBaseNotificationPublisher();
+                                monitoringService.setNotificationPublisher(listenerReg);
+                                return null;
+                            }
+
+                            @Override
+                            public void modifiedService(ServiceReference<NetconfNotificationCollector> reference,
+                                            NetconfNotificationCollector service) {
+
+                                }
+
+                            @Override
+                            public void removedService(ServiceReference<NetconfNotificationCollector> reference,
+                                           NetconfNotificationCollector service) {
+                                listenerReg.close();
+                                listenerReg = null;
+                                monitoringService.setNotificationPublisher(listenerReg);
+                            }
+                        });
             notificationServiceTracker.open();
         } catch (Exception e) {
             LOG.warn("Unable to start NetconfImplActivator", e);
         }
     }
 
-    private void startOperationServiceFactoryTracker(BundleContext context, NetconfOperationServiceFactoryListener factoriesListener) {
+    private void startOperationServiceFactoryTracker(BundleContext context,
+                                                     NetconfOperationServiceFactoryListener factoriesListener) {
         factoriesTracker = new NetconfOperationServiceFactoryTracker(context, factoriesListener);
         factoriesTracker.open();
     }
 
-    private NetconfMonitoringServiceImpl startMonitoringService(BundleContext context, AggregatedNetconfOperationServiceFactory factoriesListener) {
+    private NetconfMonitoringServiceImpl startMonitoringService(
+            BundleContext context,
+            AggregatedNetconfOperationServiceFactory factoriesListener) {
         NetconfMonitoringServiceImpl netconfMonitoringServiceImpl = new NetconfMonitoringServiceImpl(factoriesListener);
         Dictionary<String, ?> dic = new Hashtable<>();
         regMonitoring = context.registerService(NetconfMonitoringService.class, netconfMonitoringServiceImpl, dic);
index 1e118129242522058a5deedef766136ae0d216ae..b7db507ca577133acf9be0b6728ca0e962a9c61e 100644 (file)
@@ -53,8 +53,10 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         allNetconfOperations = ImmutableSet.copyOf(ops);
     }
 
+    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
-    public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws DocumentedException {
+    public Document onNetconfMessage(final Document message, final NetconfServerSession session) throws
+            DocumentedException {
         Preconditions.checkNotNull(allNetconfOperations, "Operation router was not initialized properly");
 
         final NetconfOperationExecution netconfOperationExecution;
@@ -72,10 +74,10 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
             }
 
             throw new DocumentedException(
-                String.format("Unable to handle rpc %s on session %s", messageAsString, session),
+                    String.format("Unable to handle rpc %s on session %s", messageAsString, session),
                     e, DocumentedException.ErrorType.APPLICATION,
                     tag, DocumentedException.ErrorSeverity.ERROR,
-                Collections.singletonMap(tag.toString(), e.getMessage()));
+                    Collections.singletonMap(tag.toString(), e.getMessage()));
         } catch (final RuntimeException e) {
             throw handleUnexpectedEx("Unexpected exception during netconf operation sort", e);
         }
@@ -92,20 +94,22 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         netconfOperationServiceSnapshot.close();
     }
 
-    private static DocumentedException handleUnexpectedEx(final String s, final Exception e) throws DocumentedException {
-        LOG.error("{}", s, e);
+    private static DocumentedException handleUnexpectedEx(final String message, final Exception exception) throws
+            DocumentedException {
+        LOG.error("{}", message, exception);
         return new DocumentedException("Unexpected error",
                 DocumentedException.ErrorType.APPLICATION,
                 DocumentedException.ErrorTag.OPERATION_FAILED,
                 DocumentedException.ErrorSeverity.ERROR,
-                Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), e.toString()));
+                Collections.singletonMap(DocumentedException.ErrorSeverity.ERROR.toString(), exception.toString()));
     }
 
     private Document executeOperationWithHighestPriority(final Document message,
-            final NetconfOperationExecution netconfOperationExecution)
+                                                         final NetconfOperationExecution netconfOperationExecution)
             throws DocumentedException {
         if (LOG.isDebugEnabled()) {
-            LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution.netconfOperation);
+            LOG.debug("Forwarding netconf message {} to {}", XmlUtil.toString(message), netconfOperationExecution
+                    .netconfOperation);
         }
 
         return netconfOperationExecution.execute(message);
@@ -114,19 +118,20 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
     private NetconfOperationExecution getNetconfOperationWithHighestPriority(
             final Document message, final NetconfServerSession session) throws DocumentedException {
 
-        final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority = getSortedNetconfOperationsWithCanHandle(
+        final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority =
+                getSortedNetconfOperationsWithCanHandle(
                 message, session);
 
         if (sortedByPriority.isEmpty()) {
             throw new IllegalArgumentException(String.format("No %s available to handle message %s",
-                NetconfOperation.class.getName(), XmlUtil.toString(message)));
+                    NetconfOperation.class.getName(), XmlUtil.toString(message)));
         }
 
         return NetconfOperationExecution.createExecutionChain(sortedByPriority, sortedByPriority.lastKey());
     }
 
-    private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(final Document message,
-            final NetconfServerSession session) throws DocumentedException {
+    private TreeMap<HandlingPriority, NetconfOperation> getSortedNetconfOperationsWithCanHandle(
+            final Document message, final NetconfServerSession session) throws DocumentedException {
         final TreeMap<HandlingPriority, NetconfOperation> sortedPriority = Maps.newTreeMap();
 
         for (final NetconfOperation netconfOperation : allNetconfOperations) {
@@ -134,14 +139,15 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
             if (netconfOperation instanceof DefaultNetconfOperation) {
                 ((DefaultNetconfOperation) netconfOperation).setNetconfSession(session);
             }
-            if(netconfOperation instanceof SessionAwareNetconfOperation) {
+            if (netconfOperation instanceof SessionAwareNetconfOperation) {
                 ((SessionAwareNetconfOperation) netconfOperation).setSession(session);
             }
             if (!handlingPriority.equals(HandlingPriority.CANNOT_HANDLE)) {
 
                 Preconditions.checkState(!sortedPriority.containsKey(handlingPriority),
                         "Multiple %s available to handle message %s with priority %s, %s and %s",
-                        NetconfOperation.class.getName(), message, handlingPriority, netconfOperation, sortedPriority.get(handlingPriority));
+                        NetconfOperation.class.getName(), message, handlingPriority, netconfOperation, sortedPriority
+                                .get(handlingPriority));
                 sortedPriority.put(handlingPriority, netconfOperation);
             }
         }
@@ -152,7 +158,8 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         private final NetconfOperation netconfOperation;
         private final NetconfOperationChainedExecution subsequentExecution;
 
-        private NetconfOperationExecution(final NetconfOperation netconfOperation, final NetconfOperationChainedExecution subsequentExecution) {
+        private NetconfOperationExecution(final NetconfOperation netconfOperation,
+                                          final NetconfOperationChainedExecution subsequentExecution) {
             this.netconfOperation = netconfOperation;
             this.subsequentExecution = subsequentExecution;
         }
@@ -168,7 +175,8 @@ public class NetconfOperationRouterImpl implements NetconfOperationRouter {
         }
 
         public static NetconfOperationExecution createExecutionChain(
-                final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority, final HandlingPriority handlingPriority) {
+                final NavigableMap<HandlingPriority, NetconfOperation> sortedByPriority,
+                final HandlingPriority handlingPriority) {
             final NetconfOperation netconfOperation = sortedByPriority.get(handlingPriority);
             final HandlingPriority subsequentHandlingPriority = sortedByPriority.lowerKey(handlingPriority);
 
index 33408e2d8ca65a49da60e74c93eae92b65f3ca71..b1a084424c67ba9192a9607255787cd04f0a0343 100644 (file)
@@ -19,7 +19,7 @@ class NetconfOperationServiceFactoryTracker extends
     private final NetconfOperationServiceFactoryListener factoriesListener;
 
     NetconfOperationServiceFactoryTracker(BundleContext context,
-            final NetconfOperationServiceFactoryListener factoriesListener) {
+                                          final NetconfOperationServiceFactoryListener factoriesListener) {
         super(context, NetconfOperationServiceFactory.class, null);
         this.factoriesListener = factoriesListener;
     }
@@ -38,7 +38,7 @@ class NetconfOperationServiceFactoryTracker extends
 
     @Override
     public void removedService(ServiceReference<NetconfOperationServiceFactory> reference,
-            NetconfOperationServiceFactory netconfOperationServiceFactory) {
+                               NetconfOperationServiceFactory netconfOperationServiceFactory) {
         if (netconfOperationServiceFactory != null) {
             factoriesListener.onRemoveNetconfOperationServiceFactory(netconfOperationServiceFactory);
         }
index 68883fde680b80546bd8fa1a3a2fdaa02e995158..72697ffebf1b69fc076b8ac6ca732afe61d5939b 100644 (file)
@@ -30,7 +30,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * This class implements {@link SessionListener} to receive updates about Netconf sessions. Instance notifies its listeners
+ * This class implements {@link SessionListener} to receive updates about Netconf sessions. Instance notifies its
+ * listeners
  * about session start and end. It also publishes on regular interval list of sessions,
  * where events like rpc or notification happened.
  */
@@ -46,23 +47,28 @@ class NetconfSessionMonitoringService implements SessionListener, AutoCloseable
     private boolean running;
 
     /**
-     * @param schedulingThreadPool thread pool for scheduling session stats updates. If not present, updates won't be scheduled.
-     * @param updateInterval update interval. If is less than 0, updates won't be scheduled
+     * Constructor for {@code NetconfSessionMonitoringService}.
+     *
+     * @param schedulingThreadPool thread pool for scheduling session stats updates. If not present, updates won't be
+     *                             scheduled.
+     * @param updateInterval       update interval. If is less than 0, updates won't be scheduled
      */
     NetconfSessionMonitoringService(Optional<ScheduledThreadPool> schedulingThreadPool, long updateInterval) {
         this.updateInterval = updateInterval;
         if (schedulingThreadPool.isPresent() && updateInterval > 0) {
-            this.executor =  schedulingThreadPool.get().getExecutor();
+            this.executor = schedulingThreadPool.get().getExecutor();
             LOG.info("/netconf-state/sessions will be updated every {} seconds.", updateInterval);
         } else {
-            LOG.info("Scheduling thread pool is present = {}, update interval {}: /netconf-state/sessions won't be updated.",
+            LOG.info("Scheduling thread pool is present = {}, "
+                    + "update interval {}: /netconf-state/sessions won't be updated.",
                     schedulingThreadPool.isPresent(), updateInterval);
             this.executor = null;
         }
     }
 
     synchronized Sessions getSessions() {
-        final Collection<Session> managementSessions = Collections2.transform(sessions, NetconfManagementSession::toManagementSession);
+        final Collection<Session> managementSessions = Collections2.transform(sessions,
+                NetconfManagementSession::toManagementSession);
         return new SessionsBuilder().setSession(ImmutableList.copyOf(managementSessions)).build();
     }
 
index 91d16d06a4eb46ecf6764de34adbc059754679c2..3edd91d3ae57ad909eb55cf1b3c121ce2e8149ce 100644 (file)
@@ -16,8 +16,8 @@ public class AdditionalHeaderParserTest {
 
     @Test
     public void testParsing() throws Exception {
-        String s = "[netconf;10.12.0.102:48528;ssh;;;;;;]";
-        NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s);
+        String message = "[netconf;10.12.0.102:48528;ssh;;;;;;]";
+        NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(message);
         assertEquals("netconf", header.getUserName());
         assertEquals("10.12.0.102", header.getAddress());
         assertEquals("ssh", header.getTransport());
@@ -25,8 +25,8 @@ public class AdditionalHeaderParserTest {
 
     @Test
     public void testParsing2() throws Exception {
-        String s = "[tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]";
-        NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(s);
+        String message = "[tomas;10.0.0.0/10000;tcp;1000;1000;;/home/tomas;;]";
+        NetconfHelloMessageAdditionalHeader header = NetconfHelloMessageAdditionalHeader.fromString(message);
         assertEquals("tomas", header.getUserName());
         assertEquals("10.0.0.0", header.getAddress());
         assertEquals("tcp", header.getTransport());
@@ -34,7 +34,7 @@ public class AdditionalHeaderParserTest {
 
     @Test(expected = IllegalArgumentException.class)
     public void testParsingNoUsername() throws Exception {
-        String s = "[10.12.0.102:48528;ssh;;;;;;]";
-        NetconfHelloMessageAdditionalHeader.fromString(s);
+        String message = "[10.12.0.102:48528;ssh;;;;;;]";
+        NetconfHelloMessageAdditionalHeader.fromString(message);
     }
 }
index 8f35f199cbd9ef624aeb3527d575ef2a333acc1e..c49b3ad9783a92af545b16843500360b12c290a5 100644 (file)
@@ -86,7 +86,7 @@ public class ConcurrentClientsTest {
     private static ExecutorService clientExecutor;
 
     private static final int CONCURRENCY = 32;
-    private static final InetSocketAddress netconfAddress = new InetSocketAddress("127.0.0.1", 8303);
+    private static final InetSocketAddress NETCONF_ADDRESS = new InetSocketAddress("127.0.0.1", 8303);
 
     private int nettyThreads;
     private Class<? extends Runnable> clientRunnable;
@@ -100,14 +100,15 @@ public class ConcurrentClientsTest {
 
     @Parameterized.Parameters()
     public static Collection<Object[]> data() {
-        return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
-                                            {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
-                                            // empty set of capabilities = only base 1.0 netconf capability
-                                            {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
-                                            {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
-                                            {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
-                                            {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
-                                            {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
+        return Arrays.asList(new Object[][]{{4, TestingNetconfClientRunnable.class,
+                NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
+            {1, TestingNetconfClientRunnable.class, NetconfServerSessionNegotiatorFactory.DEFAULT_BASE_CAPABILITIES},
+            // empty set of capabilities = only base 1.0 netconf capability
+            {4, TestingNetconfClientRunnable.class, Collections.emptySet()},
+            {4, TestingNetconfClientRunnable.class, getOnlyExiServerCaps()},
+            {4, TestingNetconfClientRunnable.class, getOnlyChunkServerCaps()},
+            {4, BlockingClientRunnable.class, getOnlyExiServerCaps()},
+            {1, BlockingClientRunnable.class, getOnlyExiServerCaps()},
         });
     }
 
@@ -130,19 +131,20 @@ public class ConcurrentClientsTest {
             }
         }).when(monitoring).registerCapabilitiesListener(any(NetconfMonitoringService.CapabilitiesListener.class));
         doReturn(sessionListener).when(monitoring).getSessionListener();
-        doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring).getCapabilities();
+        doReturn(new CapabilitiesBuilder().setCapability(Collections.<Uri>emptyList()).build()).when(monitoring)
+                .getCapabilities();
         return monitoring;
     }
 
     @BeforeClass
     public static void setUpClientExecutor() {
         clientExecutor = Executors.newFixedThreadPool(CONCURRENCY, new ThreadFactory() {
-            int i = 1;
+            int index = 1;
 
             @Override
-            public Thread newThread(final Runnable r) {
-                Thread thread = new Thread(r);
-                thread.setName("client-" + i++);
+            public Thread newThread(final Runnable runnable) {
+                Thread thread = new Thread(runnable);
+                thread.setName("client-" + index++);
                 thread.setDaemon(true);
                 return thread;
             }
@@ -158,11 +160,13 @@ public class ConcurrentClientsTest {
         AggregatedNetconfOperationServiceFactory factoriesListener = new AggregatedNetconfOperationServiceFactory();
 
         testingNetconfOperation = new TestingNetconfOperation();
-        factoriesListener.onAddNetconfOperationServiceFactory(new TestingOperationServiceFactory(testingNetconfOperation));
+        factoriesListener.onAddNetconfOperationServiceFactory(
+                new TestingOperationServiceFactory(testingNetconfOperation));
 
         SessionIdProvider idProvider = new SessionIdProvider();
 
-        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
+        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new
+                NetconfServerSessionNegotiatorFactoryBuilder()
                 .setTimer(hashedWheelTimer)
                 .setAggregatedOpService(factoriesListener)
                 .setIdProvider(idProvider)
@@ -171,15 +175,17 @@ public class ConcurrentClientsTest {
                 .setBaseCapabilities(serverCaps)
                 .build();
 
-        NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
-        final NetconfServerDispatcherImpl dispatch = new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
+        NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
+                new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
+        final NetconfServerDispatcherImpl dispatch =
+                new NetconfServerDispatcherImpl(serverChannelInitializer, nettyGroup, nettyGroup);
 
-        ChannelFuture s = dispatch.createServer(netconfAddress);
-        s.await();
+        ChannelFuture server = dispatch.createServer(NETCONF_ADDRESS);
+        server.await();
     }
 
     @After
-    public void tearDown(){
+    public void tearDown() {
         hashedWheelTimer.stop();
         try {
             nettyGroup.shutdownGracefully().get();
@@ -235,7 +241,7 @@ public class ConcurrentClientsTest {
     }
 
     /**
-     * Responds to all operations except start-exi and counts all requests
+     * Responds to all operations except start-exi and counts all requests.
      */
     private static class TestingNetconfOperation implements NetconfOperation {
 
@@ -243,13 +249,15 @@ public class ConcurrentClientsTest {
 
         @Override
         public HandlingPriority canHandle(Document message) {
-            return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI) ?
-                    HandlingPriority.CANNOT_HANDLE :
+            return XmlUtil.toString(message).contains(NetconfStartExiMessage.START_EXI)
+                    HandlingPriority.CANNOT_HANDLE :
                     HandlingPriority.HANDLE_WITH_MAX_PRIORITY;
         }
 
+        @SuppressWarnings("checkstyle:IllegalCatch")
         @Override
-        public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
+        public Document handle(Document requestMessage, NetconfOperationChainedExecution subsequentOperation)
+                throws DocumentedException {
             try {
                 LOG.info("Handling netconf message from test {}", XmlUtil.toString(requestMessage));
                 counter.getAndIncrement();
@@ -265,12 +273,12 @@ public class ConcurrentClientsTest {
     }
 
     /**
-     * Hardcoded operation service factory
+     * Hardcoded operation service factory.
      */
     private static class TestingOperationServiceFactory implements NetconfOperationServiceFactory {
         private final NetconfOperation[] operations;
 
-        public TestingOperationServiceFactory(final NetconfOperation... operations) {
+        TestingOperationServiceFactory(final NetconfOperation... operations) {
             this.operations = operations;
         }
 
@@ -281,9 +289,10 @@ public class ConcurrentClientsTest {
 
         @Override
         public AutoCloseable registerCapabilityListener(final CapabilityListener listener) {
-            return new AutoCloseable(){
+            return new AutoCloseable() {
                 @Override
-                public void close() throws Exception {}
+                public void close() throws Exception {
+                }
             };
         }
 
@@ -297,14 +306,16 @@ public class ConcurrentClientsTest {
                 }
 
                 @Override
-                public void close() {}
+                public void close() {
+                }
             };
         }
     }
 
     /**
-     * Pure socket based blocking client
+     * Pure socket based blocking client.
      */
+    @SuppressWarnings("checkstyle:IllegalCatch")
     public final class BlockingClientRunnable implements Runnable {
 
         @Override
@@ -319,9 +330,10 @@ public class ConcurrentClientsTest {
         private void run2() throws Exception {
             InputStream clientHello = checkNotNull(XmlFileLoader
                     .getResourceAsStream("netconfMessages/client_hello.xml"));
-            InputStream getConfig = checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
+            final InputStream getConfig =
+                    checkNotNull(XmlFileLoader.getResourceAsStream("netconfMessages/getConfig.xml"));
 
-            Socket clientSocket = new Socket(netconfAddress.getHostString(), netconfAddress.getPort());
+            Socket clientSocket = new Socket(NETCONF_ADDRESS.getHostString(), NETCONF_ADDRESS.getPort());
             DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
             InputStreamReader inFromServer = new InputStreamReader(clientSocket.getInputStream());
 
@@ -349,15 +361,17 @@ public class ConcurrentClientsTest {
     }
 
     /**
-     * TestingNetconfClient based runnable
+     * TestingNetconfClient based runnable.
      */
     public final class TestingNetconfClientRunnable implements Runnable {
 
+        @SuppressWarnings("checkstyle:IllegalCatch")
         @Override
         public void run() {
             try {
                 final TestingNetconfClient netconfClient =
-                        new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher, getClientConfig());
+                        new TestingNetconfClient(Thread.currentThread().getName(), netconfClientDispatcher,
+                                getClientConfig());
                 long sessionId = netconfClient.getSessionId();
                 LOG.info("Client with session id {}: hello exchanged", sessionId);
 
@@ -379,7 +393,7 @@ public class ConcurrentClientsTest {
 
         private NetconfClientConfiguration getClientConfig() {
             final NetconfClientConfigurationBuilder b = NetconfClientConfigurationBuilder.create();
-            b.withAddress(netconfAddress);
+            b.withAddress(NETCONF_ADDRESS);
             b.withAdditionalHeader(new NetconfHelloMessageAdditionalHeader("uname", "10.10.10.1", "830", "tcp",
                     "client"));
             b.withSessionListener(new SimpleNetconfClientSessionListener());
index 31806f73e52cb215897ea59f0f2075fb46381fc6..2fe0d5173cacce09349663f0505bd28b4edb38cd 100644 (file)
@@ -13,9 +13,9 @@ import org.junit.Test;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.util.test.XmlFileLoader;
 
-public class ExiEncodeDecodeTest  {
+public class ExiEncodeDecodeTest {
     @Test
-    public void encodeExi() throws Exception{
+    public void encodeExi() throws Exception {
 
         String startExiString = XmlFileLoader.xmlFileToString("netconfMessages/startExi.xml");
         assertNotNull(startExiString);
@@ -25,7 +25,8 @@ public class ExiEncodeDecodeTest  {
 
         /*
         ExiParameters exiParams = new ExiParameters();
-        exiParams.setParametersFromXmlElement(XmlElement.fromDomElement(startExiMessage.getDocument().getDocumentElement()));
+        exiParams.setParametersFromXmlElement(XmlElement.fromDomElement(startExiMessage.getDocument()
+        .getDocumentElement()));
         assertNotNull(exiParams);
 
         ByteBuf encodedBuf = Unpooled.buffer();
index 46a5695670da3676ac8434ea53bb428f6361f71d..10ef3cd59752704e51aeda6f331acdf4e1637ebf 100644 (file)
@@ -71,8 +71,8 @@ public class MessageParserTest {
             if (i == chunkCount) {
                 exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1));
                 byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length];
-                recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length,
-                        eom);
+                recievedOutbound
+                        .getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom);
                 assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom);
             }
 
@@ -100,7 +100,8 @@ public class MessageParserTest {
         ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound();
 
         byte[] eom = new byte[NetconfMessageConstants.END_OF_MESSAGE.length];
-        recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length, eom);
+        recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length,
+                eom);
         assertArrayEquals(NetconfMessageConstants.END_OF_MESSAGE, eom);
 
         testChunkChannel.writeInbound(recievedOutbound);
@@ -110,8 +111,8 @@ public class MessageParserTest {
     }
 
     private static long getHeaderLength(byte[] bytes) {
-        byte[] HEADER_START = new byte[] { (byte) 0x0a, (byte) 0x23 };
+        byte[] headerStart = new byte[]{(byte) 0x0a, (byte) 0x23};
         return Long.parseLong(StandardCharsets.US_ASCII.decode(
-                ByteBuffer.wrap(bytes, HEADER_START.length, bytes.length - HEADER_START.length - 1)).toString());
+                ByteBuffer.wrap(bytes, headerStart.length, bytes.length - headerStart.length - 1)).toString());
     }
 }
index ba38938917fcdf2f8ff00c39810ff5305c917202..c24aaf8cd51a2b501650c456bcb3ba6162396094 100644 (file)
@@ -34,15 +34,17 @@ public class NetconfDispatcherImplTest {
         SessionIdProvider idProvider = new SessionIdProvider();
         hashedWheelTimer = new HashedWheelTimer();
 
-        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory = new NetconfServerSessionNegotiatorFactoryBuilder()
-                .setAggregatedOpService(factoriesListener)
-                .setTimer(hashedWheelTimer)
-                .setIdProvider(idProvider)
-                .setMonitoringService(ConcurrentClientsTest.createMockedMonitoringService())
-                .setConnectionTimeoutMillis(5000)
-                .build();
+        NetconfServerSessionNegotiatorFactory serverNegotiatorFactory =
+                new NetconfServerSessionNegotiatorFactoryBuilder()
+                        .setAggregatedOpService(factoriesListener)
+                        .setTimer(hashedWheelTimer)
+                        .setIdProvider(idProvider)
+                        .setMonitoringService(ConcurrentClientsTest.createMockedMonitoringService())
+                        .setConnectionTimeoutMillis(5000)
+                        .build();
 
-        NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer = new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
+        NetconfServerDispatcherImpl.ServerChannelInitializer serverChannelInitializer =
+                new NetconfServerDispatcherImpl.ServerChannelInitializer(serverNegotiatorFactory);
 
         dispatch = new NetconfServerDispatcherImpl(
                 serverChannelInitializer, nettyGroup, nettyGroup);
@@ -57,7 +59,7 @@ public class NetconfDispatcherImplTest {
     @Test
     public void test() throws Exception {
         InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8333);
-        ChannelFuture s = dispatch.createServer(addr);
-        s.get();
+        ChannelFuture server = dispatch.createServer(addr);
+        server.get();
     }
 }
index 4b435e8f7685bcb3db39d8b8b0715262cd62f5f4..37e17659fc39b3115f6213866184dedaeb4952a6 100644 (file)
@@ -91,11 +91,11 @@ public class NetconfServerSessionListenerTest {
 
     @Test
     public void testOnMessage() throws Exception {
-        final Document reply = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" " +
-                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc-reply>");
+        final Document reply = XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\" "
+                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc-reply>");
         doReturn(reply).when(router).onNetconfMessage(any(), any());
-        final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"101\" " +
-                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc>"));
+        final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<rpc message-id=\"101\" "
+                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><example/></rpc>"));
         listener.onMessage(session, msg);
         verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.IN_RPC_SUCCESS)));
         channel.runPendingTasks();
@@ -108,8 +108,8 @@ public class NetconfServerSessionListenerTest {
     public void testOnMessageRuntimeFail() throws Exception {
         doThrow(new RuntimeException("runtime fail")).when(router).onNetconfMessage(any(), any());
         final Document reply =
-                XmlUtil.readXmlToDocument("<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">" +
-                        "<example/></rpc>");
+                XmlUtil.readXmlToDocument("<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">"
+                        "<example/></rpc>");
         final NetconfMessage msg = new NetconfMessage(reply);
         try {
             listener.onMessage(session, msg);
@@ -119,22 +119,23 @@ public class NetconfServerSessionListenerTest {
         }
     }
 
+    @SuppressWarnings("checkstyle:RegexpSinglelineJava")
     @Test
     public void testOnMessageDocumentedFail() throws Exception {
         final Document reply =
-                XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                        "<rpc-error>\n" +
-                        "<error-type>protocol</error-type>\n" +
-                        "<error-tag>unknown-element</error-tag>\n" +
-                        "<error-severity>error</error-severity>\n" +
-                        "<error-message>Unknown tag bad-rpc in message:\n" +
-                        "&lt;bad-rpc/&gt;\n" +
-                        "</error-message>\n" +
-                        "<error-info>\n" +
-                        "<bad-element>bad-rpc</bad-element>\n" +
-                        "</error-info>\n" +
-                        "</rpc-error>\n" +
-                        "</rpc-reply>");
+                XmlUtil.readXmlToDocument("<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                        + "<rpc-error>\n"
+                        + "<error-type>protocol</error-type>\n"
+                        + "<error-tag>unknown-element</error-tag>\n"
+                        + "<error-severity>error</error-severity>\n"
+                        + "<error-message>Unknown tag bad-rpc in message:\n"
+                        + "&lt;bad-rpc/&gt;\n"
+                        + "</error-message>\n"
+                        + "<error-info>\n"
+                        + "<bad-element>bad-rpc</bad-element>\n"
+                        + "</error-info>\n"
+                        + "</rpc-error>\n"
+                        "</rpc-reply>");
         final NetconfMessage msg = new NetconfMessage(XmlUtil.readXmlToDocument("<bad-rpc/>"));
         listener.onMessage(session, msg);
         verify(monitoringListener).onSessionEvent(argThat(sessionEventIs(SessionEvent.Type.IN_RPC_FAIL)));
index d9853b3b9a95d61ace81edeb20cdebd6cca7102c..068ebf6eb4a3a28edb2f9f35254cdd633ec3eb0d 100644 (file)
@@ -57,8 +57,8 @@ public class DefaultCloseSessionTest {
         AutoCloseable res = mock(AutoCloseable.class);
         doNothing().when(res).close();
         DefaultCloseSession close = new DefaultCloseSession("", res);
-        Document doc = XmlUtil.newDocument();
-        XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
+        final Document doc = XmlUtil.newDocument();
+        final XmlElement elem = XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"));
         final Channel channel = mock(Channel.class);
         doReturn("channel").when(channel).toString();
         mockEventLoop(channel);
@@ -77,17 +77,18 @@ public class DefaultCloseSessionTest {
         doReturn(sendFuture).when(channel).writeAndFlush(anyObject());
         doReturn(true).when(sendFuture).isSuccess();
         final NetconfServerSessionListener listener = mock(NetconfServerSessionListener.class);
-        doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
+        doNothing().when(listener).onSessionTerminated(any(NetconfServerSession.class),
+                any(NetconfTerminationReason.class));
         final NetconfServerSession session =
                 new NetconfServerSession(listener, channel, 1L,
                         NetconfHelloMessageAdditionalHeader.fromString("[netconf;10.12.0.102:48528;ssh;;;;;;]"));
         close.setNetconfSession(session);
         close.handleWithNoSubsequentOperations(doc, elem);
         // Fake close response to trigger delayed close
-        session.sendMessage(new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
-                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<ok/>\n" +
-                "</rpc-reply>")));
+        session.sendMessage(new NetconfMessage(XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+                + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<ok/>\n"
+                "</rpc-reply>")));
         verify(channel).close();
         verify(listener).onSessionTerminated(any(NetconfServerSession.class), any(NetconfTerminationReason.class));
     }
index a2662e4b5f806e32dac7ddd54cb4cf33cf6ab4aa..e181cc6227f5334ff264543be6d094fdf67b6e3e 100644 (file)
@@ -28,8 +28,8 @@ import org.w3c.dom.Document;
 public class DefaultStopExiTest {
     @Test
     public void testHandleWithNoSubsequentOperations() throws Exception {
-        DefaultStopExi exi = new DefaultStopExi("");
-        Document doc = XmlUtil.newDocument();
+        final DefaultStopExi exi = new DefaultStopExi("");
+        final Document doc = XmlUtil.newDocument();
         Channel channel = mock(Channel.class);
         doReturn("mockChannel").when(channel).toString();
         ChannelPipeline pipeline = mock(ChannelPipeline.class);
@@ -40,7 +40,8 @@ public class DefaultStopExiTest {
         NetconfServerSession serverSession = new NetconfServerSession(null, channel, 2L, null);
         exi.setNetconfSession(serverSession);
 
-        assertNotNull(exi.handleWithNoSubsequentOperations(doc, XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"))));
+        assertNotNull(exi.handleWithNoSubsequentOperations(doc,
+                XmlElement.fromDomElement(XmlUtil.readXmlToElement("<elem/>"))));
         verify(pipeline, times(1)).replace(anyString(), anyString(), any(ChannelHandler.class));
     }
 }
index f71cac6233cccd62ffbfd7e5d0a7636cdef5138b..7acef9165feb986171294676aadf05884490f1da 100644 (file)
@@ -53,7 +53,7 @@ public class NetconfCapabilityMonitoringServiceTest {
     private static final String TEST_MODULE_CONTENT2 = "content2";
     private static final String TEST_MODULE_REV = "1970-01-01";
     private static final String TEST_MODULE_REV2 = "1970-01-02";
-    private static final  Uri TEST_MODULE_NAMESPACE = new Uri("testModuleNamespace");
+    private static final Uri TEST_MODULE_NAMESPACE = new Uri("testModuleNamespace");
     private static final String TEST_MODULE_NAME = "testModule";
     private static Date TEST_MODULE_DATE;
     private static Date TEST_MODULE_DATE2;
@@ -67,7 +67,7 @@ public class NetconfCapabilityMonitoringServiceTest {
             .build();
     private int capabilitiesSize;
 
-    private final Set<Capability> CAPABILITIES = new HashSet<>();
+    private final Set<Capability> capabilities = new HashSet<>();
 
     @Mock
     private Module moduleMock;
@@ -87,7 +87,7 @@ public class NetconfCapabilityMonitoringServiceTest {
     @BeforeClass
     public static void suiteSetUp() throws Exception {
         TEST_MODULE_DATE = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV);
-        TEST_MODULE_DATE2= SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV2);
+        TEST_MODULE_DATE2 = SimpleDateFormatUtil.getRevisionFormat().parse(TEST_MODULE_REV2);
     }
 
     @Before
@@ -99,19 +99,21 @@ public class NetconfCapabilityMonitoringServiceTest {
         doReturn(TEST_MODULE_DATE).when(moduleMock).getRevision();
         moduleCapability1 = new YangModuleCapability(moduleMock, TEST_MODULE_CONTENT);
 
-        CAPABILITIES.add(moduleCapability1);
+        capabilities.add(moduleCapability1);
 
         doReturn(new URI(TEST_MODULE_NAMESPACE.getValue())).when(moduleMock2).getNamespace();
         doReturn(TEST_MODULE_NAME).when(moduleMock2).getName();
         doReturn(TEST_MODULE_DATE2).when(moduleMock2).getRevision();
         moduleCapability2 = new YangModuleCapability(moduleMock2, TEST_MODULE_CONTENT2);
 
-        CAPABILITIES.add(new BasicCapability("urn:ietf:params:netconf:base:1.0"));
-        CAPABILITIES.add(new BasicCapability("urn:ietf:params:netconf:base:1.1"));
-        CAPABILITIES.add(new BasicCapability("urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&amp;revision=2010-09-24"));
+        capabilities.add(new BasicCapability("urn:ietf:params:netconf:base:1.0"));
+        capabilities.add(new BasicCapability("urn:ietf:params:netconf:base:1.1"));
+        capabilities.add(new BasicCapability("urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&amp;"
+                + "revision=2010-09-24"));
 
-        doReturn(CAPABILITIES).when(operationServiceFactoryMock).getCapabilities();
-        doReturn(null).when(operationServiceFactoryMock).registerCapabilityListener(any(NetconfCapabilityMonitoringService.class));
+        doReturn(capabilities).when(operationServiceFactoryMock).getCapabilities();
+        doReturn(null).when(operationServiceFactoryMock)
+                .registerCapabilityListener(any(NetconfCapabilityMonitoringService.class));
 
         doReturn(SESSION).when(sessionMock).toManagementSession();
         doNothing().when(listener).onCapabilitiesChanged(any());
@@ -122,7 +124,7 @@ public class NetconfCapabilityMonitoringServiceTest {
         doNothing().when(notificationPublisher).onSessionEnded(any());
 
         monitoringService = new NetconfCapabilityMonitoringService(operationServiceFactoryMock);
-        monitoringService.onCapabilitiesChanged(CAPABILITIES, Collections.emptySet());
+        monitoringService.onCapabilitiesChanged(capabilities, Collections.emptySet());
         monitoringService.setNotificationPublisher(notificationPublisher);
         monitoringService.registerListener(listener);
         capabilitiesSize = monitoringService.getCapabilities().getCapability().size();
@@ -151,9 +153,11 @@ public class NetconfCapabilityMonitoringServiceTest {
     public void testGetSchemaForCapability() throws Exception {
         //test multiple revisions of the same capability
         monitoringService.onCapabilitiesChanged(Collections.singleton(moduleCapability2), Collections.emptySet());
-        final String schema = monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV));
+        final String schema =
+                monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV));
         Assert.assertEquals(TEST_MODULE_CONTENT, schema);
-        final String schema2 = monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV2));
+        final String schema2 =
+                monitoringService.getSchemaForModuleRevision(TEST_MODULE_NAME, Optional.of(TEST_MODULE_REV2));
         Assert.assertEquals(TEST_MODULE_CONTENT2, schema2);
         //remove one revision
         monitoringService.onCapabilitiesChanged(Collections.emptySet(), Collections.singleton(moduleCapability1));
@@ -166,7 +170,7 @@ public class NetconfCapabilityMonitoringServiceTest {
     public void testGetCapabilities() throws Exception {
         Capabilities actual = monitoringService.getCapabilities();
         List<Uri> exp = new ArrayList<>();
-        for (Capability capability : CAPABILITIES) {
+        for (Capability capability : capabilities) {
             exp.add(new Uri(capability.getCapabilityUri()));
         }
         //candidate is added by monitoring service automatically
@@ -188,7 +192,8 @@ public class NetconfCapabilityMonitoringServiceTest {
         final Uri uri = new Uri(capUri);
         final HashSet<Capability> testCaps = new HashSet<>();
         testCaps.add(new BasicCapability(capUri));
-        final ArgumentCaptor<NetconfCapabilityChange> capabilityChangeCaptor = ArgumentCaptor.forClass(NetconfCapabilityChange.class);
+        final ArgumentCaptor<NetconfCapabilityChange> capabilityChangeCaptor =
+                ArgumentCaptor.forClass(NetconfCapabilityChange.class);
         final ArgumentCaptor<Capabilities> monitoringListenerCaptor = ArgumentCaptor.forClass(Capabilities.class);
         //add capability
         monitoringService.onCapabilitiesChanged(testCaps, Collections.emptySet());
index 156c4d7ba9507e44d16c42dc03dfaf80f4b95ca9..5f8c6d2aa46f858c39d21e330b298b2d9adc8ea2 100644 (file)
@@ -47,7 +47,8 @@ public class NetconfImplActivatorTest {
         doReturn(refs).when(bundle).getServiceReferences(anyString(), anyString());
         doReturn(Arrays.asList(refs)).when(bundle).getServiceReferences(any(Class.class), anyString());
         doReturn("").when(bundle).getProperty(anyString());
-        doReturn(registration).when(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
+        doReturn(registration).when(bundle).registerService(any(Class.class),
+                any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
         doNothing().when(registration).unregister();
         doNothing().when(bundle).removeServiceListener(any(ServiceListener.class));
     }
@@ -56,7 +57,8 @@ public class NetconfImplActivatorTest {
     public void testStart() throws Exception {
         NetconfImplActivator activator = new NetconfImplActivator();
         activator.start(bundle);
-        verify(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class), any(Dictionary.class));
+        verify(bundle).registerService(any(Class.class), any(AggregatedNetconfOperationServiceFactory.class),
+                any(Dictionary.class));
         activator.stop(bundle);
     }
 }
index 03a74dccdb32b591c43b2c2a5a6b4d15e901d8e7..1736c72f9371e16a6db516afc7b8ceb9dd69c13a 100644 (file)
@@ -34,7 +34,8 @@ import org.xml.sax.SAXException;
 
 public class NetconfOperationRouterImplTest {
 
-    private static final String TEST_RPC = "<rpc message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><test/></rpc>\n";
+    private static final String TEST_RPC = "<rpc message-id=\"101\" "
+            + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"><test/></rpc>\n";
     private static final String MAX_PRIORITY_REPLY = "<high/>";
     private static final String DEFAULT_PRIORITY_REPLY = "<default/>";
 
@@ -62,10 +63,12 @@ public class NetconfOperationRouterImplTest {
         MockitoAnnotations.initMocks(this);
 
         doReturn(HandlingPriority.HANDLE_WITH_MAX_PRIORITY).when(maxPrioMock).canHandle(any(Document.class));
-        doReturn(XmlUtil.readXmlToDocument(MAX_PRIORITY_REPLY)).when(maxPrioMock).handle(any(Document.class), any(NetconfOperationChainedExecution.class));
+        doReturn(XmlUtil.readXmlToDocument(MAX_PRIORITY_REPLY)).when(maxPrioMock).handle(any(Document.class),
+                any(NetconfOperationChainedExecution.class));
 
         doReturn(HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY).when(defaultPrioMock).canHandle(any(Document.class));
-        doReturn(XmlUtil.readXmlToDocument(DEFAULT_PRIORITY_REPLY)).when(defaultPrioMock).handle(any(Document.class), any(NetconfOperationChainedExecution.class));
+        doReturn(XmlUtil.readXmlToDocument(DEFAULT_PRIORITY_REPLY)).when(defaultPrioMock).handle(any(Document.class),
+                any(NetconfOperationChainedExecution.class));
 
         final Set<NetconfOperation> operations = new HashSet<>();
         operations.add(maxPrioMock);
@@ -80,8 +83,10 @@ public class NetconfOperationRouterImplTest {
 
     @Test
     public void testOnNetconfMessage() throws Exception {
-        final ArgumentCaptor<NetconfOperationChainedExecution> highPriorityChainEx = ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
-        final ArgumentCaptor<NetconfOperationChainedExecution> defaultPriorityChainEx = ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
+        final ArgumentCaptor<NetconfOperationChainedExecution> highPriorityChainEx =
+                ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
+        final ArgumentCaptor<NetconfOperationChainedExecution> defaultPriorityChainEx =
+                ArgumentCaptor.forClass(NetconfOperationChainedExecution.class);
 
         final Document document = operationRouter.onNetconfMessage(TEST_RPC_DOC, null);
 
@@ -103,7 +108,7 @@ public class NetconfOperationRouterImplTest {
 
     @Test
     public void testOnNetconfMessageFail() throws Exception {
-        try{
+        try {
             emptyOperationRouter.onNetconfMessage(TEST_RPC_DOC, null);
             Assert.fail("Exception expected");
         } catch (final DocumentedException e) {
index 59fb664dab09ca675402c747ac7e91bd482a2811..967dfe6f98f9192e60d12888d018af6a43ca0dad 100644 (file)
             <artifactId>slf4j-api</artifactId>
         </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 c95e3ba7114eba5f382ff95b9b4e4a901987ad29..ea5e3b623a9db5afe7341608a623aa44c54c0507 100644 (file)
@@ -21,17 +21,17 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.not
 public interface BaseNetconfNotificationListener {
 
     /**
-     * Callback used to notify about a change in used capabilities
+     * Callback used to notify about a change in used capabilities.
      */
-    void onCapabilityChanged(final NetconfCapabilityChange capabilityChange);
+    void onCapabilityChanged(NetconfCapabilityChange capabilityChange);
 
     /**
-     * Callback used to notify about netconf session start
+     * Callback used to notify about netconf session start.
      */
     void onSessionStarted(NetconfSessionStart start);
 
     /**
-     * Callback used to notify about netconf session end
+     * Callback used to notify about netconf session end.
      */
     void onSessionEnded(NetconfSessionEnd end);
 
index 9d053242bf702193e4735c79d4bb8d7f463ab0d6..799672596044d5dc1b3cd7ff39db6777739e2ade 100644 (file)
@@ -9,8 +9,10 @@
 package org.opendaylight.netconf.notifications;
 
 /**
- * Registration for base notification publisher. This registration allows for publishing of base netconf notifications using generated classes
+ * Registration for base notification publisher.
+ * This registration allows for publishing of base netconf notifications using generated classes
  */
-public interface BaseNotificationPublisherRegistration extends NotificationRegistration, BaseNetconfNotificationListener {
+public interface BaseNotificationPublisherRegistration
+        extends NotificationRegistration, BaseNetconfNotificationListener {
 
 }
index 67b4069ac8b27fa7aee6000688fb507445eac0e0..3e7f562434770fe89cb0912e2d76b9c1b92c8836 100644 (file)
@@ -85,7 +85,8 @@ public final class NetconfNotification extends NetconfMessage {
                 while (reminderBuilder.charAt(reminderBuilder.length() - 1) == '0') {
                     reminderBuilder.deleteCharAt(reminderBuilder.length() - 1);
                 }
-                LOG.warn("Fraction of second is cut to three digits. Value that was cut {}", reminderBuilder.toString());
+                LOG.warn("Fraction of second is cut to three digits. Value that was cut {}",
+                        reminderBuilder.toString());
             }
 
             return Date.from(Instant.from(localDateTime));
@@ -104,8 +105,8 @@ public final class NetconfNotification extends NetconfMessage {
      * conversion is applied, replacing the second-of-minute of 60 with 59.
      *
      * @param time {@link String} representation of a time
-     * @return {@code null} if time isn't ISO compliant or if the time doesn't have a leap second
-     * else a {@link Date} as per as the RFC3339_DATE_PARSER.
+     *     @return {@code null} if time isn't ISO compliant or if the time doesn't have a leap second
+     *     else a {@link Date} as per as the RFC3339_DATE_PARSER.
      */
     private static Date handlePotentialLeapSecond(final String time) {
         // Parse the string from offset 0, so we get the whole value.
@@ -127,7 +128,8 @@ public final class NetconfNotification extends NetconfMessage {
             return null;
         }
 
-        LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}", time);
+        LOG.trace("Received time contains leap second, adjusting by replacing the second-of-minute of 60 with 59 {}",
+                time);
 
         // Applying simple conversion replacing the second-of-minute of 60 with 59.
 
@@ -147,10 +149,12 @@ public final class NetconfNotification extends NetconfMessage {
     }
 
     /**
+     * Get value asociated with {@code ChronoField}.
+     *
      * @param accessor The {@link TemporalAccessor}
      * @param field The {@link ChronoField} to get
      * @return the value associated with the {@link ChronoField} for the given {@link TemporalAccessor} if present,
-     * else 0.
+     *     else 0.
      */
     private static int getFieldFromTemporalAccessor(final TemporalAccessor accessor, final ChronoField field) {
         return accessor.isSupported(field) ? (int) accessor.getLong(field) : 0;
@@ -159,21 +163,21 @@ public final class NetconfNotification extends NetconfMessage {
     public static final String EVENT_TIME = "eventTime";
 
     /**
-     * Used for unknown/un-parse-able event-times
+     * Used for unknown/un-parse-able event-times.
      */
     public static final Date UNKNOWN_EVENT_TIME = new Date(0);
 
     private final Date eventTime;
 
     /**
-     * Create new notification and capture the timestamp in the constructor
+     * Create new notification and capture the timestamp in the constructor.
      */
     public NetconfNotification(final Document notificationContent) {
         this(notificationContent, new Date());
     }
 
     /**
-     * Create new notification with provided timestamp
+     * Create new notification with provided timestamp.
      */
     public NetconfNotification(final Document notificationContent, final Date eventTime) {
         super(wrapNotification(notificationContent, eventTime));
@@ -181,6 +185,8 @@ public final class NetconfNotification extends NetconfMessage {
     }
 
     /**
+     * Get the time of the event.
+     *
      * @return notification event time
      */
     public Date getEventTime() {
index 034e48a5e160cfa9020cd2f9721442977b1622be..34a80b391c7dd71ad4567886ec131e0119b48e3c 100644 (file)
@@ -17,8 +17,9 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.r
 public interface NetconfNotificationCollector {
 
     /**
-     * Add notification publisher for a particular stream
+     * Add notification publisher for a particular stream.
      *
+     * <p>
      * Implementations should allow for multiple publishers of a single stream
      * and its up to implementations to decide how to merge metadata (e.g. description)
      * for the same stream when providing information about available stream
@@ -27,7 +28,7 @@ public interface NetconfNotificationCollector {
     NotificationPublisherRegistration registerNotificationPublisher(Stream stream);
 
     /**
-     * Register base notification publisher
+     * Register base notification publisher.
      */
     BaseNotificationPublisherRegistration registerBaseNotificationPublisher();
 
@@ -35,22 +36,23 @@ public interface NetconfNotificationCollector {
      * Users of the registry have an option to get notification each time new notification stream gets registered
      * This allows for a push model in addition to pull model for retrieving information about available streams.
      *
+     * <p>
      * The listener should receive callbacks for each stream available prior to the registration when its registered
      */
     NotificationRegistration registerStreamListener(NetconfNotificationStreamListener listener);
 
     /**
-     * Simple listener that receives notifications about changes in stream availability
+     * Simple listener that receives notifications about changes in stream availability.
      */
     public interface NetconfNotificationStreamListener {
 
         /**
-         * Stream becomes available in the collector (first publisher is registered)
+         * Stream becomes available in the collector (first publisher is registered).
          */
         void onStreamRegistered(Stream stream);
 
         /**
-         * Stream is not available anymore in the collector (last publisher is unregistered)
+         * Stream is not available anymore in the collector (last publisher is unregistered).
          */
         void onStreamUnregistered(StreamNameType stream);
     }
index 48ba9da2b0127fe0d22d1174f93b8a76539736ca..3a839233defc1c9024e9662bc65b90e367768a3f 100644 (file)
@@ -11,12 +11,12 @@ package org.opendaylight.netconf.notifications;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
 
 /**
- * Generic listener for netconf notifications
+ * Generic listener for netconf notifications.
  */
 public interface NetconfNotificationListener {
 
     /**
-     * Callback used to notify the listener about any new notification
+     * Callback used to notify the listener about any new notification.
      */
     void onNotification(StreamNameType stream, NetconfNotification notification);
 
index 2b28f7f751c228af1b8a3948ab898fe4ef7143fa..c1167ea25f4085ffb5e9fecd40e03533ca1eb1eb 100644 (file)
@@ -11,23 +11,21 @@ package org.opendaylight.netconf.notifications;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714.StreamNameType;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netmod.notification.rev080714.netconf.Streams;
 
-/**
- *
- */
 public interface NetconfNotificationRegistry {
 
     /**
-     * Add listener for a certain notification type
+     * Add listener for a certain notification type.
      */
-    NotificationListenerRegistration registerNotificationListener(StreamNameType stream, NetconfNotificationListener listener);
+    NotificationListenerRegistration registerNotificationListener(StreamNameType stream,
+                                                                  NetconfNotificationListener listener);
 
     /**
-     * Check stream availability
+     * Check stream availability.
      */
     boolean isStreamAvailable(StreamNameType streamNameType);
 
     /**
-     * Get all the streams available
+     * Get all the streams available.
      */
     Streams getNotificationPublishers();
 
index aad97f3246225d3be78a5de7250ad4e90a920850..744679988aed3768ec606d93132010fc959d00c7 100644 (file)
@@ -9,7 +9,7 @@
 package org.opendaylight.netconf.notifications;
 
 /**
- * Manages the registration of a single listener
+ * Manages the registration of a single listener.
  */
 public interface NotificationListenerRegistration extends NotificationRegistration {
 
index 11bd30ad96edc3384448382428ca8b7e5b98750e..53ca343f05a28863f53a7c4dab7acd65e213196f 100644 (file)
@@ -9,7 +9,7 @@
 package org.opendaylight.netconf.notifications;
 
 /**
- * Generic registration, used as a base for other registration types
+ * Generic registration, used as a base for other registration types.
  */
 public interface NotificationRegistration extends AutoCloseable {
 
index 79eb3a92dabea0a713ccd744360681fb2c19c544..5d4a84d64354c580dde284a925fe623372097824 100644 (file)
                     </instructions>
                 </configuration>
             </plugin>
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-checkstyle-plugin</artifactId>
+                <configuration>
+                    <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+                </configuration>
+            </plugin>
         </plugins>
     </build>
 </project>
index 00552066a2ce9f73c66ab74621e0d1d8accc45e2..c8989e59496ae304ccbf721f75c4e3d3c3023c29 100644 (file)
@@ -44,7 +44,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 @ThreadSafe
-public class NetconfNotificationManager implements NetconfNotificationCollector, NetconfNotificationRegistry, NetconfNotificationListener, AutoCloseable {
+public class NetconfNotificationManager implements NetconfNotificationCollector, NetconfNotificationRegistry,
+        NetconfNotificationListener, AutoCloseable {
 
     public static final StreamNameType BASE_STREAM_NAME = new StreamNameType("NETCONF");
     public static final Stream BASE_NETCONF_STREAM;
@@ -60,11 +61,14 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfNotificationManager.class);
 
-    // TODO excessive synchronization provides thread safety but is most likely not optimal (combination of concurrent collections might improve performance)
-    // And also calling callbacks from a synchronized block is dangerous since the listeners/publishers can block the whole notification processing
+    // TODO excessive synchronization provides thread safety but is most likely not optimal
+    // (combination of concurrent collections might improve performance)
+    // And also calling callbacks from a synchronized block is dangerous
+    // since the listeners/publishers can block the whole notification processing
 
     @GuardedBy("this")
-    private final Multimap<StreamNameType, GenericNotificationListenerReg> notificationListeners = HashMultimap.create();
+    private final Multimap<StreamNameType, GenericNotificationListenerReg> notificationListeners =
+            HashMultimap.create();
 
     @GuardedBy("this")
     private final Set<NetconfNotificationStreamListener> streamListeners = Sets.newHashSet();
@@ -91,13 +95,16 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
     }
 
     @Override
-    public synchronized NotificationListenerRegistration registerNotificationListener(final StreamNameType stream, final NetconfNotificationListener listener) {
+    public synchronized NotificationListenerRegistration registerNotificationListener(
+            final StreamNameType stream,
+            final NetconfNotificationListener listener) {
         Preconditions.checkNotNull(stream);
         Preconditions.checkNotNull(listener);
 
         LOG.trace("Notification listener registered for stream: {}", stream);
 
-        final GenericNotificationListenerReg genericNotificationListenerReg = new GenericNotificationListenerReg(listener) {
+        final GenericNotificationListenerReg genericNotificationListenerReg =
+                new GenericNotificationListenerReg(listener) {
             @Override
             public void close() {
                 synchronized (NetconfNotificationManager.this) {
@@ -122,7 +129,8 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
     }
 
     @Override
-    public synchronized NotificationRegistration registerStreamListener(final NetconfNotificationStreamListener listener) {
+    public synchronized NotificationRegistration registerStreamListener(
+            final NetconfNotificationStreamListener listener) {
         streamListeners.add(listener);
 
         // Notify about all already available
@@ -169,14 +177,16 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
         }
 
         if (streamMetadata.containsKey(streamName)) {
-            LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName, streamMetadata.get(streamName));
+            LOG.warn("Notification stream {} already registered as: {}. Will be reused", streamName,
+                    streamMetadata.get(streamName));
         } else {
             streamMetadata.put(streamName, stream);
         }
 
         availableStreams.add(streamName);
 
-        final GenericNotificationPublisherReg genericNotificationPublisherReg = new GenericNotificationPublisherReg(this, streamName) {
+        final GenericNotificationPublisherReg genericNotificationPublisherReg =
+                new GenericNotificationPublisherReg(this, streamName) {
             @Override
             public void close() {
                 synchronized (NetconfNotificationManager.this) {
@@ -191,7 +201,9 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
         return genericNotificationPublisherReg;
     }
 
-    private void unregisterNotificationPublisher(final StreamNameType streamName, final GenericNotificationPublisherReg genericNotificationPublisherReg) {
+    private void unregisterNotificationPublisher(
+            final StreamNameType streamName,
+            final GenericNotificationPublisherReg genericNotificationPublisherReg) {
         availableStreams.remove(streamName);
         notificationPublishers.remove(genericNotificationPublisherReg);
 
@@ -219,7 +231,8 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
 
     @Override
     public BaseNotificationPublisherRegistration registerBaseNotificationPublisher() {
-        final NotificationPublisherRegistration notificationPublisherRegistration = registerNotificationPublisher(BASE_NETCONF_STREAM);
+        final NotificationPublisherRegistration notificationPublisherRegistration =
+                registerNotificationPublisher(BASE_NETCONF_STREAM);
         return new BaseNotificationPublisherReg(notificationPublisherRegistration);
     }
 
@@ -227,7 +240,8 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
         private NetconfNotificationManager baseListener;
         private final StreamNameType registeredStream;
 
-        public GenericNotificationPublisherReg(final NetconfNotificationManager baseListener, final StreamNameType registeredStream) {
+        GenericNotificationPublisherReg(final NetconfNotificationManager baseListener,
+                                        final StreamNameType registeredStream) {
             this.baseListener = baseListener;
             this.registeredStream = registeredStream;
         }
@@ -254,7 +268,7 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
 
         private final NotificationPublisherRegistration baseRegistration;
 
-        public BaseNotificationPublisherReg(final NotificationPublisherRegistration baseRegistration) {
+        BaseNotificationPublisherReg(final NotificationPublisherRegistration baseRegistration) {
             this.baseRegistration = baseRegistration;
         }
 
@@ -269,7 +283,8 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
 
         @Override
         public void onCapabilityChanged(final NetconfCapabilityChange capabilityChange) {
-            baseRegistration.onNotification(BASE_STREAM_NAME, serializeNotification(capabilityChange, CAPABILITY_CHANGE_SCHEMA_PATH));
+            baseRegistration.onNotification(BASE_STREAM_NAME,
+                    serializeNotification(capabilityChange, CAPABILITY_CHANGE_SCHEMA_PATH));
         }
 
         @Override
@@ -286,7 +301,7 @@ public class NetconfNotificationManager implements NetconfNotificationCollector,
     private class GenericNotificationListenerReg implements NotificationListenerRegistration {
         private final NetconfNotificationListener listener;
 
-        public GenericNotificationListenerReg(final NetconfNotificationListener listener) {
+        GenericNotificationListenerReg(final NetconfNotificationListener listener) {
             this.listener = listener;
         }
 
index d1a46a67bd7086cdab56c4ac38819932b69e2e5b..812080618cdc51a46dac9d3a2e84751a57eb7be0 100644 (file)
@@ -34,10 +34,12 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
 /**
- * Create subscription listens for create subscription requests and registers notification listeners into notification registry.
+ * Create subscription listens for create subscription requests
+ * and registers notification listeners into notification registry.
  * Received notifications are sent to the client right away
  */
-public class CreateSubscription extends AbstractSingletonNetconfOperation implements SessionAwareNetconfOperation, AutoCloseable {
+public class CreateSubscription extends AbstractSingletonNetconfOperation
+        implements SessionAwareNetconfOperation, AutoCloseable {
 
     private static final Logger LOG = LoggerFactory.getLogger(CreateSubscription.class);
 
@@ -47,13 +49,15 @@ public class CreateSubscription extends AbstractSingletonNetconfOperation implem
     private final List<NotificationListenerRegistration> subscriptions = Lists.newArrayList();
     private NetconfSession netconfSession;
 
-    public CreateSubscription(final String netconfSessionIdForReporting, final NetconfNotificationRegistry notifications) {
+    public CreateSubscription(final String netconfSessionIdForReporting,
+                              final NetconfNotificationRegistry notifications) {
         super(netconfSessionIdForReporting);
         this.notifications = notifications;
     }
 
     @Override
-    protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException {
+    protected Element handleWithNoSubsequentOperations(final Document document,
+                                                       final XmlElement operationElement) throws DocumentedException {
         operationElement.checkName(CREATE_SUBSCRIPTION);
         operationElement.checkNamespace(CreateSubscriptionInput.QNAME.getNamespace().toString());
         // FIXME reimplement using CODEC_REGISTRY and parse everything into generated class instance
@@ -63,23 +67,26 @@ public class CreateSubscription extends AbstractSingletonNetconfOperation implem
         final Optional<XmlElement> filter = operationElement.getOnlyChildElementWithSameNamespaceOptionally("filter");
 
         // Replay not supported
-        final Optional<XmlElement> startTime = operationElement.getOnlyChildElementWithSameNamespaceOptionally("startTime");
+        final Optional<XmlElement> startTime =
+                operationElement.getOnlyChildElementWithSameNamespaceOptionally("startTime");
         Preconditions.checkArgument(startTime.isPresent() == false, "StartTime element not yet supported");
 
         // Stop time not supported
-        final Optional<XmlElement> stopTime = operationElement.getOnlyChildElementWithSameNamespaceOptionally("stopTime");
+        final Optional<XmlElement> stopTime =
+                operationElement.getOnlyChildElementWithSameNamespaceOptionally("stopTime");
         Preconditions.checkArgument(stopTime.isPresent() == false, "StopTime element not yet supported");
 
         final StreamNameType streamNameType = parseStreamIfPresent(operationElement);
 
         Preconditions.checkNotNull(netconfSession);
         // Premature streams are allowed (meaning listener can register even if no provider is available yet)
-        if(notifications.isStreamAvailable(streamNameType) == false) {
-            LOG.warn("Registering premature stream {}. No publisher available yet for session {}", streamNameType, getNetconfSessionIdForReporting());
+        if (notifications.isStreamAvailable(streamNameType) == false) {
+            LOG.warn("Registering premature stream {}. No publisher available yet for session {}", streamNameType,
+                    getNetconfSessionIdForReporting());
         }
 
-        final NotificationListenerRegistration notificationListenerRegistration =
-                notifications.registerNotificationListener(streamNameType, new NotificationSubscription(netconfSession, filter));
+        final NotificationListenerRegistration notificationListenerRegistration = notifications
+                .registerNotificationListener(streamNameType, new NotificationSubscription(netconfSession, filter));
         subscriptions.add(notificationListenerRegistration);
 
         return XmlUtil.createElement(document, XmlNetconfConstants.OK, Optional.<String>absent());
@@ -87,7 +94,8 @@ public class CreateSubscription extends AbstractSingletonNetconfOperation implem
 
     private static StreamNameType parseStreamIfPresent(final XmlElement operationElement) throws DocumentedException {
         final Optional<XmlElement> stream = operationElement.getOnlyChildElementWithSameNamespaceOptionally("stream");
-        return stream.isPresent() ? new StreamNameType(stream.get().getTextContent()) : NetconfNotificationManager.BASE_STREAM_NAME;
+        return stream.isPresent() ? new StreamNameType(stream.get().getTextContent())
+                : NetconfNotificationManager.BASE_STREAM_NAME;
     }
 
     @Override
@@ -118,7 +126,7 @@ public class CreateSubscription extends AbstractSingletonNetconfOperation implem
         private final NetconfSession currentSession;
         private final Optional<XmlElement> filter;
 
-        public NotificationSubscription(final NetconfSession currentSession, final Optional<XmlElement> filter) {
+        NotificationSubscription(final NetconfSession currentSession, final Optional<XmlElement> filter) {
             this.currentSession = currentSession;
             this.filter = filter;
         }
@@ -127,7 +135,8 @@ public class CreateSubscription extends AbstractSingletonNetconfOperation implem
         public void onNotification(final StreamNameType stream, final NetconfNotification notification) {
             if (filter.isPresent()) {
                 try {
-                    final Optional<Document> filtered = SubtreeFilter.applySubtreeNotificationFilter(this.filter.get(), notification.getDocument());
+                    final Optional<Document> filtered =
+                            SubtreeFilter.applySubtreeNotificationFilter(this.filter.get(), notification.getDocument());
                     if (filtered.isPresent()) {
                         final Date eventTime = notification.getEventTime();
                         currentSession.sendMessage(new NetconfNotification(filtered.get(), eventTime));
index 78db2f6c69c88b1244ffcbcf6347aa55c8542527..3655ae209cf3ffab1e3518eae999757771b34d48 100644 (file)
@@ -37,7 +37,8 @@ import org.w3c.dom.Element;
 public class Get extends AbstractNetconfOperation implements AutoCloseable {
 
     private static final String GET = "get";
-    private static final InstanceIdentifier<Netconf> NETCONF_SUBTREE_INSTANCE_IDENTIFIER = InstanceIdentifier.builder(Netconf.class).build();
+    private static final InstanceIdentifier<Netconf> NETCONF_SUBTREE_INSTANCE_IDENTIFIER =
+            InstanceIdentifier.builder(Netconf.class).build();
 
     private final NetconfNotificationRegistry notificationRegistry;
 
@@ -53,23 +54,33 @@ public class Get extends AbstractNetconfOperation implements AutoCloseable {
     }
 
     @Override
-    public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException {
+    protected Element handle(final Document document, final XmlElement message,
+                             final NetconfOperationChainedExecution subsequentOperation)
+            throws DocumentedException {
+        throw new UnsupportedOperationException("Never gets called");
+    }
+
+    @Override
+    public Document handle(final Document requestMessage, final NetconfOperationChainedExecution subsequentOperation)
+            throws DocumentedException {
         final Document partialResponse = subsequentOperation.execute(requestMessage);
         final Streams availableStreams = notificationRegistry.getNotificationPublishers();
-        if(availableStreams.getStream().isEmpty() == false) {
+        if (availableStreams.getStream().isEmpty() == false) {
             serializeStreamsSubtree(partialResponse, availableStreams);
         }
         return partialResponse;
     }
 
-    static void serializeStreamsSubtree(final Document partialResponse, final Streams availableStreams) throws DocumentedException {
+    static void serializeStreamsSubtree(final Document partialResponse, final Streams availableStreams)
+            throws DocumentedException {
         final Netconf netconfSubtree = new NetconfBuilder().setStreams(availableStreams).build();
         final NormalizedNode<?, ?> normalized = toNormalized(netconfSubtree);
 
         final DOMResult result = new DOMResult(getPlaceholder(partialResponse));
 
         try {
-            NetconfUtil.writeNormalizedNode(normalized, result, SchemaPath.ROOT, NotificationsTransformUtil.NOTIFICATIONS_SCHEMA_CTX);
+            NetconfUtil.writeNormalizedNode(normalized, result, SchemaPath.ROOT,
+                    NotificationsTransformUtil.NOTIFICATIONS_SCHEMA_CTX);
         } catch (final XMLStreamException | IOException e) {
             throw new IllegalStateException("Unable to serialize " + netconfSubtree, e);
         }
@@ -77,19 +88,14 @@ public class Get extends AbstractNetconfOperation implements AutoCloseable {
 
     private static Element getPlaceholder(final Document innerResult)
             throws DocumentedException {
-        final XmlElement rootElement = XmlElement.fromDomElementWithExpected(
-                innerResult.getDocumentElement(), XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
+        final XmlElement rootElement = XmlElement.fromDomElementWithExpected(innerResult.getDocumentElement(),
+                XmlMappingConstants.RPC_REPLY_KEY, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0);
         return rootElement.getOnlyChildElement(XmlNetconfConstants.DATA_KEY).getDomElement();
     }
 
     private static NormalizedNode<?, ?> toNormalized(final Netconf netconfSubtree) {
-        return NotificationsTransformUtil.CODEC_REGISTRY.toNormalizedNode(NETCONF_SUBTREE_INSTANCE_IDENTIFIER, netconfSubtree).getValue();
-    }
-
-    @Override
-    protected Element handle(final Document document, final XmlElement message, final NetconfOperationChainedExecution subsequentOperation)
-            throws DocumentedException {
-        throw new UnsupportedOperationException("Never gets called");
+        return NotificationsTransformUtil.CODEC_REGISTRY
+                .toNormalizedNode(NETCONF_SUBTREE_INSTANCE_IDENTIFIER, netconfSubtree).getValue();
     }
 
     @Override
index 8b74054c78e11d943c9b2853a2286c13604c1bdf..d3e7a2eb5da3d161ec23ea2721b227705a102ca2 100644 (file)
@@ -51,7 +51,8 @@ public final class NotificationsTransformUtil {
 
         final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create();
         moduleInfoBackedContext.addModuleInfos(Collections.singletonList($YangModuleInfoImpl.getInstance()));
-        moduleInfoBackedContext.addModuleInfos(Collections.singletonList(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()));
+        moduleInfoBackedContext.addModuleInfos(Collections.singletonList(org.opendaylight.yang.gen.v1.urn.ietf.params
+                .xml.ns.yang.ietf.netconf.notifications.rev120206.$YangModuleInfoImpl.getInstance()));
         final Optional<SchemaContext> schemaContextOptional = moduleInfoBackedContext.tryToCreateSchemaContext();
         Preconditions.checkState(schemaContextOptional.isPresent());
         NOTIFICATIONS_SCHEMA_CTX = schemaContextOptional.get();
@@ -62,41 +63,43 @@ public final class NotificationsTransformUtil {
 
         final JavassistUtils javassist = JavassistUtils.forClassPool(ClassPool.getDefault());
         CODEC_REGISTRY = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(javassist));
-        CODEC_REGISTRY.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext, NOTIFICATIONS_SCHEMA_CTX));
+        CODEC_REGISTRY.onBindingRuntimeContextUpdated(BindingRuntimeContext.create(moduleInfoBackedContext,
+                NOTIFICATIONS_SCHEMA_CTX));
     }
 
     private static RpcDefinition findCreateSubscriptionRpc() {
-        return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(), new Predicate<RpcDefinition>() {
-            @Override
-            public boolean apply(final RpcDefinition input) {
-                return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
-            }
-        }), null);
+        return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(),
+            new Predicate<RpcDefinition>() {
+                @Override
+                public boolean apply(final RpcDefinition input) {
+                    return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION);
+                }
+            }), null);
     }
 
     /**
-     * Transform base notification for capabilities into NetconfNotification
+     * Transform base notification for capabilities into NetconfNotification.
      */
     public static NetconfNotification transform(final Notification notification, SchemaPath path) {
         return transform(notification, Optional.<Date>absent(), path);
     }
 
-    public static NetconfNotification transform(final Notification notification, final Date eventTime, SchemaPath path) {
+    public static NetconfNotification transform(final Notification notification,
+                                                final Date eventTime, SchemaPath path) {
         return transform(notification, Optional.fromNullable(eventTime), path);
     }
 
-    private static NetconfNotification transform(final Notification notification, final Optional<Date> eventTime, SchemaPath path) {
+    private static NetconfNotification transform(final Notification notification,
+                                                 final Optional<Date> eventTime, SchemaPath path) {
         final ContainerNode containerNode = CODEC_REGISTRY.toNormalizedNodeNotification(notification);
         final DOMResult result = new DOMResult(XmlUtil.newDocument());
         try {
             NetconfUtil.writeNormalizedNode(containerNode, result, path, NOTIFICATIONS_SCHEMA_CTX);
-        } catch (final XMLStreamException| IOException e) {
+        } catch (final XMLStreamException | IOException e) {
             throw new IllegalStateException("Unable to serialize " + notification, e);
         }
         final Document node = (Document) result.getNode();
-        return eventTime.isPresent() ?
-                new NetconfNotification(node, eventTime.get()):
-                new NetconfNotification(node);
+        return eventTime.isPresent() ? new NetconfNotification(node, eventTime.get()) : new NetconfNotification(node);
     }
 
 }
index 1cbd5237389dad5900da775ce0458399ecb20721..146f5e7116aa3f56c2277b687d495696ef658360 100644 (file)
@@ -46,11 +46,13 @@ public class Activator implements BundleActivator {
         // Add properties to autowire with netconf-impl instance for cfg subsystem
         final Dictionary<String, String> props = new Hashtable<>();
         props.put(NetconfConstants.SERVICE_NAME, NetconfConstants.NETCONF_NOTIFICATION);
-        netconfNotificationCollectorServiceRegistration = context.registerService(NetconfNotificationCollector.class, netconfNotificationManager, new Hashtable<String, Object>());
+        netconfNotificationCollectorServiceRegistration = context.registerService(NetconfNotificationCollector.class,
+                netconfNotificationManager, new Hashtable<String, Object>());
 
         final NetconfOperationServiceFactory netconfOperationServiceFactory = new NetconfOperationServiceFactory() {
 
-            private final Set<Capability> capabilities = Collections.<Capability>singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
+            private final Set<Capability> capabilities =
+                    Collections.<Capability>singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
 
             @Override
             public Set<Capability> getCapabilities() {
@@ -72,7 +74,8 @@ public class Activator implements BundleActivator {
             public NetconfOperationService createService(final String netconfSessionIdForReporting) {
                 return new NetconfOperationService() {
 
-                    private final CreateSubscription createSubscription = new CreateSubscription(netconfSessionIdForReporting, netconfNotificationManager);
+                    private final CreateSubscription createSubscription =
+                            new CreateSubscription(netconfSessionIdForReporting, netconfNotificationManager);
 
                     @Override
                     public Set<NetconfOperation> getNetconfOperations() {
@@ -91,12 +94,13 @@ public class Activator implements BundleActivator {
 
         final Dictionary<String, String> properties = new Hashtable<>();
         properties.put(NetconfConstants.SERVICE_NAME, NetconfConstants.NETCONF_MONITORING);
-        operationaServiceRegistration = context.registerService(NetconfOperationServiceFactory.class, netconfOperationServiceFactory, properties);
+        operationaServiceRegistration = context.registerService(NetconfOperationServiceFactory.class,
+                netconfOperationServiceFactory, properties);
     }
 
     @Override
     public void stop(final BundleContext context) throws Exception {
-        if(netconfNotificationCollectorServiceRegistration != null) {
+        if (netconfNotificationCollectorServiceRegistration != null) {
             netconfNotificationCollectorServiceRegistration.unregister();
             netconfNotificationCollectorServiceRegistration = null;
         }
index 98c5e6bc5e77b02533f73b945ea711d397816b04..a40b2c58dc1733bae42263b44cf4abb5b53ca732 100644 (file)
@@ -97,7 +97,8 @@ public class NetconfNotificationManagerTest {
         )) {
             try {
                 final Date apply = NetconfNotification.RFC3339_DATE_PARSER.apply(time);
-                final Date parse = new SimpleDateFormat(RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT).parse(iterator.next());
+                final Date parse =
+                        new SimpleDateFormat(RFC3339_DATE_FORMAT_WITH_MILLIS_BLUEPRINT).parse(iterator.next());
                 assertEquals(parse.getTime(), apply.getTime());
                 // Testing that we're consistent from formatting to parsing.
                 final String dateString = NetconfNotification.RFC3339_DATE_FORMATTER.apply(apply);
@@ -147,7 +148,8 @@ public class NetconfNotificationManagerTest {
 
         final NetconfNotificationListener listener = mock(NetconfNotificationListener.class);
         doNothing().when(listener).onNotification(any(StreamNameType.class), any(NetconfNotification.class));
-        final NotificationListenerRegistration notificationListenerRegistration = netconfNotificationManager.registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
+        final NotificationListenerRegistration notificationListenerRegistration = netconfNotificationManager
+                .registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
         final NetconfCapabilityChange notification = capabilityChangedBuilder.build();
         baseNotificationPublisherRegistration.onCapabilityChanged(notification);
 
@@ -163,12 +165,14 @@ public class NetconfNotificationManagerTest {
     public void testClose() throws Exception {
         final NetconfNotificationManager netconfNotificationManager = new NetconfNotificationManager();
 
-        final BaseNotificationPublisherRegistration baseNotificationPublisherRegistration = netconfNotificationManager.registerBaseNotificationPublisher();
+        final BaseNotificationPublisherRegistration baseNotificationPublisherRegistration =
+                netconfNotificationManager.registerBaseNotificationPublisher();
 
         final NetconfNotificationListener listener = mock(NetconfNotificationListener.class);
         doNothing().when(listener).onNotification(any(StreamNameType.class), any(NetconfNotification.class));
 
-        netconfNotificationManager.registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
+        netconfNotificationManager
+                .registerNotificationListener(NetconfNotificationManager.BASE_NETCONF_STREAM.getName(), listener);
 
         final NetconfNotificationCollector.NetconfNotificationStreamListener streamListener =
                 mock(NetconfNotificationCollector.NetconfNotificationStreamListener.class);
@@ -196,7 +200,8 @@ public class NetconfNotificationManagerTest {
     public void testStreamListeners() throws Exception {
         final NetconfNotificationManager netconfNotificationManager = new NetconfNotificationManager();
 
-        final NetconfNotificationCollector.NetconfNotificationStreamListener streamListener = mock(NetconfNotificationCollector.NetconfNotificationStreamListener.class);
+        final NetconfNotificationCollector.NetconfNotificationStreamListener streamListener =
+                mock(NetconfNotificationCollector.NetconfNotificationStreamListener.class);
         doNothing().when(streamListener).onStreamRegistered(any(Stream.class));
         doNothing().when(streamListener).onStreamUnregistered(any(StreamNameType.class));
 
index 4de90fab238649d79d60ab2dd1d8aa5bae1275fb..69bdb1fb843452f305716d4e8bef179ebd87687b 100644 (file)
@@ -29,10 +29,11 @@ import org.w3c.dom.Element;
 
 public class CreateSubscriptionTest {
 
-    private static final String CREATE_SUBSCRIPTION_XML = "<create-subscription\n" +
-            "xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\" xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-            "<stream>TESTSTREAM</stream>" +
-            "</create-subscription>";
+    private static final String CREATE_SUBSCRIPTION_XML = "<create-subscription\n"
+            + "xmlns=\"urn:ietf:params:xml:ns:netconf:notification:1.0\" "
+            + "xmlns:netconf=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+            + "<stream>TESTSTREAM</stream>"
+            + "</create-subscription>";
 
     @Mock
     private NetconfNotificationRegistry notificationRegistry;
@@ -41,7 +42,8 @@ public class CreateSubscriptionTest {
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
         doReturn(true).when(notificationRegistry).isStreamAvailable(any(StreamNameType.class));
-        doReturn(mock(NotificationListenerRegistration.class)).when(notificationRegistry).registerNotificationListener(any(StreamNameType.class), any(NetconfNotificationListener.class));
+        doReturn(mock(NotificationListenerRegistration.class)).when(notificationRegistry)
+                .registerNotificationListener(any(StreamNameType.class), any(NetconfNotificationListener.class));
     }
 
     @Test
@@ -52,7 +54,8 @@ public class CreateSubscriptionTest {
         final Element e = XmlUtil.readXmlToElement(CREATE_SUBSCRIPTION_XML);
 
         final XmlElement operationElement = XmlElement.fromDomElement(e);
-        final Element element = createSubscription.handleWithNoSubsequentOperations(XmlUtil.newDocument(), operationElement);
+        final Element element =
+                createSubscription.handleWithNoSubsequentOperations(XmlUtil.newDocument(), operationElement);
 
         Assert.assertThat(XmlUtil.toString(element), CoreMatchers.containsString("ok"));
     }
index f3dbc249fbd6f7ef9e92a4c85fad0335d1085035..0abf5cbf9c8a644e9241573d998d7026c5847c3f 100644 (file)
@@ -37,27 +37,27 @@ public class GetTest {
         final Document response = getBlankResponse();
         Get.serializeStreamsSubtree(response, streams);
         NotificationsTransformUtilTest.compareXml(XmlUtil.toString(response),
-                "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                        "<data>\n" +
-                        "<netconf xmlns=\"urn:ietf:params:xml:ns:netmod:notification\">\n" +
-                        "<streams>\n" +
-                        "<stream>\n" +
-                        "<name>base</name>\n" +
-                        "<description>description</description>\n" +
-                        "<replaySupport>false</replaySupport>\n" +
-                        "</stream>\n" +
-                        "</streams>\n" +
-                        "</netconf>\n" +
-                        "</data>\n" +
-                        "</rpc-reply>\n");
+                "<rpc-reply message-id=\"101\" xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                        + "<data>\n"
+                        + "<netconf xmlns=\"urn:ietf:params:xml:ns:netmod:notification\">\n"
+                        + "<streams>\n"
+                        + "<stream>\n"
+                        + "<name>base</name>\n"
+                        + "<description>description</description>\n"
+                        + "<replaySupport>false</replaySupport>\n"
+                        + "</stream>\n"
+                        + "</streams>\n"
+                        + "</netconf>\n"
+                        + "</data>\n"
+                        "</rpc-reply>\n");
     }
 
     private static Document getBlankResponse() throws IOException, SAXException {
 
-        return XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n" +
-                "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n" +
-                "<data>\n" +
-                "</data>\n" +
-                "</rpc-reply>");
+        return XmlUtil.readXmlToDocument("<rpc-reply message-id=\"101\"\n"
+                + "xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">\n"
+                + "<data>\n"
+                + "</data>\n"
+                "</rpc-reply>");
     }
 }
\ No newline at end of file
index 84d77ef16381040e6ba933bbfdf1a36cbc092902..4ae9d85316ab86af092c7b65327982fad49d85e4 100644 (file)
@@ -29,19 +29,20 @@ import org.xml.sax.SAXException;
 public class NotificationsTransformUtilTest {
 
     private static final Date DATE = new Date();
-    private static final String innerNotification = "<netconf-capability-change xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-notifications\">" +
-            "<deleted-capability>uri4</deleted-capability>" +
-            "<deleted-capability>uri3</deleted-capability>" +
-            "<added-capability>uri1</added-capability>" +
-            "</netconf-capability-change>";
+    private static final String INNER_NOTIFICATION =
+            "<netconf-capability-change xmlns=\"urn:ietf:params:xml:ns:yang:ietf-netconf-notifications\">"
+                    + "<deleted-capability>uri4</deleted-capability>"
+                    + "<deleted-capability>uri3</deleted-capability>"
+                    + "<added-capability>uri1</added-capability>"
+                    + "</netconf-capability-change>";
 
-    private static final String expectedNotification =
+    private static final String EXPECTED_NOTIFICATION =
             "<notification xmlns=\"urn:ietf:params:netconf:capability:notification:1.0\">"
-                    + innerNotification
+                    + INNER_NOTIFICATION
                     + "<eventTime>"
-                        + NetconfNotification.RFC3339_DATE_FORMATTER.apply(DATE)
-                    + "</eventTime>" +
-            "</notification>";
+                    + NetconfNotification.RFC3339_DATE_FORMATTER.apply(DATE)
+                    + "</eventTime>"
+                    + "</notification>";
 
     @Test
     public void testTransform() throws Exception {
@@ -51,11 +52,12 @@ public class NotificationsTransformUtilTest {
         netconfCapabilityChangeBuilder.setDeletedCapability(Lists.newArrayList(new Uri("uri4"), new Uri("uri3")));
 
         final NetconfCapabilityChange capabilityChange = netconfCapabilityChangeBuilder.build();
-        final NetconfNotification transform = NotificationsTransformUtil.transform(capabilityChange, DATE, SchemaPath.create(true, NetconfCapabilityChange.QNAME));
+        final NetconfNotification transform = NotificationsTransformUtil.transform(capabilityChange, DATE,
+                SchemaPath.create(true, NetconfCapabilityChange.QNAME));
 
         final String serialized = XmlUtil.toString(transform.getDocument());
 
-        compareXml(expectedNotification, serialized);
+        compareXml(EXPECTED_NOTIFICATION, serialized);
     }
 
     static void compareXml(final String expected, final String actual) throws SAXException, IOException {
@@ -68,10 +70,11 @@ public class NotificationsTransformUtilTest {
 
     @Test
     public void testTransformFromDOM() throws Exception {
-        final NetconfNotification netconfNotification = new NetconfNotification(XmlUtil.readXmlToDocument(innerNotification), DATE);
+        final NetconfNotification netconfNotification =
+                new NetconfNotification(XmlUtil.readXmlToDocument(INNER_NOTIFICATION), DATE);
 
         XMLUnit.setIgnoreWhitespace(true);
-        compareXml(expectedNotification, netconfNotification.toString());
+        compareXml(EXPECTED_NOTIFICATION, netconfNotification.toString());
     }
 
 }
index 24e865212786d591cef43c0cceca5af717754bf5..66e9370c6db9a8e2985afe6f46bad82b2d67d489 100644 (file)
@@ -50,10 +50,10 @@ public class ActivatorTest {
         final ServiceRegistration operationaServiceRegistration = mock(ServiceRegistration.class);
 
         // test registering services
-        doReturn(netconfNotificationCollectorServiceRegistration).when(context).
-                registerService(eq(NetconfNotificationCollector.class), any(NetconfNotificationManager.class), any());
-        doReturn(operationaServiceRegistration).when(context).
-                registerService(eq(NetconfOperationServiceFactory.class), any(NetconfOperationServiceFactory.class), any());
+        doReturn(netconfNotificationCollectorServiceRegistration).when(context)
+                .registerService(eq(NetconfNotificationCollector.class), any(NetconfNotificationManager.class), any());
+        doReturn(operationaServiceRegistration).when(context).registerService(eq(NetconfOperationServiceFactory.class),
+                any(NetconfOperationServiceFactory.class), any());
 
         activator.start(context);
 
@@ -72,12 +72,17 @@ public class ActivatorTest {
         // test service factory argument requisites
         final NetconfOperationServiceFactory serviceFactory = serviceFactoryArgumentCaptor.getValue();
 
-        final Set<Capability> capabilities = Collections.singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
+        final Set<Capability> capabilities =
+                Collections.singleton(new BasicCapability(NetconfNotification.NOTIFICATION_NAMESPACE));
 
-        assertEquals(capabilities.iterator().next().getCapabilityUri(), serviceFactory.getCapabilities().iterator().next().getCapabilityUri());
-        assertEquals(capabilities.iterator().next().getCapabilitySchema(), serviceFactory.getCapabilities().iterator().next().getCapabilitySchema());
-        assertEquals(capabilities.iterator().next().getModuleNamespace(), serviceFactory.getCapabilities().iterator().next().getModuleNamespace());
-        assertEquals(capabilities.iterator().next().getModuleName(), serviceFactory.getCapabilities().iterator().next().getModuleName());
+        assertEquals(capabilities.iterator().next()
+                .getCapabilityUri(), serviceFactory.getCapabilities().iterator().next().getCapabilityUri());
+        assertEquals(capabilities.iterator().next()
+                .getCapabilitySchema(), serviceFactory.getCapabilities().iterator().next().getCapabilitySchema());
+        assertEquals(capabilities.iterator().next()
+                .getModuleNamespace(), serviceFactory.getCapabilities().iterator().next().getModuleNamespace());
+        assertEquals(capabilities.iterator().next()
+                .getModuleName(), serviceFactory.getCapabilities().iterator().next().getModuleName());
 
         final CapabilityListener listener = mock(CapabilityListener.class);
 
@@ -90,17 +95,18 @@ public class ActivatorTest {
         final NetconfOperationService netconfOperationService = serviceFactory.createService("id");
         final Set<NetconfOperation> netconfOperations = netconfOperationService.getNetconfOperations();
 
-        final CreateSubscription createSubscription = new CreateSubscription("id", activator.getNetconfNotificationManager());
+        final CreateSubscription createSubscription =
+                new CreateSubscription("id", activator.getNetconfNotificationManager());
 
         netconfOperations.forEach(
-                operation -> {
-                    if (operation instanceof CreateSubscription) {
-                        assertEquals(createSubscription.toString(), operation.toString());
-                    }
-                    if (operation instanceof Get) {
-                        assertEquals("id", ((Get) operation).getNetconfSessionIdForReporting());
-                    }
+            operation -> {
+                if (operation instanceof CreateSubscription) {
+                    assertEquals(createSubscription.toString(), operation.toString());
                 }
+                if (operation instanceof Get) {
+                    assertEquals("id", ((Get) operation).getNetconfSessionIdForReporting());
+                }
+            }
         );
 
         // test unregister after stop
index 6d0b9fb0fd68d3752befc248ee3ab3f3588755fa..9466d17e301835a3cc11612778d873991738e646 100644 (file)
           </instructions>
         </configuration>
       </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <configuration>
+          <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index 5792ebb61e31c805b2678afb9cfde6959ca8dc22..f45f7ba80f5a073328ad612b53364926e03d244d 100644 (file)
@@ -44,8 +44,8 @@ public class NetconfNorthboundTcpServer implements AutoCloseable {
     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());
+            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 tcp endpoint to address " + bindingAddress, e);
diff --git a/netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/netty/ProxyClientHandler.java b/netconf/netconf-tcp/src/main/java/org/opendaylight/netconf/tcp/netty/ProxyClientHandler.java
new file mode 100644 (file)
index 0000000..2cde077
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * 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.tcp.netty;
+
+import static com.google.common.base.Preconditions.checkState;
+
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
+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;
+    private ChannelHandlerContext localCtx;
+
+    ProxyClientHandler(ChannelHandlerContext remoteCtx) {
+        this.remoteCtx = remoteCtx;
+    }
+
+    @Override
+    public void channelActive(ChannelHandlerContext ctx) {
+        checkState(this.localCtx == null);
+        LOG.trace("Client channel active");
+        this.localCtx = ctx;
+    }
+
+    @Override
+    public void channelRead(ChannelHandlerContext ctx, Object msg) {
+        LOG.trace("Forwarding message");
+        remoteCtx.write(msg);
+    }
+
+    @Override
+    public void channelReadComplete(ChannelHandlerContext ctx) {
+        LOG.trace("Flushing remote 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);
+        checkState(this.localCtx.equals(ctx));
+        ctx.close();
+    }
+
+    // called both when local or remote connection dies
+    @Override
+    public void channelInactive(ChannelHandlerContext ctx) {
+        LOG.trace("channelInactive() called, closing remote client ctx");
+        remoteCtx.close();
+    }
+
+}
index 971fd1592c67aa11a8c47892a1bdc2f0869f976f..4731b0fed965b899fc36fb35cf8b174c41697021 100644 (file)
@@ -8,8 +8,6 @@
 
 package org.opendaylight.netconf.tcp.netty;
 
-import static com.google.common.base.Preconditions.checkState;
-
 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
@@ -72,48 +70,3 @@ public class ProxyServerHandler extends ChannelInboundHandlerAdapter {
     }
 }
 
-class ProxyClientHandler extends ChannelInboundHandlerAdapter {
-    private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class);
-
-    private final ChannelHandlerContext remoteCtx;
-    private ChannelHandlerContext localCtx;
-
-    public ProxyClientHandler(ChannelHandlerContext remoteCtx) {
-        this.remoteCtx = remoteCtx;
-    }
-
-    @Override
-    public void channelActive(ChannelHandlerContext ctx) {
-        checkState(this.localCtx == null);
-        LOG.trace("Client channel active");
-        this.localCtx = ctx;
-    }
-
-    @Override
-    public void channelRead(ChannelHandlerContext ctx, Object msg) {
-        LOG.trace("Forwarding message");
-        remoteCtx.write(msg);
-    }
-
-    @Override
-    public void channelReadComplete(ChannelHandlerContext ctx) {
-        LOG.trace("Flushing remote 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);
-        checkState(this.localCtx.equals(ctx));
-        ctx.close();
-    }
-
-    // called both when local or remote connection dies
-    @Override
-    public void channelInactive(ChannelHandlerContext ctx) {
-        LOG.trace("channelInactive() called, closing remote client ctx");
-        remoteCtx.close();
-    }
-
-}
index 232d9177846634e76ee4680fbbc5daadd98af5c4..d95d2b84a2a793bce5f9b10309385e3695bd3c88 100644 (file)
@@ -32,8 +32,8 @@ public class NetconfTCPActivator implements BundleActivator {
         final InetSocketAddress address = netconfConfiguration.getTcpServerAddress();
 
         if (address.getAddress().isAnyLocalAddress()) {
-            LOG.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. " +
-                            "Consider changing tcp-address in netconf.cfg to 127.0.0.1");
+            LOG.warn("Unprotected netconf TCP address is configured to ANY local address. This is a security risk. "
+                    + "Consider changing tcp-address in netconf.cfg to 127.0.0.1");
         }
         LOG.info("Starting TCP netconf server at {}", address);
         proxyServer = new ProxyServer(address, NetconfConfiguration.NETCONF_LOCAL_ADDRESS);
index 8728ce2f4e5c281903317f0a901f8559b5c9f6d3..11e922f34d9220a3f153a3bfce9671f7fbd2f52e 100755 (executable)
     <reference id="clientDispatcherDependency"
                interface="org.opendaylight.netconf.client.NetconfClientDispatcher"
                odl:type="netconf-client-dispatcher"/>
-    <reference id="bindingAwareBroker"
-               interface="org.opendaylight.controller.sal.binding.api.BindingAwareBroker"/>
     <reference id="keepAliveExecutor"
                interface="org.opendaylight.controller.config.threadpool.ScheduledThreadPool"
                odl:type="global-netconf-ssh-scheduled-executor"/>
     <reference id="processingExecutor"
                interface="org.opendaylight.controller.config.threadpool.ThreadPool"
                odl:type="global-netconf-processing-executor"/>
-    <reference id="domBroker"
-               interface="org.opendaylight.controller.sal.core.api.Broker"/>
     <reference id="eventExecutor"
                interface="io.netty.util.concurrent.EventExecutor"
                odl:type="global-event-executor"/>
     <reference id="dataBroker"
                interface="org.opendaylight.controller.md.sal.binding.api.DataBroker"/>
+    <reference id="mountPointService"
+               interface="org.opendaylight.controller.md.sal.dom.api.DOMMountPointService"
+               odl:type="default"/>
 
     <bean id="schemaRepository" class="org.opendaylight.netconf.topology.impl.SchemaRepositoryProviderImpl">
         <argument value="shared-schema-repository-impl"/>
           destroy-method="close">
         <argument value="topology-netconf"/>
         <argument ref="clientDispatcherDependency"/>
-        <argument ref="bindingAwareBroker"/>
-        <argument ref="domBroker"/>
         <argument ref="eventExecutor"/>
         <argument ref="keepAliveExecutor"/>
         <argument ref="processingExecutor"/>
         <argument ref="schemaRepository"/>
         <argument ref="dataBroker"/>
+        <argument ref="mountPointService"/>
     </bean>
 
     <bean id="netconfConnectorFactory" class="org.opendaylight.netconf.topology.impl.NetconfConnectorFactoryImpl"/>
index 1087df67f3b9947845b45c575252e081efc3d2be..3b04d0fa957f6ec6f09de077241137f733c2464e 100644 (file)
@@ -18,11 +18,11 @@ import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import java.util.List;
 import java.util.stream.Collectors;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
@@ -45,37 +45,26 @@ class MasterSalFacade implements AutoCloseable, RemoteDeviceHandler<NetconfSessi
 
     private final RemoteDeviceId id;
     private final Timeout actorResponseWaitTime;
+    private final NetconfDeviceSalProvider salProvider;
+    private final ActorRef masterActorRef;
+    private final ActorSystem actorSystem;
 
     private SchemaContext remoteSchemaContext = null;
     private NetconfSessionPreferences netconfSessionPreferences = null;
     private DOMRpcService deviceRpc = null;
-    private final NetconfDeviceSalProvider salProvider;
-
-    private final ActorRef masterActorRef;
-    private final ActorSystem actorSystem;
     private DOMDataBroker deviceDataBroker = null;
 
     MasterSalFacade(final RemoteDeviceId id,
-                    final Broker domBroker,
-                    final BindingAwareBroker bindingBroker,
                     final ActorSystem actorSystem,
                     final ActorRef masterActorRef,
-                    final Timeout actorResponseWaitTime) {
+                    final Timeout actorResponseWaitTime,
+                    final DOMMountPointService mountService,
+                    final DataBroker dataBroker) {
         this.id = id;
-        this.salProvider = new NetconfDeviceSalProvider(id);
+        this.salProvider = new NetconfDeviceSalProvider(id, mountService, dataBroker);
         this.actorSystem = actorSystem;
         this.masterActorRef = masterActorRef;
         this.actorResponseWaitTime = actorResponseWaitTime;
-
-        registerToSal(domBroker, bindingBroker);
-    }
-
-    private void registerToSal(final Broker domRegistryDependency, final BindingAwareBroker bindingBroker) {
-        // TODO: remove use of provider, there is possible directly create mount instance and
-        // TODO: NetconfDeviceTopologyAdapter in constructor = less complexity
-
-        domRegistryDependency.registerProvider(salProvider);
-        bindingBroker.registerProvider(salProvider);
     }
 
     @Override
index 6ec40e5747999159fd2d635216e3645305ab254a..a33953291f60c333369efbbe1adb47bcc0f25bbe 100644 (file)
@@ -14,10 +14,12 @@ import akka.util.Timeout;
 import java.util.Collection;
 import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.binding.api.ClusteredDataTreeChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.DataObjectModification;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService;
 import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
@@ -45,21 +47,26 @@ class NetconfNodeManager
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfNodeManager.class);
 
+    private final Timeout actorResponseWaitTime;
+    private final DOMMountPointService mountPointService;
+    private final SchemaSourceRegistry schemaRegistry;
+    private final SchemaRepository schemaRepository;
+
     private NetconfTopologySetup setup;
     private ListenerRegistration<NetconfNodeManager> dataChangeListenerRegistration;
     private RemoteDeviceId id;
-    private final SchemaSourceRegistry schemaRegistry;
-    private final SchemaRepository schemaRepository;
     private ActorRef slaveActorRef;
-    private final Timeout actorResponseWaitTime;
+
 
     NetconfNodeManager(final NetconfTopologySetup setup,
-                       final RemoteDeviceId id, final Timeout actorResponseWaitTime) {
+                       final RemoteDeviceId id, final Timeout actorResponseWaitTime,
+                       final DOMMountPointService mountPointService) {
         this.setup = setup;
         this.id = id;
         this.schemaRegistry = setup.getSchemaResourcesDTO().getSchemaRegistry();
         this.schemaRepository = setup.getSchemaResourcesDTO().getSchemaRepository();
         this.actorResponseWaitTime = actorResponseWaitTime;
+        this.mountPointService = mountPointService;
     }
 
     @Override
@@ -134,7 +141,7 @@ class NetconfNodeManager
     private void createActorRef() {
         if (slaveActorRef == null) {
             slaveActorRef = setup.getActorSystem().actorOf(NetconfNodeActor.props(setup, id, schemaRegistry,
-                    schemaRepository, actorResponseWaitTime), id.getName());
+                    schemaRepository, actorResponseWaitTime, mountPointService), id.getName());
         }
     }
 
index 8b2ccf66afb6719d21c7b0f56b8de1c0d99f13fa..31a7f64d6cc021e8d99a5c5fdb9883bc91f17f54 100644 (file)
@@ -19,6 +19,7 @@ import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
@@ -38,28 +39,30 @@ class NetconfTopologyContext implements ClusterSingletonService {
 
     private final ServiceGroupIdentifier serviceGroupIdent;
     private final Timeout actorResponseWaitTime;
+    private final DOMMountPointService mountService;
+
     private NetconfTopologySetup netconfTopologyDeviceSetup;
     private RemoteDeviceId remoteDeviceId;
     private RemoteDeviceConnector remoteDeviceConnector;
     private NetconfNodeManager netconfNodeManager;
+    private ActorRef masterActorRef;
     private boolean finalClose = false;
     private boolean closed = false;
     private boolean isMaster;
 
-    private ActorRef masterActorRef;
-
     NetconfTopologyContext(final NetconfTopologySetup netconfTopologyDeviceSetup,
                            final ServiceGroupIdentifier serviceGroupIdent,
-                           final Timeout actorResponseWaitTime) {
+                           final Timeout actorResponseWaitTime, final DOMMountPointService mountService) {
         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
         this.serviceGroupIdent = serviceGroupIdent;
         this.actorResponseWaitTime = actorResponseWaitTime;
+        this.mountService = mountService;
 
         remoteDeviceId = NetconfTopologyUtils.createRemoteDeviceId(netconfTopologyDeviceSetup.getNode().getNodeId(),
                 netconfTopologyDeviceSetup.getNode().getAugmentation(NetconfNode.class));
 
         remoteDeviceConnector = new RemoteDeviceConnectorImpl(netconfTopologyDeviceSetup, remoteDeviceId,
-                actorResponseWaitTime);
+                actorResponseWaitTime, mountService);
 
         netconfNodeManager = createNodeDeviceManager();
     }
@@ -80,7 +83,7 @@ class NetconfTopologyContext implements ClusterSingletonService {
             final String masterAddress = Cluster.get(netconfTopologyDeviceSetup.getActorSystem()).selfAddress().toString();
             masterActorRef = netconfTopologyDeviceSetup.getActorSystem().actorOf(NetconfNodeActor.props(
                     netconfTopologyDeviceSetup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY, DEFAULT_SCHEMA_REPOSITORY,
-                    actorResponseWaitTime),
+                    actorResponseWaitTime, mountService),
                     NetconfTopologyUtils.createMasterActorName(remoteDeviceId.getName(), masterAddress));
 
             remoteDeviceConnector.startRemoteDeviceConnection(masterActorRef);
@@ -108,7 +111,7 @@ class NetconfTopologyContext implements ClusterSingletonService {
 
     private NetconfNodeManager createNodeDeviceManager() {
         final NetconfNodeManager ndm =
-                new NetconfNodeManager(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime);
+                new NetconfNodeManager(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime, mountService);
         ndm.registerDataTreeChangeListener(netconfTopologyDeviceSetup.getTopologyId(),
                 netconfTopologyDeviceSetup.getNode().getKey());
 
@@ -140,7 +143,8 @@ class NetconfTopologyContext implements ClusterSingletonService {
         if (!isMaster) {
             netconfNodeManager.refreshDevice(netconfTopologyDeviceSetup, remoteDeviceId);
         }
-        remoteDeviceConnector = new RemoteDeviceConnectorImpl(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime);
+        remoteDeviceConnector = new RemoteDeviceConnectorImpl(netconfTopologyDeviceSetup, remoteDeviceId,
+                actorResponseWaitTime, mountService);
 
         if (isMaster) {
             final Future<Object> future = Patterns.ask(masterActorRef, new RefreshSetupMasterActorData(
index 0ca6325f6293308ff8a11582173d713c4b33770a..1a9816c3f7707a2d9f4905887b2931728862d3c6 100644 (file)
@@ -29,9 +29,8 @@ import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
 import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
@@ -65,40 +64,38 @@ public class NetconfTopologyManager
     private final Map<InstanceIdentifier<Node>, ClusterSingletonServiceRegistration>
             clusterRegistrations = new HashMap<>();
 
-    private ListenerRegistration<NetconfTopologyManager> dataChangeListenerRegistration;
-
     private final DataBroker dataBroker;
     private final RpcProviderRegistry rpcProviderRegistry;
     private final ClusterSingletonServiceProvider clusterSingletonServiceProvider;
-    private final BindingAwareBroker bindingAwareBroker;
     private final ScheduledThreadPool keepaliveExecutor;
     private final ThreadPool processingExecutor;
-    private final Broker domBroker;
     private final ActorSystem actorSystem;
     private final EventExecutor eventExecutor;
     private final NetconfClientDispatcher clientDispatcher;
     private final String topologyId;
     private final Duration writeTxIdleTimeout;
+    private final DOMMountPointService mountPointService;
+
+    private ListenerRegistration<NetconfTopologyManager> dataChangeListenerRegistration;
 
     public NetconfTopologyManager(final DataBroker dataBroker, final RpcProviderRegistry rpcProviderRegistry,
                                   final ClusterSingletonServiceProvider clusterSingletonServiceProvider,
-                                  final BindingAwareBroker bindingAwareBroker,
                                   final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor,
-                                  final Broker domBroker, final ActorSystemProvider actorSystemProvider,
+                                  final ActorSystemProvider actorSystemProvider,
                                   final EventExecutor eventExecutor, final NetconfClientDispatcher clientDispatcher,
-                                  final String topologyId, final Config config) {
+                                  final String topologyId, final Config config,
+                                  final DOMMountPointService mountPointService) {
         this.dataBroker = Preconditions.checkNotNull(dataBroker);
         this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry);
         this.clusterSingletonServiceProvider = Preconditions.checkNotNull(clusterSingletonServiceProvider);
-        this.bindingAwareBroker = Preconditions.checkNotNull(bindingAwareBroker);
         this.keepaliveExecutor = Preconditions.checkNotNull(keepaliveExecutor);
         this.processingExecutor = Preconditions.checkNotNull(processingExecutor);
-        this.domBroker = Preconditions.checkNotNull(domBroker);
         this.actorSystem = Preconditions.checkNotNull(actorSystemProvider).getActorSystem();
         this.eventExecutor = Preconditions.checkNotNull(eventExecutor);
         this.clientDispatcher = Preconditions.checkNotNull(clientDispatcher);
         this.topologyId = Preconditions.checkNotNull(topologyId);
         this.writeTxIdleTimeout = Duration.apply(config.getWriteTransactionIdleTimeout(), TimeUnit.SECONDS);
+        this.mountPointService = mountPointService;
     }
 
     // Blueprint init method
@@ -155,9 +152,9 @@ public class NetconfTopologyManager
 
         final NetconfTopologyContext newNetconfTopologyContext =
                 new NetconfTopologyContext(createSetup(instanceIdentifier, node), serviceGroupIdent,
-                        actorResponseWaitTime);
+                        actorResponseWaitTime, mountPointService);
 
-        final ClusterSingletonServiceRegistration clusterSingletonServiceRegistration  =
+        final ClusterSingletonServiceRegistration clusterSingletonServiceRegistration =
                 clusterSingletonServiceProvider.registerClusterSingletonService(newNetconfTopologyContext);
 
         clusterRegistrations.put(instanceIdentifier, clusterSingletonServiceRegistration);
@@ -219,8 +216,8 @@ public class NetconfTopologyManager
 
         LOG.debug("Registering datastore listener");
         return dataBroker.registerDataTreeChangeListener(
-                        new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
-                                NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this);
+                new DataTreeIdentifier<>(LogicalDatastoreType.CONFIGURATION,
+                        NetconfTopologyUtils.createTopologyListPath(topologyId).child(Node.class)), this);
     }
 
     private void initTopology(final WriteTransaction wtx, final LogicalDatastoreType datastoreType, final String topologyId) {
@@ -240,10 +237,8 @@ public class NetconfTopologyManager
                 .setInstanceIdentifier(instanceIdentifier)
                 .setRpcProviderRegistry(rpcProviderRegistry)
                 .setNode(node)
-                .setBindingAwareBroker(bindingAwareBroker)
                 .setActorSystem(actorSystem)
                 .setEventExecutor(eventExecutor)
-                .setDomBroker(domBroker)
                 .setKeepaliveExecutor(keepaliveExecutor)
                 .setProcessingExecutor(processingExecutor)
                 .setTopologyId(topologyId)
index 416d9bdfd2ac0902a1f256349114bb5c9081a258..d5c9c25a17366aa6887c67762245d89acf4101b8 100644 (file)
@@ -25,12 +25,14 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
-import org.opendaylight.netconf.sal.connect.netconf.sal.tx.ReadWriteTx;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.netconf.topology.singleton.impl.tx.ProxyReadTransaction;
+import org.opendaylight.netconf.topology.singleton.impl.tx.ProxyReadWriteTransaction;
 import org.opendaylight.netconf.topology.singleton.impl.tx.ProxyWriteTransaction;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionReply;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionReply;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
@@ -49,7 +51,7 @@ public class ProxyDOMDataBroker implements DOMDataBroker {
      * @param actorSystem system
      * @param id          id
      * @param masterNode  {@link org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor} ref
-     * @param askTimeout ask timeout
+     * @param askTimeout  ask timeout
      */
     public ProxyDOMDataBroker(final ActorSystem actorSystem, final RemoteDeviceId id,
                               final ActorRef masterNode, final Timeout askTimeout) {
@@ -77,7 +79,18 @@ public class ProxyDOMDataBroker implements DOMDataBroker {
 
     @Override
     public DOMDataReadWriteTransaction newReadWriteTransaction() {
-        return new ReadWriteTx(newReadOnlyTransaction(), newWriteOnlyTransaction());
+        final Future<Object> txActorFuture = Patterns.ask(masterNode, new NewReadWriteTransactionRequest(), askTimeout);
+        try {
+            final Object msg = Await.result(txActorFuture, askTimeout.duration());
+            if (msg instanceof Throwable) {
+                throw (Throwable) msg;
+            }
+            Preconditions.checkState(msg instanceof NewReadWriteTransactionReply);
+            final NewReadWriteTransactionReply reply = (NewReadWriteTransactionReply) msg;
+            return new ProxyReadWriteTransaction(reply.getTxActor(), id, actorSystem, askTimeout);
+        } catch (final Throwable t) {
+            throw new IllegalStateException("Can't create ProxyReadTransaction", t);
+        }
     }
 
     @Override
index 9a9ad5e3572a9aca70c1a08c70b7cb0722c50a8e..02f9fe8aba3131a4a6ef86599a2f3511f9ba5a70 100644 (file)
@@ -25,6 +25,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Optional;
 import javax.annotation.Nullable;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.client.NetconfClientSessionListener;
 import org.opendaylight.netconf.client.conf.NetconfClientConfiguration;
@@ -69,21 +70,24 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
 
     private static final Logger LOG = LoggerFactory.getLogger(RemoteDeviceConnectorImpl.class);
 
-    private final Timeout actorResponseWaitTime;
-
     // Initializes default constant instances for the case when the default schema repository
     // directory cache/schema is used.
 
     private final NetconfTopologySetup netconfTopologyDeviceSetup;
     private final RemoteDeviceId remoteDeviceId;
+    private final DOMMountPointService mountService;
+    private final Timeout actorResponseWaitTime;
+
     private NetconfConnectorDTO deviceCommunicatorDTO;
 
     public RemoteDeviceConnectorImpl(final NetconfTopologySetup netconfTopologyDeviceSetup,
-                                     final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime) {
+                                     final RemoteDeviceId remoteDeviceId, final Timeout actorResponseWaitTime,
+                                     final DOMMountPointService mountService) {
 
         this.netconfTopologyDeviceSetup = Preconditions.checkNotNull(netconfTopologyDeviceSetup);
         this.remoteDeviceId = remoteDeviceId;
         this.actorResponseWaitTime = actorResponseWaitTime;
+        this.mountService = mountService;
     }
 
     @Override
@@ -138,8 +142,8 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector {
                 ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema();
 
         RemoteDeviceHandler<NetconfSessionPreferences> salFacade = new MasterSalFacade(remoteDeviceId,
-                netconfTopologyDeviceSetup.getDomBroker(), netconfTopologyDeviceSetup.getBindingAwareBroker(),
-                netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime);
+                netconfTopologyDeviceSetup.getActorSystem(), deviceContextActorRef, actorResponseWaitTime,
+                mountService, netconfTopologyDeviceSetup.getDataBroker());
         if (keepaliveDelay > 0) {
             LOG.info("{}: Adding keepalive facade.", remoteDeviceId);
             salFacade = new KeepaliveSalFacade(remoteDeviceId, salFacade,
index 92d7e1a36ac6f8228075935ae6d32d0515c2a366..ed4a27530c807de19270e24d861716765f516c49 100644 (file)
@@ -11,8 +11,8 @@ package org.opendaylight.netconf.topology.singleton.impl;
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
 import akka.util.Timeout;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceNotificationService;
 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceSalProvider;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
@@ -26,25 +26,17 @@ public class SlaveSalFacade {
 
     private final RemoteDeviceId id;
     private final NetconfDeviceSalProvider salProvider;
-
     private final ActorSystem actorSystem;
     private final Timeout actorResponseWaitTime;
 
     public SlaveSalFacade(final RemoteDeviceId id,
-                          final Broker domBroker,
                           final ActorSystem actorSystem,
-                          final Timeout actorResponseWaitTime) {
+                          final Timeout actorResponseWaitTime,
+                          final DOMMountPointService mountPointService) {
         this.id = id;
-        this.salProvider = new NetconfDeviceSalProvider(id);
+        this.salProvider = new NetconfDeviceSalProvider(id, mountPointService);
         this.actorSystem = actorSystem;
         this.actorResponseWaitTime = actorResponseWaitTime;
-
-        registerToSal(domBroker);
-    }
-
-    private void registerToSal(final Broker domRegistryDependency) {
-        domRegistryDependency.registerProvider(salProvider);
-
     }
 
     public void registerSlaveMountPoint(final SchemaContext remoteSchemaContext, final DOMRpcService deviceRpc,
index fbd0422b692c66129f336dbb0f38bd8440ef31fe..dd5e9129279e9de4fc28e9344969b8e06b3be707 100644 (file)
@@ -25,7 +25,9 @@ import org.opendaylight.controller.cluster.schema.provider.impl.RemoteSchemaProv
 import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 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;
@@ -47,6 +49,8 @@ import org.opendaylight.netconf.topology.singleton.messages.rpc.InvokeRpcMessage
 import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyResultResponse;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionReply;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadTransactionRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.NewReadWriteTransactionRequest;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionReply;
 import org.opendaylight.netconf.topology.singleton.messages.transactions.NewWriteTransactionRequest;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@@ -74,6 +78,7 @@ public class NetconfNodeActor extends UntypedActor {
     private final SchemaRepository schemaRepository;
     private final Timeout actorResponseWaitTime;
     private final Duration writeTxIdleTimeout;
+    private final DOMMountPointService mountPointService;
 
     private RemoteDeviceId id;
     private NetconfTopologySetup setup;
@@ -87,20 +92,24 @@ public class NetconfNodeActor extends UntypedActor {
 
     public static Props props(final NetconfTopologySetup setup,
                               final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
-                              final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime) {
+                              final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
+                              final DOMMountPointService mountPointService) {
         return Props.create(NetconfNodeActor.class, () ->
-                new NetconfNodeActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime));
+                new NetconfNodeActor(setup, id, schemaRegistry, schemaRepository, actorResponseWaitTime,
+                        mountPointService));
     }
 
     private NetconfNodeActor(final NetconfTopologySetup setup,
                              final RemoteDeviceId id, final SchemaSourceRegistry schemaRegistry,
-                             final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime) {
+                             final SchemaRepository schemaRepository, final Timeout actorResponseWaitTime,
+                             final DOMMountPointService mountPointService) {
         this.setup = setup;
         this.id = id;
         this.schemaRegistry = schemaRegistry;
         this.schemaRepository = schemaRepository;
         this.actorResponseWaitTime = actorResponseWaitTime;
         this.writeTxIdleTimeout = setup.getIdleTimeout();
+        this.mountPointService = mountPointService;
     }
 
     @Override
@@ -146,6 +155,14 @@ public class NetconfNodeActor extends UntypedActor {
                 sender().tell(t, self());
             }
 
+        } else if (message instanceof NewReadWriteTransactionRequest) {
+            try {
+                final DOMDataReadWriteTransaction tx = deviceDataBroker.newReadWriteTransaction();
+                final ActorRef txActor = context().actorOf(ReadWriteTransactionActor.props(tx, writeTxIdleTimeout));
+                sender().tell(new NewReadWriteTransactionReply(txActor), self());
+            } catch (final Throwable t) {
+                sender().tell(t, self());
+            }
         } else if (message instanceof InvokeRpcMessage) { // master
 
             final InvokeRpcMessage invokeRpcMessage = ((InvokeRpcMessage) message);
@@ -225,7 +242,8 @@ public class NetconfNodeActor extends UntypedActor {
             slaveSalManager.close();
         }
         closeSchemaSourceRegistrations();
-        slaveSalManager = new SlaveSalFacade(id, setup.getDomBroker(), setup.getActorSystem(), actorResponseWaitTime);
+        slaveSalManager = new SlaveSalFacade(id, setup.getActorSystem(), actorResponseWaitTime,
+                mountPointService);
 
         final CheckedFuture<SchemaContext, SchemaResolutionException> remoteSchemaContext =
                 getSchemaContext(masterReference);
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java
new file mode 100644 (file)
index 0000000..0ef08f0
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * 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.topology.singleton.impl.actors;
+
+import akka.actor.ActorRef;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+class ReadAdapter {
+
+    private final DOMDataReadTransaction tx;
+
+    public ReadAdapter(final DOMDataReadTransaction tx) {
+        this.tx = tx;
+    }
+
+    public void handle(final Object message, final ActorRef sender, final ActorRef self) throws Throwable {
+        if (message instanceof ReadRequest) {
+
+            final ReadRequest readRequest = (ReadRequest) message;
+            final YangInstanceIdentifier path = readRequest.getPath();
+            final LogicalDatastoreType store = readRequest.getStore();
+            read(path, store, sender, self);
+
+        } else if (message instanceof ExistsRequest) {
+            final ExistsRequest readRequest = (ExistsRequest) message;
+            final YangInstanceIdentifier path = readRequest.getPath();
+            final LogicalDatastoreType store = readRequest.getStore();
+            exists(path, store, sender, self);
+        }
+    }
+
+    private void read(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
+                      final ActorRef self) {
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(store, path);
+        Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
+
+            @Override
+            public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
+                if (!result.isPresent()) {
+                    sender.tell(new EmptyReadResponse(), self);
+                    return;
+                }
+                sender.tell(new NormalizedNodeMessage(path, result.get()), self);
+            }
+
+            @Override
+            public void onFailure(@Nonnull final Throwable throwable) {
+                sender.tell(throwable, self);
+            }
+        });
+    }
+
+    private void exists(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
+                        final ActorRef self) {
+        final CheckedFuture<Boolean, ReadFailedException> readFuture = tx.exists(store, path);
+        Futures.addCallback(readFuture, new FutureCallback<Boolean>() {
+            @Override
+            public void onSuccess(final Boolean result) {
+                if (result == null) {
+                    sender.tell(false, self);
+                } else {
+                    sender.tell(result, self);
+                }
+            }
+
+            @Override
+            public void onFailure(@Nonnull final Throwable throwable) {
+                sender.tell(throwable, self);
+            }
+        });
+    }
+}
index b6bf651ea277518e80753b77f177922fd94d69c1..777140cd4fc2974fdc4e9f6aad71d09a62ad3b7c 100644 (file)
@@ -8,30 +8,21 @@
 
 package org.opendaylight.netconf.topology.singleton.impl.actors;
 
-import akka.actor.ActorRef;
 import akka.actor.Props;
 import akka.actor.UntypedActor;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import javax.annotation.Nonnull;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadActorMessage;
 
 /**
  * ReadTransactionActor is an interface to device's {@link DOMDataReadOnlyTransaction} for cluster nodes.
  */
 public class ReadTransactionActor extends UntypedActor {
 
-    private final DOMDataReadOnlyTransaction tx;
+    private final ReadAdapter readAdapter;
+
+    private ReadTransactionActor(final DOMDataReadOnlyTransaction tx) {
+        readAdapter = new ReadAdapter(tx);
+    }
 
     /**
      * Creates new actor Props.
@@ -43,68 +34,13 @@ public class ReadTransactionActor extends UntypedActor {
         return Props.create(ReadTransactionActor.class, () -> new ReadTransactionActor(tx));
     }
 
-    private ReadTransactionActor(final DOMDataReadOnlyTransaction tx) {
-        this.tx = tx;
-    }
-
     @Override
     public void onReceive(final Object message) throws Throwable {
-        if (message instanceof ReadRequest) {
-
-            final ReadRequest readRequest = (ReadRequest) message;
-            final YangInstanceIdentifier path = readRequest.getPath();
-            final LogicalDatastoreType store = readRequest.getStore();
-            read(path, store, sender(), self());
-
-        } else if (message instanceof ExistsRequest) {
-            final ExistsRequest readRequest = (ExistsRequest) message;
-            final YangInstanceIdentifier path = readRequest.getPath();
-            final LogicalDatastoreType store = readRequest.getStore();
-            exists(path, store, sender(), self());
-
+        if (message instanceof ReadActorMessage) {
+            readAdapter.handle(message, sender(), self());
         } else {
             unhandled(message);
         }
     }
 
-    private void read(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
-                      final ActorRef self) {
-        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(store, path);
-        Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
-
-            @Override
-            public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
-                if (!result.isPresent()) {
-                    sender.tell(new EmptyReadResponse(), self);
-                    return;
-                }
-                sender.tell(new NormalizedNodeMessage(path, result.get()), self);
-            }
-
-            @Override
-            public void onFailure(@Nonnull final Throwable throwable) {
-                sender.tell(throwable, self);
-            }
-        });
-    }
-
-    private void exists(final YangInstanceIdentifier path, final LogicalDatastoreType store, final ActorRef sender,
-                        final ActorRef self) {
-        final CheckedFuture<Boolean, ReadFailedException> readFuture = tx.exists(store, path);
-        Futures.addCallback(readFuture, new FutureCallback<Boolean>() {
-            @Override
-            public void onSuccess(final Boolean result) {
-                if (result == null) {
-                    sender.tell(false, self);
-                } else {
-                    sender.tell(result, self);
-                }
-            }
-
-            @Override
-            public void onFailure(@Nonnull final Throwable throwable) {
-                sender.tell(throwable, self);
-            }
-        });
-    }
 }
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActor.java
new file mode 100644 (file)
index 0000000..1c263c0
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * 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.topology.singleton.impl.actors;
+
+import akka.actor.Props;
+import akka.actor.ReceiveTimeout;
+import akka.actor.UntypedActor;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadActorMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.WriteActorMessage;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.duration.Duration;
+
+public class ReadWriteTransactionActor extends UntypedActor {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ReadWriteTransactionActor.class);
+
+    private final DOMDataReadWriteTransaction tx;
+    private final long idleTimeout;
+    private final ReadAdapter readAdapter;
+    private final WriteAdapter writeAdapter;
+
+    private ReadWriteTransactionActor(final DOMDataReadWriteTransaction tx, final Duration idleTimeout) {
+        this.tx = tx;
+        this.idleTimeout = idleTimeout.toSeconds();
+        if (this.idleTimeout > 0) {
+            context().setReceiveTimeout(idleTimeout);
+        }
+        readAdapter = new ReadAdapter(tx);
+        writeAdapter = new WriteAdapter(tx);
+    }
+
+    /**
+     * Creates new actor Props.
+     *
+     * @param tx          delegate device read write transaction
+     * @param idleTimeout idle time in seconds, after which transaction is closed automatically
+     * @return props
+     */
+    static Props props(final DOMDataReadWriteTransaction tx, final Duration idleTimeout) {
+        return Props.create(ReadWriteTransactionActor.class, () -> new ReadWriteTransactionActor(tx, idleTimeout));
+    }
+
+    @Override
+    public void onReceive(final Object message) throws Throwable {
+        if (message instanceof ReadActorMessage) {
+            readAdapter.handle(message, sender(), self());
+        } else if (message instanceof WriteActorMessage) {
+            writeAdapter.handle(message, sender(), context(), self());
+        } else if (message instanceof ReceiveTimeout) {
+            LOG.warn("Haven't received any message for {} seconds, cancelling transaction and stopping actor",
+                    idleTimeout);
+            tx.cancel();
+            context().stop(self());
+        } else {
+            unhandled(message);
+        }
+    }
+
+}
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteAdapter.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/WriteAdapter.java
new file mode 100644 (file)
index 0000000..7e762bf
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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.topology.singleton.impl.actors;
+
+import akka.actor.ActorContext;
+import akka.actor.ActorRef;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
+import javax.annotation.Nonnull;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+
+class WriteAdapter {
+    private final DOMDataWriteTransaction tx;
+
+    public WriteAdapter(final DOMDataWriteTransaction tx) {
+        this.tx = tx;
+    }
+
+    private void cancel(final ActorContext context, final ActorRef sender, final ActorRef self) {
+        final boolean cancelled = tx.cancel();
+        sender.tell(cancelled, self);
+        context.stop(self);
+    }
+
+    private void submit(final ActorRef requester, final ActorRef self, final ActorContext context) {
+        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+        context.stop(self);
+        Futures.addCallback(submitFuture, new FutureCallback<Void>() {
+            @Override
+            public void onSuccess(final Void result) {
+                requester.tell(new SubmitReply(), self);
+            }
+
+            @Override
+            public void onFailure(@Nonnull final Throwable throwable) {
+                requester.tell(throwable, self);
+            }
+        });
+    }
+
+    public void handle(final Object message, final ActorRef sender, final ActorContext context, final ActorRef self) {
+        if (message instanceof MergeRequest) {
+            final MergeRequest mergeRequest = (MergeRequest) message;
+            final NormalizedNodeMessage data = mergeRequest.getNormalizedNodeMessage();
+            tx.merge(mergeRequest.getStore(), data.getIdentifier(), data.getNode());
+        } else if (message instanceof PutRequest) {
+            final PutRequest putRequest = (PutRequest) message;
+            final NormalizedNodeMessage data = putRequest.getNormalizedNodeMessage();
+            tx.put(putRequest.getStore(), data.getIdentifier(), data.getNode());
+        } else if (message instanceof DeleteRequest) {
+            final DeleteRequest deleteRequest = (DeleteRequest) message;
+            tx.delete(deleteRequest.getStore(), deleteRequest.getPath());
+        } else if (message instanceof CancelRequest) {
+            cancel(context, sender, self);
+        } else if (message instanceof SubmitRequest) {
+            submit(sender, self, context);
+        }
+    }
+}
index 008559ec9bfc39b4c0b930f07b5c836ec7bb50c2..8a1f53af5297a0772d4e8ca3f80656c1fbe532a4 100644 (file)
@@ -8,24 +8,12 @@
 
 package org.opendaylight.netconf.topology.singleton.impl.actors;
 
-import akka.actor.ActorRef;
 import akka.actor.Props;
 import akka.actor.ReceiveTimeout;
 import akka.actor.UntypedActor;
-import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import javax.annotation.Nonnull;
-import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.WriteActorMessage;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import scala.concurrent.duration.Duration;
@@ -39,11 +27,21 @@ public class WriteTransactionActor extends UntypedActor {
 
     private final DOMDataWriteTransaction tx;
     private final long idleTimeout;
+    private final WriteAdapter writeAdapter;
+
+    private WriteTransactionActor(final DOMDataWriteTransaction tx, final Duration idleTimeout) {
+        this.tx = tx;
+        this.idleTimeout = idleTimeout.toSeconds();
+        if (this.idleTimeout > 0) {
+            context().setReceiveTimeout(idleTimeout);
+        }
+        writeAdapter = new WriteAdapter(tx);
+    }
 
     /**
      * Creates new actor Props.
      *
-     * @param tx delegate device write transaction
+     * @param tx          delegate device write transaction
      * @param idleTimeout idle time in seconds, after which transaction is closed automatically
      * @return props
      */
@@ -51,31 +49,10 @@ public class WriteTransactionActor extends UntypedActor {
         return Props.create(WriteTransactionActor.class, () -> new WriteTransactionActor(tx, idleTimeout));
     }
 
-    private WriteTransactionActor(final DOMDataWriteTransaction tx, final Duration idleTimeout) {
-        this.tx = tx;
-        this.idleTimeout = idleTimeout.toSeconds();
-        if (this.idleTimeout > 0) {
-            context().setReceiveTimeout(idleTimeout);
-        }
-    }
-
     @Override
     public void onReceive(final Object message) throws Throwable {
-        if (message instanceof MergeRequest) {
-            final MergeRequest mergeRequest = (MergeRequest) message;
-            final NormalizedNodeMessage data = mergeRequest.getNormalizedNodeMessage();
-            tx.merge(mergeRequest.getStore(), data.getIdentifier(), data.getNode());
-        } else if (message instanceof PutRequest) {
-            final PutRequest putRequest = (PutRequest) message;
-            final NormalizedNodeMessage data = putRequest.getNormalizedNodeMessage();
-            tx.put(putRequest.getStore(), data.getIdentifier(), data.getNode());
-        } else if (message instanceof DeleteRequest) {
-            final DeleteRequest deleteRequest = (DeleteRequest) message;
-            tx.delete(deleteRequest.getStore(), deleteRequest.getPath());
-        } else if (message instanceof CancelRequest) {
-            cancel();
-        } else if (message instanceof SubmitRequest) {
-            submit(sender(), self());
+        if (message instanceof WriteActorMessage) {
+            writeAdapter.handle(message, sender(), context(), self());
         } else if (message instanceof ReceiveTimeout) {
             LOG.warn("Haven't received any message for {} seconds, cancelling transaction and stopping actor",
                     idleTimeout);
@@ -86,25 +63,5 @@ public class WriteTransactionActor extends UntypedActor {
         }
     }
 
-    private void cancel() {
-        final boolean cancelled = tx.cancel();
-        sender().tell(cancelled, self());
-        context().stop(self());
-    }
-
-    private void submit(final ActorRef requester, final ActorRef self) {
-        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
-        context().stop(self);
-        Futures.addCallback(submitFuture, new FutureCallback<Void>() {
-            @Override
-            public void onSuccess(final Void result) {
-                requester.tell(new SubmitReply(), self);
-            }
 
-            @Override
-            public void onFailure(@Nonnull final Throwable throwable) {
-                requester.tell(throwable, self);
-            }
-        });
-    }
 }
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadAdapter.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadAdapter.java
new file mode 100644 (file)
index 0000000..b500e0d
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ * 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.topology.singleton.impl.tx;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.dispatch.OnComplete;
+import akka.pattern.Patterns;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.SettableFuture;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.Future;
+
+class ProxyReadAdapter {
+    private static final Logger LOG = LoggerFactory.getLogger(ProxyReadAdapter.class);
+
+    private final ActorRef masterTxActor;
+    private final RemoteDeviceId id;
+    private final ActorSystem actorSystem;
+    private final Timeout askTimeout;
+
+    public ProxyReadAdapter(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
+                            final Timeout askTimeout) {
+        this.masterTxActor = masterTxActor;
+        this.id = id;
+        this.actorSystem = actorSystem;
+        this.askTimeout = askTimeout;
+    }
+
+    public void close() {
+        //noop
+    }
+
+    public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
+                                                                                   final YangInstanceIdentifier path) {
+        LOG.trace("{}: Read {} via NETCONF: {}", id, store, path);
+
+        final Future<Object> future = Patterns.ask(masterTxActor, new ReadRequest(store, path), askTimeout);
+        final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create();
+        future.onComplete(new OnComplete<Object>() {
+            @Override
+            public void onComplete(final Throwable failure,
+                                   final Object success) throws Throwable {
+                if (failure != null) { // ask timeout
+                    final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
+                    settableFuture.setException(exception);
+                    return;
+                }
+                if (success instanceof Throwable) { // Error sended by master
+                    settableFuture.setException((Throwable) success);
+                    return;
+                }
+                if (success instanceof EmptyReadResponse) {
+                    settableFuture.set(Optional.absent());
+                    return;
+                }
+                if (success instanceof NormalizedNodeMessage) {
+                    final NormalizedNodeMessage data = (NormalizedNodeMessage) success;
+                    settableFuture.set(Optional.of(data.getNode()));
+                }
+            }
+        }, actorSystem.dispatcher());
+        return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+    }
+
+    public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+                                                              final YangInstanceIdentifier path) {
+        final Future<Object> existsScalaFuture =
+                Patterns.ask(masterTxActor, new ExistsRequest(store, path), askTimeout);
+
+        LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);
+
+        final SettableFuture<Boolean> settableFuture = SettableFuture.create();
+        existsScalaFuture.onComplete(new OnComplete<Object>() {
+            @Override
+            public void onComplete(final Throwable failure, final Object success) throws Throwable {
+                if (failure != null) { // ask timeout
+                    final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
+                    settableFuture.setException(exception);
+                    return;
+                }
+                if (success instanceof Throwable) {
+                    settableFuture.setException((Throwable) success);
+                    return;
+                }
+                settableFuture.set((Boolean) success);
+            }
+        }, actorSystem.dispatcher());
+        return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+    }
+
+}
index 0756f33ddfbc445c64ed72c24fb4a3ccb21ac068..9ef11bc63d0b2f4361180e8dd719b889f174c2f1 100644 (file)
@@ -10,27 +10,15 @@ package org.opendaylight.netconf.topology.singleton.impl.tx;
 
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
-import akka.dispatch.OnComplete;
-import akka.pattern.Patterns;
 import akka.util.Timeout;
 import com.google.common.base.Optional;
 import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.SettableFuture;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
 
 /**
  * ProxyReadTransaction uses provided {@link ActorRef} to delegate method calls to master
@@ -38,12 +26,7 @@ import scala.concurrent.Future;
  */
 public class ProxyReadTransaction implements DOMDataReadOnlyTransaction {
 
-    private static final Logger LOG = LoggerFactory.getLogger(ProxyReadTransaction.class);
-
-    private final ActorRef masterTxActor;
-    private final RemoteDeviceId id;
-    private final ActorSystem actorSystem;
-    private final Timeout askTimeout;
+    private final ProxyReadAdapter delegate;
 
     /**
      * @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadTransactionActor} ref
@@ -53,75 +36,24 @@ public class ProxyReadTransaction implements DOMDataReadOnlyTransaction {
      */
     public ProxyReadTransaction(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
                                 final Timeout askTimeout) {
-        this.masterTxActor = masterTxActor;
-        this.id = id;
-        this.actorSystem = actorSystem;
-        this.askTimeout = askTimeout;
+        delegate = new ProxyReadAdapter(masterTxActor, id, actorSystem, askTimeout);
     }
 
     @Override
     public void close() {
-        //noop
+        delegate.close();
     }
 
     @Override
     public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
                                                                                    final YangInstanceIdentifier path) {
-        LOG.trace("{}: Read {} via NETCONF: {}", id, store, path);
-
-        final Future<Object> future = Patterns.ask(masterTxActor, new ReadRequest(store, path), askTimeout);
-        final SettableFuture<Optional<NormalizedNode<?, ?>>> settableFuture = SettableFuture.create();
-        future.onComplete(new OnComplete<Object>() {
-            @Override
-            public void onComplete(final Throwable failure,
-                                   final Object success) throws Throwable {
-                if (failure != null) { // ask timeout
-                    final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
-                    settableFuture.setException(exception);
-                    return;
-                }
-                if (success instanceof Throwable) { // Error sended by master
-                    settableFuture.setException((Throwable) success);
-                    return;
-                }
-                if (success instanceof EmptyReadResponse) {
-                    settableFuture.set(Optional.absent());
-                    return;
-                }
-                if (success instanceof NormalizedNodeMessage) {
-                    final NormalizedNodeMessage data = (NormalizedNodeMessage) success;
-                    settableFuture.set(Optional.of(data.getNode()));
-                }
-            }
-        }, actorSystem.dispatcher());
-        return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+        return delegate.read(store, path);
     }
 
     @Override
     public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
                                                               final YangInstanceIdentifier path) {
-        final Future<Object> existsScalaFuture =
-                Patterns.ask(masterTxActor, new ExistsRequest(store, path), askTimeout);
-
-        LOG.trace("{}: Exists {} via NETCONF: {}", id, store, path);
-
-        final SettableFuture<Boolean> settableFuture = SettableFuture.create();
-        existsScalaFuture.onComplete(new OnComplete<Object>() {
-            @Override
-            public void onComplete(final Throwable failure, final Object success) throws Throwable {
-                if (failure != null) { // ask timeout
-                    final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
-                    settableFuture.setException(exception);
-                    return;
-                }
-                if (success instanceof Throwable) {
-                    settableFuture.setException((Throwable) success);
-                    return;
-                }
-                settableFuture.set((Boolean) success);
-            }
-        }, actorSystem.dispatcher());
-        return Futures.makeChecked(settableFuture, ReadFailedException.MAPPER);
+        return delegate.exists(store, path);
     }
 
 
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransaction.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransaction.java
new file mode 100644 (file)
index 0000000..2791389
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * 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.topology.singleton.impl.tx;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * ProxyReadWriteTransaction uses provided {@link ActorRef} to delegate method calls to master
+ * {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadWriteTransactionActor}.
+ */
+public class ProxyReadWriteTransaction implements DOMDataReadWriteTransaction {
+
+    private final ProxyReadAdapter delegateRead;
+    private final ProxyWriteAdapter delegateWrite;
+
+    /**
+     * @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.ReadWriteTransactionActor} ref
+     * @param id            device id
+     * @param actorSystem   system
+     * @param askTimeout
+     */
+    public ProxyReadWriteTransaction(final ActorRef masterTxActor, final RemoteDeviceId id,
+                                     final ActorSystem actorSystem, final Timeout askTimeout) {
+        delegateRead = new ProxyReadAdapter(masterTxActor, id, actorSystem, askTimeout);
+        delegateWrite = new ProxyWriteAdapter(masterTxActor, id, actorSystem, askTimeout);
+    }
+
+    @Override
+    public boolean cancel() {
+        return delegateWrite.cancel();
+    }
+
+    @Override
+    public ListenableFuture<RpcResult<TransactionStatus>> commit() {
+        return delegateWrite.commit(getIdentifier());
+    }
+
+    @Override
+    public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
+                                                                                   final YangInstanceIdentifier path) {
+        return delegateRead.read(store, path);
+    }
+
+    @Override
+    public CheckedFuture<Boolean, ReadFailedException> exists(final LogicalDatastoreType store,
+                                                              final YangInstanceIdentifier path) {
+        return delegateRead.exists(store, path);
+    }
+
+    @Override
+    public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
+        delegateWrite.delete(store, path);
+    }
+
+    @Override
+    public CheckedFuture<Void, TransactionCommitFailedException> submit() {
+        return delegateWrite.submit(getIdentifier());
+    }
+
+    @Override
+    public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                    final NormalizedNode<?, ?> data) {
+        delegateWrite.put(store, path, data, getIdentifier());
+    }
+
+    @Override
+    public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                      final NormalizedNode<?, ?> data) {
+        delegateWrite.merge(store, path, data, getIdentifier());
+    }
+
+    @Override
+    public Object getIdentifier() {
+        return this;
+    }
+}
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteAdapter.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyWriteAdapter.java
new file mode 100644 (file)
index 0000000..e9be9e7
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * 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.topology.singleton.impl.tx;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.dispatch.OnComplete;
+import akka.pattern.Patterns;
+import akka.util.Timeout;
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
+import java.util.concurrent.atomic.AtomicBoolean;
+import javax.annotation.Nullable;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitFailedReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+
+public class ProxyWriteAdapter {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ProxyWriteAdapter.class);
+
+    private final ActorRef masterTxActor;
+    private final RemoteDeviceId id;
+    private final ActorSystem actorSystem;
+    private final AtomicBoolean opened = new AtomicBoolean(true);
+    private final Timeout askTimeout;
+
+    public ProxyWriteAdapter(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
+                             final Timeout askTimeout) {
+        this.masterTxActor = masterTxActor;
+        this.id = id;
+        this.actorSystem = actorSystem;
+        this.askTimeout = askTimeout;
+    }
+
+    public boolean cancel() {
+        if (!opened.compareAndSet(true, false)) {
+            return false;
+        }
+        final Future<Object> cancelScalaFuture =
+                Patterns.ask(masterTxActor, new CancelRequest(), askTimeout);
+
+        LOG.trace("{}: Cancel {} via NETCONF", id);
+
+        try {
+            // here must be Await because AsyncWriteTransaction do not return future
+            return (boolean) Await.result(cancelScalaFuture, askTimeout.duration());
+        } catch (final Exception e) {
+            return false;
+        }
+    }
+
+    public CheckedFuture<Void, TransactionCommitFailedException> submit(final Object identifier) {
+        if (!opened.compareAndSet(true, false)) {
+            throw new IllegalStateException(id + ": Transaction" + identifier + " is closed");
+        }
+        final Future<Object> submitScalaFuture =
+                Patterns.ask(masterTxActor, new SubmitRequest(), askTimeout);
+
+        LOG.trace("{}: Submit {} via NETCONF", id);
+
+        final SettableFuture<Void> settableFuture = SettableFuture.create();
+        submitScalaFuture.onComplete(new OnComplete<Object>() {
+            @Override
+            public void onComplete(final Throwable failure, final Object success) throws Throwable {
+                if (failure != null) { // ask timeout
+                    final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
+                    settableFuture.setException(exception);
+                    return;
+                }
+                if (success instanceof Throwable) {
+                    settableFuture.setException((Throwable) success);
+                } else {
+                    if (success instanceof SubmitFailedReply) {
+                        LOG.error("{}: Transaction was not submitted because already closed.", id);
+                    }
+                    settableFuture.set(null);
+                }
+            }
+        }, actorSystem.dispatcher());
+
+        return Futures.makeChecked(settableFuture, new Function<Exception, TransactionCommitFailedException>() {
+            @Nullable
+            @Override
+            public TransactionCommitFailedException apply(@Nullable final Exception input) {
+                final String message = "Submit of transaction " + identifier + " failed";
+                return new TransactionCommitFailedException(message, input);
+            }
+        });
+    }
+
+    public ListenableFuture<RpcResult<TransactionStatus>> commit(final Object identifier) {
+        LOG.trace("{}: Commit", id);
+
+        final CheckedFuture<Void, TransactionCommitFailedException> submit = submit(identifier);
+        return Futures.transform(submit, new Function<Void, RpcResult<TransactionStatus>>() {
+            @Nullable
+            @Override
+            public RpcResult<TransactionStatus> apply(@Nullable final Void input) {
+                return RpcResultBuilder.success(TransactionStatus.SUBMITED).build();
+            }
+        });
+    }
+
+    public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier identifier) {
+        Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, identifier);
+        LOG.trace("{}: Delete {} via NETCONF: {}", id, store, identifier);
+        masterTxActor.tell(new DeleteRequest(store, identifier), ActorRef.noSender());
+    }
+
+    public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                    final NormalizedNode<?, ?> data, final Object identifier) {
+        Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, identifier);
+        final NormalizedNodeMessage msg = new NormalizedNodeMessage(path, data);
+        LOG.trace("{}: Put {} via NETCONF: {} with payload {}", id, store, path, data);
+        masterTxActor.tell(new PutRequest(store, msg), ActorRef.noSender());
+    }
+
+    public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path,
+                      final NormalizedNode<?, ?> data, final Object identifier) {
+        Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, identifier);
+        final NormalizedNodeMessage msg = new NormalizedNodeMessage(path, data);
+        LOG.trace("{}: Merge {} via NETCONF: {} with payload {}", id, store, path, data);
+        masterTxActor.tell(new MergeRequest(store, msg), ActorRef.noSender());
+    }
+
+}
index 072f6227b4fc7768c0d3e3a945edcf02e97d3194..eb64eaf8860fee2c7747dc45310491f8dfebe748 100644 (file)
@@ -10,38 +10,17 @@ package org.opendaylight.netconf.topology.singleton.impl.tx;
 
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
-import akka.dispatch.OnComplete;
-import akka.pattern.Patterns;
 import akka.util.Timeout;
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.CheckedFuture;
-import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.concurrent.atomic.AtomicBoolean;
-import javax.annotation.Nullable;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
-import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils;
-import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitFailedReply;
-import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
 import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Await;
-import scala.concurrent.Future;
 
 /**
  * ProxyWriteTransaction uses provided {@link ActorRef} to delegate method calls to master
@@ -49,13 +28,7 @@ import scala.concurrent.Future;
  */
 public class ProxyWriteTransaction implements DOMDataWriteTransaction {
 
-    private static final Logger LOG = LoggerFactory.getLogger(ProxyWriteTransaction.class);
-
-    private final ActorRef masterTxActor;
-    private final RemoteDeviceId id;
-    private final ActorSystem actorSystem;
-    private final AtomicBoolean opened = new AtomicBoolean(true);
-    private final Timeout askTimeout;
+    private final ProxyWriteAdapter proxyWriteAdapter;
 
     /**
      * @param masterTxActor {@link org.opendaylight.netconf.topology.singleton.impl.actors.WriteTransactionActor} ref
@@ -65,107 +38,39 @@ public class ProxyWriteTransaction implements DOMDataWriteTransaction {
      */
     public ProxyWriteTransaction(final ActorRef masterTxActor, final RemoteDeviceId id, final ActorSystem actorSystem,
                                  final Timeout askTimeout) {
-        this.masterTxActor = masterTxActor;
-        this.id = id;
-        this.actorSystem = actorSystem;
-        this.askTimeout = askTimeout;
+        proxyWriteAdapter = new ProxyWriteAdapter(masterTxActor, id, actorSystem, askTimeout);
     }
 
     @Override
     public boolean cancel() {
-        if (!opened.compareAndSet(true, false)) {
-            return false;
-        }
-        final Future<Object> cancelScalaFuture =
-                Patterns.ask(masterTxActor, new CancelRequest(), askTimeout);
-
-        LOG.trace("{}: Cancel {} via NETCONF", id);
-
-        try {
-            // here must be Await because AsyncWriteTransaction do not return future
-            return (boolean) Await.result(cancelScalaFuture, askTimeout.duration());
-        } catch (final Exception e) {
-            return false;
-        }
+        return proxyWriteAdapter.cancel();
     }
 
     @Override
     public CheckedFuture<Void, TransactionCommitFailedException> submit() {
-        if (!opened.compareAndSet(true, false)) {
-            throw new IllegalStateException(id + ": Transaction" + getIdentifier() + " is closed");
-        }
-        final Future<Object> submitScalaFuture =
-                Patterns.ask(masterTxActor, new SubmitRequest(), askTimeout);
-
-        LOG.trace("{}: Submit {} via NETCONF", id);
-
-        final SettableFuture<Void> settableFuture = SettableFuture.create();
-        submitScalaFuture.onComplete(new OnComplete<Object>() {
-            @Override
-            public void onComplete(final Throwable failure, final Object success) throws Throwable {
-                if (failure != null) { // ask timeout
-                    final Exception exception = NetconfTopologyUtils.createMasterIsDownException(id);
-                    settableFuture.setException(exception);
-                    return;
-                }
-                if (success instanceof Throwable) {
-                    settableFuture.setException((Throwable) success);
-                } else {
-                    if (success instanceof SubmitFailedReply) {
-                        LOG.error("{}: Transaction was not submitted because already closed.", id);
-                    }
-                    settableFuture.set(null);
-                }
-            }
-        }, actorSystem.dispatcher());
-
-        return Futures.makeChecked(settableFuture, new Function<Exception, TransactionCommitFailedException>() {
-            @Nullable
-            @Override
-            public TransactionCommitFailedException apply(@Nullable final Exception input) {
-                final String message = "Submit of transaction " + getIdentifier() + " failed";
-                return new TransactionCommitFailedException(message, input);
-            }
-        });
+        return proxyWriteAdapter.submit(getIdentifier());
     }
 
     @Override
     public ListenableFuture<RpcResult<TransactionStatus>> commit() {
-        LOG.trace("{}: Commit", id);
-
-        final CheckedFuture<Void, TransactionCommitFailedException> submit = submit();
-        return Futures.transform(submit, new Function<Void, RpcResult<TransactionStatus>>() {
-            @Nullable
-            @Override
-            public RpcResult<TransactionStatus> apply(@Nullable final Void input) {
-                return RpcResultBuilder.success(TransactionStatus.SUBMITED).build();
-            }
-        });
+        return proxyWriteAdapter.commit(getIdentifier());
     }
 
     @Override
     public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier identifier) {
-        Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, getIdentifier());
-        LOG.trace("{}: Delete {} via NETCONF: {}", id, store, identifier);
-        masterTxActor.tell(new DeleteRequest(store, identifier), ActorRef.noSender());
+        proxyWriteAdapter.delete(store, identifier);
     }
 
     @Override
     public void put(final LogicalDatastoreType store, final YangInstanceIdentifier identifier,
                     final NormalizedNode<?, ?> data) {
-        Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, getIdentifier());
-        final NormalizedNodeMessage msg = new NormalizedNodeMessage(identifier, data);
-        LOG.trace("{}: Put {} via NETCONF: {} with payload {}", id, store, identifier, data);
-        masterTxActor.tell(new PutRequest(store, msg), ActorRef.noSender());
+        proxyWriteAdapter.put(store, identifier, data, getIdentifier());
     }
 
     @Override
     public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier identifier,
                       final NormalizedNode<?, ?> data) {
-        Preconditions.checkState(opened.get(), "%s: Transaction was closed %s", id, getIdentifier());
-        final NormalizedNodeMessage msg = new NormalizedNodeMessage(identifier, data);
-        LOG.trace("{}: Merge {} via NETCONF: {} with payload {}", id, store, identifier, data);
-        masterTxActor.tell(new MergeRequest(store, msg), ActorRef.noSender());
+        proxyWriteAdapter.merge(store, identifier, data, getIdentifier());
     }
 
     @Override
index be57ce35aa7b0ae6dcf4608f696653cc8d263e5a..cee8c0d80774b077665c771a27a36142439872b1 100644 (file)
@@ -13,9 +13,7 @@ import io.netty.util.concurrent.EventExecutor;
 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.sal.connect.netconf.NetconfDevice;
@@ -30,10 +28,8 @@ public class NetconfTopologySetup {
     private final DataBroker dataBroker;
     private final InstanceIdentifier<Node> instanceIdentifier;
     private final Node node;
-    private final BindingAwareBroker bindingAwareBroker;
     private final ScheduledThreadPool keepaliveExecutor;
     private final ThreadPool processingExecutor;
-    private final Broker domBroker;
     private final ActorSystem actorSystem;
     private final EventExecutor eventExecutor;
     private final NetconfClientDispatcher netconfClientDispatcher;
@@ -47,10 +43,8 @@ public class NetconfTopologySetup {
         this.dataBroker = builder.getDataBroker();
         this.instanceIdentifier = builder.getInstanceIdentifier();
         this.node = builder.getNode();
-        this.bindingAwareBroker = builder.getBindingAwareBroker();
         this.keepaliveExecutor = builder.getKeepaliveExecutor();
         this.processingExecutor = builder.getProcessingExecutor();
-        this.domBroker = builder.getDomBroker();
         this.actorSystem = builder.getActorSystem();
         this.eventExecutor = builder.getEventExecutor();
         this.netconfClientDispatcher = builder.getNetconfClientDispatcher();
@@ -79,10 +73,6 @@ public class NetconfTopologySetup {
         return node;
     }
 
-    public BindingAwareBroker getBindingAwareBroker() {
-        return bindingAwareBroker;
-    }
-
     public ThreadPool getProcessingExecutor() {
         return processingExecutor;
     }
@@ -91,10 +81,6 @@ public class NetconfTopologySetup {
         return keepaliveExecutor;
     }
 
-    public Broker getDomBroker() {
-        return domBroker;
-    }
-
     public ActorSystem getActorSystem() {
         return actorSystem;
     }
@@ -126,10 +112,8 @@ public class NetconfTopologySetup {
         private DataBroker dataBroker;
         private InstanceIdentifier<Node> instanceIdentifier;
         private Node node;
-        private BindingAwareBroker bindingAwareBroker;
         private ScheduledThreadPool keepaliveExecutor;
         private ThreadPool processingExecutor;
-        private Broker domBroker;
         private ActorSystem actorSystem;
         private EventExecutor eventExecutor;
         private String topologyId;
@@ -190,15 +174,6 @@ public class NetconfTopologySetup {
             return new NetconfTopologySetup(this);
         }
 
-        private BindingAwareBroker getBindingAwareBroker() {
-            return bindingAwareBroker;
-        }
-
-        public NetconfTopologySetupBuilder setBindingAwareBroker(final BindingAwareBroker bindingAwareBroker) {
-            this.bindingAwareBroker = bindingAwareBroker;
-            return this;
-        }
-
         private ScheduledThreadPool getKeepaliveExecutor() {
             return keepaliveExecutor;
         }
@@ -217,15 +192,6 @@ public class NetconfTopologySetup {
             return this;
         }
 
-        private Broker getDomBroker() {
-            return domBroker;
-        }
-
-        public NetconfTopologySetupBuilder setDomBroker(final Broker domBroker) {
-            this.domBroker = domBroker;
-            return this;
-        }
-
         private ActorSystem getActorSystem() {
             return actorSystem;
         }
index 7a73fe2e90e0fcecaffcd0a28290782ade7f32e5..72d8e9e84926f06862d076c4ed941c40d3ada33d 100644 (file)
@@ -8,6 +8,6 @@
 
 package org.opendaylight.netconf.topology.singleton.messages.transactions;
 
-public class CancelRequest implements TransactionRequest {
+public class CancelRequest implements WriteActorMessage {
     private static final long serialVersionUID = 1L;
 }
index 1548dc791ae4e639231a1c8ebe504e79fac3612e..5e46157e40e046268f3a86ae4930be3a0f073e7d 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 
-public class DeleteRequest implements TransactionRequest {
+public class DeleteRequest implements WriteActorMessage {
     private static final long serialVersionUID = 1L;
 
     private final LogicalDatastoreType store;
index b5fae5f02931f434babca317b12e22c33b77855d..9bce961fcd42935c5aaff699b402306bb9f1208a 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 
-public class ExistsRequest implements TransactionRequest {
+public class ExistsRequest implements ReadActorMessage {
     private static final long serialVersionUID = 1L;
 
     private final LogicalDatastoreType store;
index 8c03023654f295393e791819cdf20cb3cf22dcf7..536d52172d1d3f07590f40223bea23f1c2d2a1fe 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
 
-public class MergeRequest implements TransactionRequest {
+public class MergeRequest implements WriteActorMessage {
     private static final long serialVersionUID = 1L;
 
     private final NormalizedNodeMessage data;
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java
new file mode 100644 (file)
index 0000000..141eccc
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * 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.topology.singleton.messages.transactions;
+
+import akka.actor.ActorRef;
+import java.io.Serializable;
+
+public class NewReadWriteTransactionReply implements Serializable {
+
+    private final ActorRef txActor;
+
+    public NewReadWriteTransactionReply(final ActorRef txActor) {
+        this.txActor = txActor;
+    }
+
+    public ActorRef getTxActor() {
+        return txActor;
+    }
+}
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionRequest.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionRequest.java
new file mode 100644 (file)
index 0000000..9a9a585
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * 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.topology.singleton.messages.transactions;
+
+import java.io.Serializable;
+
+public class NewReadWriteTransactionRequest implements Serializable {
+    private static final long serialVersionUID = 1L;
+}
index 41de9c22b7daf1a0ef434ad79633a4e780793d95..c9084b813eb7a7a97e4d2afa7574abe7c9a74942 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
 
-public class PutRequest implements TransactionRequest {
+public class PutRequest implements WriteActorMessage {
     private static final long serialVersionUID = 1L;
 
     private final LogicalDatastoreType store;
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/ReadActorMessage.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/ReadActorMessage.java
new file mode 100644 (file)
index 0000000..88bae04
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.topology.singleton.messages.transactions;
+
+public interface ReadActorMessage extends TransactionRequest {
+}
index d950f285576bd8a1a3fcfda8c8eb13554ed1efbd..b64f46cd9177930d245f4ab537de9232a4240f06 100644 (file)
@@ -11,7 +11,7 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 
-public class ReadRequest implements TransactionRequest {
+public class ReadRequest implements ReadActorMessage {
     private static final long serialVersionUID = 1L;
 
     private final LogicalDatastoreType store;
index 6b6af7e77310cfee9b63a98cc0d797f595156016..64da32a0fe2ec0fb4e26ecf403a2f17c03cd8627 100644 (file)
@@ -8,6 +8,6 @@
 
 package org.opendaylight.netconf.topology.singleton.messages.transactions;
 
-public class SubmitRequest implements TransactionRequest {
+public class SubmitRequest implements WriteActorMessage {
     private static final long serialVersionUID = 1L;
 }
diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/WriteActorMessage.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/WriteActorMessage.java
new file mode 100644 (file)
index 0000000..07af556
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.topology.singleton.messages.transactions;
+
+public interface WriteActorMessage extends TransactionRequest {
+}
index 977018f62c57d8689f0f81042e76e3814062137d..8c60682605e6f2534db9cc9bbdcb69cd67369368 100644 (file)
@@ -17,16 +17,12 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
                interface="org.opendaylight.controller.sal.binding.api.RpcProviderRegistry"/>
     <reference id="clusterSingletonService"
                interface="org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider"/>
-    <reference id="bindingAwareBroker"
-               interface="org.opendaylight.controller.sal.binding.api.BindingAwareBroker"/>
     <reference id="keepAliveExecutor"
                interface="org.opendaylight.controller.config.threadpool.ScheduledThreadPool"
                odl:type="global-netconf-ssh-scheduled-executor"/>
     <reference id="processingExecutor"
                interface="org.opendaylight.controller.config.threadpool.ThreadPool"
                odl:type="global-netconf-processing-executor"/>
-    <reference id="domBroker"
-               interface="org.opendaylight.controller.sal.core.api.Broker"/>
     <reference id="actorSystemProvider"
                interface="org.opendaylight.controller.cluster.ActorSystemProvider"/>
     <reference id="eventExecutor"
@@ -35,6 +31,9 @@ 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"/>
+    <reference id="mountPointService"
+               interface="org.opendaylight.controller.md.sal.dom.api.DOMMountPointService"
+               odl:type="default"/>
     <odl:clustered-app-config
             id="singletonConfig"
             binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config"
@@ -46,15 +45,14 @@ and is available at http://www.eclipse.org/legal/epl-v10.html
         <argument ref="dataBroker"/>
         <argument ref="rpcRegistry"/>
         <argument ref="clusterSingletonService"/>
-        <argument ref="bindingAwareBroker"/>
         <argument ref="keepAliveExecutor"/>
         <argument ref="processingExecutor"/>
-        <argument ref="domBroker"/>
         <argument ref="actorSystemProvider"/>
         <argument ref="eventExecutor"/>
         <argument ref="clientDispatcherDependency"/>
         <argument value="topology-netconf"/>
         <argument ref="singletonConfig"/>
+        <argument ref="mountPointService"/>
     </bean>
     <service ref="netconfTopologyManager"
              interface="org.opendaylight.netconf.topology.singleton.api.NetconfTopologySingletonService"/>
index 02e4440dc2a67ab8ed8528f47afca50c3fa1f027..3bb0125c700dfeee95de8f3bb6500cfc6150664c 100644 (file)
@@ -51,12 +51,13 @@ 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.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 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;
@@ -103,6 +104,10 @@ public class NetconfNodeActorTest {
 
     @Mock
     private DOMRpcService domRpcService;
+    @Mock
+    private DOMMountPointService mountPointService;
+    @Mock
+    private DataBroker dataBroker;
 
     @Before
     public void setup() throws UnknownHostException {
@@ -113,7 +118,7 @@ public class NetconfNodeActorTest {
         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
 
         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
-                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT);
+                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
 
         system = ActorSystem.create();
 
@@ -191,7 +196,6 @@ 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);
@@ -207,7 +211,8 @@ public class NetconfNodeActorTest {
                 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));
+                system.actorOf(NetconfNodeActor.props(setup, remoteDeviceId, registry, schemaRepository, TIMEOUT,
+                        mountPointService));
         final List<SourceIdentifier> sources = ImmutableList.of(yang1, yang2);
         slaveRef.tell(new RegisterMountPoint(sources), masterRef);
 
@@ -226,7 +231,7 @@ public class NetconfNodeActorTest {
         final SchemaRepository schemaRepository = mock(SchemaRepository.class);
         final SourceIdentifier sourceIdentifier = RevisionSourceIdentifier.create("testID", Optional.absent());
         final Props props = NetconfNodeActor.props(mock(NetconfTopologySetup.class), remoteDeviceId,
-                DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT);
+                DEFAULT_SCHEMA_REPOSITORY, schemaRepository, TIMEOUT, mountPointService);
 
         final ActorRef actorRefSchemaRepo = TestActorRef.create(system, props, "master_mocked_schema_repository");
         final ActorContext actorContext = mock(ActorContext.class);
index 060ed0e987c964b666864add576c872dafc26773..ffc52a5f4663184c2d9f01e575f378a9af9b4ba2 100644 (file)
@@ -40,9 +40,8 @@ import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
@@ -78,18 +77,17 @@ public class NetconfTopologyManagerTest {
         initMocks(this);
 
         final RpcProviderRegistry rpcProviderRegistry = mock(RpcProviderRegistry.class);
-        final BindingAwareBroker bindingAwareBroker = mock(BindingAwareBroker.class);
         final ScheduledThreadPool keepaliveExecutor = mock(ScheduledThreadPool.class);
         final ThreadPool processingExecutor = mock(ThreadPool.class);
-        final Broker domBroker = mock(Broker.class);
         final ActorSystemProvider actorSystemProvider = mock(ActorSystemProvider.class);
         final EventExecutor eventExecutor = mock(EventExecutor.class);
         final NetconfClientDispatcher clientDispatcher = mock(NetconfClientDispatcher.class);
+        final DOMMountPointService mountPointService = mock(DOMMountPointService.class);
 
         final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build();
         netconfTopologyManager = new NetconfTopologyManager(dataBroker, rpcProviderRegistry,
-                clusterSingletonServiceProvider, bindingAwareBroker, keepaliveExecutor, processingExecutor, domBroker,
-                actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config);
+                clusterSingletonServiceProvider, keepaliveExecutor, processingExecutor,
+                actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config, mountPointService);
     }
 
     @Test
index fbdde9466d0778239a8fc825cd0b5f42a08b5aaa..a8df0afd38dc9eb590dceb7815448179917ed883 100644 (file)
@@ -11,7 +11,10 @@ package org.opendaylight.netconf.topology.singleton.impl;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertSame;
 import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -20,6 +23,7 @@ import static org.mockito.MockitoAnnotations.initMocks;
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
 import akka.util.Timeout;
+import com.google.common.util.concurrent.Futures;
 import io.netty.util.concurrent.EventExecutor;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
@@ -30,10 +34,13 @@ import org.junit.Test;
 import org.mockito.Mock;
 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
+import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.client.NetconfClientSessionListener;
@@ -74,18 +81,12 @@ public class RemoteDeviceConnectorImplTest {
     @Mock
     private ClusterSingletonServiceProvider clusterSingletonServiceProvider;
 
-    @Mock
-    private BindingAwareBroker bindingAwareBroker;
-
     @Mock
     private ScheduledThreadPool keepaliveExecutor;
 
     @Mock
     private ThreadPool processingExecutor;
 
-    @Mock
-    private Broker domBroker;
-
     @Mock
     private ActorSystem actorSystem;
 
@@ -95,6 +96,15 @@ public class RemoteDeviceConnectorImplTest {
     @Mock
     private NetconfClientDispatcher clientDispatcher;
 
+    @Mock
+    private DOMMountPointService mountPointService;
+
+    @Mock
+    private BindingTransactionChain txChain;
+
+    @Mock
+    private WriteTransaction writeTx;
+
     private NetconfTopologySetup.NetconfTopologySetupBuilder builder;
     private RemoteDeviceId remoteDeviceId;
 
@@ -105,14 +115,17 @@ public class RemoteDeviceConnectorImplTest {
         remoteDeviceId = new RemoteDeviceId(TOPOLOGY_ID,
                 new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
 
+        doReturn(txChain).when(dataBroker).createTransactionChain(any(TransactionChainListener.class));
+        doReturn(writeTx).when(txChain).newWriteOnlyTransaction();
+        doNothing().when(writeTx).merge(eq(LogicalDatastoreType.OPERATIONAL), any(), any());
+        doReturn("Some object").when(writeTx).getIdentifier();
+        doReturn(Futures.immediateCheckedFuture(null)).when(writeTx).submit();
         builder = new NetconfTopologySetup.NetconfTopologySetupBuilder();
         builder.setDataBroker(dataBroker);
         builder.setRpcProviderRegistry(rpcProviderRegistry);
         builder.setClusterSingletonServiceProvider(clusterSingletonServiceProvider);
-        builder.setBindingAwareBroker(bindingAwareBroker);
         builder.setKeepaliveExecutor(keepaliveExecutor);
         builder.setProcessingExecutor(processingExecutor);
-        builder.setDomBroker(domBroker);
         builder.setActorSystem(actorSystem);
         builder.setEventExecutor(eventExecutor);
         builder.setNetconfClientDispatcher(clientDispatcher);
@@ -141,7 +154,8 @@ public class RemoteDeviceConnectorImplTest {
         final RemoteDeviceHandler salFacade = mock(RemoteDeviceHandler.class);
 
         final TestingRemoteDeviceConnectorImpl remoteDeviceConnection =
-                new TestingRemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, communicator, salFacade, TIMEOUT);
+                new TestingRemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, communicator, salFacade, TIMEOUT,
+                        mountPointService);
 
         final ActorRef masterRef = mock(ActorRef.class);
 
@@ -174,7 +188,7 @@ public class RemoteDeviceConnectorImplTest {
         final Node node = new NodeBuilder().setNodeId(NODE_ID).addAugmentation(NetconfNode.class, netconfNode).build();
         builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node));
         final RemoteDeviceConnectorImpl remoteDeviceConnection =
-                new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT);
+                new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT, mountPointService);
 
         final ActorRef masterRef = mock(ActorRef.class);
 
@@ -208,7 +222,7 @@ public class RemoteDeviceConnectorImplTest {
         builder.setSchemaResourceDTO(NetconfTopologyUtils.setupSchemaCacheDTO(node));
 
         final RemoteDeviceConnectorImpl remoteDeviceConnection =
-                new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT);
+                new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT, mountPointService);
 
         final ActorRef masterRef = mock(ActorRef.class);
 
@@ -235,7 +249,7 @@ public class RemoteDeviceConnectorImplTest {
                 .build();
 
         final RemoteDeviceConnectorImpl remoteDeviceConnection =
-                new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT);
+                new RemoteDeviceConnectorImpl(builder.build(), remoteDeviceId, TIMEOUT, mountPointService);
 
         final NetconfReconnectingClientConfiguration defaultClientConfig =
                 remoteDeviceConnection.getClientConfig(listener, testingNode);
index d2a515b1e04db97190bfdea5febfed00ce9af673..96eb505844f9fa8d83743bc7ab6837fc3b6cc8e9 100644 (file)
@@ -14,6 +14,7 @@ import static org.mockito.Mockito.doReturn;
 import akka.actor.ActorRef;
 import akka.util.Timeout;
 import com.google.common.util.concurrent.Futures;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
@@ -31,8 +32,9 @@ class TestingRemoteDeviceConnectorImpl extends RemoteDeviceConnectorImpl {
                                      final RemoteDeviceId remoteDeviceId,
                                      final NetconfDeviceCommunicator communicator,
                                      final RemoteDeviceHandler salFacade,
-                                     final Timeout actorResponseWaitTime) {
-        super(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime);
+                                     final Timeout actorResponseWaitTime,
+                                     final DOMMountPointService mountPointService) {
+        super(netconfTopologyDeviceSetup, remoteDeviceId, actorResponseWaitTime, mountPointService);
         this.communicator = communicator;
         this.salFacade = salFacade;
     }
diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadWriteTransactionActorTest.java
new file mode 100644 (file)
index 0000000..08b755e
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * 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.topology.singleton.impl.actors;
+
+import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import akka.actor.ActorSystem;
+import akka.pattern.Patterns;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestActorRef;
+import akka.testkit.TestProbe;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.Futures;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+import scala.concurrent.duration.Duration;
+
+public class ReadWriteTransactionActorTest {
+
+    private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.EMPTY;
+    private static final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
+    private static final Timeout TIMEOUT = Timeout.apply(5, TimeUnit.SECONDS);
+
+    @Mock
+    private DOMDataReadWriteTransaction deviceReadWriteTx;
+    private TestProbe probe;
+    private ActorSystem system;
+    private TestActorRef<WriteTransactionActor> actorRef;
+    private NormalizedNode<?, ?> node;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+        system = ActorSystem.apply();
+        probe = TestProbe.apply(system);
+        node = Builders.containerBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+                .build();
+        actorRef = TestActorRef.create(system, ReadWriteTransactionActor.props(deviceReadWriteTx,
+                Duration.apply(2, TimeUnit.SECONDS)), "testA");
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        JavaTestKit.shutdownActorSystem(system, null, true);
+    }
+
+    @Test
+    public void testRead() throws Exception {
+        final ContainerNode node = Builders.containerBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+                .build();
+        when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.of(node)));
+        actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+        verify(deviceReadWriteTx).read(STORE, PATH);
+        probe.expectMsgClass(NormalizedNodeMessage.class);
+    }
+
+    @Test
+    public void testReadEmpty() throws Exception {
+        when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(Optional.absent()));
+        actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+        verify(deviceReadWriteTx).read(STORE, PATH);
+        probe.expectMsgClass(EmptyReadResponse.class);
+    }
+
+    @Test
+    public void testReadFailure() throws Exception {
+        final ReadFailedException cause = new ReadFailedException("fail");
+        when(deviceReadWriteTx.read(STORE, PATH)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+        actorRef.tell(new ReadRequest(STORE, PATH), probe.ref());
+        verify(deviceReadWriteTx).read(STORE, PATH);
+        probe.expectMsg(cause);
+    }
+
+    @Test
+    public void testExists() throws Exception {
+        when(deviceReadWriteTx.exists(STORE, PATH)).thenReturn(Futures.immediateCheckedFuture(true));
+        actorRef.tell(new ExistsRequest(STORE, PATH), probe.ref());
+        verify(deviceReadWriteTx).exists(STORE, PATH);
+        probe.expectMsg(true);
+    }
+
+    @Test
+    public void testExistsFailure() throws Exception {
+        final ReadFailedException cause = new ReadFailedException("fail");
+        when(deviceReadWriteTx.exists(STORE, PATH)).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+        actorRef.tell(new ExistsRequest(STORE, PATH), probe.ref());
+        verify(deviceReadWriteTx).exists(STORE, PATH);
+        probe.expectMsg(cause);
+    }
+
+    @Test
+    public void testPut() throws Exception {
+        final NormalizedNodeMessage normalizedNodeMessage = new NormalizedNodeMessage(PATH, node);
+        actorRef.tell(new PutRequest(STORE, normalizedNodeMessage), probe.ref());
+        verify(deviceReadWriteTx).put(STORE, PATH, node);
+    }
+
+    @Test
+    public void testMerge() throws Exception {
+        final NormalizedNodeMessage normalizedNodeMessage = new NormalizedNodeMessage(PATH, node);
+        actorRef.tell(new MergeRequest(STORE, normalizedNodeMessage), probe.ref());
+        verify(deviceReadWriteTx).merge(STORE, PATH, node);
+    }
+
+    @Test
+    public void testDelete() throws Exception {
+        actorRef.tell(new DeleteRequest(STORE, PATH), probe.ref());
+        verify(deviceReadWriteTx).delete(STORE, PATH);
+    }
+
+    @Test
+    public void testCancel() throws Exception {
+        when(deviceReadWriteTx.cancel()).thenReturn(true);
+        final Future<Object> cancelFuture = Patterns.ask(actorRef, new CancelRequest(), TIMEOUT);
+        final Object result = Await.result(cancelFuture, TIMEOUT.duration());
+        Preconditions.checkState(result instanceof Boolean);
+        verify(deviceReadWriteTx).cancel();
+        Assert.assertTrue((Boolean) result);
+    }
+
+    @Test
+    public void testSubmit() throws Exception {
+        when(deviceReadWriteTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
+        final Future<Object> submitFuture = Patterns.ask(actorRef, new SubmitRequest(), TIMEOUT);
+        final Object result = Await.result(submitFuture, TIMEOUT.duration());
+        Assert.assertTrue(result instanceof SubmitReply);
+        verify(deviceReadWriteTx).submit();
+    }
+
+    @Test
+    public void testSubmitFail() throws Exception {
+        final RpcError rpcError =
+                RpcResultBuilder.newError(RpcError.ErrorType.APPLICATION, "fail", "fail");
+        final TransactionCommitFailedException cause = new TransactionCommitFailedException("fail", rpcError);
+        when(deviceReadWriteTx.submit()).thenReturn(Futures.immediateFailedCheckedFuture(cause));
+        final Future<Object> submitFuture = Patterns.ask(actorRef, new SubmitRequest(), TIMEOUT);
+        final Object result = Await.result(submitFuture, TIMEOUT.duration());
+        Assert.assertEquals(cause, result);
+        verify(deviceReadWriteTx).submit();
+    }
+
+    @Test
+    public void testIdleTimeout() throws Exception {
+        final TestProbe probe = new TestProbe(system);
+        probe.watch(actorRef);
+        verify(deviceReadWriteTx, timeout(3000)).cancel();
+        probe.expectTerminated(actorRef, TIMEOUT.duration());
+    }
+}
\ No newline at end of file
diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransactionTest.java
new file mode 100644 (file)
index 0000000..a24f2b1
--- /dev/null
@@ -0,0 +1,247 @@
+/*
+ * 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.topology.singleton.impl.tx;
+
+import akka.actor.ActorSystem;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestProbe;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.ListenableFuture;
+import java.net.InetSocketAddress;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.config.util.xml.DocumentedException;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.messages.NormalizedNodeMessage;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.CancelRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.DeleteRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.EmptyReadResponse;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ExistsRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.MergeRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.PutRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.ReadRequest;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitReply;
+import org.opendaylight.netconf.topology.singleton.messages.transactions.SubmitRequest;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+
+public class ProxyReadWriteTransactionTest {
+    private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.EMPTY;
+    private static final LogicalDatastoreType STORE = LogicalDatastoreType.CONFIGURATION;
+
+    private ActorSystem system;
+    private TestProbe masterActor;
+    private ContainerNode node;
+    private ProxyReadWriteTransaction tx;
+
+    @Before
+    public void setUp() throws Exception {
+        system = ActorSystem.apply();
+        masterActor = new TestProbe(system);
+        final RemoteDeviceId id = new RemoteDeviceId("dev1", InetSocketAddress.createUnresolved("localhost", 17830));
+        node = Builders.containerBuilder()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("cont")))
+                .build();
+        tx = new ProxyReadWriteTransaction(masterActor.ref(), id, system, Timeout.apply(5, TimeUnit.SECONDS));
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        JavaTestKit.shutdownActorSystem(system, null, true);
+    }
+
+    @Test
+    public void testCancel() throws Exception {
+        final Future<Boolean> submit = Executors.newSingleThreadExecutor().submit(() -> tx.cancel());
+        masterActor.expectMsgClass(CancelRequest.class);
+        masterActor.reply(true);
+        Assert.assertTrue(submit.get());
+    }
+
+    @Test
+    public void testCancelSubmitted() throws Exception {
+        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+        masterActor.expectMsgClass(SubmitRequest.class);
+        masterActor.reply(new SubmitReply());
+        submitFuture.checkedGet();
+        final Future<Boolean> submit = Executors.newSingleThreadExecutor().submit(() -> tx.cancel());
+        masterActor.expectNoMsg();
+        Assert.assertFalse(submit.get());
+    }
+
+    @Test
+    public void testSubmit() throws Exception {
+        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+        masterActor.expectMsgClass(SubmitRequest.class);
+        masterActor.reply(new SubmitReply());
+        submitFuture.checkedGet();
+    }
+
+    @Test
+    public void testDoubleSubmit() throws Exception {
+        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+        masterActor.expectMsgClass(SubmitRequest.class);
+        masterActor.reply(new SubmitReply());
+        submitFuture.checkedGet();
+        try {
+            tx.submit().checkedGet();
+            Assert.fail("Should throw IllegalStateException");
+        } catch (final IllegalStateException e) {
+            masterActor.expectNoMsg();
+        }
+    }
+
+    @Test
+    public void testCommit() throws Exception {
+        final ListenableFuture<RpcResult<TransactionStatus>> submitFuture = tx.commit();
+        masterActor.expectMsgClass(SubmitRequest.class);
+        masterActor.reply(new SubmitReply());
+        Assert.assertEquals(TransactionStatus.SUBMITED, submitFuture.get().getResult());
+    }
+
+    @Test
+    public void testDelete() throws Exception {
+        tx.delete(STORE, PATH);
+        masterActor.expectMsgClass(DeleteRequest.class);
+    }
+
+    @Test
+    public void testDeleteClosed() throws Exception {
+        submit();
+        try {
+            tx.delete(STORE, PATH);
+            Assert.fail("Should throw IllegalStateException");
+        } catch (final IllegalStateException e) {
+            masterActor.expectNoMsg();
+        }
+    }
+
+    @Test
+    public void testPut() throws Exception {
+        tx.put(STORE, PATH, node);
+        masterActor.expectMsgClass(PutRequest.class);
+    }
+
+    @Test
+    public void testPutClosed() throws Exception {
+        submit();
+        try {
+            tx.put(STORE, PATH, node);
+            Assert.fail("Should throw IllegalStateException");
+        } catch (final IllegalStateException e) {
+            masterActor.expectNoMsg();
+        }
+    }
+
+    @Test
+    public void testMerge() throws Exception {
+        tx.merge(STORE, PATH, node);
+        masterActor.expectMsgClass(MergeRequest.class);
+    }
+
+    @Test
+    public void testMergeClosed() throws Exception {
+        submit();
+        try {
+            tx.merge(STORE, PATH, node);
+            Assert.fail("Should throw IllegalStateException");
+        } catch (final IllegalStateException e) {
+            masterActor.expectNoMsg();
+        }
+    }
+
+    @Test
+    public void testGetIdentifier() throws Exception {
+        Assert.assertEquals(tx, tx.getIdentifier());
+    }
+
+    private void submit() throws TransactionCommitFailedException {
+        final CheckedFuture<Void, TransactionCommitFailedException> submit = tx.submit();
+        masterActor.expectMsgClass(SubmitRequest.class);
+        masterActor.reply(new SubmitReply());
+        submit.checkedGet();
+    }
+
+    @Test
+    public void testRead() throws Exception {
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+        masterActor.expectMsgClass(ReadRequest.class);
+        masterActor.reply(new NormalizedNodeMessage(PATH, node));
+        final Optional<NormalizedNode<?, ?>> result = read.checkedGet();
+        Assert.assertTrue(result.isPresent());
+        Assert.assertEquals(node, result.get());
+    }
+
+    @Test
+    public void testReadEmpty() throws Exception {
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+        masterActor.expectMsgClass(ReadRequest.class);
+        masterActor.reply(new EmptyReadResponse());
+        final Optional<NormalizedNode<?, ?>> result = read.checkedGet();
+        Assert.assertFalse(result.isPresent());
+    }
+
+    @Test(expected = ReadFailedException.class)
+    public void testReadFail() throws Exception {
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+        masterActor.expectMsgClass(ReadRequest.class);
+        masterActor.reply(new RuntimeException("fail"));
+        read.checkedGet();
+    }
+
+    @Test
+    public void testExists() throws Exception {
+        final CheckedFuture<Boolean, ReadFailedException> read = tx.exists(STORE, PATH);
+        masterActor.expectMsgClass(ExistsRequest.class);
+        masterActor.reply(true);
+        final Boolean result = read.checkedGet();
+        Assert.assertTrue(result);
+    }
+
+    @Test(expected = ReadFailedException.class)
+    public void testExistsFail() throws Exception {
+        final CheckedFuture<Boolean, ReadFailedException> read = tx.exists(STORE, PATH);
+        masterActor.expectMsgClass(ExistsRequest.class);
+        masterActor.reply(new RuntimeException("fail"));
+        read.checkedGet();
+    }
+
+    @Test
+    public void testMasterDownRead() throws Exception {
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read = tx.read(STORE, PATH);
+        masterActor.expectMsgClass(ReadRequest.class);
+        //master doesn't reply
+        try {
+            read.checkedGet();
+            Assert.fail("Exception should be thrown");
+        } catch (final ReadFailedException e) {
+            final Throwable cause = e.getCause();
+            Assert.assertTrue(cause instanceof DocumentedException);
+            final DocumentedException de = (DocumentedException) cause;
+            Assert.assertEquals(DocumentedException.ErrorSeverity.WARNING, de.getErrorSeverity());
+            Assert.assertEquals(DocumentedException.ErrorTag.OPERATION_FAILED, de.getErrorTag());
+            Assert.assertEquals(DocumentedException.ErrorType.APPLICATION, de.getErrorType());
+        }
+    }
+}
\ No newline at end of file
index 7ff9869dac6402b49ada1f9862352ea025cdb054..b214a51899326eb3c78afcac1e164338939c234d 100644 (file)
@@ -28,7 +28,6 @@ import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import org.junit.After;
@@ -41,6 +40,7 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMDataBroker;
@@ -69,15 +69,20 @@ public class ReadOnlyTransactionTest {
     private ActorRef masterRef;
     private ProxyDOMDataBroker slaveDataBroker;
     private List<SourceIdentifier> sourceIdentifiers;
+    private YangInstanceIdentifier instanceIdentifier;
+    private LogicalDatastoreType storeType;
     @Mock
     private DOMDataBroker deviceDataBroker;
     @Mock
     private DOMDataReadOnlyTransaction readTx;
     @Mock
     private DOMRpcService domRpcService;
+    @Mock
+    private DOMMountPointService mountPointService;
+
 
     @Before
-    public void setup() throws UnknownHostException {
+    public void setup() throws Exception {
         initMocks(this);
 
         system = ActorSystem.create();
@@ -87,19 +92,21 @@ public class ReadOnlyTransactionTest {
 
         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
-                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT);
+                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
 
         masterRef = TestActorRef.create(system, props, "master_read");
 
         sourceIdentifiers = Lists.newArrayList();
 
         //device read tx
-        readTx = mock(DOMDataReadOnlyTransaction.class);
         doReturn(readTx).when(deviceDataBroker).newReadOnlyTransaction();
 
         // Create slave data broker for testing proxy
         slaveDataBroker =
                 new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
+        initializeDataTest();
+        instanceIdentifier = YangInstanceIdentifier.EMPTY;
+        storeType = LogicalDatastoreType.CONFIGURATION;
     }
 
     @After
@@ -110,19 +117,29 @@ public class ReadOnlyTransactionTest {
 
     @Test
     public void testRead() throws Exception {
+        // Message: NormalizedNodeMessage
+        final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
+                Futures.immediateCheckedFuture(Optional.of(outputNode));
+        doReturn(resultNormalizedNodeMessage).when(readTx).read(storeType, instanceIdentifier);
 
-        /* Initialize data on master */
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNodeMessageResponse =
+                slaveDataBroker.newReadOnlyTransaction().read(storeType, instanceIdentifier);
 
-        initializeDataTest();
+        final Optional<NormalizedNode<?, ?>> resultNodeMessage =
+                resultNodeMessageResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
 
-        final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
-        final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
+        assertTrue(resultNodeMessage.isPresent());
+        assertEquals(resultNodeMessage.get(), outputNode);
+    }
 
+    @Test
+    public void testReadEmpty() throws Exception {
         // Message: EmptyReadResponse
-
         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmpty =
                 Futures.immediateCheckedFuture(Optional.absent());
-
         doReturn(resultEmpty).when(readTx).read(storeType, instanceIdentifier);
 
         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmptyResponse =
@@ -133,29 +150,11 @@ public class ReadOnlyTransactionTest {
                 resultEmptyResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
 
         assertEquals(resultEmptyMessage, Optional.absent());
+    }
 
-        // Message: NormalizedNodeMessage
-
-        final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
-                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
-
-        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
-                Futures.immediateCheckedFuture(Optional.of(outputNode));
-
-        doReturn(resultNormalizedNodeMessage).when(readTx).read(storeType, instanceIdentifier);
-
-        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNodeMessageResponse =
-                slaveDataBroker.newReadOnlyTransaction().read(storeType, instanceIdentifier);
-
-        final Optional<NormalizedNode<?, ?>> resultNodeMessage =
-                resultNodeMessageResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
-        assertTrue(resultNodeMessage.isPresent());
-        assertEquals(resultNodeMessage.get(), outputNode);
-
+    @Test
+    public void testReadFail() throws Exception {
         // Message: Throwable
-
         final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
         final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultThrowable =
                 Futures.immediateFailedCheckedFuture(readFailedException);
@@ -167,24 +166,13 @@ public class ReadOnlyTransactionTest {
 
         exception.expect(ReadFailedException.class);
         resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
     }
 
     @Test
     public void testExist() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
-
-        final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
-        final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-
         // Message: True
-
         final CheckedFuture<Boolean, ReadFailedException> resultTrue =
                 Futures.immediateCheckedFuture(true);
-
         doReturn(resultTrue).when(readTx).exists(storeType, instanceIdentifier);
 
         final CheckedFuture<Boolean, ReadFailedException> trueResponse =
@@ -193,25 +181,12 @@ public class ReadOnlyTransactionTest {
         final Boolean trueMessage = trueResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
 
         assertEquals(true, trueMessage);
+    }
 
-        // Message: False
-
-        final CheckedFuture<Boolean, ReadFailedException> resultFalse = Futures.immediateCheckedFuture(false);
-
-        doReturn(resultFalse).when(readTx).exists(storeType, instanceIdentifier);
-
-        final CheckedFuture<Boolean, ReadFailedException> falseResponse =
-                slaveDataBroker.newReadOnlyTransaction().exists(storeType,
-                        instanceIdentifier);
-
-        final Boolean falseMessage = falseResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
-        assertEquals(false, falseMessage);
-
+    @Test
+    public void testExistsNull() throws Exception {
         // Message: False, result null
-
         final CheckedFuture<Boolean, ReadFailedException> resultNull = Futures.immediateCheckedFuture(null);
-
         doReturn(resultNull).when(readTx).exists(storeType, instanceIdentifier);
 
         final CheckedFuture<Boolean, ReadFailedException> nullResponse =
@@ -221,13 +196,29 @@ public class ReadOnlyTransactionTest {
         final Boolean nullFalseMessage = nullResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
 
         assertEquals(false, nullFalseMessage);
+    }
 
-        // Message: Throwable
+    @Test
+    public void testExistsFalse() throws Exception {
+        // Message: False
+        final CheckedFuture<Boolean, ReadFailedException> resultFalse = Futures.immediateCheckedFuture(false);
+        doReturn(resultFalse).when(readTx).exists(storeType, instanceIdentifier);
+
+        final CheckedFuture<Boolean, ReadFailedException> falseResponse =
+                slaveDataBroker.newReadOnlyTransaction().exists(storeType,
+                        instanceIdentifier);
+
+        final Boolean falseMessage = falseResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
 
+        assertEquals(false, falseMessage);
+    }
+
+    @Test
+    public void testExistsFail() throws Exception {
+        // Message: Throwable
         final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
         final CheckedFuture<Boolean, ReadFailedException> resultThrowable =
                 Futures.immediateFailedCheckedFuture(readFailedException);
-
         doReturn(resultThrowable).when(readTx).exists(storeType, instanceIdentifier);
 
         final CheckedFuture<Boolean, ReadFailedException> resultThrowableResponse =
@@ -235,7 +226,6 @@ public class ReadOnlyTransactionTest {
 
         exception.expect(ReadFailedException.class);
         resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
-
     }
 
     private void initializeDataTest() throws Exception {
diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/tx/ReadWriteTransactionTest.java
new file mode 100644 (file)
index 0000000..c50cef4
--- /dev/null
@@ -0,0 +1,361 @@
+/*
+ * Copyright (c) 2016 Cisco Systems, Inc. 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.topology.singleton.impl.tx;
+
+import static junit.framework.TestCase.assertNull;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doNothing;
+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;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Props;
+import akka.pattern.Patterns;
+import akka.testkit.JavaTestKit;
+import akka.testkit.TestActorRef;
+import akka.util.Timeout;
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import org.mockito.Mock;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
+import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
+import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMDataBroker;
+import org.opendaylight.netconf.topology.singleton.impl.actors.NetconfNodeActor;
+import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup;
+import org.opendaylight.netconf.topology.singleton.messages.CreateInitialMasterActorData;
+import org.opendaylight.netconf.topology.singleton.messages.MasterActorDataInitialized;
+import org.opendaylight.yangtools.yang.common.QName;
+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.repo.api.SourceIdentifier;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+import scala.concurrent.duration.Duration;
+
+public class ReadWriteTransactionTest {
+    private static final Timeout TIMEOUT = new Timeout(Duration.create(5, "seconds"));
+    private static final int TIMEOUT_SEC = 5;
+    private static ActorSystem system;
+
+    @Rule
+    public final ExpectedException exception = ExpectedException.none();
+
+    @Mock
+    private DOMDataBroker deviceDataBroker;
+    @Mock
+    private DOMDataReadWriteTransaction readWriteTx;
+    @Mock
+    private DOMRpcService domRpcService;
+    @Mock
+    private DOMMountPointService mountPointService;
+    private ActorRef masterRef;
+    private ProxyDOMDataBroker slaveDataBroker;
+    private List<SourceIdentifier> sourceIdentifiers;
+    private NormalizedNode<?, ?> testNode;
+    private YangInstanceIdentifier instanceIdentifier;
+    private LogicalDatastoreType storeType;
+
+    @Before
+    public void setup() throws Exception {
+        initMocks(this);
+
+        system = ActorSystem.create();
+
+        final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("netconf-topology",
+                new InetSocketAddress(InetAddress.getByName("127.0.0.1"), 9999));
+
+        final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
+        doReturn(Duration.apply(0, TimeUnit.SECONDS)).when(setup).getIdleTimeout();
+        final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
+                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
+
+        masterRef = TestActorRef.create(system, props, "master_read");
+
+        sourceIdentifiers = Lists.newArrayList();
+
+        doReturn(readWriteTx).when(deviceDataBroker).newReadWriteTransaction();
+        doNothing().when(readWriteTx).put(storeType, instanceIdentifier, testNode);
+        doNothing().when(readWriteTx).merge(storeType, instanceIdentifier, testNode);
+        doNothing().when(readWriteTx).delete(storeType, instanceIdentifier);
+
+        // Create slave data broker for testing proxy
+        slaveDataBroker =
+                new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
+        initializeDataTest();
+        testNode = ImmutableContainerNodeBuilder.create()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+        instanceIdentifier = YangInstanceIdentifier.EMPTY;
+        storeType = LogicalDatastoreType.CONFIGURATION;
+    }
+
+    @After
+    public void teardown() {
+        JavaTestKit.shutdownActorSystem(system, null, true);
+        system = null;
+    }
+
+    @Test
+    public void testPut() throws Exception {
+        // Test of invoking put on master through slave proxy
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        wTx.put(storeType, instanceIdentifier, testNode);
+
+        verify(readWriteTx, timeout(2000)).put(storeType, instanceIdentifier, testNode);
+
+        wTx.cancel();
+    }
+
+    @Test
+    public void testMerge() throws Exception {
+        // Test of invoking merge on master through slave proxy
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        wTx.merge(storeType, instanceIdentifier, testNode);
+
+        verify(readWriteTx, timeout(2000)).merge(storeType, instanceIdentifier, testNode);
+
+        wTx.cancel();
+    }
+
+    @Test
+    public void testDelete() throws Exception {
+        final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
+        final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
+
+        // Test of invoking delete on master through slave proxy
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        wTx.delete(storeType, instanceIdentifier);
+        wTx.cancel();
+
+        verify(readWriteTx, timeout(2000)).delete(storeType, instanceIdentifier);
+    }
+
+    @Test
+    public void testSubmit() throws Exception {
+        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmit = Futures.immediateCheckedFuture(null);
+        doReturn(resultSubmit).when(readWriteTx).submit();
+
+        // Without Tx
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+
+        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitResponse = wTx.submit();
+
+        final Object result = resultSubmitResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertNull(result);
+    }
+
+    @Test
+    public void testSubmitWithOperation() throws Exception {
+        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
+        doReturn(resultSubmitTx).when(readWriteTx).submit();
+        // With Tx
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        wTx.delete(LogicalDatastoreType.CONFIGURATION,
+                YangInstanceIdentifier.EMPTY);
+
+        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTxResponse = wTx.submit();
+
+        final Object resultTx = resultSubmitTxResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertNull(resultTx);
+    }
+
+    @Test
+    public void testSubmitFail() throws Exception {
+        final TransactionCommitFailedException throwable = new TransactionCommitFailedException("Fail", null);
+        final CheckedFuture<Void, TransactionCommitFailedException> resultThrowable =
+                Futures.immediateFailedCheckedFuture(throwable);
+        doReturn(resultThrowable).when(readWriteTx).submit();
+
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        wTx.delete(LogicalDatastoreType.CONFIGURATION,
+                YangInstanceIdentifier.EMPTY);
+        final CheckedFuture<Void, TransactionCommitFailedException> resultThrowableResponse =
+                wTx.submit();
+        exception.expect(TransactionCommitFailedException.class);
+        resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+    }
+
+    @Test
+    public void testCancel() throws Exception {
+        doReturn(true).when(readWriteTx).cancel();
+
+        // Without Tx
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        final Boolean resultFalseNoTx = wTx.cancel();
+        assertEquals(true, resultFalseNoTx);
+    }
+
+    @Test
+    public void testCancelWithOperation() throws Exception {
+        doReturn(true).when(readWriteTx).cancel();
+
+        // With Tx, readWriteTx test
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newReadWriteTransaction();
+        wTx.delete(LogicalDatastoreType.CONFIGURATION,
+                YangInstanceIdentifier.EMPTY);
+
+        final Boolean resultTrue = wTx.cancel();
+        assertEquals(true, resultTrue);
+
+        final Boolean resultFalse = wTx.cancel();
+        assertEquals(false, resultFalse);
+    }
+
+    @Test
+    public void testRead() throws Exception {
+        // Message: NormalizedNodeMessage
+        final NormalizedNode<?, ?> outputNode = ImmutableContainerNodeBuilder.create()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNormalizedNodeMessage =
+                Futures.immediateCheckedFuture(Optional.of(outputNode));
+        doReturn(resultNormalizedNodeMessage).when(readWriteTx).read(storeType, instanceIdentifier);
+
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultNodeMessageResponse =
+                slaveDataBroker.newReadWriteTransaction().read(storeType, instanceIdentifier);
+
+        final Optional<NormalizedNode<?, ?>> resultNodeMessage =
+                resultNodeMessageResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertTrue(resultNodeMessage.isPresent());
+        assertEquals(resultNodeMessage.get(), outputNode);
+    }
+
+    @Test
+    public void testReadEmpty() throws Exception {
+        // Message: EmptyReadResponse
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmpty =
+                Futures.immediateCheckedFuture(Optional.absent());
+        doReturn(resultEmpty).when(readWriteTx).read(storeType, instanceIdentifier);
+
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultEmptyResponse =
+                slaveDataBroker.newReadWriteTransaction().read(storeType,
+                        instanceIdentifier);
+
+        final Optional<NormalizedNode<?, ?>> resultEmptyMessage =
+                resultEmptyResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertEquals(resultEmptyMessage, Optional.absent());
+    }
+
+    @Test
+    public void testReadFail() throws Exception {
+        // Message: Throwable
+        final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultThrowable =
+                Futures.immediateFailedCheckedFuture(readFailedException);
+
+        doReturn(resultThrowable).when(readWriteTx).read(storeType, instanceIdentifier);
+
+        final CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> resultThrowableResponse =
+                slaveDataBroker.newReadWriteTransaction().read(storeType, instanceIdentifier);
+
+        exception.expect(ReadFailedException.class);
+        resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+    }
+
+    @Test
+    public void testExist() throws Exception {
+        // Message: True
+        final CheckedFuture<Boolean, ReadFailedException> resultTrue =
+                Futures.immediateCheckedFuture(true);
+        doReturn(resultTrue).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+        final CheckedFuture<Boolean, ReadFailedException> trueResponse =
+                slaveDataBroker.newReadWriteTransaction().exists(storeType, instanceIdentifier);
+
+        final Boolean trueMessage = trueResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertEquals(true, trueMessage);
+    }
+
+    @Test
+    public void testExistsNull() throws Exception {
+        // Message: False, result null
+        final CheckedFuture<Boolean, ReadFailedException> resultNull = Futures.immediateCheckedFuture(null);
+        doReturn(resultNull).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+        final CheckedFuture<Boolean, ReadFailedException> nullResponse =
+                slaveDataBroker.newReadWriteTransaction().exists(storeType,
+                        instanceIdentifier);
+
+        final Boolean nullFalseMessage = nullResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertEquals(false, nullFalseMessage);
+    }
+
+    @Test
+    public void testExistsFalse() throws Exception {
+        // Message: False
+        final CheckedFuture<Boolean, ReadFailedException> resultFalse = Futures.immediateCheckedFuture(false);
+        doReturn(resultFalse).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+        final CheckedFuture<Boolean, ReadFailedException> falseResponse =
+                slaveDataBroker.newReadWriteTransaction().exists(storeType,
+                        instanceIdentifier);
+
+        final Boolean falseMessage = falseResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+
+        assertEquals(false, falseMessage);
+    }
+
+    @Test
+    public void testExistsFail() throws Exception {
+        // Message: Throwable
+        final ReadFailedException readFailedException = new ReadFailedException("Fail", null);
+        final CheckedFuture<Boolean, ReadFailedException> resultThrowable =
+                Futures.immediateFailedCheckedFuture(readFailedException);
+        doReturn(resultThrowable).when(readWriteTx).exists(storeType, instanceIdentifier);
+
+        final CheckedFuture<Boolean, ReadFailedException> resultThrowableResponse =
+                slaveDataBroker.newReadWriteTransaction().exists(storeType, instanceIdentifier);
+
+        exception.expect(ReadFailedException.class);
+        resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
+    }
+
+    private void initializeDataTest() throws Exception {
+        final Future<Object> initialDataToActor =
+                Patterns.ask(masterRef, new CreateInitialMasterActorData(deviceDataBroker, sourceIdentifiers,
+                        domRpcService), TIMEOUT);
+
+        final Object success = Await.result(initialDataToActor, TIMEOUT.duration());
+
+        assertTrue(success instanceof MasterActorDataInitialized);
+    }
+
+}
index 0e1d474a5da18ffdf350b2b4d8625c3decfc9ecc..9cd9adcaeecbd337ab43f2576a278414e7fc3815 100644 (file)
@@ -11,7 +11,6 @@ package org.opendaylight.netconf.topology.singleton.impl.tx;
 import static junit.framework.TestCase.assertNull;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
@@ -32,7 +31,6 @@ import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
 import java.net.InetAddress;
 import java.net.InetSocketAddress;
-import java.net.UnknownHostException;
 import java.util.List;
 import java.util.concurrent.TimeUnit;
 import org.junit.After;
@@ -46,6 +44,7 @@ import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFaile
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.netconf.topology.singleton.impl.ProxyDOMDataBroker;
@@ -71,18 +70,23 @@ public class WriteOnlyTransactionTest {
     @Rule
     public final ExpectedException exception = ExpectedException.none();
 
-    private ActorRef masterRef;
-    private ProxyDOMDataBroker slaveDataBroker;
-    private List<SourceIdentifier> sourceIdentifiers;
     @Mock
     private DOMDataBroker deviceDataBroker;
     @Mock
     private DOMDataWriteTransaction writeTx;
     @Mock
     private DOMRpcService domRpcService;
+    @Mock
+    private DOMMountPointService mountPointService;
+    private ActorRef masterRef;
+    private ProxyDOMDataBroker slaveDataBroker;
+    private List<SourceIdentifier> sourceIdentifiers;
+    private NormalizedNode<?, ?> testNode;
+    private YangInstanceIdentifier instanceIdentifier;
+    private LogicalDatastoreType storeType;
 
     @Before
-    public void setup() throws UnknownHostException {
+    public void setup() throws Exception {
         initMocks(this);
 
         system = ActorSystem.create();
@@ -93,21 +97,29 @@ public class WriteOnlyTransactionTest {
         final NetconfTopologySetup setup = mock(NetconfTopologySetup.class);
         doReturn(Duration.apply(0, TimeUnit.SECONDS)).when(setup).getIdleTimeout();
         final Props props = NetconfNodeActor.props(setup, remoteDeviceId, DEFAULT_SCHEMA_REPOSITORY,
-                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT);
+                DEFAULT_SCHEMA_REPOSITORY, TIMEOUT, mountPointService);
 
         masterRef = TestActorRef.create(system, props, "master_read");
 
         sourceIdentifiers = Lists.newArrayList();
 
-        writeTx = mock(DOMDataWriteTransaction.class);
         final DOMDataReadOnlyTransaction readTx = mock(DOMDataReadOnlyTransaction.class);
 
         doReturn(writeTx).when(deviceDataBroker).newWriteOnlyTransaction();
         doReturn(readTx).when(deviceDataBroker).newReadOnlyTransaction();
+        doNothing().when(writeTx).put(storeType, instanceIdentifier, testNode);
+        doNothing().when(writeTx).merge(storeType, instanceIdentifier, testNode);
+        doNothing().when(writeTx).delete(storeType, instanceIdentifier);
 
         // Create slave data broker for testing proxy
         slaveDataBroker =
                 new ProxyDOMDataBroker(system, remoteDeviceId, masterRef, Timeout.apply(5, TimeUnit.SECONDS));
+        initializeDataTest();
+        testNode = ImmutableContainerNodeBuilder.create()
+                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
+                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
+        instanceIdentifier = YangInstanceIdentifier.EMPTY;
+        storeType = LogicalDatastoreType.CONFIGURATION;
     }
 
     @After
@@ -118,85 +130,46 @@ public class WriteOnlyTransactionTest {
 
     @Test
     public void testPut() throws Exception {
-        /* Initialize data on master */
-
-        initializeDataTest();
-
-        final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
-        final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-        final NormalizedNode<?, ?> testNode = ImmutableContainerNodeBuilder.create()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
-                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
-
         // Test of invoking put on master through slave proxy
-
-        doNothing().when(writeTx).put(storeType, instanceIdentifier, testNode);
-
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
         wTx.put(storeType, instanceIdentifier, testNode);
 
         verify(writeTx, timeout(2000)).put(storeType, instanceIdentifier, testNode);
 
         wTx.cancel();
-
     }
 
     @Test
     public void testMerge() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
-
-        final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
-        final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-        final NormalizedNode<?, ?> testNode = ImmutableContainerNodeBuilder.create()
-                .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(QName.create("TestQname")))
-                .withChild(ImmutableNodes.leafNode(QName.create("NodeQname"), "foo")).build();
         // Test of invoking merge on master through slave proxy
-
-        doNothing().when(writeTx).merge(storeType, instanceIdentifier, testNode);
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
         wTx.merge(storeType, instanceIdentifier, testNode);
 
         verify(writeTx, timeout(2000)).merge(storeType, instanceIdentifier, testNode);
 
         wTx.cancel();
-
     }
 
     @Test
     public void testDelete() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
-
         final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.EMPTY;
         final LogicalDatastoreType storeType = LogicalDatastoreType.CONFIGURATION;
-        // Test of invoking delete on master through slave proxy
 
-        doNothing().when(writeTx).delete(storeType, instanceIdentifier);
+        // Test of invoking delete on master through slave proxy
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
         wTx.delete(storeType, instanceIdentifier);
         wTx.cancel();
 
         verify(writeTx, timeout(2000)).delete(storeType, instanceIdentifier);
-
     }
 
     @Test
     public void testSubmit() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
+        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmit = Futures.immediateCheckedFuture(null);
+        doReturn(resultSubmit).when(writeTx).submit();
 
         // Without Tx
-
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
-        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmit = Futures.immediateCheckedFuture(null);
-        doReturn(resultSubmit).when(writeTx).submit();
 
         final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitResponse = wTx.submit();
 
@@ -207,19 +180,13 @@ public class WriteOnlyTransactionTest {
 
     @Test
     public void testSubmitWithOperation() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
+        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
+        doReturn(resultSubmitTx).when(writeTx).submit();
         // With Tx
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
-        doNothing().when(writeTx).delete(any(), any());
         wTx.delete(LogicalDatastoreType.CONFIGURATION,
                 YangInstanceIdentifier.EMPTY);
 
-        final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTx = Futures.immediateCheckedFuture(null);
-        doReturn(resultSubmitTx).when(writeTx).submit();
-
         final CheckedFuture<Void, TransactionCommitFailedException> resultSubmitTxResponse = wTx.submit();
 
         final Object resultTx = resultSubmitTxResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
@@ -229,36 +196,25 @@ public class WriteOnlyTransactionTest {
 
     @Test
     public void testSubmitFail() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
-        final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
-        wTx.delete(LogicalDatastoreType.CONFIGURATION,
-                YangInstanceIdentifier.EMPTY);
-
         final TransactionCommitFailedException throwable = new TransactionCommitFailedException("Fail", null);
-        final CheckedFuture<Void,TransactionCommitFailedException> resultThrowable =
+        final CheckedFuture<Void, TransactionCommitFailedException> resultThrowable =
                 Futures.immediateFailedCheckedFuture(throwable);
-
         doReturn(resultThrowable).when(writeTx).submit();
 
+        final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
+        wTx.delete(LogicalDatastoreType.CONFIGURATION,
+                YangInstanceIdentifier.EMPTY);
         final CheckedFuture<Void, TransactionCommitFailedException> resultThrowableResponse =
                 wTx.submit();
-
         exception.expect(TransactionCommitFailedException.class);
         resultThrowableResponse.checkedGet(TIMEOUT_SEC, TimeUnit.SECONDS);
     }
 
     @Test
     public void testCancel() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
+        doReturn(true).when(writeTx).cancel();
 
         // Without Tx
-        doReturn(true).when(writeTx).cancel();
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
         final Boolean resultFalseNoTx = wTx.cancel();
         assertEquals(true, resultFalseNoTx);
@@ -266,25 +222,18 @@ public class WriteOnlyTransactionTest {
 
     @Test
     public void testCancelWithOperation() throws Exception {
-
-        /* Initialize data on master */
-
-        initializeDataTest();
+        doReturn(true).when(writeTx).cancel();
 
         // With Tx, readWriteTx test
-
         final DOMDataWriteTransaction wTx = slaveDataBroker.newWriteOnlyTransaction();
-        doNothing().when(writeTx).delete(any(), any());
         wTx.delete(LogicalDatastoreType.CONFIGURATION,
                 YangInstanceIdentifier.EMPTY);
 
-        doReturn(true).when(writeTx).cancel();
         final Boolean resultTrue = wTx.cancel();
         assertEquals(true, resultTrue);
 
         final Boolean resultFalse = wTx.cancel();
         assertEquals(false, resultFalse);
-
     }
 
     private void initializeDataTest() throws Exception {
index 836d9bdb10b3524c95a8aa76dd26ad0aef3b571f..68a6f11f9fd7319abafd8ece766d76dc5263a173 100644 (file)
@@ -27,8 +27,7 @@ import java.util.Map;
 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.client.NetconfClientSessionListener;
@@ -154,13 +153,12 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
 
     protected final String topologyId;
     private final NetconfClientDispatcher clientDispatcher;
-    protected final BindingAwareBroker bindingAwareBroker;
-    protected final Broker domBroker;
     private final EventExecutor eventExecutor;
     protected final ScheduledThreadPool keepaliveExecutor;
     protected final ThreadPool processingExecutor;
     protected final SharedSchemaRepository sharedSchemaRepository;
     protected final DataBroker dataBroker;
+    protected final DOMMountPointService mountPointService;
 
     protected SchemaSourceRegistry schemaRegistry = DEFAULT_SCHEMA_REPOSITORY;
     protected SchemaRepository schemaRepository = DEFAULT_SCHEMA_REPOSITORY;
@@ -169,19 +167,17 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
     protected final HashMap<NodeId, NetconfConnectorDTO> activeConnectors = new HashMap<>();
 
     protected AbstractNetconfTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher,
-                                      final BindingAwareBroker bindingAwareBroker, final Broker domBroker,
                                       final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
                                       final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
-                                      final DataBroker dataBroker) {
+                                      final DataBroker dataBroker, final DOMMountPointService mountPointService) {
         this.topologyId = topologyId;
         this.clientDispatcher = clientDispatcher;
-        this.bindingAwareBroker = bindingAwareBroker;
-        this.domBroker = domBroker;
         this.eventExecutor = eventExecutor;
         this.keepaliveExecutor = keepaliveExecutor;
         this.processingExecutor = processingExecutor;
         this.sharedSchemaRepository = schemaRepositoryProvider.getSharedSchemaRepository();
         this.dataBroker = dataBroker;
+        this.mountPointService = mountPointService;
     }
 
     public void setSchemaRegistry(final SchemaSourceRegistry schemaRegistry) {
@@ -258,7 +254,7 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId(nodeId.getValue(), address);
 
         RemoteDeviceHandler<NetconfSessionPreferences> salFacade =
-                createSalFacade(remoteDeviceId, domBroker, bindingAwareBroker);
+                createSalFacade(remoteDeviceId);
 
         if (keepaliveDelay > 0) {
             LOG.warn("Adding keepalive facade, for device {}", nodeId);
@@ -423,7 +419,7 @@ public abstract class AbstractNetconfTopology implements NetconfTopology {
                 .build();
     }
 
-    protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker);
+    protected abstract RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id);
 
     private InetSocketAddress getSocketAddress(final Host host, final int port) {
         if(host.getDomainName() != null) {
index fc4be281236039ea0ab19005bbdb653e5565d55e..243f09a77f8e1a49837e686d7ce102f27a825096 100644 (file)
@@ -22,8 +22,7 @@ import org.opendaylight.controller.md.sal.binding.api.DataTreeIdentifier;
 import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
@@ -50,19 +49,17 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
     private ListenerRegistration<NetconfTopologyImpl> datastoreListenerRegistration = null;
 
     public NetconfTopologyImpl(final String topologyId, final NetconfClientDispatcher clientDispatcher,
-                               final BindingAwareBroker bindingAwareBroker, final Broker domBroker,
                                final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
                                final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
-                               final DataBroker dataBroker) {
-        super(topologyId, clientDispatcher,
-                bindingAwareBroker, domBroker, eventExecutor,
-                keepaliveExecutor, processingExecutor, schemaRepositoryProvider, dataBroker);
+                               final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+        super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor, processingExecutor,
+                schemaRepositoryProvider, dataBroker, mountPointService);
     }
 
     @Override
     public void close() throws Exception {
         // close all existing connectors, delete whole topology in datastore?
-        for (NetconfConnectorDTO connectorDTO : activeConnectors.values()) {
+        for (final NetconfConnectorDTO connectorDTO : activeConnectors.values()) {
             connectorDTO.close();
         }
         activeConnectors.clear();
@@ -74,8 +71,8 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
     }
 
     @Override
-    protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(RemoteDeviceId id, Broker domBroker, BindingAwareBroker bindingBroker) {
-        return new NetconfDeviceSalFacade(id, domBroker, bindingAwareBroker);
+    protected RemoteDeviceHandler<NetconfSessionPreferences> createSalFacade(final RemoteDeviceId id) {
+        return new NetconfDeviceSalFacade(id, mountPointService, dataBroker);
     }
 
     /**
@@ -87,12 +84,12 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
         initTopology(wtx, LogicalDatastoreType.OPERATIONAL);
         Futures.addCallback(wtx.submit(), new FutureCallback<Void>() {
             @Override
-            public void onSuccess(Void result) {
+            public void onSuccess(final Void result) {
                 LOG.debug("topology initialization successful");
             }
 
             @Override
-            public void onFailure(Throwable t) {
+            public void onFailure(final Throwable t) {
                 LOG.error("Unable to initialize netconf-topology, {}", t);
             }
         });
@@ -107,8 +104,8 @@ public class NetconfTopologyImpl extends AbstractNetconfTopology implements Data
     }
 
     @Override
-    public void onDataTreeChanged(@Nonnull Collection<DataTreeModification<Node>> collection) {
-        for (DataTreeModification<Node> change : collection) {
+    public void onDataTreeChanged(@Nonnull final Collection<DataTreeModification<Node>> collection) {
+        for (final DataTreeModification<Node> change : collection) {
             final DataObjectModification<Node> rootNode = change.getRootNode();
             switch (rootNode.getModificationType()) {
                 case SUBTREE_MODIFIED:
index 6798d1d0ee9294d693802ee7a4cdb40bdcc5459e..235086f4cf17e5542663048b831cb1daf23f09cc 100644 (file)
@@ -37,8 +37,7 @@ import org.opendaylight.controller.md.sal.binding.api.DataTreeModification;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
@@ -69,15 +68,9 @@ public class NetconfTopologyImplTest {
     private static final NodeId NODE_ID = new NodeId("testing-node");
     private static final String TOPOLOGY_ID = "testing-topology";
 
-    @Mock
-    private Broker mockedDataBroker;
-
     @Mock
     private NetconfClientDispatcher mockedClientDispatcher;
 
-    @Mock
-    private BindingAwareBroker mockedBindingAwareBroker;
-
     @Mock
     private EventExecutor mockedEventExecutor;
 
@@ -93,6 +86,9 @@ public class NetconfTopologyImplTest {
     @Mock
     private DataBroker dataBroker;
 
+    @Mock
+    private DOMMountPointService mountPointService;
+
     private TestingNetconfTopologyImpl topology;
     private TestingNetconfTopologyImpl spyTopology;
 
@@ -102,19 +98,19 @@ public class NetconfTopologyImplTest {
 
         when(mockedSchemaRepositoryProvider.getSharedSchemaRepository()).thenReturn(new SharedSchemaRepository("testingSharedSchemaRepo"));
         when(mockedProcessingExecutor.getExecutor()).thenReturn(MoreExecutors.newDirectExecutorService());
-        Future future = new SucceededFuture(ImmediateEventExecutor.INSTANCE, new NetconfDeviceCapabilities());
+        final Future future = new SucceededFuture(ImmediateEventExecutor.INSTANCE, new NetconfDeviceCapabilities());
         when(mockedClientDispatcher.createReconnectingClient(any(NetconfReconnectingClientConfiguration.class))).thenReturn(future);
 
-        topology = new TestingNetconfTopologyImpl(TOPOLOGY_ID, mockedClientDispatcher, mockedBindingAwareBroker,
-                mockedDataBroker, mockedEventExecutor, mockedKeepaliveExecutor, mockedProcessingExecutor, mockedSchemaRepositoryProvider,
-                dataBroker);
+        topology = new TestingNetconfTopologyImpl(TOPOLOGY_ID, mockedClientDispatcher,
+                mockedEventExecutor, mockedKeepaliveExecutor, mockedProcessingExecutor, mockedSchemaRepositoryProvider,
+                dataBroker, mountPointService);
 
         spyTopology = spy(topology);
     }
 
     @Test
     public void testInit() {
-        WriteTransaction wtx = mock(WriteTransaction.class);
+        final WriteTransaction wtx = mock(WriteTransaction.class);
         when(dataBroker.newWriteOnlyTransaction()).thenReturn(wtx);
         doNothing().when(wtx).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class), any(DataObject.class));
         when(wtx.submit()).thenReturn(Futures.<Void, TransactionCommitFailedException>immediateCheckedFuture(null));
@@ -133,19 +129,19 @@ public class NetconfTopologyImplTest {
     @Test
     public void testOnDataTreeChange() {
 
-        DataObjectModification<Node> newNode = mock(DataObjectModification.class);
+        final DataObjectModification<Node> newNode = mock(DataObjectModification.class);
         when(newNode.getModificationType()).thenReturn(DataObjectModification.ModificationType.WRITE);
 
         InstanceIdentifier.PathArgument pa = null;
 
-        for (InstanceIdentifier.PathArgument p : TopologyUtil.createTopologyListPath(TOPOLOGY_ID).child(Node.class, new NodeKey(NODE_ID)).getPathArguments()) {
+        for (final InstanceIdentifier.PathArgument p : TopologyUtil.createTopologyListPath(TOPOLOGY_ID).child(Node.class, new NodeKey(NODE_ID)).getPathArguments()) {
             pa = p;
         }
 
         when(newNode.getIdentifier()).thenReturn(pa);
 
 
-        NetconfNode testingNode = new NetconfNodeBuilder()
+        final NetconfNode testingNode = new NetconfNodeBuilder()
                 .setHost(new Host(new IpAddress(new Ipv4Address("127.0.0.1"))))
                 .setPort(new PortNumber(9999))
                 .setReconnectOnChangedSchema(true)
@@ -156,14 +152,13 @@ public class NetconfTopologyImplTest {
                 .setCredentials(new LoginPasswordBuilder().setUsername("testuser").setPassword("testpassword").build())
                 .build();
 
-        NodeBuilder nn = new NodeBuilder().addAugmentation(NetconfNode.class, testingNode);
+        final NodeBuilder nn = new NodeBuilder().addAugmentation(NetconfNode.class, testingNode);
 
         when(newNode.getDataAfter()).thenReturn(nn.build());
 
 
-
-        Collection<DataTreeModification<Node>> changes = Sets.newHashSet();
-        DataTreeModification<Node> ch = mock(DataTreeModification.class);
+        final Collection<DataTreeModification<Node>> changes = Sets.newHashSet();
+        final DataTreeModification<Node> ch = mock(DataTreeModification.class);
         when(ch.getRootNode()).thenReturn(newNode);
         changes.add(ch);
         spyTopology.onDataTreeChanged(changes);
@@ -185,22 +180,21 @@ public class NetconfTopologyImplTest {
 
     public static class TestingNetconfTopologyImpl extends NetconfTopologyImpl {
 
-        public TestingNetconfTopologyImpl(String topologyId, NetconfClientDispatcher clientDispatcher,
-                                          BindingAwareBroker bindingAwareBroker, Broker domBroker,
-                                          EventExecutor eventExecutor, ScheduledThreadPool keepaliveExecutor,
-                                          ThreadPool processingExecutor, SchemaRepositoryProvider schemaRepositoryProvider,
-                                          DataBroker dataBroker) {
-            super(topologyId, clientDispatcher, bindingAwareBroker, domBroker, eventExecutor, keepaliveExecutor,
-                    processingExecutor, schemaRepositoryProvider, dataBroker);
+        public TestingNetconfTopologyImpl(final String topologyId, final NetconfClientDispatcher clientDispatcher,
+                                          final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor,
+                                          final ThreadPool processingExecutor, final SchemaRepositoryProvider schemaRepositoryProvider,
+                                          final DataBroker dataBroker, final DOMMountPointService mountPointService) {
+            super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor,
+                    processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService);
         }
 
         @Override
-        public ListenableFuture<NetconfDeviceCapabilities> connectNode(NodeId nodeId, Node configNode) {
+        public ListenableFuture<NetconfDeviceCapabilities> connectNode(final NodeId nodeId, final Node configNode) {
             return Futures.immediateFuture(new NetconfDeviceCapabilities());
         }
 
         @Override
-        public ListenableFuture<Void> disconnectNode(NodeId nodeId) {
+        public ListenableFuture<Void> disconnectNode(final NodeId nodeId) {
             return Futures.immediateFuture(null);
         }
     }
index d2f73ae468b37d52f7e706ce59fc0a0a94ed18b8..86ef2abc7f770db998bbc18997cfde26215799e1 100644 (file)
@@ -201,7 +201,9 @@ public class NetconfDevice implements RemoteDevice<NetconfSessionPreferences, Ne
         return remoteSessionCapabilities.isNotificationsSupported() && reconnectOnSchemasChange;
     }
 
-    void handleSalInitializationSuccess(final SchemaContext result, final NetconfSessionPreferences remoteSessionCapabilities, final DOMRpcService deviceRpc) {
+    void handleSalInitializationSuccess(final SchemaContext result,
+                                        final NetconfSessionPreferences remoteSessionCapabilities,
+                                        final DOMRpcService deviceRpc) {
         final BaseSchema baseSchema =
                 remoteSessionCapabilities.isNotificationsSupported() ?
                 BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS :
index 90408690f33d008960856597a611ed7db2988e7b..a6ffe7aeb18823c68f64db619a5ac33bd427f828 100644 (file)
@@ -10,11 +10,11 @@ package org.opendaylight.netconf.sal.connect.netconf.sal;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.Lists;
 import java.util.List;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
@@ -29,26 +29,18 @@ public final class NetconfDeviceSalFacade implements AutoCloseable, RemoteDevice
 
     private final RemoteDeviceId id;
     private final NetconfDeviceSalProvider salProvider;
-
     private final List<AutoCloseable> salRegistrations = Lists.newArrayList();
 
-    public NetconfDeviceSalFacade(final RemoteDeviceId id, final Broker domBroker, final BindingAwareBroker bindingBroker) {
+    public NetconfDeviceSalFacade(final RemoteDeviceId id, final DOMMountPointService mountPointService,
+                                  final DataBroker dataBroker) {
         this.id = id;
-        this.salProvider = new NetconfDeviceSalProvider(id);
-        registerToSal(domBroker, bindingBroker);
+        this.salProvider = new NetconfDeviceSalProvider(id, mountPointService, dataBroker);
     }
 
     @VisibleForTesting
-    NetconfDeviceSalFacade(final RemoteDeviceId id, NetconfDeviceSalProvider salProvider,
-                           final Broker domBroker, final BindingAwareBroker bindingBroker) {
+    NetconfDeviceSalFacade(final RemoteDeviceId id, final NetconfDeviceSalProvider salProvider) {
         this.id = id;
         this.salProvider = salProvider;
-        registerToSal(domBroker, bindingBroker);
-    }
-
-    public void registerToSal(final Broker domRegistryDependency, final BindingAwareBroker bindingBroker) {
-        domRegistryDependency.registerProvider(salProvider);
-        bindingBroker.registerProvider(salProvider);
     }
 
     @Override
index c0f066ffdc07f8a27dc099b7d15eeca65d0606d8..e9d74c0637beb8b1bd9ff0eb2bfd19770a60253b 100644 (file)
@@ -8,8 +8,6 @@
 package org.opendaylight.netconf.sal.connect.netconf.sal;
 
 import com.google.common.base.Preconditions;
-import java.util.Collection;
-import java.util.Collections;
 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
@@ -21,31 +19,27 @@ import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
 import org.opendaylight.controller.md.sal.dom.api.DOMNotificationService;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.controller.sal.core.api.Provider;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.yangtools.concepts.ObjectRegistration;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfDeviceSalProvider implements AutoCloseable, Provider, BindingAwareProvider {
+public class NetconfDeviceSalProvider implements AutoCloseable {
 
     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
 
     private final RemoteDeviceId id;
-    private MountInstance mountInstance;
+    private final MountInstance mountInstance;
+    private final DataBroker dataBroker;
 
     private volatile NetconfDeviceTopologyAdapter topologyDatastoreAdapter;
 
-    private DataBroker dataBroker;
     private BindingTransactionChain txChain;
 
     private final TransactionChainListener transactionChainListener =  new TransactionChainListener() {
         @Override
-        public void onTransactionChainFailed(TransactionChain<?, ?> chain, AsyncTransaction<?, ?> transaction, Throwable cause) {
+        public void onTransactionChainFailed(final TransactionChain<?, ?> chain, final AsyncTransaction<?, ?> transaction, final Throwable cause) {
             logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause);
             chain.close();
             resetTransactionChainForAdapaters();
@@ -53,13 +47,25 @@ public class NetconfDeviceSalProvider implements AutoCloseable, Provider, Bindin
         }
 
         @Override
-        public void onTransactionChainSuccessful(TransactionChain<?, ?> chain) {
+        public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
             logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain);
         }
     };
 
-    public NetconfDeviceSalProvider(final RemoteDeviceId deviceId) {
+    public NetconfDeviceSalProvider(final RemoteDeviceId deviceId, final DOMMountPointService mountService,
+                                    final DataBroker dataBroker) {
         this.id = deviceId;
+        mountInstance = new MountInstance(mountService, id);
+        this.dataBroker = dataBroker;
+        txChain = Preconditions.checkNotNull(dataBroker).createTransactionChain(transactionChainListener);
+
+        topologyDatastoreAdapter = new NetconfDeviceTopologyAdapter(id, txChain);
+    }
+
+    public NetconfDeviceSalProvider(final RemoteDeviceId deviceId, final DOMMountPointService mountService) {
+        this.id = deviceId;
+        mountInstance = new MountInstance(mountService, id);
+        this.dataBroker = null;
     }
 
     public MountInstance getMountInstance() {
@@ -74,31 +80,6 @@ public class NetconfDeviceSalProvider implements AutoCloseable, Provider, Bindin
         return topologyDatastoreAdapter;
     }
 
-    @Override
-    public void onSessionInitiated(final Broker.ProviderSession session) {
-        logger.debug("{}: (BI)Session with sal established {}", id, session);
-
-        final DOMMountPointService mountService = session.getService(DOMMountPointService.class);
-        if (mountService != null) {
-            mountInstance = new MountInstance(mountService, id);
-        }
-    }
-
-    @Override
-    public Collection<Provider.ProviderFunctionality> getProviderFunctionality() {
-        return Collections.emptySet();
-    }
-
-    @Override
-    public void onSessionInitiated(final BindingAwareBroker.ProviderContext session) {
-        logger.debug("{}: Session with sal established {}", id, session);
-
-        this.dataBroker = session.getSALService(DataBroker.class);
-        txChain = Preconditions.checkNotNull(dataBroker).createTransactionChain(transactionChainListener);
-
-        topologyDatastoreAdapter = new NetconfDeviceTopologyAdapter(id, txChain);
-    }
-
     private void resetTransactionChainForAdapaters() {
         txChain = Preconditions.checkNotNull(dataBroker).createTransactionChain(transactionChainListener);
 
@@ -121,7 +102,7 @@ public class NetconfDeviceSalProvider implements AutoCloseable, Provider, Bindin
 
     public static final class MountInstance implements AutoCloseable {
 
-        private DOMMountPointService mountService;
+        private final DOMMountPointService mountService;
         private final RemoteDeviceId id;
         private NetconfDeviceNotificationService notificationService;
 
@@ -133,9 +114,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable, Provider, Bindin
         }
 
         public synchronized void onTopologyDeviceConnected(final SchemaContext initialCtx,
-                                                    final DOMDataBroker broker, final DOMRpcService rpc,
-                                                    final NetconfDeviceNotificationService notificationService) {
-
+                                                           final DOMDataBroker broker, final DOMRpcService rpc,
+                                                           final NetconfDeviceNotificationService notificationService) {
             Preconditions.checkNotNull(mountService, "Closed");
             Preconditions.checkState(topologyRegistration == null, "Already initialized");
 
@@ -172,7 +152,6 @@ public class NetconfDeviceSalProvider implements AutoCloseable, Provider, Bindin
         @Override
         public synchronized void close() throws Exception {
             onTopologyDeviceDisconnected();
-            mountService = null;
         }
 
         public synchronized void publish(final DOMNotification domNotification) {
index 8df394c77332d01d0165d3d87c33165930d9dbc8..4cb0ed7a155d480d31fa51d152ff34e461a78284 100644 (file)
@@ -27,8 +27,6 @@ import org.mockito.Mock;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
-import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
@@ -56,9 +54,7 @@ public class NetconfDeviceSalFacadeTest {
         final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);
         final RemoteDeviceId remoteDeviceId = new RemoteDeviceId("test", address);
 
-        final Broker domRegistry = mock(Broker.class);
-        final BindingAwareBroker bindingRegistry = mock(BindingAwareBroker.class);
-        deviceFacade = new NetconfDeviceSalFacade(remoteDeviceId, salProvider, domRegistry, bindingRegistry);
+        deviceFacade = new NetconfDeviceSalFacade(remoteDeviceId, salProvider);
 
         netconfDeviceTopologyAdapter = PowerMockito.mock(NetconfDeviceTopologyAdapter.class);
         mountInstance = PowerMockito.mock(NetconfDeviceSalProvider.MountInstance.class);
index b49b3fd3fbe93091133a8db3ced5b983479059ba..16ca3da8cfe4d9364c51ee62e4b2deba14af8f96 100644 (file)
@@ -9,13 +9,15 @@
 package org.opendaylight.netconf.sal.connect.netconf.sal;
 
 import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import com.google.common.util.concurrent.Futures;
 import java.net.InetSocketAddress;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
@@ -24,6 +26,7 @@ import org.mockito.MockitoAnnotations;
 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
 import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
@@ -44,38 +47,31 @@ public class NetconfDeviceSalProviderTest {
     private DataBroker dataBroker;
     @Mock
     private BindingTransactionChain chain;
+    @Mock
+    private DOMMountPointService mountPointService;
+    @Mock
+    private WriteTransaction writeTx;
     private NetconfDeviceSalProvider provider;
 
     @Before
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
-        provider = new NetconfDeviceSalProvider(new RemoteDeviceId("device1", InetSocketAddress.createUnresolved("localhost", 17830)));
+        doReturn(chain).when(dataBroker).createTransactionChain(any(TransactionChainListener.class));
+        doReturn(writeTx).when(chain).newWriteOnlyTransaction();
+        doNothing().when(writeTx).merge(eq(LogicalDatastoreType.OPERATIONAL), any(), any());
+        doReturn("Some object").when(writeTx).getIdentifier();
+        doReturn(Futures.immediateCheckedFuture(null)).when(writeTx).submit();
+        provider = new NetconfDeviceSalProvider(new RemoteDeviceId("device1",
+                InetSocketAddress.createUnresolved("localhost", 17830)), mountPointService, dataBroker);
         when(session.getService(DOMMountPointService.class)).thenReturn(mountpointService);
         when(context.getSALService(DataBroker.class)).thenReturn(dataBroker);
-        when(dataBroker.createTransactionChain(any())).thenReturn(chain);
         when(chain.newWriteOnlyTransaction()).thenReturn(tx);
         when(tx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
         when(tx.getIdentifier()).thenReturn(tx);
     }
 
-    @Test
-    public void onSessionInitiated() throws Exception {
-        provider.onSessionInitiated(session);
-        provider.onSessionInitiated(context);
-        Assert.assertNotNull(provider.getMountInstance());
-        Assert.assertNotNull(provider.getTopologyDatastoreAdapter());
-    }
-
-    @Test
-    public void getProviderFunctionality() throws Exception {
-        Assert.assertTrue(provider.getProviderFunctionality().isEmpty());
-    }
-
     @Test
     public void replaceChainIfFailed() throws Exception {
-        provider.onSessionInitiated(session);
-        provider.onSessionInitiated(context);
-        Assert.assertNotNull(provider.getMountInstance());
         final ArgumentCaptor<TransactionChainListener> captor = ArgumentCaptor.forClass(TransactionChainListener.class);
         verify(dataBroker).createTransactionChain(captor.capture());
         try {
@@ -88,16 +84,12 @@ public class NetconfDeviceSalProviderTest {
 
     @Test
     public void close() throws Exception {
-        provider.onSessionInitiated(session);
-        provider.onSessionInitiated(context);
         provider.close();
         verify(chain).close();
     }
 
     @Test
     public void closeWithoutNPE() throws Exception {
-        provider.onSessionInitiated(session);
-        provider.onSessionInitiated(context);
         provider.close();
         provider.close();
         verify(chain, times(2)).close();