From 476cc2164a06b77e7dd38859e0124d82cd2c8847 Mon Sep 17 00:00:00 2001 From: "matus.kubica" Date: Thu, 27 Apr 2017 15:06:53 +0200 Subject: [PATCH] Bug 8153: Enforce check-style rules for netconf - sal-netconf-connector Organize Imports for Checkstyle compliance. Checkstyle compliance: line length. Checkstyle compliance: various types of small changes. Checkstyle compliant Exception handling. Checkstyle final clean up & enforcement. Add the fail on violation flag into the pom.xml . Change-Id: I741ea586178981d6c66533259619c27c24bbd744 Signed-off-by: matus.kubica --- netconf/sal-netconf-connector/pom.xml | 12 + .../netconf/NetconfConnectorModule.java | 36 +- .../NetconfConnectorModuleFactory.java | 11 +- .../api/NetconfDeviceSchemasResolver.java | 5 +- .../netconf/sal/connect/api/RemoteDevice.java | 2 +- .../netconf/LibraryModulesSchemas.java | 104 ++--- .../sal/connect/netconf/NetconfDevice.java | 210 ++++++---- .../connect/netconf/NetconfStateSchemas.java | 130 ++++--- .../NetconfStateSchemasResolverImpl.java | 9 +- .../connect/netconf/NotificationHandler.java | 13 +- .../listener/NetconfDeviceCommunicator.java | 134 +++---- .../listener/NetconfSessionPreferences.java | 46 ++- .../netconf/listener/UncancellableFuture.java | 2 +- .../netconf/listener/UserPreferences.java | 2 +- .../netconf/sal/KeepaliveSalFacade.java | 55 +-- .../netconf/sal/NetconfDeviceDataBroker.java | 14 +- .../sal/NetconfDeviceNotificationService.java | 7 +- .../connect/netconf/sal/NetconfDeviceRpc.java | 48 ++- .../netconf/sal/NetconfDeviceSalFacade.java | 13 +- .../netconf/sal/NetconfDeviceSalProvider.java | 28 +- .../sal/NetconfDeviceTopologyAdapter.java | 44 ++- .../sal/SchemalessNetconfDeviceRpc.java | 38 +- .../netconf/sal/tx/AbstractWriteTx.java | 55 ++- .../connect/netconf/sal/tx/ReadOnlyTx.java | 24 +- .../connect/netconf/sal/tx/ReadWriteTx.java | 6 +- .../sal/connect/netconf/sal/tx/TxChain.java | 1 + .../sal/tx/WriteCandidateRunningTx.java | 8 +- .../netconf/sal/tx/WriteCandidateTx.java | 36 +- .../netconf/sal/tx/WriteRunningTx.java | 21 +- ...NetconfRemoteSchemaYangSourceProvider.java | 49 ++- .../YangLibrarySchemaYangSourceProvider.java | 20 +- .../mapping/BaseRpcSchemalessTransformer.java | 20 +- .../netconf/schema/mapping/BaseSchema.java | 19 +- .../mapping/NetconfMessageTransformer.java | 67 ++-- .../mapping/SchemalessMessageTransformer.java | 15 +- .../connect/netconf/util/NetconfBaseOps.java | 106 ++++-- .../util/NetconfMessageTransformUtil.java | 150 +++++--- .../util/NetconfRpcFutureCallback.java | 8 +- .../util/NetconfRpcStructureTransformer.java | 8 +- .../netconf/util/NodeContainerProxy.java | 24 +- .../netconf/util/RpcStructureTransformer.java | 4 +- .../SchemalessRpcStructureTransformer.java | 34 +- .../sal/connect/util/MessageCounter.java | 4 +- .../sal/connect/util/RemoteDeviceId.java | 51 ++- .../connect/netconf/NetconfDeviceTest.java | 135 ++++--- .../netconf/NetconfStateSchemasTest.java | 49 ++- .../netconf/NetconfToNotificationTest.java | 3 +- .../netconf/NetconfToRpcRequestTest.java | 42 +- .../netconf/SchemalessNetconfDeviceTest.java | 17 +- .../NetconfDeviceCommunicatorTest.java | 360 +++++++++--------- .../NetconfSessionPreferencesTest.java | 18 +- .../netconf/sal/KeepaliveSalFacadeTest.java | 13 +- .../netconf/sal/MountInstanceTest.java | 15 +- .../sal/NetconfDeviceDataBrokerTest.java | 15 +- .../netconf/sal/NetconfDeviceRpcTest.java | 20 +- .../sal/NetconfDeviceSalFacadeTest.java | 19 +- .../sal/NetconfDeviceTopologyAdapterTest.java | 67 ++-- .../sal/SchemalessNetconfDeviceRpcTest.java | 32 +- .../sal/tx/NetconfDeviceWriteOnlyTxTest.java | 44 ++- .../netconf/sal/tx/ReadOnlyTxTest.java | 30 +- .../connect/netconf/sal/tx/TxChainTest.java | 3 +- .../sal/tx/WriteCandidateRunningTxTest.java | 21 +- .../netconf/sal/tx/WriteCandidateTxTest.java | 6 +- .../netconf/sal/tx/WriteRunningTxTest.java | 6 +- ...onfRemoteSchemaYangSourceProviderTest.java | 9 +- .../BaseRpcSchemalessTransformerTest.java | 65 ++-- .../NetconfMessageTransformerTest.java | 203 +++++----- .../SchemalessMessageTransformerTest.java | 35 +- ...SchemalessRpcStructureTransformerTest.java | 33 +- 69 files changed, 1739 insertions(+), 1214 deletions(-) diff --git a/netconf/sal-netconf-connector/pom.xml b/netconf/sal-netconf-connector/pom.xml index 8106409eee..bccd4a782f 100644 --- a/netconf/sal-netconf-connector/pom.xml +++ b/netconf/sal-netconf-connector/pom.xml @@ -233,4 +233,16 @@ HEAD https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL + + + + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + + + diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java index 755959b64f..34f2cbed1f 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java @@ -44,14 +44,20 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Instead of using loopback (controller-config mount point) to create your netconf-connector, you should use the network-topology capability. + * Instead of using loopback (controller-config mount point) to create your netconf-connector, + * you should use the network-topology capability. + * *

- * Follow instructions provided in this wiki. + * Follow instructions provided in this + * wiki. + * *

* Deprecation notice in Carbon, removal planned for Nitrogen. */ @Deprecated -public final class NetconfConnectorModule extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule implements BindingAwareConsumer { +public final class NetconfConnectorModule + extends org.opendaylight.controller.config.yang.md.sal.connector.netconf.AbstractNetconfConnectorModule + implements BindingAwareConsumer { private static final Logger LOG = LoggerFactory.getLogger(NetconfConnectorModule.class); private static final InstanceIdentifier TOPOLOGY_PATH = InstanceIdentifier.create(NetworkTopology.class) @@ -60,12 +66,15 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co private InstanceIdentifier nodePath; private DataBroker dataBroker; - public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { + public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, + final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) { super(identifier, dependencyResolver); instanceName = identifier.getInstanceName(); } - public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) { + public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, + final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, + final NetconfConnectorModule oldModule, final java.lang.AutoCloseable oldInstance) { super(identifier, dependencyResolver, oldModule, oldInstance); instanceName = identifier.getInstanceName(); } @@ -73,7 +82,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co @Override protected void customValidation() { checkNotNull(getAddress(), addressJmxAttribute); - checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute); + checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), + addressJmxAttribute); checkNotNull(getPort(), portJmxAttribute); checkNotNull(getConnectionTimeoutMillis(), connectionTimeoutMillisJmxAttribute); @@ -93,8 +103,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co } private static boolean isHostAddressPresent(final Host address) { - return address.getDomainName() != null || - address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null); + return address.getDomainName() != null || address.getIpAddress() != null + && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null); } @Override @@ -120,8 +130,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co } @Override - public void onFailure(final Throwable t) { - LOG.error("Node {} creation failed: {}", instanceName, t); + public void onFailure(final Throwable throwable) { + LOG.error("Node {} creation failed: {}", instanceName, throwable); } }); } @@ -138,8 +148,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co } @Override - public void onFailure(final Throwable t) { - LOG.error("Node {} deletion failed: {}", instanceName, t); + public void onFailure(final Throwable throwable) { + LOG.error("Node {} deletion failed: {}", instanceName, throwable); } }); @@ -161,7 +171,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co } NonModuleCapabilities nonModuleCapabilities = null; - if(getNonModuleCapabilities() != null) { + if (getNonModuleCapabilities() != null) { nonModuleCapabilities = new NonModuleCapabilitiesBuilder() .setOverride(getNonModuleCapabilities().getOverride()) .setCapability(getNonModuleCapabilities().getCapability()) diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModuleFactory.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModuleFactory.java index 3e5fe6b247..0e5bb46b6b 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModuleFactory.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModuleFactory.java @@ -19,15 +19,16 @@ public class NetconfConnectorModuleFactory extends @Override public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception { - final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, - old, bundleContext); + final NetconfConnectorModule module = + (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, old, bundleContext); return module; } @Override - public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) { - final NetconfConnectorModule module = (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, - bundleContext); + public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, + final BundleContext bundleContext) { + final NetconfConnectorModule module = + (NetconfConnectorModule) super.createModule(instanceName, dependencyResolver, bundleContext); return module; } } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/NetconfDeviceSchemasResolver.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/NetconfDeviceSchemasResolver.java index c1a465ef6e..8031c15554 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/NetconfDeviceSchemasResolver.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/NetconfDeviceSchemasResolver.java @@ -13,8 +13,9 @@ import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; /** - * Factory for netconf device schemas + * Factory for netconf device schemas. */ public interface NetconfDeviceSchemasResolver { - NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id); + NetconfDeviceSchemas resolve( + NetconfDeviceRpc deviceRpc, NetconfSessionPreferences remoteSessionCapabilities, RemoteDeviceId id); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/RemoteDevice.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/RemoteDevice.java index dac321c749..e4f45f64bc 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/RemoteDevice.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/api/RemoteDevice.java @@ -8,7 +8,7 @@ package org.opendaylight.netconf.sal.connect.api; /** - * + * Remote device. */ public interface RemoteDevice> { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java index 9924d6fc75..9f59dba695 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java @@ -66,7 +66,7 @@ import org.xml.sax.SAXException; /** * Holds URLs with YANG schema resources for all yang modules reported in - * ietf-netconf-yang-library/modules-state/modules node + * ietf-netconf-yang-library/modules-state/modules node. */ public class LibraryModulesSchemas implements NetconfDeviceSchemas { @@ -76,9 +76,8 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { static { final ModuleInfoBackedContext moduleInfoBackedContext = ModuleInfoBackedContext.create(); - moduleInfoBackedContext.registerModuleInfo( - org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.library.rev160409. - $YangModuleInfoImpl.getInstance()); + moduleInfoBackedContext.registerModuleInfo(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang + .library.rev160409.$YangModuleInfoImpl.getInstance()); LIBRARY_CONTEXT = moduleInfoBackedContext.tryToCreateSchemaContext().get(); } @@ -104,7 +103,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { final Map result = Maps.newHashMap(); for (final Map.Entry entry : availableModels.entrySet()) { final SourceIdentifier sId = RevisionSourceIdentifier - .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision())); + .create(entry.getKey().getLocalName(), Optional.fromNullable(entry.getKey().getFormattedRevision())); result.put(sId, entry.getValue()); } @@ -123,7 +122,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { final URL urlConnection = new URL(url); final URLConnection connection = urlConnection.openConnection(); - if(connection instanceof HttpURLConnection) { + if (connection instanceof HttpURLConnection) { connection.setRequestProperty("Accept", "application/xml"); final String userpass = username + ":" + password; final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes()); @@ -150,11 +149,12 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { throw new RuntimeException(deviceId + ": Interrupted while waiting for response to " + MODULES_STATE_MODULE_LIST, e); } catch (final ExecutionException e) { - LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId, MODULES_STATE_MODULE_LIST, e); + LOG.warn("{}: Unable to detect available schemas, get to {} failed", deviceId, + MODULES_STATE_MODULE_LIST, e); return new LibraryModulesSchemas(Collections.emptyMap()); } - if(moduleListNodeResult.getErrors().isEmpty() == false) { + if (moduleListNodeResult.getErrors().isEmpty() == false) { LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", deviceId, MODULES_STATE_MODULE_LIST, moduleListNodeResult.getErrors()); return new LibraryModulesSchemas(Collections.emptyMap()); @@ -163,7 +163,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { final Optional> modulesStateNode = findModulesStateNode(moduleListNodeResult.getResult()); - if(modulesStateNode.isPresent()) { + if (modulesStateNode.isPresent()) { Preconditions.checkState(modulesStateNode.get() instanceof ContainerNode, "Expecting container containing schemas, but was %s", modulesStateNode.get()); return create(((ContainerNode) modulesStateNode.get())); @@ -173,18 +173,6 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { } } - private static Optional> findModulesStateNode(final NormalizedNode result) { - if(result == null) { - return Optional.absent(); - } - final Optional> dataNode = ((DataContainerNode) result).getChild(toId(NETCONF_DATA_QNAME)); - if(dataNode.isPresent() == false) { - return Optional.absent(); - } - - return ((DataContainerNode) dataNode.get()).getChild(toId(ModulesState.QNAME)); - } - private static LibraryModulesSchemas create(final ContainerNode modulesStateNode) { final YangInstanceIdentifier.NodeIdentifier moduleListNodeId = new YangInstanceIdentifier.NodeIdentifier(Module.QNAME); @@ -207,6 +195,42 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { return new LibraryModulesSchemas(schemasMapping.build()); } + /** + * Resolves URLs with YANG schema resources from modules-state. + * @param url URL pointing to yang library + * @return Resolved URLs with YANG schema resources for all yang modules from yang library + */ + public static LibraryModulesSchemas create(final String url) { + Preconditions.checkNotNull(url); + try { + final URL urlConnection = new URL(url); + final URLConnection connection = urlConnection.openConnection(); + + if (connection instanceof HttpURLConnection) { + connection.setRequestProperty("Accept", "application/xml"); + } + + return createFromURLConnection(connection); + + } catch (final IOException e) { + LOG.warn("Unable to download yang library from {}", url, e); + return new LibraryModulesSchemas(Collections.emptyMap()); + } + } + + private static Optional> findModulesStateNode(final NormalizedNode result) { + if (result == null) { + return Optional.absent(); + } + final Optional> dataNode = + ((DataContainerNode) result).getChild(toId(NETCONF_DATA_QNAME)); + if (dataNode.isPresent() == false) { + return Optional.absent(); + } + + return ((DataContainerNode) dataNode.get()).getChild(toId(ModulesState.QNAME)); + } + private static LibraryModulesSchemas createFromURLConnection(final URLConnection connection) { String contentType = connection.getContentType(); @@ -219,7 +243,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { Preconditions.checkNotNull(contentType, "Content type unknown"); Preconditions.checkState(contentType.equals("application/json") || contentType.equals("application/xml"), "Only XML and JSON types are supported."); - try (final InputStream in = connection.getInputStream()) { + try (InputStream in = connection.getInputStream()) { final Optional> optionalModulesStateNode = contentType.equals("application/json") ? readJson(in) : readXml(in); @@ -258,33 +282,10 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { } } - /** - * Resolves URLs with YANG schema resources from modules-state - * @param url URL pointing to yang library - * @return Resolved URLs with YANG schema resources for all yang modules from yang library - */ - public static LibraryModulesSchemas create(final String url) { - Preconditions.checkNotNull(url); - try { - final URL urlConnection = new URL(url); - final URLConnection connection = urlConnection.openConnection(); - - if(connection instanceof HttpURLConnection) { - connection.setRequestProperty("Accept", "application/xml"); - } - - return createFromURLConnection(connection); - - } catch (final IOException e) { - LOG.warn("Unable to download yang library from {}", url, e); - return new LibraryModulesSchemas(Collections.emptyMap()); - } - } - private static boolean guessJsonFromFileName(final String fileName) { String extension = ""; final int i = fileName.lastIndexOf(46); - if(i != -1) { + if (i != -1) { extension = fileName.substring(i).toLowerCase(); } @@ -300,9 +301,8 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { jsonParser.parse(reader); - return resultHolder.isFinished() ? - Optional.of(resultHolder.getResult()) : - Optional.>absent(); + return resultHolder.isFinished() + ? Optional.of(resultHolder.getResult()) : Optional.>absent(); } private static Optional> readXml(final InputStream in) { @@ -317,7 +317,7 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { parserFactory.getContainerNodeParser().parse(Collections.singleton(XmlUtil.readXmlToElement(in)), (ContainerSchemaNode) LIBRARY_CONTEXT.getDataChildByName(ModulesState.QNAME)); return Optional.of(parsed); - } catch (IOException|SAXException e) { + } catch (IOException | SAXException e) { LOG.warn("Unable to parse yang library xml content", e); } @@ -334,8 +334,8 @@ public class LibraryModulesSchemas implements NetconfDeviceSchemas { childNodeId = new YangInstanceIdentifier.NodeIdentifier(QName.create(Module.QNAME, "revision")); final Optional revision = getSingleChildNodeValue(moduleNode, childNodeId); - if(revision.isPresent()) { - if(!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) { + if (revision.isPresent()) { + if (!SourceIdentifier.REVISION_PATTERN.matcher(revision.get()).matches()) { LOG.warn("Skipping library schema for {}. Revision {} is in wrong format.", moduleNode, revision.get()); return Optional.>absent(); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java index 86ef2abc7f..45e67e3631 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java @@ -72,14 +72,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade + * This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade. */ -public class NetconfDevice implements RemoteDevice { +public class NetconfDevice + implements RemoteDevice { private static final Logger LOG = LoggerFactory.getLogger(NetconfDevice.class); public static final Function QNAME_TO_SOURCE_ID_FUNCTION = - input -> RevisionSourceIdentifier.create(input.getLocalName(), + input -> RevisionSourceIdentifier.create(input.getLocalName(), Optional.fromNullable(input.getFormattedRevision())); protected final RemoteDeviceId id; @@ -92,23 +93,28 @@ public class NetconfDevice implements RemoteDevice> sourceRegistrations = Lists.newArrayList(); + protected final List> sourceRegistrations = + Lists.newArrayList(); // Message transformer is constructed once the schemas are available private MessageTransformer messageTransformer; /** - * Create rpc implementation capable of handling RPC for monitoring and notifications even before the schemas of remote device are downloaded + * Create rpc implementation capable of handling RPC for monitoring and notifications + * even before the schemas of remote device are downloaded. */ - static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, final boolean notificationSupport) { - final BaseSchema baseSchema = notificationSupport ? - BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS : - BaseSchema.BASE_NETCONF_CTX; - - return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema)); + static NetconfDeviceRpc getRpcForInitialization(final NetconfDeviceCommunicator listener, + final boolean notificationSupport) { + final BaseSchema baseSchema = notificationSupport + ? BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS + : BaseSchema.BASE_NETCONF_CTX; + + return new NetconfDeviceRpc(baseSchema.getSchemaContext(), listener, + new NetconfMessageTransformer(baseSchema.getSchemaContext(), false, baseSchema)); } - public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, final RemoteDeviceHandler salFacade, + public NetconfDevice(final SchemaResourcesDTO schemaResourcesDTO, final RemoteDeviceId id, + final RemoteDeviceHandler salFacade, final ExecutorService globalProcessingExecutor, final boolean reconnectOnSchemasChange) { this.id = id; this.reconnectOnSchemasChange = reconnectOnSchemasChange; @@ -131,8 +137,10 @@ public class NetconfDevice implements RemoteDevice sourceResolverFuture = processingExecutor.submit(task); if (shouldListenOnSchemaChange(remoteSessionCapabilities)) { @@ -151,18 +159,20 @@ public class NetconfDevice implements RemoteDevice rpcResultListenableFuture = deviceRpc.invokeRpc( NetconfMessageTransformUtil.toPath(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME), NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_CONTENT); @@ -172,7 +182,8 @@ public class NetconfDevice implements RemoteDevice filterNotification(final DOMNotification notification) { if (isCapabilityChanged(notification)) { LOG.info("{}: Schemas change detected, reconnecting", id); - // Only disconnect is enough, the reconnecting nature of the connector will take care of reconnecting + // Only disconnect is enough, + // the reconnecting nature of the connector will take care of reconnecting listener.disconnect(); return Optional.absent(); } @@ -191,8 +202,9 @@ public class NetconfDevice implements RemoteDevice listener) { - LOG.error("{}: Initialization in sal failed, disconnecting from device", id, t); + void handleSalInitializationFailure(final Throwable throwable, + final RemoteDeviceCommunicator listener) { + LOG.error("{}: Initialization in sal failed, disconnecting from device", id, throwable); listener.close(); onRemoteSessionDown(); resetMessageTransformer(); } /** - * Set the transformer to null as is in initial state + * Set the transformer to null as is in initial state. */ private void resetMessageTransformer() { updateTransformer(null); @@ -240,7 +252,8 @@ public class NetconfDevice implements RemoteDevice yangProvider = deviceSources.getSourceProvider(); for (final SourceIdentifier sourceId : deviceSources.getProvidedSources()) { sourceRegistrations.add(schemaRegistry.registerSchemaSource(yangProvider, - PotentialSchemaSource.create(sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue()))); + PotentialSchemaSource.create( + sourceId, YangTextSchemaSource.class, PotentialSchemaSource.Costs.REMOTE_IO.getValue()))); } } @@ -249,7 +262,8 @@ public class NetconfDevice implements RemoteDevice sourceRegistration : sourceRegistrations) { + for (final SchemaSourceRegistration sourceRegistration + : sourceRegistrations) { sourceRegistration.close(); } resetMessageTransformer(); @@ -311,48 +325,54 @@ public class NetconfDevice implements RemoteDevice requiredSources = Sets.newHashSet(remoteSessionCapabilities.getModuleBasedCaps()); final Set providedSources = availableSchemas.getAvailableYangSchemasQNames(); final Set requiredSourcesNotProvided = Sets.difference(requiredSources, providedSources); if (!requiredSourcesNotProvided.isEmpty()) { - LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities, required but not provided: {}", - id, requiredSourcesNotProvided); + LOG.warn("{}: Netconf device does not provide all yang models reported in hello message capabilities," + + " required but not provided: {}", id, requiredSourcesNotProvided); LOG.warn("{}: Attempting to build schema context from required sources", id); } // Here all the sources reported in netconf monitoring are merged with those reported in hello. // It is necessary to perform this since submodules are not mentioned in hello but still required. - // This clashes with the option of a user to specify supported yang models manually in configuration for netconf-connector - // and as a result one is not able to fully override yang models of a device. It is only possible to add additional models. + // This clashes with the option of a user to specify supported yang models manually in configuration + // for netconf-connector and as a result one is not able to fully override yang models of a device. + // It is only possible to add additional models. final Set providedSourcesNotRequired = Sets.difference(providedSources, requiredSources); if (!providedSourcesNotRequired.isEmpty()) { - LOG.warn("{}: Netconf device provides additional yang models not reported in hello message capabilities: {}", - id, providedSourcesNotRequired); + LOG.warn("{}: Netconf device provides additional yang models not reported in " + + "hello message capabilities: {}", id, providedSourcesNotRequired); LOG.warn("{}: Adding provided but not required sources as required to prevent failures", id); LOG.debug("{}: Netconf device reported in hello: {}", id, requiredSources); requiredSources.addAll(providedSourcesNotRequired); } final SchemaSourceProvider sourceProvider; - if(availableSchemas instanceof LibraryModulesSchemas) { + if (availableSchemas instanceof LibraryModulesSchemas) { sourceProvider = new YangLibrarySchemaYangSourceProvider(id, ((LibraryModulesSchemas) availableSchemas).getAvailableModels()); } else { @@ -371,7 +391,7 @@ public class NetconfDevice implements RemoteDevice providedSources; private final SchemaSourceProvider sourceProvider; - public DeviceSources(final Set requiredSources, final Set providedSources, + DeviceSources(final Set requiredSources, final Set providedSources, final SchemaSourceProvider sourceProvider) { this.requiredSources = requiredSources; this.providedSources = providedSources; @@ -408,7 +428,8 @@ public class NetconfDevice implements RemoteDevice listener; private final NetconfDeviceCapabilities capabilities; - public SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceCommunicator listener) { + SchemaSetup(final DeviceSources deviceSources, final NetconfSessionPreferences remoteSessionCapabilities, + final RemoteDeviceCommunicator listener) { this.deviceSources = deviceSources; this.remoteSessionCapabilities = remoteSessionCapabilities; this.listener = listener; @@ -431,49 +452,58 @@ public class NetconfDevice implements RemoteDevice filterMissingSources(final Collection requiredSources) { return requiredSources.parallelStream().filter(sourceIdentifier -> { - boolean remove = false; - try { - schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet(); - } catch (SchemaSourceException e) { - remove = true; - } - return remove; - }).collect(Collectors.toList()); + boolean remove = false; + try { + schemaRepository.getSchemaSource(sourceIdentifier, ASTSchemaSource.class).checkedGet(); + } catch (SchemaSourceException e) { + remove = true; + } + return remove; + }).collect(Collectors.toList()); } /** - * Build schema context, in case of success or final failure notify device + * Build schema context, in case of success or final failure notify device. */ + @SuppressWarnings("checkstyle:IllegalCatch") private void setUpSchema(Collection requiredSources) { while (!requiredSources.isEmpty()) { LOG.trace("{}: Trying to build schema context from {}", id, requiredSources); try { - final CheckedFuture schemaBuilderFuture = schemaContextFactory.createSchemaContext(requiredSources); + final CheckedFuture schemaBuilderFuture = + schemaContextFactory.createSchemaContext(requiredSources); final SchemaContext result = schemaBuilderFuture.checkedGet(); LOG.debug("{}: Schema context built successfully from {}", id, requiredSources); - final Collection filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), capabilities.getUnresolvedCapabilites().keySet()); + final Collection filteredQNames = Sets.difference(deviceSources.getRequiredSourcesQName(), + capabilities.getUnresolvedCapabilites().keySet()); capabilities.addCapabilities(filteredQNames.stream().map(entry -> new AvailableCapabilityBuilder() - .setCapability(entry.toString()).setCapabilityOrigin(remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build()) + .setCapability(entry.toString()).setCapabilityOrigin( + remoteSessionCapabilities.getModuleBasedCapsOrigin().get(entry)).build()) .collect(Collectors.toList())); - capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities.getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder() - .setCapability(entry).setCapabilityOrigin(remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build()) + capabilities.addNonModuleBasedCapabilities(remoteSessionCapabilities + .getNonModuleCaps().stream().map(entry -> new AvailableCapabilityBuilder() + .setCapability(entry).setCapabilityOrigin( + remoteSessionCapabilities.getNonModuleBasedCapsOrigin().get(entry)).build()) .collect(Collectors.toList())); handleSalInitializationSuccess(result, remoteSessionCapabilities, getDeviceSpecificRpc(result)); return; } catch (final Throwable t) { - if (t instanceof MissingSchemaSourceException){ - requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t); + if (t instanceof MissingSchemaSourceException) { + requiredSources = + handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t); } else if (t instanceof SchemaResolutionException) { // schemaBuilderFuture.checkedGet() throws only SchemaResolutionException // that might be wrapping a MissingSchemaSourceException so we need to look // at the cause of the exception to make sure we don't misinterpret it. if (t.getCause() instanceof MissingSchemaSourceException) { - requiredSources = handleMissingSchemaSourceException(requiredSources, (MissingSchemaSourceException) t.getCause()); + requiredSources = handleMissingSchemaSourceException( + requiredSources, (MissingSchemaSourceException) t.getCause()); continue; } - requiredSources = handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t); + requiredSources = + handleSchemaResolutionException(requiredSources, (SchemaResolutionException) t); } else { // unknown error, fail handleSalInitializationFailure(t, listener); @@ -487,36 +517,47 @@ public class NetconfDevice implements RemoteDevice handleMissingSchemaSourceException(final Collection requiredSources, final MissingSchemaSourceException t) { + private Collection handleMissingSchemaSourceException( + final Collection requiredSources, final MissingSchemaSourceException exception) { // In case source missing, try without it - final SourceIdentifier missingSource = t.getSourceId(); - LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, missingSource); - LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", t); - final Collection qNameOfMissingSource = getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource)); + final SourceIdentifier missingSource = exception.getSourceId(); + LOG.warn("{}: Unable to build schema context, missing source {}, will reattempt without it", id, + missingSource); + LOG.debug("{}: Unable to build schema context, missing source {}, will reattempt without it", + exception); + final Collection qNameOfMissingSource = + getQNameFromSourceIdentifiers(Sets.newHashSet(missingSource)); if (!qNameOfMissingSource.isEmpty()) { - capabilities.addUnresolvedCapabilities(qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource); + capabilities.addUnresolvedCapabilities( + qNameOfMissingSource, UnavailableCapability.FailureReason.MissingSource); } return stripUnavailableSource(requiredSources, missingSource); } - private Collection handleSchemaResolutionException(final Collection requiredSources, final SchemaResolutionException resolutionException) { + private Collection handleSchemaResolutionException( + final Collection requiredSources, final SchemaResolutionException resolutionException) { // In case resolution error, try only with resolved sources // There are two options why schema resolution exception occurred : unsatisfied imports or flawed model // FIXME Do we really have assurance that these two cases cannot happen at once? if (resolutionException.getFailedSource() != null) { // flawed model - exclude it final SourceIdentifier failedSourceId = resolutionException.getFailedSource(); - LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, failedSourceId); - LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", id, resolutionException); - capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(Collections.singleton(failedSourceId)), - UnavailableCapability.FailureReason.UnableToResolve); + LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", + id, failedSourceId); + LOG.warn("{}: Unable to build schema context, failed to resolve source {}, will reattempt without it", + id, resolutionException); + capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers( + Collections.singleton(failedSourceId)), UnavailableCapability.FailureReason.UnableToResolve); return stripUnavailableSource(requiredSources, resolutionException.getFailedSource()); } // unsatisfied imports final Set unresolvedSources = resolutionException.getUnsatisfiedImports().keySet(); - capabilities.addUnresolvedCapabilities(getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve); - LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", id, resolutionException.getUnsatisfiedImports()); - LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", resolutionException); + capabilities.addUnresolvedCapabilities( + getQNameFromSourceIdentifiers(unresolvedSources), UnavailableCapability.FailureReason.UnableToResolve); + LOG.warn("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", + id, resolutionException.getUnsatisfiedImports()); + LOG.debug("{}: Unable to build schema context, unsatisfied imports {}, will reattempt with resolved only", + resolutionException); return resolutionException.getResolvedSources(); } @@ -524,10 +565,12 @@ public class NetconfDevice implements RemoteDevice stripUnavailableSource(final Collection requiredSources, final SourceIdentifier sIdToRemove) { + private Collection stripUnavailableSource(final Collection requiredSources, + final SourceIdentifier sourceIdToRemove) { final LinkedList sourceIdentifiers = Lists.newLinkedList(requiredSources); - final boolean removed = sourceIdentifiers.remove(sIdToRemove); - Preconditions.checkState(removed, "{}: Trying to remove {} from {} failed", id, sIdToRemove, requiredSources); + final boolean removed = sourceIdentifiers.remove(sourceIdToRemove); + Preconditions.checkState( + removed, "{}: Trying to remove {} from {} failed", id, sourceIdToRemove, requiredSources); return sourceIdentifiers; } @@ -535,7 +578,8 @@ public class NetconfDevice implements RemoteDevice qNames = Collections2.transform(identifiers, this::getQNameFromSourceIdentifier); if (qNames.isEmpty()) { - LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, identifiers); + LOG.debug("{}: Unable to map any source identifiers to a capability reported by device : {}", id, + identifiers); } return Collections2.filter(qNames, Predicates.notNull()); } @@ -556,8 +600,10 @@ public class NetconfDevice implements RemoteDevice filter = NetconfMessageTransformUtil.toFilterStructure(STATE_SCHEMAS_IDENTIFIER, BaseSchema.BASE_NETCONF_CTX_WITH_NOTIFICATIONS.getSchemaContext()); @@ -81,19 +82,21 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { @Override public Set getAvailableYangSchemasQNames() { - return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), new Function() { - @Override - public QName apply(final RemoteYangSchema input) { - return input.getQName(); - } - })); + return Sets.newHashSet(Collections2.transform(getAvailableYangSchemas(), + new Function() { + @Override + public QName apply(final RemoteYangSchema input) { + return input.getQName(); + } + })); } /** - * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas + * Issue get request to remote device and parse response to find all schemas under netconf-state/schemas. */ - static NetconfStateSchemas create(final DOMRpcService deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) { - if(remoteSessionCapabilities.isMonitoringSupported() == false) { + static NetconfStateSchemas create(final DOMRpcService deviceRpc, + final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) { + if (remoteSessionCapabilities.isMonitoringSupported() == false) { // TODO - need to search for get-schema support, not just ietf-netconf-monitoring support // issue might be a deviation to ietf-netconf-monitoring where get-schema is unsupported... LOG.warn("{}: Netconf monitoring not supported on device, cannot detect provided schemas", id); @@ -105,20 +108,22 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { schemasNodeResult = deviceRpc.invokeRpc(toPath(NETCONF_GET_QNAME), GET_SCHEMAS_RPC).get(); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); - throw new RuntimeException(id + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e); + throw new RuntimeException(id + + ": Interrupted while waiting for response to " + STATE_SCHEMAS_IDENTIFIER, e); } catch (final ExecutionException e) { LOG.warn("{}: Unable to detect available schemas, get to {} failed", id, STATE_SCHEMAS_IDENTIFIER, e); return EMPTY; } - if(schemasNodeResult.getErrors().isEmpty() == false) { - LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors()); + if (schemasNodeResult.getErrors().isEmpty() == false) { + LOG.warn("{}: Unable to detect available schemas, get to {} failed, {}", + id, STATE_SCHEMAS_IDENTIFIER, schemasNodeResult.getErrors()); return EMPTY; } final Optional> schemasNode = findSchemasNode(schemasNodeResult.getResult()); - if(schemasNode.isPresent()) { + if (schemasNode.isPresent()) { Preconditions.checkState(schemasNode.get() instanceof ContainerNode, "Expecting container containing schemas, but was %s", schemasNode.get()); return create(id, (ContainerNode) schemasNode.get()); @@ -128,38 +133,25 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { } } - private static Optional> findSchemasNode(final NormalizedNode result) { - if(result == null) { - return Optional.absent(); - } - final Optional> dataNode = ((DataContainerNode) result).getChild(toId(NETCONF_DATA_QNAME)); - if(dataNode.isPresent() == false) { - return Optional.absent(); - } - - final Optional> nStateNode = - ((DataContainerNode) dataNode.get()).getChild(toId(NetconfState.QNAME)); - if(nStateNode.isPresent() == false) { - return Optional.absent(); - } - - return ((DataContainerNode) nStateNode.get()).getChild(toId(Schemas.QNAME)); - } - /** - * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas + * Parse response of get(netconf-state/schemas) to find all schemas under netconf-state/schemas. */ @VisibleForTesting protected static NetconfStateSchemas create(final RemoteDeviceId id, final ContainerNode schemasNode) { final Set availableYangSchemas = Sets.newHashSet(); - final Optional> child = schemasNode.getChild(toId(Schema.QNAME)); - Preconditions.checkState(child.isPresent(), "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode); - Preconditions.checkState(child.get() instanceof MapNode, "Unexpected structure for container: %s in response: %s. Expecting a list", Schema.QNAME.withoutRevision(), schemasNode); + final Optional> child = + schemasNode.getChild(toId(Schema.QNAME)); + Preconditions.checkState(child.isPresent(), + "Unable to find list: %s in response: %s", Schema.QNAME.withoutRevision(), schemasNode); + Preconditions.checkState(child.get() instanceof MapNode, + "Unexpected structure for container: %s in response: %s. Expecting a list", + Schema.QNAME.withoutRevision(), schemasNode); for (final MapEntryNode schemaNode : ((MapNode) child.get()).getValue()) { - final Optional fromCompositeNode = RemoteYangSchema.createFromNormalizedNode(id, schemaNode); - if(fromCompositeNode.isPresent()) { + final Optional fromCompositeNode = + RemoteYangSchema.createFromNormalizedNode(id, schemaNode); + if (fromCompositeNode.isPresent()) { availableYangSchemas.add(fromCompositeNode.get()); } } @@ -167,7 +159,26 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { return new NetconfStateSchemas(availableYangSchemas); } - public final static class RemoteYangSchema { + private static Optional> findSchemasNode(final NormalizedNode result) { + if (result == null) { + return Optional.absent(); + } + final Optional> dataNode = + ((DataContainerNode) result).getChild(toId(NETCONF_DATA_QNAME)); + if (dataNode.isPresent() == false) { + return Optional.absent(); + } + + final Optional> nStateNode = + ((DataContainerNode) dataNode.get()).getChild(toId(NetconfState.QNAME)); + if (nStateNode.isPresent() == false) { + return Optional.absent(); + } + + return ((DataContainerNode) nStateNode.get()).getChild(toId(Schemas.QNAME)); + } + + public static final class RemoteYangSchema { private final QName qname; RemoteYangSchema(final QName qname) { @@ -178,21 +189,23 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { return qname; } - static Optional createFromNormalizedNode(final RemoteDeviceId id, final MapEntryNode schemaNode) { - Preconditions.checkArgument(schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType()); + static Optional createFromNormalizedNode(final RemoteDeviceId id, + final MapEntryNode schemaNode) { + Preconditions.checkArgument( + schemaNode.getNodeType().equals(Schema.QNAME), "Wrong QName %s", schemaNode.getNodeType()); QName childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_FORMAT; final String formatAsString = getSingleChildNodeValue(schemaNode, childNode).get(); - if(formatAsString.equals(Yang.QNAME.toString()) == false) { + if (formatAsString.equals(Yang.QNAME.toString()) == false) { LOG.debug("{}: Ignoring schema due to unsupported format: {}", id, formatAsString); return Optional.absent(); } childNode = NetconfMessageTransformUtil.IETF_NETCONF_MONITORING_SCHEMA_LOCATION; final Set locationsAsString = getAllChildNodeValues(schemaNode, childNode); - if(locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) { + if (locationsAsString.contains(Schema.Location.Enumeration.NETCONF.toString()) == false) { LOG.debug("{}: Ignoring schema due to unsupported location: {}", id, locationsAsString); return Optional.absent(); } @@ -220,21 +233,26 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { } /** - * Extracts all values of a leaf-list node as a set of strings + * Extracts all values of a leaf-list node as a set of strings. */ - private static Set getAllChildNodeValues(final DataContainerNode schemaNode, final QName childNodeQName) { + private static Set getAllChildNodeValues(final DataContainerNode schemaNode, + final QName childNodeQName) { final Set extractedValues = Sets.newHashSet(); - final Optional> child = schemaNode.getChild(toId(childNodeQName)); + final Optional> child = + schemaNode.getChild(toId(childNodeQName)); Preconditions.checkArgument(child.isPresent(), "Child nodes %s not present", childNodeQName); - Preconditions.checkArgument(child.get() instanceof LeafSetNode, "Child nodes %s not present", childNodeQName); + Preconditions.checkArgument(child.get() instanceof LeafSetNode, + "Child nodes %s not present", childNodeQName); for (final LeafSetEntryNode childNode : ((LeafSetNode) child.get()).getValue()) { extractedValues.add(getValueOfSimpleNode(childNode).get()); } return extractedValues; } - private static Optional getSingleChildNodeValue(final DataContainerNode schemaNode, final QName childNode) { - final Optional> node = schemaNode.getChild(toId(childNode)); + private static Optional getSingleChildNodeValue(final DataContainerNode schemaNode, + final QName childNode) { + final Optional> node = + schemaNode.getChild(toId(childNode)); if (node.isPresent()) { return getValueOfSimpleNode(node.get()); } else { @@ -243,21 +261,23 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { } } - private static Optional getValueOfSimpleNode(final NormalizedNode node) { + private static Optional getValueOfSimpleNode( + final NormalizedNode node) { final Object value = node.getValue(); - return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.absent() : Optional.of(value.toString().trim()); + return value == null || Strings.isNullOrEmpty(value.toString()) + ? Optional.absent() : Optional.of(value.toString().trim()); } @Override - public boolean equals(final Object o) { - if (this == o) { + public boolean equals(final Object obj) { + if (this == obj) { return true; } - if (o == null || getClass() != o.getClass()) { + if (obj == null || getClass() != obj.getClass()) { return false; } - final RemoteYangSchema that = (RemoteYangSchema) o; + final RemoteYangSchema that = (RemoteYangSchema) obj; if (!qname.equals(that.qname)) { return false; diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasResolverImpl.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasResolverImpl.java index 6931cf8733..c2947d9860 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasResolverImpl.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemasResolverImpl.java @@ -17,15 +17,18 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.librar import org.opendaylight.yangtools.yang.common.QName; /** - * Default implementation resolving schemas QNames from netconf-state or from modules-state + * Default implementation resolving schemas QNames from netconf-state or from modules-state. */ public final class NetconfStateSchemasResolverImpl implements NetconfDeviceSchemasResolver { @Override - public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) { + public NetconfDeviceSchemas resolve(final NetconfDeviceRpc deviceRpc, + final NetconfSessionPreferences remoteSessionCapabilities, + final RemoteDeviceId id) { if (remoteSessionCapabilities.isMonitoringSupported()) { return NetconfStateSchemas.create(deviceRpc, remoteSessionCapabilities, id); - } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME, "ietf-yang-library"))) { + } else if (remoteSessionCapabilities.containsModuleCapability(QName.create(ModulesState.QNAME, + "ietf-yang-library"))) { return LibraryModulesSchemas.create(deviceRpc, id); } return NetconfStateSchemas.EMPTY; diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java index 232c7c7569..5b28366c07 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NotificationHandler.java @@ -41,7 +41,7 @@ final class NotificationHandler { } synchronized void handleNotification(final NetconfMessage notification) { - if(passNotifications) { + if (passNotifications) { passNotification(transformNotification(notification)); } else { queueNotification(notification); @@ -50,7 +50,7 @@ final class NotificationHandler { /** * Forward all cached notifications and pass all notifications from this point directly to sal facade. - * @param messageTransformer + * @param messageTransformer Message transformer */ synchronized void onRemoteSchemaUp(final MessageTransformer messageTransformer) { this.messageTransformer = Preconditions.checkNotNull(messageTransformer); @@ -66,7 +66,8 @@ final class NotificationHandler { private DOMNotification transformNotification(final NetconfMessage cachedNotification) { final DOMNotification parsedNotification = messageTransformer.toNotification(cachedNotification); - Preconditions.checkNotNull(parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification); + Preconditions.checkNotNull( + parsedNotification, "%s: Unable to parse received notification: %s", id, cachedNotification); return parsedNotification; } @@ -74,7 +75,7 @@ final class NotificationHandler { Preconditions.checkState(passNotifications == false); LOG.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification); - if(LOG.isTraceEnabled()) { + if (LOG.isTraceEnabled()) { LOG.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument())); } @@ -84,7 +85,7 @@ final class NotificationHandler { private synchronized void passNotification(final DOMNotification parsedNotification) { LOG.debug("{}: Forwarding notification {}", id, parsedNotification); - if(filter == null || filter.filterNotification(parsedNotification).isPresent()) { + if (filter == null || filter.filterNotification(parsedNotification).isPresent()) { salFacade.onNotification(parsedNotification); } } @@ -99,7 +100,7 @@ final class NotificationHandler { messageTransformer = null; } - static interface NotificationFilter { + interface NotificationFilter { Optional filterNotification(DOMNotification notification); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java index 00dd66f260..83ee068eb6 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java @@ -44,7 +44,8 @@ import org.opendaylight.yangtools.yang.common.RpcResultBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator { +public class NetconfDeviceCommunicator + implements NetconfClientSessionListener, RemoteDeviceCommunicator { private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceCommunicator.class); @@ -73,19 +74,24 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, return isSessionClosing.get(); } - public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice remoteDevice, - final UserPreferences NetconfSessionPreferences, final int rpcMessageLimit) { - this(id, remoteDevice, Optional.of(NetconfSessionPreferences), rpcMessageLimit); + public NetconfDeviceCommunicator( + final RemoteDeviceId id, + final RemoteDevice remoteDevice, + final UserPreferences netconfSessionPreferences, final int rpcMessageLimit) { + this(id, remoteDevice, Optional.of(netconfSessionPreferences), rpcMessageLimit); } - public NetconfDeviceCommunicator(final RemoteDeviceId id, - final RemoteDevice remoteDevice, - final int rpcMessageLimit) { + public NetconfDeviceCommunicator( + final RemoteDeviceId id, + final RemoteDevice remoteDevice, + final int rpcMessageLimit) { this(id, remoteDevice, Optional.absent(), rpcMessageLimit); } - private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice remoteDevice, - final Optional overrideNetconfCapabilities, final int rpcMessageLimit) { + private NetconfDeviceCommunicator( + final RemoteDeviceId id, + final RemoteDevice remoteDevice, + final Optional overrideNetconfCapabilities, final int rpcMessageLimit) { this.concurentRpcMsgs = rpcMessageLimit; this.id = id; this.remoteDevice = remoteDevice; @@ -124,21 +130,22 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, if (!firstConnectionFuture.isDone()) { firstConnectionFuture.set(netconfSessionPreferences.getNetconfDeviceCapabilities()); } - } - finally { + } finally { sessionLock.unlock(); } } /** + * Initialize remote connection. * - * @param dispatcher - * @param config + * @param dispatcher {@code NetconfCLientDispatcher} + * @param config {@code NetconfClientConfiguration} * @return future that returns succes on first succesfull connection and failure when the underlying - * reconnecting strategy runs out of reconnection attempts + * reconnecting strategy runs out of reconnection attempts */ - public ListenableFuture initializeRemoteConnection(final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) { - if(config instanceof NetconfReconnectingClientConfiguration) { + public ListenableFuture initializeRemoteConnection( + final NetconfClientDispatcher dispatcher, final NetconfClientConfiguration config) { + if (config instanceof NetconfReconnectingClientConfiguration) { initFuture = dispatcher.createReconnectingClient((NetconfReconnectingClientConfiguration) config); } else { initFuture = dispatcher.createClient(config); @@ -159,7 +166,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, public void disconnect() { // If session is already in closing, no need to close it again - if(session != null && isSessionClosing.compareAndSet(false, true)) { + if (session != null && isSessionClosing.compareAndSet(false, true)) { session.close(); } } @@ -172,9 +179,8 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, final List>> futuresToCancel = Lists.newArrayList(); sessionLock.lock(); try { - if( session != null ) { + if (session != null) { session = null; - /* * Walk all requests, check if they have been executing * or cancelled and remove them from the queue. @@ -183,7 +189,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, while (it.hasNext()) { final Request r = it.next(); if (r.future.isUncancellable()) { - futuresToCancel.add( r.future ); + futuresToCancel.add(r.future); it.remove(); } else if (r.future.isCancelled()) { // This just does some house-cleaning @@ -193,18 +199,17 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, remoteDevice.onRemoteSessionDown(); } - } - finally { + } finally { sessionLock.unlock(); } // Notify pending request futures outside of the sessionLock to avoid unnecessarily // blocking the caller. for (final UncancellableFuture> future : futuresToCancel) { - if( Strings.isNullOrEmpty( reason ) ) { - future.set( createSessionDownRpcResult() ); + if (Strings.isNullOrEmpty(reason)) { + future.set(createSessionDownRpcResult()); } else { - future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, reason ) ); + future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, reason)); } } @@ -212,22 +217,22 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, } private RpcResult createSessionDownRpcResult() { - return createErrorRpcResult( RpcError.ErrorType.TRANSPORT, - String.format( "The netconf session to %1$s is disconnected", id.getName() ) ); + return createErrorRpcResult(RpcError.ErrorType.TRANSPORT, + String.format("The netconf session to %1$s is disconnected", id.getName())); } private static RpcResult createErrorRpcResult(final RpcError.ErrorType errorType, final String message) { return RpcResultBuilder.failed() - .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build(); + .withError(errorType, NetconfDocumentedException.ErrorTag.OPERATION_FAILED.getTagValue(), message).build(); } @Override - public void onSessionDown(final NetconfClientSession session, final Exception e) { + public void onSessionDown(final NetconfClientSession session, final Exception exception) { // If session is already in closing, no need to call tearDown again. if (isSessionClosing.compareAndSet(false, true)) { - LOG.warn("{}: Session went down", id, e); - tearDown( null ); + LOG.warn("{}: Session went down", id, exception); + tearDown(null); } } @@ -235,13 +240,13 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, public void onSessionTerminated(final NetconfClientSession session, final NetconfTerminationReason reason) { // onSessionTerminated is called directly by disconnect, no need to compare and set isSessionClosing. LOG.warn("{}: Session terminated {}", id, reason); - tearDown( reason.getErrorMessage() ); + tearDown(reason.getErrorMessage()); } @Override public void close() { // Cancel reconnect if in progress - if(initFuture != null) { + if (initFuture != null) { initFuture.cancel(false); } // Disconnect from device @@ -272,7 +277,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, requests.poll(); // we have just removed one request from the queue // we can also release one permit - if(semaphore != null) { + if (semaphore != null) { semaphore.release(); } } else { @@ -280,28 +285,28 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, LOG.warn("{}: Ignoring unsolicited message {}", id, msgToS(message)); } - } - finally { + } finally { sessionLock.unlock(); } - if( request != null ) { + if (request != null) { LOG.debug("{}: Message received {}", id, message); - if(LOG.isTraceEnabled()) { - LOG.trace( "{}: Matched request: {} to response: {}", id, msgToS( request.request ), msgToS( message ) ); + if (LOG.isTraceEnabled()) { + LOG.trace("{}: Matched request: {} to response: {}", id, msgToS(request.request), msgToS(message)); } try { - NetconfMessageTransformUtil.checkValidReply( request.request, message ); + NetconfMessageTransformUtil.checkValidReply(request.request, message); } catch (final NetconfDocumentedException e) { LOG.warn( - "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}", + "{}: Invalid request-reply match," + + "reply message contains different message-id, request: {}, response: {}", id, msgToS(request.request), msgToS(message), e); - request.future.set( RpcResultBuilder.failed() - .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() ); + request.future.set(RpcResultBuilder.failed() + .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build()); //recursively processing message to eventually find matching request processMessage(message); @@ -311,17 +316,17 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, try { NetconfMessageTransformUtil.checkSuccessReply(message); - } catch(final NetconfDocumentedException e) { + } catch (final NetconfDocumentedException e) { LOG.warn( "{}: Error reply from remote device, request: {}, response: {}", id, msgToS(request.request), msgToS(message), e); - request.future.set( RpcResultBuilder.failed() - .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() ); + request.future.set(RpcResultBuilder.failed() + .withRpcError(NetconfMessageTransformUtil.toRpcError(e)).build()); return; } - request.future.set( RpcResultBuilder.success( message ).build() ); + request.future.set(RpcResultBuilder.success(message).build()); } } @@ -334,11 +339,13 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, sessionLock.lock(); if (semaphore != null && !semaphore.tryAcquire()) { - LOG.warn("Limit of concurrent rpc messages was reached (limit :" + - concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName()); + LOG.warn("Limit of concurrent rpc messages was reached (limit :" + + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" + + id.getName()); sessionLock.unlock(); - return Futures.immediateFailedFuture(new NetconfDocumentedException("Limit of rpc messages was reached (Limit :" + - concurentRpcMsgs + ") waiting for emptying the queue of Netconf device with id" + id.getName())); + return Futures.immediateFailedFuture(new NetconfDocumentedException( + "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs + + ") waiting for emptying the queue of Netconf device with id" + id.getName())); } try { @@ -348,37 +355,36 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, } } - private ListenableFuture> sendRequestWithLock( - final NetconfMessage message, final QName rpc) { - if(LOG.isTraceEnabled()) { + private ListenableFuture> sendRequestWithLock(final NetconfMessage message, + final QName rpc) { + if (LOG.isTraceEnabled()) { LOG.trace("{}: Sending message {}", id, msgToS(message)); } if (session == null) { LOG.warn("{}: Session is disconnected, failing RPC request {}", id, message); - return Futures.immediateFuture( createSessionDownRpcResult() ); + return Futures.immediateFuture(createSessionDownRpcResult()); } final Request req = new Request(new UncancellableFuture<>(true), message); requests.add(req); session.sendMessage(req.request).addListener(future -> { - if( !future.isSuccess() ) { + if (!future.isSuccess()) { // We expect that a session down will occur at this point LOG.debug("{}: Failed to send request {}", id, XmlUtil.toString(req.request.getDocument()), future.cause()); - if( future.cause() != null ) { - req.future.set( createErrorRpcResult( RpcError.ErrorType.TRANSPORT, - future.cause().getLocalizedMessage() ) ); + if (future.cause() != null) { + req.future.set(createErrorRpcResult(RpcError.ErrorType.TRANSPORT, + future.cause().getLocalizedMessage())); } else { - req.future.set( createSessionDownRpcResult() ); // assume session is down + req.future.set(createSessionDownRpcResult()); // assume session is down } - req.future.setException( future.cause() ); - } - else { + req.future.setException(future.cause()); + } else { LOG.trace("Finished sending request {}", req.request); } }); @@ -387,7 +393,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener, } private void processNotification(final NetconfMessage notification) { - if(LOG.isTraceEnabled()) { + if (LOG.isTraceEnabled()) { LOG.trace("{}: Notification received: {}", id, notification); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java index 6525f019d7..a08996da90 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfSessionPreferences.java @@ -72,7 +72,8 @@ public final class NetconfSessionPreferences { private final Map moduleBasedCaps; private final Map nonModuleCaps; - NetconfSessionPreferences(final Map nonModuleCaps, final Map moduleBasedCaps) { + NetconfSessionPreferences(final Map nonModuleCaps, + final Map moduleBasedCaps) { this.nonModuleCaps = Preconditions.checkNotNull(nonModuleCaps); this.moduleBasedCaps = Preconditions.checkNotNull(moduleBasedCaps); } @@ -96,7 +97,7 @@ public final class NetconfSessionPreferences { // allows partial matches - assuming parameters are in the same order public boolean containsPartialNonModuleCapability(final String capability) { final Iterator iterator = getNonModuleCaps().iterator(); - while(iterator.hasNext()) { + while (iterator.hasNext()) { if (iterator.next().startsWith(capability)) { LOG.trace("capability {} partially matches {}", capability, nonModuleCaps); return true; @@ -144,32 +145,35 @@ public final class NetconfSessionPreferences { public boolean isMonitoringSupported() { return containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING) - || containsPartialNonModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString()); + || containsPartialNonModuleCapability( + NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString()); } /** - * Merge module-based list of capabilities with current list of module-based capabilities + * Merge module-based list of capabilities with current list of module-based capabilities. * * @param netconfSessionModuleCapabilities capabilities to merge into this * * @return new instance of preferences with merged module-based capabilities */ public NetconfSessionPreferences addModuleCaps(final NetconfSessionPreferences netconfSessionModuleCapabilities) { - final Map mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size() + netconfSessionModuleCapabilities.getModuleBasedCaps().size()); + final Map mergedCaps = Maps.newHashMapWithExpectedSize(moduleBasedCaps.size() + + netconfSessionModuleCapabilities.getModuleBasedCaps().size()); mergedCaps.putAll(moduleBasedCaps); mergedCaps.putAll(netconfSessionModuleCapabilities.getModuleBasedCapsOrigin()); return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), mergedCaps); } /** - * Override current list of module-based capabilities + * Override current list of module-based capabilities. * * @param netconfSessionPreferences capabilities to override in this * * @return new instance of preferences with replaced module-based capabilities */ public NetconfSessionPreferences replaceModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) { - return new NetconfSessionPreferences(getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin()); + return new NetconfSessionPreferences( + getNonModuleBasedCapsOrigin(), netconfSessionPreferences.getModuleBasedCapsOrigin()); } public NetconfSessionPreferences replaceModuleCaps(final Map newModuleBasedCaps) { @@ -178,7 +182,7 @@ public final class NetconfSessionPreferences { /** - * Merge list of non-module based capabilities with current list of non-module based capabilities + * Merge list of non-module based capabilities with current list of non-module based capabilities. * * @param netconfSessionNonModuleCapabilities capabilities to merge into this * @@ -194,14 +198,15 @@ public final class NetconfSessionPreferences { } /** - * Override current list of non-module based capabilities + * Override current list of non-module based capabilities. * * @param netconfSessionPreferences capabilities to override in this * * @return new instance of preferences with replaced non-module based capabilities */ public NetconfSessionPreferences replaceNonModuleCaps(final NetconfSessionPreferences netconfSessionPreferences) { - return new NetconfSessionPreferences(netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin()); + return new NetconfSessionPreferences( + netconfSessionPreferences.getNonModuleBasedCapsOrigin(), getModuleBasedCapsOrigin()); } public static NetconfSessionPreferences fromNetconfSession(final NetconfClientSession session) { @@ -221,7 +226,8 @@ public final class NetconfSessionPreferences { return fromStrings(capabilities, CapabilityOrigin.DeviceAdvertised); } - public static NetconfSessionPreferences fromStrings(final Collection capabilities, final CapabilityOrigin capabilityOrigin) { + public static NetconfSessionPreferences fromStrings(final Collection capabilities, + final CapabilityOrigin capabilityOrigin) { final Map moduleBasedCaps = new HashMap<>(); final Map nonModuleCaps = new HashMap<>(); @@ -241,7 +247,8 @@ public final class NetconfSessionPreferences { String revision = REVISION_PARAM.from(queryParams); if (!Strings.isNullOrEmpty(revision)) { - addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin); + addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), + capabilityOrigin); continue; } @@ -255,22 +262,27 @@ public final class NetconfSessionPreferences { revision = BROKEN_REVISON_PARAM.from(queryParams); if (Strings.isNullOrEmpty(revision)) { LOG.warn("Netconf device returned revision incorrectly escaped for {}, ignoring it", capability); - addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin); + addModuleQName(moduleBasedCaps, nonModuleCaps, capability, + cachedQName(namespace, moduleName), capabilityOrigin); } else { - addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, revision, moduleName), capabilityOrigin); + addModuleQName(moduleBasedCaps, nonModuleCaps, capability, + cachedQName(namespace, revision, moduleName), capabilityOrigin); } continue; } // Fallback, no revision provided for module - addModuleQName(moduleBasedCaps, nonModuleCaps, capability, cachedQName(namespace, moduleName), capabilityOrigin); + addModuleQName(moduleBasedCaps, nonModuleCaps, capability, + cachedQName(namespace, moduleName), capabilityOrigin); } return new NetconfSessionPreferences(ImmutableMap.copyOf(nonModuleCaps), ImmutableMap.copyOf(moduleBasedCaps)); } - private static void addModuleQName(final Map moduleBasedCaps, final Map nonModuleCaps, final String capability, final QName qName, final CapabilityOrigin capabilityOrigin) { - moduleBasedCaps.put(qName, capabilityOrigin); + private static void addModuleQName(final Map moduleBasedCaps, + final Map nonModuleCaps, final String capability, + final QName qualifiedName, final CapabilityOrigin capabilityOrigin) { + moduleBasedCaps.put(qualifiedName, capabilityOrigin); nonModuleCaps.remove(capability); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java index d4973e6aa7..85b45e9f94 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java @@ -16,7 +16,7 @@ final class UncancellableFuture extends AbstractFuture { @GuardedBy("this") private boolean uncancellable = false; - public UncancellableFuture(final boolean uncancellable) { + UncancellableFuture(final boolean uncancellable) { this.uncancellable = uncancellable; } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UserPreferences.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UserPreferences.java index 10742e0b5c..627bf226fd 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UserPreferences.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UserPreferences.java @@ -10,7 +10,7 @@ package org.opendaylight.netconf.sal.connect.netconf.listener; import javax.annotation.Nonnull; /** - * DTO with user capabilities to override or merge with device specific capabilities + * DTO with user capabilities to override or merge with device specific capabilities. */ public class UserPreferences { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java index c450ac68fe..2e33b57beb 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java @@ -66,7 +66,8 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler salFacade, - final ScheduledExecutorService executor, final long keepaliveDelaySeconds, final long defaultRequestTimeoutMillis) { + final ScheduledExecutorService executor, final long keepaliveDelaySeconds, + final long defaultRequestTimeoutMillis) { this.id = id; this.salFacade = salFacade; this.executor = executor; @@ -81,7 +82,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler * Then schedule next keepalive. */ private void resetKeepalive() { LOG.trace("{}: Resetting netconf keepalive timer", id); - if(currentKeepalive != null) { + if (currentKeepalive != null) { currentKeepalive.cancel(false); } scheduleKeepalive(); } /** - * Cancel current keepalive and also reset current deviceRpc + * Cancel current keepalive and also reset current deviceRpc. */ private void stopKeepalives() { - if(currentKeepalive != null) { + if (currentKeepalive != null) { currentKeepalive.cancel(false); } currentDeviceRpc = null; @@ -121,9 +123,11 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler previousKeepalive; - public Keepalive(final ScheduledFuture previousKeepalive) { + Keepalive(final ScheduledFuture previousKeepalive) { this.previousKeepalive = previousKeepalive; } @@ -184,7 +188,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler { @Override public void onSuccess(@Nullable final DOMRpcResult result) { - // No matter what response we got, rpc-reply or rpc-error, we got it from device so the netconf session is OK + // No matter what response we got, + // rpc-reply or rpc-error, we got it from device so the netconf session is OK. resetKeepalive(); } @Override - public void onFailure(@Nonnull final Throwable t) { - // User/Application RPC failed (The RPC did not reach the remote device or .. TODO what other reasons could cause this ?) + public void onFailure(@Nonnull final Throwable throwable) { + // User/Application RPC failed (The RPC did not reach the remote device or .. + // TODO what other reasons could cause this ?) // There is no point in keeping this session. Reconnect. - LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, t); + LOG.warn("{}: Rpc failure detected. Reconnecting netconf session", id, throwable); reconnect(); } } @@ -244,7 +250,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler rpcResultFuture; - public RequestTimeoutTask(final CheckedFuture rpcResultFuture) { + RequestTimeoutTask(final CheckedFuture rpcResultFuture) { this.rpcResultFuture = rpcResultFuture; } @@ -267,7 +273,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler invokeRpc(@Nonnull final SchemaPath type, final NormalizedNode input) { - final CheckedFuture domRpcResultDOMRpcExceptionCheckedFuture = deviceRpc.invokeRpc(type, input); + public CheckedFuture invokeRpc(@Nonnull final SchemaPath type, + final NormalizedNode input) { + final CheckedFuture domRpcResultDOMRpcExceptionCheckedFuture = + deviceRpc.invokeRpc(type, input); Futures.addCallback(domRpcResultDOMRpcExceptionCheckedFuture, resetKeepaliveTask); final RequestTimeoutTask timeoutTask = new RequestTimeoutTask(domRpcResultDOMRpcExceptionCheckedFuture); @@ -288,7 +296,8 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler ListenerRegistration registerRpcListener(@Nonnull final T listener) { + public ListenerRegistration registerRpcListener( + @Nonnull final T listener) { // There is no real communication with the device (yet), no reset here return deviceRpc.registerRpcListener(listener); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceDataBroker.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceDataBroker.java index 2a56d01b1a..803b8ca524 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceDataBroker.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceDataBroker.java @@ -42,7 +42,8 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker { private final boolean candidateSupported; private final boolean runningWritable; - public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext, final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) { + public NetconfDeviceDataBroker(final RemoteDeviceId id, final SchemaContext schemaContext, + final DOMRpcService rpc, final NetconfSessionPreferences netconfSessionPreferences) { this.id = id; this.netconfOps = new NetconfBaseOps(rpc, schemaContext); // get specific attributes from netconf preferences and get rid of it @@ -51,7 +52,8 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker { runningWritable = netconfSessionPreferences.isRunningWritable(); rollbackSupport = netconfSessionPreferences.isRollbackSupported(); Preconditions.checkArgument(candidateSupported || runningWritable, - "Device %s has advertised neither :writable-running nor :candidate capability. At least one of these should be advertised. Failed to establish a session.", id.getName()); + "Device %s has advertised neither :writable-running nor :candidate capability." + + "At least one of these should be advertised. Failed to establish a session.", id.getName()); } @Override @@ -66,8 +68,8 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker { @Override public DOMDataWriteTransaction newWriteOnlyTransaction() { - if(candidateSupported) { - if(runningWritable) { + if (candidateSupported) { + if (runningWritable) { return new WriteCandidateRunningTx(id, netconfOps, rollbackSupport); } else { return new WriteCandidateTx(id, netconfOps, rollbackSupport); @@ -78,7 +80,9 @@ public final class NetconfDeviceDataBroker implements DOMDataBroker { } @Override - public ListenerRegistration registerDataChangeListener(final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener, final DataChangeScope triggeringScope) { + public ListenerRegistration registerDataChangeListener( + final LogicalDatastoreType store, final YangInstanceIdentifier path, final DOMDataChangeListener listener, + final DataChangeScope triggeringScope) { throw new UnsupportedOperationException(id + ": Data change listeners not supported for netconf mount point"); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationService.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationService.java index 8838ef15ee..e27a7b2ec2 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationService.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceNotificationService.java @@ -29,6 +29,7 @@ public class NetconfDeviceNotificationService implements DOMNotificationService // Notification publish is very simple and hijacks the thread of the caller // TODO shouldnt we reuse the implementation for notification router from sal-broker-impl ? + @SuppressWarnings("checkstyle:IllegalCatch") public synchronized void publishNotification(final DOMNotification notification) { for (final DOMNotificationListener domNotificationListener : listeners.get(notification.getType())) { try { @@ -41,7 +42,8 @@ public class NetconfDeviceNotificationService implements DOMNotificationService } @Override - public synchronized ListenerRegistration registerNotificationListener(@Nonnull final T listener, @Nonnull final Collection types) { + public synchronized ListenerRegistration registerNotificationListener( + @Nonnull final T listener, @Nonnull final Collection types) { for (final SchemaPath type : types) { listeners.put(type, listener); } @@ -62,7 +64,8 @@ public class NetconfDeviceNotificationService implements DOMNotificationService } @Override - public synchronized ListenerRegistration registerNotificationListener(@Nonnull final T listener, final SchemaPath... types) { + public synchronized ListenerRegistration registerNotificationListener( + @Nonnull final T listener, final SchemaPath... types) { return registerNotificationListener(listener, Lists.newArrayList(types)); } } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java index ff27e3c912..cd9311b9c3 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java @@ -37,18 +37,20 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath; */ public final class NetconfDeviceRpc implements DOMRpcService { - private static final Function RPC_TO_RPC_IDENTIFIER = new Function() { - @Override - public DOMRpcIdentifier apply(final RpcDefinition input) { - return DOMRpcIdentifier.create(input.getPath()); - } - }; + private static final Function RPC_TO_RPC_IDENTIFIER = + new Function() { + @Override + public DOMRpcIdentifier apply(final RpcDefinition input) { + return DOMRpcIdentifier.create(input.getPath()); + } + }; private final RemoteDeviceCommunicator listener; private final MessageTransformer transformer; private final Collection availableRpcs; - public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator listener, final MessageTransformer transformer) { + public NetconfDeviceRpc(final SchemaContext schemaContext, final RemoteDeviceCommunicator listener, + final MessageTransformer transformer) { this.listener = listener; this.transformer = transformer; @@ -57,33 +59,37 @@ public final class NetconfDeviceRpc implements DOMRpcService { @Nonnull @Override - public CheckedFuture invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode input) { + public CheckedFuture invokeRpc(@Nonnull final SchemaPath type, + @Nullable final NormalizedNode input) { final NetconfMessage message = transformer.toRpcRequest(type, input); - final ListenableFuture> delegateFutureWithPureResult = listener.sendRequest(message, type.getLastComponent()); + final ListenableFuture> delegateFutureWithPureResult = + listener.sendRequest(message, type.getLastComponent()); - final ListenableFuture transformed = Futures.transform(delegateFutureWithPureResult, new Function, DOMRpcResult>() { - @Override - public DOMRpcResult apply(final RpcResult input) { - if (input.isSuccessful()) { - return transformer.toRpcResult(input.getResult(), type); - } else { - return new DefaultDOMRpcResult(input.getErrors()); + final ListenableFuture transformed = + Futures.transform(delegateFutureWithPureResult, new Function, DOMRpcResult>() { + @Override + public DOMRpcResult apply(final RpcResult input) { + if (input.isSuccessful()) { + return transformer.toRpcResult(input.getResult(), type); + } else { + return new DefaultDOMRpcResult(input.getErrors()); + } } - } - }); + }); return Futures.makeChecked(transformed, new Function() { @Nullable @Override - public DOMRpcException apply(@Nullable final Exception e) { - return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s", type); + public DOMRpcException apply(@Nullable final Exception exception) { + return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type); } }); } @Nonnull @Override - public ListenerRegistration registerRpcListener(@Nonnull final T listener) { + public ListenerRegistration registerRpcListener( + @Nonnull final T listener) { listener.onRpcAvailable(availableRpcs); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacade.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacade.java index a6ffe7aeb1..5d42d3de4d 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacade.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalFacade.java @@ -50,14 +50,18 @@ public final class NetconfDeviceSalFacade implements AutoCloseable, RemoteDevice @Override public synchronized void onDeviceConnected(final SchemaContext schemaContext, - final NetconfSessionPreferences netconfSessionPreferences, final DOMRpcService deviceRpc) { + final NetconfSessionPreferences netconfSessionPreferences, + final DOMRpcService deviceRpc) { - final DOMDataBroker domBroker = new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences); + final DOMDataBroker domBroker = + new NetconfDeviceDataBroker(id, schemaContext, deviceRpc, netconfSessionPreferences); final NetconfDeviceNotificationService notificationService = new NetconfDeviceNotificationService(); - salProvider.getMountInstance().onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService); - salProvider.getTopologyDatastoreAdapter().updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities()); + salProvider.getMountInstance() + .onTopologyDeviceConnected(schemaContext, domBroker, deviceRpc, notificationService); + salProvider.getTopologyDatastoreAdapter() + .updateDeviceData(true, netconfSessionPreferences.getNetconfDeviceCapabilities()); } @Override @@ -80,6 +84,7 @@ public final class NetconfDeviceSalFacade implements AutoCloseable, RemoteDevice closeGracefully(salProvider); } + @SuppressWarnings("checkstyle:IllegalCatch") private void closeGracefully(final AutoCloseable resource) { if (resource != null) { try { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java index e9d74c0637..4ad1dde5fe 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceSalProvider.java @@ -27,7 +27,7 @@ import org.slf4j.LoggerFactory; public class NetconfDeviceSalProvider implements AutoCloseable { - private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class); + private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSalProvider.class); private final RemoteDeviceId id; private final MountInstance mountInstance; @@ -39,8 +39,9 @@ public class NetconfDeviceSalProvider implements AutoCloseable { private final TransactionChainListener transactionChainListener = new TransactionChainListener() { @Override - public void onTransactionChainFailed(final TransactionChain chain, final AsyncTransaction transaction, final Throwable cause) { - logger.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause); + public void onTransactionChainFailed(final TransactionChain chain, + final AsyncTransaction transaction, final Throwable cause) { + LOG.error("{}: TransactionChain({}) {} FAILED!", id, chain, transaction.getIdentifier(), cause); chain.close(); resetTransactionChainForAdapaters(); throw new IllegalStateException(id + " TransactionChain(" + chain + ") not committed correctly", cause); @@ -48,7 +49,7 @@ public class NetconfDeviceSalProvider implements AutoCloseable { @Override public void onTransactionChainSuccessful(final TransactionChain chain) { - logger.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain); + LOG.trace("{}: TransactionChain({}) {} SUCCESSFUL", id, chain); } }; @@ -85,7 +86,7 @@ public class NetconfDeviceSalProvider implements AutoCloseable { topologyDatastoreAdapter.setTxChain(txChain); - logger.trace("{}: Resetting TransactionChain {}", id, txChain); + LOG.trace("{}: Resetting TransactionChain {}", id, txChain); } @@ -119,7 +120,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable { Preconditions.checkNotNull(mountService, "Closed"); Preconditions.checkState(topologyRegistration == null, "Already initialized"); - final DOMMountPointService.DOMMountPointBuilder mountBuilder = mountService.createMountPoint(id.getTopologyPath()); + final DOMMountPointService.DOMMountPointBuilder mountBuilder = + mountService.createMountPoint(id.getTopologyPath()); mountBuilder.addInitialSchemaContext(initialCtx); mountBuilder.addService(DOMDataBroker.class, broker); @@ -128,13 +130,14 @@ public class NetconfDeviceSalProvider implements AutoCloseable { this.notificationService = notificationService; topologyRegistration = mountBuilder.register(); - logger.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration); + LOG.debug("{}: TOPOLOGY Mountpoint exposed into MD-SAL {}", id, topologyRegistration); } + @SuppressWarnings("checkstyle:IllegalCatch") public synchronized void onTopologyDeviceDisconnected() { - if(topologyRegistration == null) { - logger.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id); + if (topologyRegistration == null) { + LOG.trace("{}: Not removing TOPOLOGY mountpoint from MD-SAL, mountpoint was not registered yet", id); return; } @@ -142,9 +145,9 @@ public class NetconfDeviceSalProvider implements AutoCloseable { topologyRegistration.close(); } catch (final Exception e) { // Only log and ignore - logger.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e); + LOG.warn("Unable to unregister mount instance for {}. Ignoring exception", id.getTopologyPath(), e); } finally { - logger.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration); + LOG.debug("{}: TOPOLOGY Mountpoint removed from MD-SAL {}", id, topologyRegistration); topologyRegistration = null; } } @@ -155,7 +158,8 @@ public class NetconfDeviceSalProvider implements AutoCloseable { } public synchronized void publish(final DOMNotification domNotification) { - Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}", domNotification); + Preconditions.checkNotNull(notificationService, "Device not set up yet, cannot handle notification {}", + domNotification); notificationService.publishNotification(domNotification); } } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java index 4d67bdd662..8d068bb548 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java @@ -57,9 +57,10 @@ import org.slf4j.LoggerFactory; public final class NetconfDeviceTopologyAdapter implements AutoCloseable { private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceTopologyAdapter.class); - public static final Function, UnavailableCapability> UNAVAILABLE_CAPABILITY_TRANSFORMER = input -> new UnavailableCapabilityBuilder() - .setCapability(input.getKey().toString()) - .setFailureReason(input.getValue()).build(); + public static final Function, UnavailableCapability> + UNAVAILABLE_CAPABILITY_TRANSFORMER = + input -> new UnavailableCapabilityBuilder() + .setCapability(input.getKey().toString()).setFailureReason(input.getValue()).build(); private final RemoteDeviceId id; private BindingTransactionChain txChain; @@ -73,7 +74,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { this.txChain = Preconditions.checkNotNull(txChain); this.networkTopologyPath = InstanceIdentifier.builder(NetworkTopology.class).build(); - this.topologyListPath = networkTopologyPath.child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); + this.topologyListPath = networkTopologyPath + .child(Topology.class, new TopologyKey(new TopologyId(TopologyNetconf.QNAME.getLocalName()))); initDeviceData(); } @@ -84,7 +86,7 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { createNetworkTopologyIfNotPresent(writeTx); final InstanceIdentifier path = id.getTopologyBindingPath(); - NodeBuilder nodeBuilder = getNodeIdBuilder(id); + final NodeBuilder nodeBuilder = getNodeIdBuilder(id); NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder(); netconfNodeBuilder.setConnectionStatus(ConnectionStatus.Connecting); netconfNodeBuilder.setHost(id.getHost()); @@ -117,7 +119,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { LOG.trace( "{}: Update device state transaction {} merging operational data started.", id, writeTx.getIdentifier()); - writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true); + writeTx.put(LogicalDatastoreType.OPERATIONAL, + id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true); LOG.trace( "{}: Update device state transaction {} merging operational data ended.", id, writeTx.getIdentifier()); @@ -125,14 +128,16 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { commitTransaction(writeTx, "update"); } - public void updateClusteredDeviceData(final boolean up, final String masterAddress, final NetconfDeviceCapabilities capabilities) { + public void updateClusteredDeviceData(final boolean up, final String masterAddress, + final NetconfDeviceCapabilities capabilities) { final NetconfNode data = buildDataForNetconfClusteredNode(up, masterAddress, capabilities); final WriteTransaction writeTx = txChain.newWriteOnlyTransaction(); LOG.trace( "{}: Update device state transaction {} merging operational data started.", id, writeTx.getIdentifier()); - writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true); + writeTx.put(LogicalDatastoreType.OPERATIONAL, + id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true); LOG.trace( "{}: Update device state transaction {} merging operational data ended.", id, writeTx.getIdentifier()); @@ -143,13 +148,15 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { public void setDeviceAsFailed(final Throwable throwable) { String reason = (throwable != null && throwable.getMessage() != null) ? throwable.getMessage() : UNKNOWN_REASON; - final NetconfNode data = new NetconfNodeBuilder().setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build(); + final NetconfNode data = new NetconfNodeBuilder() + .setConnectionStatus(ConnectionStatus.UnableToConnect).setConnectedMessage(reason).build(); final WriteTransaction writeTx = txChain.newWriteOnlyTransaction(); LOG.trace( "{}: Setting device state as failed {} putting operational data started.", id, writeTx.getIdentifier()); - writeTx.put(LogicalDatastoreType.OPERATIONAL, id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true); + writeTx.put(LogicalDatastoreType.OPERATIONAL, + id.getTopologyBindingPath().augmentation(NetconfNode.class), data, true); LOG.trace( "{}: Setting device state as failed {} putting operational data ended.", id, writeTx.getIdentifier()); @@ -165,8 +172,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { final AvailableCapabilitiesBuilder avCapabalitiesBuilder = new AvailableCapabilitiesBuilder(); avCapabalitiesBuilder.setAvailableCapability(capabilityList); - final UnavailableCapabilities unavailableCapabilities = - new UnavailableCapabilitiesBuilder().setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet()) + final UnavailableCapabilities unavailableCapabilities = new UnavailableCapabilitiesBuilder() + .setUnavailableCapability(FluentIterable.from(capabilities.getUnresolvedCapabilites().entrySet()) .transform(UNAVAILABLE_CAPABILITY_TRANSFORMER).toList()).build(); final NetconfNodeBuilder netconfNodeBuilder = new NetconfNodeBuilder() @@ -179,7 +186,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { return netconfNodeBuilder.build(); } - private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress, final NetconfDeviceCapabilities capabilities) { + private NetconfNode buildDataForNetconfClusteredNode(final boolean up, final String masterNodeAddress, + final NetconfDeviceCapabilities capabilities) { List capabilityList = new ArrayList<>(); capabilityList.addAll(capabilities.getNonModuleBasedCapabilities()); capabilityList.addAll(capabilities.getResolvedCapabilities()); @@ -229,7 +237,8 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { NetworkTopology.QNAME, writeTx.getIdentifier()); writeTx.merge(LogicalDatastoreType.OPERATIONAL, networkTopologyPath, networkTopology); - final Topology topology = new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build(); + final Topology topology = + new TopologyBuilder().setTopologyId(new TopologyId(TopologyNetconf.QNAME.getLocalName())).build(); LOG.trace("{}: Merging {} container to ensure its presence", id, Topology.QNAME, writeTx.getIdentifier()); writeTx.merge(LogicalDatastoreType.OPERATIONAL, topologyListPath, topology); @@ -248,10 +257,11 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { } @Override - public void onFailure(final Throwable t) { + public void onFailure(final Throwable throwable) { LOG.error("{}: Transaction({}) {} FAILED!", id, txType, - transaction.getIdentifier(), t); - throw new IllegalStateException(id + " Transaction(" + txType + ") not committed correctly", t); + transaction.getIdentifier(), throwable); + throw new IllegalStateException( + id + " Transaction(" + txType + ") not committed correctly", throwable); } }); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java index 7448367e0c..4856e1178d 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/SchemalessNetconfDeviceRpc.java @@ -42,7 +42,8 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService { private final SchemalessMessageTransformer schemalessTransformer; private final RemoteDeviceId deviceId; - public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId, final RemoteDeviceCommunicator listener, + public SchemalessNetconfDeviceRpc(final RemoteDeviceId deviceId, + final RemoteDeviceCommunicator listener, final BaseRpcSchemalessTransformer baseRpcTransformer, final SchemalessMessageTransformer messageTransformer) { this.deviceId = deviceId; @@ -61,30 +62,34 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService { } else if (isBaseRpc(type)) { transformer = baseRpcTransformer; } else { - return Futures.immediateFailedCheckedFuture(new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type)); + return Futures.immediateFailedCheckedFuture( + new DOMRpcImplementationNotAvailableException("Unable to invoke rpc %s", type)); } return handleRpc(type, input, transformer); } - private CheckedFuture handleRpc(@Nonnull final SchemaPath type, - @Nullable final NormalizedNode input, - final MessageTransformer transformer) { + private CheckedFuture handleRpc( + @Nonnull final SchemaPath type, @Nullable final NormalizedNode input, + final MessageTransformer transformer) { final NetconfMessage netconfMessage = transformer.toRpcRequest(type, input); - final ListenableFuture> rpcResultListenableFuture = listener.sendRequest(netconfMessage, type.getLastComponent()); + final ListenableFuture> rpcResultListenableFuture = + listener.sendRequest(netconfMessage, type.getLastComponent()); - final ListenableFuture transformed = Futures.transform(rpcResultListenableFuture, (Function, DOMRpcResult>) input1 -> { - if (input1.isSuccessful()) { - return transformer.toRpcResult(input1.getResult(), type); - } else { - return new DefaultDOMRpcResult(input1.getErrors()); - } - }); + final ListenableFuture transformed = + Futures.transform(rpcResultListenableFuture, (Function, DOMRpcResult>) input1 -> { + if (input1.isSuccessful()) { + return transformer.toRpcResult(input1.getResult(), type); + } else { + return new DefaultDOMRpcResult(input1.getErrors()); + } + }); return Futures.makeChecked(transformed, new Function() { @Nullable @Override - public DOMRpcException apply(@Nullable final Exception e) { - return new DOMRpcImplementationNotAvailableException(e, "Unable to invoke rpc %s on device %s", type, deviceId); + public DOMRpcException apply(@Nullable final Exception exception) { + return new DOMRpcImplementationNotAvailableException( + exception, "Unable to invoke rpc %s on device %s", type, deviceId); } }); } @@ -96,7 +101,8 @@ public final class SchemalessNetconfDeviceRpc implements DOMRpcService { @Nonnull @Override - public ListenerRegistration registerRpcListener(@Nonnull final T listener) { + public ListenerRegistration registerRpcListener( + @Nonnull final T listener) { throw new UnsupportedOperationException("Not available for netconf 1.0"); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java index d0f89bc9b4..14926d99f2 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java @@ -72,7 +72,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { @Override public synchronized boolean cancel() { - if(isFinished()) { + if (isFinished()) { return false; } listeners.forEach(listener -> listener.onTransactionCancelled(this)); @@ -91,37 +91,46 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { } @Override - public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + public synchronized void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, + final NormalizedNode data) { checkEditable(store); - // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc - if(containsOnlyNonVisibleData(path, data)) { + // Trying to write only mixin nodes (not visible when serialized). + // Ignoring. Some devices cannot handle empty edit-config rpc + if (containsOnlyNonVisibleData(path, data)) { LOG.debug("Ignoring put for {} and data {}. Resulting data structure is empty.", path, data); return; } - final DataContainerChild editStructure = netOps.createEditConfigStrcture(Optional.>fromNullable(data), Optional.of(ModifyAction.REPLACE), path); + final DataContainerChild editStructure = + netOps.createEditConfigStrcture(Optional.>fromNullable(data), + Optional.of(ModifyAction.REPLACE), path); editConfig(path, Optional.fromNullable(data), editStructure, Optional.of(ModifyAction.NONE), "put"); } @Override - public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + public synchronized void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, + final NormalizedNode data) { checkEditable(store); - // trying to write only mixin nodes (not visible when serialized). Ignoring. Some devices cannot handle empty edit-config rpc + // Trying to write only mixin nodes (not visible when serialized). + // Ignoring. Some devices cannot handle empty edit-config rpc if (containsOnlyNonVisibleData(path, data)) { LOG.debug("Ignoring merge for {} and data {}. Resulting data structure is empty.", path, data); return; } - final DataContainerChild editStructure = netOps.createEditConfigStrcture(Optional.>fromNullable(data), Optional.absent(), path); + final DataContainerChild editStructure = + netOps.createEditConfigStrcture(Optional.>fromNullable(data), + Optional.absent(), path); editConfig(path, Optional.fromNullable(data), editStructure, Optional.absent(), "merge"); } /** - * Check whether the data to be written consists only from mixins + * Check whether the data to be written consists only from mixins. */ - private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, final NormalizedNode data) { + private static boolean containsOnlyNonVisibleData(final YangInstanceIdentifier path, + final NormalizedNode data) { // There's only one such case:top level list (pathArguments == 1 && data is Mixin) // any other mixin nodes are contained by a "regular" node thus visible when serialized return path.getPathArguments().size() == 1 && data instanceof MixinNode; @@ -130,8 +139,11 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { @Override public synchronized void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) { checkEditable(store); - final DataContainerChild editStructure = netOps.createEditConfigStrcture(Optional.>absent(), Optional.of(ModifyAction.DELETE), path); - editConfig(path, Optional.>absent(), editStructure, Optional.of(ModifyAction.NONE), "delete"); + final DataContainerChild editStructure = + netOps.createEditConfigStrcture(Optional.>absent(), + Optional.of(ModifyAction.DELETE), path); + editConfig(path, Optional.>absent(), + editStructure, Optional.of(ModifyAction.NONE), "delete"); } @Override @@ -146,14 +158,16 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { if (result != null && result.isSuccessful()) { listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this)); } else { - final TransactionCommitFailedException cause = new TransactionCommitFailedException("Transaction failed", result.getErrors().toArray(new RpcError[result.getErrors().size()])); + final TransactionCommitFailedException cause = + new TransactionCommitFailedException("Transaction failed", + result.getErrors().toArray(new RpcError[result.getErrors().size()])); listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause)); } } @Override - public void onFailure(final Throwable t) { - listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, t)); + public void onFailure(final Throwable throwable) { + listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, throwable)); } }); return result; @@ -163,10 +177,13 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { private void checkEditable(final LogicalDatastoreType store) { checkNotFinished(); - Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can edit only configuration data, not %s", store); + Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, + "Can edit only configuration data, not %s", store); } - protected abstract void editConfig(final YangInstanceIdentifier path, final Optional> data, final DataContainerChild editStructure, final Optional defaultOperation, final String operation); + protected abstract void editConfig(YangInstanceIdentifier path, Optional> data, + DataContainerChild editStructure, + Optional defaultOperation, String operation); protected ListenableFuture> resultsToTxStatus() { final SettableFuture> transformed = SettableFuture.create(); @@ -175,7 +192,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { @Override public void onSuccess(final List domRpcResults) { domRpcResults.forEach(domRpcResult -> { - if(!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) { + if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) { final NetconfDocumentedException exception = new NetconfDocumentedException(id + ":RPC during tx failed", DocumentedException.ErrorType.APPLICATION, @@ -185,7 +202,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { } }); - if(!transformed.isDone()) { + if (!transformed.isDone()) { transformed.set(RpcResultBuilder.success(TransactionStatus.COMMITED).build()); } } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadOnlyTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadOnlyTx.java index a420c3cdff..b974d9fc9a 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadOnlyTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadOnlyTx.java @@ -62,22 +62,28 @@ public final class ReadOnlyTx implements DOMDataReadOnlyTransaction { public CheckedFuture>, ReadFailedException> read( final LogicalDatastoreType store, final YangInstanceIdentifier path) { switch (store) { - case CONFIGURATION: { - return readConfigurationData(path); - } - case OPERATIONAL: { - return readOperationalData(path); - } + case CONFIGURATION: { + return readConfigurationData(path); + } + case OPERATIONAL: { + return readOperationalData(path); + } + default: { + LOG.info("Unknown datastore type: {}.", store); + } } - throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store)); + throw new IllegalArgumentException(String.format( + "%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store)); } @Override - public CheckedFuture exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) { + public CheckedFuture exists(final LogicalDatastoreType store, + final YangInstanceIdentifier path) { final CheckedFuture>, ReadFailedException> data = read(store, path); final ListenableFuture result = - Futures.transform(data, (Optional> a) -> a != null && a.isPresent()); + Futures.transform(data, (Optional> optionalNode) -> + optionalNode != null && optionalNode.isPresent()); return MappingCheckedFuture.create(result, ReadFailedException.MAPPER); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadWriteTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadWriteTx.java index b063cba63a..c6012bbf21 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadWriteTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/ReadWriteTx.java @@ -38,12 +38,14 @@ public class ReadWriteTx implements DOMDataReadWriteTransaction { } @Override - public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, + final NormalizedNode data) { delegateWriteTx.put(store, path, data); } @Override - public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) { + public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, + final NormalizedNode data) { delegateWriteTx.merge(store, path, data); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChain.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChain.java index 7dbc835a3f..2547d7013c 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChain.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/TxChain.java @@ -104,6 +104,7 @@ public class TxChain implements DOMTransactionChain, TxListener { currentTransaction = null; } + @SuppressWarnings("checkstyle:IllegalCatch") private void removePendingTx(final AbstractWriteTx transaction) { try { pendingTransactions.remove(transaction).close(); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTx.java index 2729444311..b5198ec836 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateRunningTx.java @@ -15,7 +15,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Tx implementation for netconf devices that support only candidate datastore and writable running + * Tx implementation for netconf devices that support only candidate datastore and writable running. * The sequence goes exactly as with only candidate supported, with one addition: *