From: Tomas Cere Date: Thu, 27 Apr 2017 12:51:34 +0000 (+0000) Subject: Merge "Bug 8153: Enforce check-style rules for netconf - client." X-Git-Tag: release/nitrogen~123 X-Git-Url: https://git.opendaylight.org/gerrit/gitweb?a=commitdiff_plain;h=9cc422be10034f5f3cfa401fc20539c560aa7fe3;hp=895c72e912e96c2b234e6ce59f23c3dbea856433;p=netconf.git Merge "Bug 8153: Enforce check-style rules for netconf - client." --- diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java index eadc45d6f4..f55e299fc2 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/EditConfig.java @@ -61,14 +61,16 @@ public class EditConfig extends AbstractSingletonNetconfOperation { private final CurrentSchemaContext schemaContext; private final TransactionProvider transactionProvider; - public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, final TransactionProvider transactionProvider) { + public EditConfig(final String netconfSessionIdForReporting, final CurrentSchemaContext schemaContext, + final TransactionProvider transactionProvider) { super(netconfSessionIdForReporting); this.schemaContext = schemaContext; this.transactionProvider = transactionProvider; } @Override - protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) throws DocumentedException { + protected Element handleWithNoSubsequentOperations(final Document document, final XmlElement operationElement) + throws DocumentedException { final Datastore targetDatastore = extractTargetParameter(operationElement); if (targetDatastore == Datastore.running) { throw new DocumentedException("edit-config on running datastore is not supported", @@ -86,7 +88,8 @@ public class EditConfig extends AbstractSingletonNetconfOperation { final DataSchemaNode schemaNode = getSchemaNodeFromNamespace(ns, element).get(); final DataTreeChangeTracker changeTracker = new DataTreeChangeTracker(defaultAction); - final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider = new EditOperationStrategyProvider(changeTracker); + final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider = + new EditOperationStrategyProvider(changeTracker); parseIntoNormalizedNode(schemaNode, element, editOperationStrategyProvider); executeOperations(changeTracker); @@ -106,7 +109,8 @@ public class EditConfig extends AbstractSingletonNetconfOperation { } } - private void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) throws DocumentedException { + private static void executeChange(final DOMDataReadWriteTransaction rwtx, final DataTreeChange change) + throws DocumentedException { final YangInstanceIdentifier path = YangInstanceIdentifier.create(change.getPath()); final NormalizedNode changeData = change.getChangeRoot(); switch (change.getAction()) { @@ -120,7 +124,8 @@ public class EditConfig extends AbstractSingletonNetconfOperation { try { final Optional> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet(); if (readResult.isPresent()) { - throw new DocumentedException("Data already exists, cannot execute CREATE operation", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR); + throw new DocumentedException("Data already exists, cannot execute CREATE operation", + ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, ErrorSeverity.ERROR); } mergeParentMap(rwtx, path, changeData); rwtx.put(LogicalDatastoreType.CONFIGURATION, path, changeData); @@ -136,7 +141,8 @@ public class EditConfig extends AbstractSingletonNetconfOperation { try { final Optional> readResult = rwtx.read(LogicalDatastoreType.CONFIGURATION, path).checkedGet(); if (!readResult.isPresent()) { - throw new DocumentedException("Data is missing, cannot execute DELETE operation", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR); + throw new DocumentedException("Data is missing, cannot execute DELETE operation", + ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, ErrorSeverity.ERROR); } rwtx.delete(LogicalDatastoreType.CONFIGURATION, path); } catch (final ReadFailedException e) { @@ -151,8 +157,8 @@ public class EditConfig extends AbstractSingletonNetconfOperation { } } - private void mergeParentMap(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path, - final NormalizedNode change) { + private static void mergeParentMap(final DOMDataReadWriteTransaction rwtx, final YangInstanceIdentifier path, + final NormalizedNode change) { if (change instanceof MapEntryNode) { final YangInstanceIdentifier mapNodeYid = path.getParent(); //merge empty map @@ -163,10 +169,8 @@ public class EditConfig extends AbstractSingletonNetconfOperation { } } - private NormalizedNode parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element, - final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) { - - + private NormalizedNode parseIntoNormalizedNode(final DataSchemaNode schemaNode, final XmlElement element, + final DomToNormalizedNodeParserFactory.BuildingStrategyProvider editOperationStrategyProvider) { if (schemaNode instanceof ContainerSchemaNode) { return DomToNormalizedNodeParserFactory .getInstance(DomUtils.defaultValueCodecProvider(), schemaContext.getCurrentContext(), editOperationStrategyProvider) @@ -184,10 +188,12 @@ public class EditConfig extends AbstractSingletonNetconfOperation { throw new UnsupportedOperationException("implement exception if parse fails"); } - private Optional getSchemaNodeFromNamespace(final String namespace, final XmlElement element) throws DocumentedException{ + private Optional getSchemaNodeFromNamespace(final String namespace, final XmlElement element) + throws DocumentedException { Optional dataSchemaNode = Optional.absent(); try { - //returns module with newest revision since findModuleByNamespace returns a set of modules and we only need the newest one + // returns module with newest revision since findModuleByNamespace returns a set of modules and we only + // need the newest one final Module module = schemaContext.getCurrentContext().findModuleByNamespaceAndRevision(new URI(namespace), null); if (module == null) { // no module is present with this namespace @@ -211,35 +217,38 @@ public class EditConfig extends AbstractSingletonNetconfOperation { return dataSchemaNode; } - private Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException { + private static Datastore extractTargetParameter(final XmlElement operationElement) throws DocumentedException { final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(TARGET_KEY); // Direct lookup instead of using XmlElement class due to performance if (elementsByTagName.getLength() == 0) { - final Map errorInfo = ImmutableMap.of("bad-attribute", TARGET_KEY, "bad-element", OPERATION_NAME); - throw new DocumentedException("Missing target element", - ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, ErrorSeverity.ERROR, errorInfo); + final Map errorInfo = ImmutableMap.of("bad-attribute", TARGET_KEY, "bad-element", + OPERATION_NAME); + throw new DocumentedException("Missing target element", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, + ErrorSeverity.ERROR, errorInfo); } else if (elementsByTagName.getLength() > 1) { - throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR); + throw new DocumentedException("Multiple target elements", ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE, + ErrorSeverity.ERROR); } else { final XmlElement targetChildNode = XmlElement.fromDomElement((Element) elementsByTagName.item(0)).getOnlyChildElement(); return Datastore.valueOf(targetChildNode.getName()); } } - private ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException { + private static ModifyAction getDefaultOperation(final XmlElement operationElement) throws DocumentedException { final NodeList elementsByTagName = operationElement.getDomElement().getElementsByTagName(DEFAULT_OPERATION_KEY); - if(elementsByTagName.getLength() == 0) { + if (elementsByTagName.getLength() == 0) { return ModifyAction.MERGE; - } else if(elementsByTagName.getLength() > 1) { - throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements", - ErrorType.RPC, ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR); + } else if (elementsByTagName.getLength() > 1) { + throw new DocumentedException("Multiple " + DEFAULT_OPERATION_KEY + " elements", ErrorType.RPC, + ErrorTag.UNKNOWN_ATTRIBUTE, ErrorSeverity.ERROR); } else { return ModifyAction.fromXmlValue(elementsByTagName.item(0).getTextContent()); } } - private XmlElement getElement(final XmlElement operationElement, final String elementName) throws DocumentedException { + private static XmlElement getElement(final XmlElement operationElement, final String elementName) + throws DocumentedException { final Optional childNode = operationElement.getOnlyChildElementOptionally(elementName); if (!childNode.isPresent()) { throw new DocumentedException(elementName + " element is missing", diff --git a/netconf/netconf-artifacts/pom.xml b/netconf/netconf-artifacts/pom.xml index 6817400337..7019ffbf36 100644 --- a/netconf/netconf-artifacts/pom.xml +++ b/netconf/netconf-artifacts/pom.xml @@ -157,7 +157,6 @@ ${project.version} features xml - runtime @@ -286,17 +285,210 @@ ${project.groupId} features-netconf ${project.version} + xml + features + + + + + ${project.groupId} + features4-netconf + ${project.version} + xml + features + + + ${project.groupId} + odl-aaa-netconf-plugin + ${project.version} + xml + features + + + ${project.groupId} + odl-aaa-netconf-plugin-no-cluster + ${project.version} + xml + features + + + ${project.groupId} + odl-config-netconf-connector + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-all + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-api + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-client + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-impl + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-mapping-api + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-mdsal + 1.6.0-SNAPSHOT + xml + features + + + ${project.groupId} + odl-netconf-monitoring + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-netty-util + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-notifications-api + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-notifications-impl + ${project.version} + xml features + + + ${project.groupId} + odl-netconf-ssh + ${project.version} xml - runtime + features + + + ${project.groupId} + odl-netconf-tcp + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-util + ${project.version} + xml + features + + + + + ${project.groupId} + features4-netconf-connector + ${project.version} + xml + features + + + ${project.groupId} + odl-message-bus + ${project.version} + xml + features ${project.groupId} odl-netconf-clustered-topology ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-connector + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-connector-all + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-connector-ssh + ${project.version} + xml features + + + ${project.groupId} + odl-netconf-callhome-ssh + ${project.version} + xml + features + + + ${project.groupId} + odl-netconf-console + ${project.version} xml - runtime + features + + + ${project.groupId} + odl-netconf-topology + ${project.version} + xml + features + + + + + ${project.groupId} + features4-yanglib + ${project.version} + xml + features + + + ${project.groupId} + odl-yanglib + ${project.version} + xml + features diff --git a/netconf/netconf-ssh/pom.xml b/netconf/netconf-ssh/pom.xml index 64caf33c69..66f87fb699 100644 --- a/netconf/netconf-ssh/pom.xml +++ b/netconf/netconf-ssh/pom.xml @@ -126,6 +126,13 @@ org.opendaylight.yangtools yang-maven-plugin + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java index fca99e0b3c..300e19f594 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/NetconfNorthboundSshServer.java @@ -44,7 +44,8 @@ public class NetconfNorthboundSshServer { sshProxyServer = new SshProxyServer(Executors.newScheduledThreadPool(1), workerGroup, eventExecutor); final InetSocketAddress inetAddress = getInetAddress(bindingAddress, portNumber); - final SshProxyServerConfigurationBuilder sshProxyServerConfigurationBuilder = new SshProxyServerConfigurationBuilder(); + final SshProxyServerConfigurationBuilder sshProxyServerConfigurationBuilder = + new SshProxyServerConfigurationBuilder(); sshProxyServerConfigurationBuilder.setBindingAddress(inetAddress); sshProxyServerConfigurationBuilder.setLocalAddress(localAddress); sshProxyServerConfigurationBuilder.setAuthenticator(authProvider); @@ -68,8 +69,9 @@ public class NetconfNorthboundSshServer { private InetSocketAddress getInetAddress(final String bindingAddress, final String portNumber) { try { - IpAddress ipAddress= IpAddressBuilder.getDefaultInstance(bindingAddress); - final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue()); + IpAddress ipAddress = IpAddressBuilder.getDefaultInstance(bindingAddress); + final InetAddress inetAd = InetAddress.getByName(ipAddress.getIpv4Address() == null + ? ipAddress.getIpv6Address().getValue() : ipAddress.getIpv4Address().getValue()); return new InetSocketAddress(inetAd, Integer.valueOf(portNumber)); } catch (final UnknownHostException e) { throw new IllegalArgumentException("Unable to bind netconf endpoint to address " + bindingAddress, e); diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java index 69dd6bc6f9..b5a6355d29 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java @@ -39,6 +39,7 @@ import org.slf4j.LoggerFactory; * This command handles all netconf related rpc and forwards to delegate server. * Uses netty to make a local connection to delegate server. * + *

* Command is Apache Mina SSH terminology for objects handling ssh data. */ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { @@ -105,24 +106,26 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { final Bootstrap clientBootstrap = new Bootstrap(); clientBootstrap.group(clientEventGroup).channel(LocalChannel.class); - clientBootstrap - .handler(new ChannelInitializer() { - @Override - public void initChannel(final LocalChannel ch) throws Exception { - ch.pipeline().addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback)); - } - }); + clientBootstrap.handler(new ChannelInitializer() { + @Override + public void initChannel(final LocalChannel ch) throws Exception { + ch.pipeline() + .addLast(new SshProxyClientHandler(in, out, netconfHelloMessageAdditionalHeader, callback)); + } + }); clientChannelFuture = clientBootstrap.connect(localAddress); clientChannelFuture.addListener(new GenericFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { - if(future.isSuccess()) { + if (future.isSuccess()) { clientChannel = clientChannelFuture.channel(); } else { - LOG.warn("Unable to establish internal connection to netconf server for client: {}", getClientAddress()); + LOG.warn("Unable to establish internal connection to netconf server for client: {}", + getClientAddress()); Preconditions.checkNotNull(callback, "Exit callback must be set"); - callback.onExit(1, "Unable to establish internal connection to netconf server for client: "+ getClientAddress()); + callback.onExit(1, "Unable to establish internal connection to netconf server for client: " + + getClientAddress()); } } }); @@ -134,13 +137,14 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { getClientAddress(), clientChannel); clientChannelFuture.cancel(true); - if(clientChannel != null) { + if (clientChannel != null) { clientChannel.close().addListener(new GenericFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (future.isSuccess() == false) { - LOG.warn("Unable to release internal connection to netconf server on channel: {}", clientChannel); + LOG.warn("Unable to release internal connection to netconf server on channel: {}", + clientChannel); } } }); @@ -156,7 +160,7 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware { final SocketAddress remoteAddress = session.getIoSession().getRemoteAddress(); String hostName = ""; String port = ""; - if(remoteAddress instanceof InetSocketAddress) { + if (remoteAddress instanceof InetSocketAddress) { hostName = ((InetSocketAddress) remoteAddress).getAddress().getHostAddress(); port = Integer.toString(((InetSocketAddress) remoteAddress).getPort()); } diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyClientHandler.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyClientHandler.java index 66a3374338..2a198383a6 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyClientHandler.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyClientHandler.java @@ -22,7 +22,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Netty handler that reads SSH from remote client and writes to delegate server and reads from delegate server and writes to remote client + * Netty handler that reads SSH from remote client and writes to delegate server + * and reads from delegate server and writes to remote client. */ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { @@ -37,9 +38,9 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { private final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader; private final ExitCallback callback; - public SshProxyClientHandler(final IoInputStream in, final IoOutputStream out, - final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader, - final ExitCallback callback) { + SshProxyClientHandler(final IoInputStream in, final IoOutputStream out, + final NetconfHelloMessageAdditionalHeader netconfHelloMessageAdditionalHeader, + final ExitCallback callback) { this.in = in; this.out = out; this.netconfHelloMessageAdditionalHeader = netconfHelloMessageAdditionalHeader; @@ -64,9 +65,10 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { }, new AsyncSshHandlerReader.ReadMsgHandler() { @Override public void onMessageRead(final ByteBuf msg) { - if(LOG.isTraceEnabled()) { + if (LOG.isTraceEnabled()) { LOG.trace("Forwarding message for client: {} on channel: {}, message: {}", - netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), AsyncSshHandlerWriter.byteBufToString(msg)); + netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), + AsyncSshHandlerWriter.byteBufToString(msg)); } // Just forward to delegate ctx.writeAndFlush(msg); @@ -90,8 +92,8 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { public void channelInactive(final ChannelHandlerContext ctx) throws Exception { LOG.debug("Internal connection to netconf server was dropped for client: {} on channel: ", netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel()); - callback.onExit(1, "Internal connection to netconf server was dropped for client: " + - netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel()); + callback.onExit(1, "Internal connection to netconf server was dropped for client: " + + netconfHelloMessageAdditionalHeader.getAddress() + " on channel: " + ctx.channel()); super.channelInactive(ctx); } diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java index 9fa4bb33ab..ab8e22228b 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java @@ -52,10 +52,12 @@ public class SshProxyServer implements AutoCloseable { private final EventLoopGroup clientGroup; private final IoServiceFactoryFactory nioServiceWithPoolFactoryFactory; - public SshProxyServer(final ScheduledExecutorService minaTimerExecutor, final EventLoopGroup clientGroup, final ExecutorService nioExecutor) { + public SshProxyServer(final ScheduledExecutorService minaTimerExecutor, + final EventLoopGroup clientGroup, final ExecutorService nioExecutor) { this.minaTimerExecutor = minaTimerExecutor; this.clientGroup = clientGroup; - this.nioServiceWithPoolFactoryFactory = new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor); + this.nioServiceWithPoolFactoryFactory = + new NioServiceWithPoolFactory.NioServiceWithPoolFactoryFactory(nioExecutor); this.sshServer = SshServer.setUpDefaultServer(); } @@ -86,7 +88,8 @@ public class SshProxyServer implements AutoCloseable { sshServer.setProperties(getProperties(sshProxyServerConfiguration)); final RemoteNetconfCommand.NetconfCommandFactory netconfCommandFactory = - new RemoteNetconfCommand.NetconfCommandFactory(clientGroup, sshProxyServerConfiguration.getLocalAddress()); + new RemoteNetconfCommand.NetconfCommandFactory(clientGroup, + sshProxyServerConfiguration.getLocalAddress()); sshServer.setSubsystemFactories(ImmutableList.of(netconfCommandFactory)); sshServer.start(); } @@ -112,14 +115,15 @@ public class SshProxyServer implements AutoCloseable { } /** - * Based on Nio2ServiceFactory with one addition: injectable executor + * Based on Nio2ServiceFactory with one addition: injectable executor. */ - private static final class NioServiceWithPoolFactory extends CloseableUtils.AbstractCloseable implements IoServiceFactory { + private static final class NioServiceWithPoolFactory + extends CloseableUtils.AbstractCloseable implements IoServiceFactory { private final FactoryManager manager; private final AsynchronousChannelGroup group; - public NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) { + NioServiceWithPoolFactory(final FactoryManager manager, final ExecutorService executor) { this.manager = manager; try { group = AsynchronousChannelGroup.withThreadPool(executor); @@ -138,6 +142,7 @@ public class SshProxyServer implements AutoCloseable { return new Nio2Acceptor(manager, handler, group); } + @SuppressWarnings("checkstyle:IllegalCatch") @Override protected void doCloseImmediately() { try { diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java index 55b54862d2..9fe57a40b6 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfiguration.java @@ -21,7 +21,8 @@ public final class SshProxyServerConfiguration { private final KeyPairProvider keyPairProvider; private final int idleTimeout; - SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress, final AuthProvider authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) { + SshProxyServerConfiguration(final InetSocketAddress bindingAddress, final LocalAddress localAddress, + final AuthProvider authenticator, final KeyPairProvider keyPairProvider, final int idleTimeout) { this.bindingAddress = Preconditions.checkNotNull(bindingAddress); this.localAddress = Preconditions.checkNotNull(localAddress); this.authenticator = Preconditions.checkNotNull(authenticator); diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java index 14b00b462d..5b7948ed6f 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServerConfigurationBuilder.java @@ -46,7 +46,8 @@ public final class SshProxyServerConfigurationBuilder { } public SshProxyServerConfiguration createSshProxyServerConfiguration() { - return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, keyPairProvider, idleTimeout); + return new SshProxyServerConfiguration(bindingAddress, localAddress, authenticator, + keyPairProvider, idleTimeout); } public static SshProxyServerConfigurationBuilder create() { diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/AuthProviderTracker.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/AuthProviderTracker.java index 51be1bc3ea..124e7e7ac1 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/AuthProviderTracker.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/AuthProviderTracker.java @@ -24,7 +24,7 @@ final class AuthProviderTracker implements ServiceTrackerCustomizer listenerTracker; private volatile AuthProvider authProvider; - public AuthProviderTracker(final BundleContext bundleContext) { + AuthProviderTracker(final BundleContext bundleContext) { this.bundleContext = bundleContext; listenerTracker = new ServiceTracker<>(bundleContext, AuthProvider.class, this); listenerTracker.open(); diff --git a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java index fddbc7389b..f31f7b95b1 100644 --- a/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java +++ b/netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/osgi/NetconfSSHActivator.java @@ -46,8 +46,8 @@ public class NetconfSSHActivator implements BundleActivator { public void start(final BundleContext bundleContext) throws IOException, InvalidSyntaxException { minaTimerExecutor = Executors.newScheduledThreadPool(POOL_SIZE, new ThreadFactory() { @Override - public Thread newThread(final Runnable r) { - return new Thread(r, "netconf-ssh-server-mina-timers"); + public Thread newThread(final Runnable runnable) { + return new Thread(runnable, "netconf-ssh-server-mina-timers"); } }); clientGroup = new NioEventLoopGroup(); @@ -61,19 +61,19 @@ public class NetconfSSHActivator implements BundleActivator { server.close(); } - if(authProviderTracker != null) { + if (authProviderTracker != null) { authProviderTracker.stop(); } - if(nioExecutor!=null) { + if (nioExecutor != null) { nioExecutor.shutdownNow(); } - if(clientGroup != null) { + if (clientGroup != null) { clientGroup.shutdownGracefully(); } - if(minaTimerExecutor != null) { + if (minaTimerExecutor != null) { minaTimerExecutor.shutdownNow(); } } diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClient.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClient.java index c8584a7ed8..2cdd97c9f9 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClient.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClient.java @@ -45,23 +45,24 @@ public class EchoClient extends Thread { this.channelInitializer = channelInitializer; } + @SuppressWarnings("checkstyle:IllegalCatch") @Override public void run() { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try { - Bootstrap b = new Bootstrap(); + Bootstrap bootstrap = new Bootstrap(); - b.group(group) + bootstrap.group(group) .channel(LocalChannel.class) .handler(channelInitializer); // Start the client. LocalAddress localAddress = new LocalAddress("foo"); - ChannelFuture f = b.connect(localAddress).sync(); + ChannelFuture future = bootstrap.connect(localAddress).sync(); // Wait until the connection is closed. - f.channel().closeFuture().sync(); + future.channel().closeFuture().sync(); } catch (Exception e) { LOG.error("Error in client", e); throw new RuntimeException("Error in client", e); diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java index 5d571a5caa..2a94d38161 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoClientHandler.java @@ -31,7 +31,9 @@ public class EchoClientHandler extends ChannelInboundHandlerAdapter implements C private ChannelHandlerContext ctx; private final StringBuilder fromServer = new StringBuilder(); - public static enum State {CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED} + public enum State { + CONNECTING, CONNECTED, FAILED_TO_CONNECT, CONNECTION_CLOSED + } private State state = State.CONNECTING; diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServer.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServer.java index a6f9e6cb66..c660ffd02b 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServer.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServer.java @@ -31,13 +31,14 @@ import org.slf4j.LoggerFactory; public class EchoServer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(EchoServer.class); + @SuppressWarnings("checkstyle:IllegalCatch") public void run() { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { - ServerBootstrap b = new ServerBootstrap(); - b.group(bossGroup, workerGroup) + ServerBootstrap bootstrap = new ServerBootstrap(); + bootstrap.group(bossGroup, workerGroup) .channel(LocalServerChannel.class) .option(ChannelOption.SO_BACKLOG, 100) .handler(new LoggingHandler(LogLevel.INFO)) @@ -50,10 +51,10 @@ public class EchoServer implements Runnable { // Start the server. LocalAddress localAddress = NetconfConfiguration.NETCONF_LOCAL_ADDRESS; - ChannelFuture f = b.bind(localAddress).sync(); + ChannelFuture future = bootstrap.bind(localAddress).sync(); // Wait until the server socket is closed. - f.channel().closeFuture().sync(); + future.channel().closeFuture().sync(); } catch (Exception e) { throw new RuntimeException(e); } finally { diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServerHandler.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServerHandler.java index 38634280ff..632d207ea7 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServerHandler.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/EchoServerHandler.java @@ -26,6 +26,7 @@ public class EchoServerHandler extends ChannelInboundHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(EchoServerHandler.class); private String fromLastNewLine = ""; private final Splitter splitter = Splitter.onPattern("\r?\n"); + @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { LOG.debug("sleep start"); diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyClientHandler.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyClientHandler.java new file mode 100644 index 0000000000..dd1daedaa6 --- /dev/null +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyClientHandler.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License v1.0 which accompanies this distribution, + * and is available at http://www.eclipse.org/legal/epl-v10.html + */ +package org.opendaylight.netconf.netty; + +import io.netty.buffer.ByteBuf; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import java.nio.charset.StandardCharsets; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +class ProxyClientHandler extends ChannelInboundHandlerAdapter { + private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class); + + private final ChannelHandlerContext remoteCtx; + + + ProxyClientHandler(ChannelHandlerContext remoteCtx) { + this.remoteCtx = remoteCtx; + } + + @Override + public void channelActive(ChannelHandlerContext ctx) { + LOG.info("client active"); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + ByteBuf bb = (ByteBuf) msg; + LOG.info(">{}", bb.toString(StandardCharsets.UTF_8)); + remoteCtx.write(msg); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) { + LOG.debug("Flushing server ctx"); + remoteCtx.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + // Close the connection when an exception is raised. + LOG.warn("Unexpected exception from downstream", cause); + ctx.close(); + } + + // called both when local or remote connection dies + @Override + public void channelInactive(ChannelHandlerContext ctx) { + LOG.debug("channelInactive() called, closing remote client ctx"); + remoteCtx.close(); + } +} diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServer.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServer.java index ee34f8fd2f..3b693512ea 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServer.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServer.java @@ -30,6 +30,7 @@ public class ProxyServer implements Runnable { this.proxyHandlerFactory = proxyHandlerFactory; } + @SuppressWarnings("checkstyle:IllegalCatch") public void run() { // Configure the server. final EventLoopGroup bossGroup = new NioEventLoopGroup(); @@ -50,10 +51,10 @@ public class ProxyServer implements Runnable { // Start the server. InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8080); - ChannelFuture f = serverBootstrap.bind(address).sync(); + ChannelFuture future = serverBootstrap.bind(address).sync(); // Wait until the server socket is closed. - f.channel().closeFuture().sync(); + future.channel().closeFuture().sync(); } catch (Exception e) { throw new RuntimeException(e); } finally { @@ -62,7 +63,8 @@ public class ProxyServer implements Runnable { workerGroup.shutdownGracefully(); } } - public static interface ProxyHandlerFactory { + + public interface ProxyHandlerFactory { ChannelHandler create(EventLoopGroup bossGroup, LocalAddress localAddress); } diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServerHandler.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServerHandler.java index dc879c2332..c70efcdb34 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServerHandler.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/ProxyServerHandler.java @@ -9,7 +9,6 @@ package org.opendaylight.netconf.netty; import io.netty.bootstrap.Bootstrap; -import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; @@ -19,7 +18,6 @@ import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; -import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -77,45 +75,3 @@ public class ProxyServerHandler extends ChannelInboundHandlerAdapter { } } -class ProxyClientHandler extends ChannelInboundHandlerAdapter { - private static final Logger LOG = LoggerFactory.getLogger(ProxyClientHandler.class); - - private final ChannelHandlerContext remoteCtx; - - - public ProxyClientHandler(ChannelHandlerContext remoteCtx) { - this.remoteCtx = remoteCtx; - } - - @Override - public void channelActive(ChannelHandlerContext ctx) { - LOG.info("client active"); - } - - @Override - public void channelRead(ChannelHandlerContext ctx, Object msg) { - ByteBuf bb = (ByteBuf) msg; - LOG.info(">{}", bb.toString(StandardCharsets.UTF_8)); - remoteCtx.write(msg); - } - - @Override - public void channelReadComplete(ChannelHandlerContext ctx) { - LOG.debug("Flushing server ctx"); - remoteCtx.flush(); - } - - @Override - public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { - // Close the connection when an exception is raised. - LOG.warn("Unexpected exception from downstream", cause); - ctx.close(); - } - - // called both when local or remote connection dies - @Override - public void channelInactive(ChannelHandlerContext ctx) { - LOG.debug("channelInactive() called, closing remote client ctx"); - remoteCtx.close(); - } -} diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java index 759b96210b..3b1a695028 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/netty/SSHTest.java @@ -73,18 +73,21 @@ public class SSHTest { final InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 10831); final SshProxyServer sshProxyServer = new SshProxyServer(minaTimerEx, nettyGroup, nioExec); - sshProxyServer.bind( - new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() { - @Override - public boolean authenticated(final String username, final String password) { - return true; - } - }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); + sshProxyServer.bind(new SshProxyServerConfigurationBuilder() + .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS) + .setAuthenticator(new AuthProvider() { + @Override + public boolean authenticated(final String username, final String password) { + return true; + } + }) + .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())) + .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); final EchoClientHandler echoClientHandler = connectClient(addr); Stopwatch stopwatch = Stopwatch.createStarted(); - while(echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) { + while (echoClientHandler.isConnected() == false && stopwatch.elapsed(TimeUnit.SECONDS) < 30) { Thread.sleep(500); } assertTrue(echoClientHandler.isConnected()); @@ -131,7 +134,7 @@ public class SSHTest { final InetSocketAddress address = new InetSocketAddress(12345); final EchoClientHandler echoClientHandler = connectClient(address); final Stopwatch stopwatch = Stopwatch.createStarted(); - while(echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) { + while (echoClientHandler.getState() == State.CONNECTING && stopwatch.elapsed(TimeUnit.SECONDS) < 5) { Thread.sleep(100); } assertFalse(echoClientHandler.isConnected()); diff --git a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java index 1257e4b7e9..7af4598997 100644 --- a/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java +++ b/netconf/netconf-ssh/src/test/java/org/opendaylight/netconf/ssh/authentication/SSHServerTest.java @@ -72,13 +72,16 @@ public class SSHServerTest { final InetSocketAddress addr = InetSocketAddress.createUnresolved(HOST, PORT); server = new SshProxyServer(minaTimerEx, clientGroup, nioExec); - server.bind( - new SshProxyServerConfigurationBuilder().setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS).setAuthenticator(new AuthProvider() { + server.bind(new SshProxyServerConfigurationBuilder() + .setBindingAddress(addr).setLocalAddress(NetconfConfiguration.NETCONF_LOCAL_ADDRESS) + .setAuthenticator(new AuthProvider() { @Override public boolean authenticated(final String username, final String password) { return true; } - }).setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())).setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); + }) + .setKeyPairProvider(new PEMGeneratorHostKeyProvider(sshKeyPair.toPath().toAbsolutePath().toString())) + .setIdleTimeout(Integer.MAX_VALUE).createSshProxyServerConfiguration()); LOG.info("SSH server started on {}", PORT); } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java index 734461ac9c..0ca6325f62 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java @@ -41,6 +41,7 @@ import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySet import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup.NetconfTopologySetupBuilder; import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologyUtils; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopologyBuilder; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; @@ -83,9 +84,9 @@ public class NetconfTopologyManager final ClusterSingletonServiceProvider clusterSingletonServiceProvider, final BindingAwareBroker bindingAwareBroker, final ScheduledThreadPool keepaliveExecutor, final ThreadPool processingExecutor, - final Broker domBroker, final ActorSystemProvider actorSystemProvider, final EventExecutor eventExecutor, - final NetconfClientDispatcher clientDispatcher, final String topologyId, - final int writeTxIdleTimeout) { + final Broker domBroker, final ActorSystemProvider actorSystemProvider, + final EventExecutor eventExecutor, final NetconfClientDispatcher clientDispatcher, + final String topologyId, final Config config) { this.dataBroker = Preconditions.checkNotNull(dataBroker); this.rpcProviderRegistry = Preconditions.checkNotNull(rpcProviderRegistry); this.clusterSingletonServiceProvider = Preconditions.checkNotNull(clusterSingletonServiceProvider); @@ -97,7 +98,7 @@ public class NetconfTopologyManager this.eventExecutor = Preconditions.checkNotNull(eventExecutor); this.clientDispatcher = Preconditions.checkNotNull(clientDispatcher); this.topologyId = Preconditions.checkNotNull(topologyId); - this.writeTxIdleTimeout = Duration.apply(writeTxIdleTimeout, TimeUnit.SECONDS); + this.writeTxIdleTimeout = Duration.apply(config.getWriteTransactionIdleTimeout(), TimeUnit.SECONDS); } // Blueprint init method diff --git a/netconf/netconf-topology-singleton/src/main/resources/org/opendaylight/blueprint/netconf-topology-singleton.xml b/netconf/netconf-topology-singleton/src/main/resources/org/opendaylight/blueprint/netconf-topology-singleton.xml index 0997ea5af2..977018f62c 100644 --- a/netconf/netconf-topology-singleton/src/main/resources/org/opendaylight/blueprint/netconf-topology-singleton.xml +++ b/netconf/netconf-topology-singleton/src/main/resources/org/opendaylight/blueprint/netconf-topology-singleton.xml @@ -35,6 +35,10 @@ and is available at http://www.eclipse.org/legal/epl-v10.html + - + diff --git a/netconf/netconf-topology-singleton/src/main/yang/netconf-clustered-topology-config.yang b/netconf/netconf-topology-singleton/src/main/yang/netconf-clustered-topology-config.yang new file mode 100644 index 0000000000..b8cf643e33 --- /dev/null +++ b/netconf/netconf-topology-singleton/src/main/yang/netconf-clustered-topology-config.yang @@ -0,0 +1,22 @@ +module netconf-clustered-topology-config { + yang-version 1; + namespace "urn:opendaylight:netconf:topology:singleton:config"; + prefix nctc; + + description + "Configuration for Netconf Clustered Topology"; + + revision "2017-04-19" { + description + "Initial revision."; + } + + container config { + leaf write-transaction-idle-timeout { + type uint16; + default 0; + description "Idle time in seconds after which write transaction is cancelled + automatically. If 0, automatic cancellation is turned off."; + } + } +} \ No newline at end of file diff --git a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManagerTest.java b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManagerTest.java index 99ef75f2a4..060ed0e987 100644 --- a/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManagerTest.java +++ b/netconf/netconf-topology-singleton/src/test/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManagerTest.java @@ -53,6 +53,8 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types. import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.PortNumber; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNode; import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.NetconfNodeBuilder; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.Config; +import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.topology.singleton.config.rev170419.ConfigBuilder; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder; @@ -84,9 +86,10 @@ public class NetconfTopologyManagerTest { final EventExecutor eventExecutor = mock(EventExecutor.class); final NetconfClientDispatcher clientDispatcher = mock(NetconfClientDispatcher.class); + final Config config = new ConfigBuilder().setWriteTransactionIdleTimeout(0).build(); netconfTopologyManager = new NetconfTopologyManager(dataBroker, rpcProviderRegistry, clusterSingletonServiceProvider, bindingAwareBroker, keepaliveExecutor, processingExecutor, domBroker, - actorSystemProvider, eventExecutor, clientDispatcher, topologyId, 0); + actorSystemProvider, eventExecutor, clientDispatcher, topologyId, config); } @Test diff --git a/netconf/netconf-util/pom.xml b/netconf/netconf-util/pom.xml index 6e8c024d15..9e30e95320 100644 --- a/netconf/netconf-util/pom.xml +++ b/netconf/netconf-util/pom.xml @@ -139,6 +139,13 @@ + + org.apache.maven.plugins + maven-checkstyle-plugin + + checkstyle.violationSeverity=error + + diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java index cff8b2a890..1067da9d91 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/CloseableUtil.java @@ -10,6 +10,7 @@ package org.opendaylight.netconf.util; public class CloseableUtil { + @SuppressWarnings("checkstyle:IllegalCatch") public static void closeAll(Iterable autoCloseables) throws Exception { Exception lastException = null; for (AutoCloseable autoCloseable : autoCloseables) { diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/NetconfUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/NetconfUtil.java index 0e8b9aeec4..d81e5c9be7 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/NetconfUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/NetconfUtil.java @@ -52,18 +52,22 @@ public final class NetconfUtil { + XmlUtil.toString(response)); } - public static void writeNormalizedNode(final NormalizedNode normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext context) + @SuppressWarnings("checkstyle:IllegalCatch") + public static void writeNormalizedNode(final NormalizedNode normalized, final DOMResult result, + final SchemaPath schemaPath, final SchemaContext context) throws IOException, XMLStreamException { final XMLStreamWriter writer = XML_FACTORY.createXMLStreamWriter(result); try ( - final NormalizedNodeStreamWriter normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath); - final NormalizedNodeWriter normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter) + NormalizedNodeStreamWriter normalizedNodeStreamWriter = + XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath); + NormalizedNodeWriter normalizedNodeWriter = + NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter) ) { normalizedNodeWriter.write(normalized); normalizedNodeWriter.flush(); } finally { try { - if(writer != null) { + if (writer != null) { writer.close(); } } catch (final Exception e) { diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperation.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperation.java index 32d6d79cc2..e66e59f3e7 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperation.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperation.java @@ -23,8 +23,9 @@ public abstract class AbstractLastNetconfOperation extends AbstractNetconfOperat @Override protected Element handle(final Document document, final XmlElement operationElement, final NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { - if (!subsequentOperation.isExecutionTermination()){ - throw new DocumentedException(String.format("No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation), + if (!subsequentOperation.isExecutionTermination()) { + throw new DocumentedException(String.format( + "No netconf operation expected to be subsequent to %s, but is %s", this, subsequentOperation), DocumentedException.ErrorType.APPLICATION, DocumentedException.ErrorTag.MALFORMED_MESSAGE, DocumentedException.ErrorSeverity.ERROR); @@ -38,5 +39,6 @@ public abstract class AbstractLastNetconfOperation extends AbstractNetconfOperat return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY; } - protected abstract Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException; + protected abstract Element handleWithNoSubsequentOperations(Document document, + XmlElement operationElement) throws DocumentedException; } diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperation.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperation.java index 6a4d2ae504..4d988112ea 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperation.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperation.java @@ -41,8 +41,16 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { return canHandle(operationNameAndNamespace.getOperationName(), operationNameAndNamespace.getNamespace()); } + protected HandlingPriority canHandle(final String operationName, final String operationNamespace) { + return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace()) + ? getHandlingPriority() + : HandlingPriority.CANNOT_HANDLE; + } + public static final class OperationNameAndNamespace { - private final String operationName, namespace; + private final String operationName; + private final String namespace; + private final XmlElement operationElement; public OperationNameAndNamespace(final Document message) throws DocumentedException { @@ -64,6 +72,7 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { public XmlElement getOperationElement() { return operationElement; } + } protected static XmlElement getRequestElementWithCheck(final Document message) throws DocumentedException { @@ -71,12 +80,6 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); } - protected HandlingPriority canHandle(final String operationName, final String operationNamespace) { - return operationName.equals(getOperationName()) && operationNamespace.equals(getOperationNamespace()) - ? getHandlingPriority() - : HandlingPriority.CANNOT_HANDLE; - } - protected HandlingPriority getHandlingPriority() { return HandlingPriority.HANDLE_WITH_DEFAULT_PRIORITY; } @@ -99,14 +102,16 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { Map attributes = requestElement.getAttributes(); Element response = handle(document, operationElement, subsequentOperation); - Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); + Element rpcReply = XmlUtil.createElement(document, XmlMappingConstants.RPC_REPLY_KEY, + Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); - if(XmlElement.fromDomElement(response).hasNamespace()) { + if (XmlElement.fromDomElement(response).hasNamespace()) { rpcReply.appendChild(response); } else { - Element responseNS = XmlUtil.createElement(document, response.getNodeName(), Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); + Element responseNS = XmlUtil.createElement(document, response.getNodeName(), + Optional.of(XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); NodeList list = response.getChildNodes(); - while(list.getLength()!=0) { + while (list.getLength() != 0) { responseNS.appendChild(list.item(0)); } rpcReply.appendChild(responseNS); @@ -119,7 +124,8 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { return document; } - protected abstract Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) + protected abstract Element handle(Document document, XmlElement message, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException; @Override @@ -127,7 +133,7 @@ public abstract class AbstractNetconfOperation implements NetconfOperation { final StringBuffer sb = new StringBuffer(getClass().getName()); try { sb.append("{name=").append(getOperationName()); - } catch(UnsupportedOperationException e) { + } catch (UnsupportedOperationException e) { // no problem } sb.append(", namespace=").append(getOperationNamespace()); diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/FramingMechanism.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/FramingMechanism.java index b85a0ad3a8..ae7d7472e9 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/FramingMechanism.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/FramingMechanism.java @@ -13,11 +13,15 @@ package org.opendaylight.netconf.util.messages; */ public enum FramingMechanism { /** + * Chunked framing mechanism. + * * @see Chunked * framing mechanism */ CHUNK, /** + * End-of-Message framing mechanism. + * * @see End-of-message * framing mechanism diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageUtil.java index 021ba009fa..995f6a47d0 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageUtil.java @@ -38,7 +38,7 @@ public final class NetconfMessageUtil { } public static boolean isOKMessage(XmlElement xmlElement) throws NetconfDocumentedException { - if(xmlElement.getChildElements().size() != 1) { + if (xmlElement.getChildElements().size() != 1) { return false; } try { @@ -57,7 +57,7 @@ public final class NetconfMessageUtil { } public static boolean isErrorMessage(XmlElement xmlElement) throws NetconfDocumentedException { - if(xmlElement.getChildElements().size() != 1) { + if (xmlElement.getChildElements().size() != 1) { return false; } try { diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SendErrorExceptionUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SendErrorExceptionUtil.java index 8b72bb836b..4768fad00e 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SendErrorExceptionUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SendErrorExceptionUtil.java @@ -34,15 +34,15 @@ public final class SendErrorExceptionUtil { final DocumentedException sendErrorException) { LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException); final Document errorDocument = createDocument(sendErrorException); - ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument)); - f.addListener(new SendErrorVerifyingListener(sendErrorException)); + ChannelFuture channelFuture = session.sendMessage(new NetconfMessage(errorDocument)); + channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException)); } public static void sendErrorMessage(final Channel channel, final DocumentedException sendErrorException) { LOG.trace("Sending error {}", sendErrorException.getMessage(), sendErrorException); final Document errorDocument = createDocument(sendErrorException); - ChannelFuture f = channel.writeAndFlush(new NetconfMessage(errorDocument)); - f.addListener(new SendErrorVerifyingListener(sendErrorException)); + ChannelFuture channelFuture = channel.writeAndFlush(new NetconfMessage(errorDocument)); + channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException)); } public static void sendErrorMessage(final NetconfSession session, final DocumentedException sendErrorException, @@ -53,20 +53,21 @@ public final class SendErrorExceptionUtil { } tryToCopyAttributes(incommingMessage.getDocument(), errorDocument, sendErrorException); - ChannelFuture f = session.sendMessage(new NetconfMessage(errorDocument)); - f.addListener(new SendErrorVerifyingListener(sendErrorException)); + ChannelFuture channelFuture = session.sendMessage(new NetconfMessage(errorDocument)); + channelFuture.addListener(new SendErrorVerifyingListener(sendErrorException)); } + @SuppressWarnings("checkstyle:IllegalCatch") private static void tryToCopyAttributes(final Document incommingDocument, final Document errorDocument, final DocumentedException sendErrorException) { try { final Element incommingRpc = incommingDocument.getDocumentElement(); - Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY), "Missing %s element", - XmlNetconfConstants.RPC_KEY); + Preconditions.checkState(incommingRpc.getTagName().equals(XmlNetconfConstants.RPC_KEY), + "Missing %s element", XmlNetconfConstants.RPC_KEY); final Element rpcReply = errorDocument.getDocumentElement(); - Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY), "Missing %s element", - XmlMappingConstants.RPC_REPLY_KEY); + Preconditions.checkState(rpcReply.getTagName().equals(XmlMappingConstants.RPC_REPLY_KEY), + "Missing %s element", XmlMappingConstants.RPC_REPLY_KEY); final NamedNodeMap incomingAttributes = incommingRpc.getAttributes(); for (int i = 0; i < incomingAttributes.getLength(); i++) { @@ -93,7 +94,7 @@ public final class SendErrorExceptionUtil { private static final class SendErrorVerifyingListener implements ChannelFutureListener { private final DocumentedException sendErrorException; - public SendErrorVerifyingListener(final DocumentedException sendErrorException) { + SendErrorVerifyingListener(final DocumentedException sendErrorException) { this.sendErrorException = sendErrorException; } diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java index aa570952d6..96e19b9378 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/SubtreeFilter.java @@ -28,15 +28,17 @@ import org.w3c.dom.Node; public class SubtreeFilter { private static final Logger LOG = LoggerFactory.getLogger(SubtreeFilter.class); - public static Document applyRpcSubtreeFilter(Document requestDocument, Document rpcReply) throws DocumentedException { + public static Document applyRpcSubtreeFilter(Document requestDocument, + Document rpcReply) throws DocumentedException { OperationNameAndNamespace operationNameAndNamespace = new OperationNameAndNamespace(requestDocument); - if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace()) && - XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName()) || - XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) { + if (XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0.equals(operationNameAndNamespace.getNamespace()) + && XmlNetconfConstants.GET.equals(operationNameAndNamespace.getOperationName()) + || XmlNetconfConstants.GET_CONFIG.equals(operationNameAndNamespace.getOperationName())) { // process subtree filtering here, in case registered netconf operations do // not implement filtering. - Optional maybeFilter = operationNameAndNamespace.getOperationElement().getOnlyChildElementOptionally( - XmlNetconfConstants.FILTER, XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + Optional maybeFilter = operationNameAndNamespace.getOperationElement() + .getOnlyChildElementOptionally(XmlNetconfConstants.FILTER, + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); if (!maybeFilter.isPresent()) { return rpcReply; } @@ -57,9 +59,10 @@ public class SubtreeFilter { * @param filter filter * @param notification notification * @return document containing filtered notification content - * @throws DocumentedException + * @throws DocumentedException if operation fails */ - public static Optional applySubtreeNotificationFilter(XmlElement filter, Document notification) throws DocumentedException { + public static Optional applySubtreeNotificationFilter(XmlElement filter, + Document notification) throws DocumentedException { removeEventTimeNode(notification); if (isSupported(filter)) { return Optional.fromNullable(filteredNotification(filter, notification)); @@ -68,14 +71,15 @@ public class SubtreeFilter { } private static void removeEventTimeNode(Document document) { - final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS( - XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0); + final Node eventTimeNode = document.getDocumentElement().getElementsByTagNameNS(XmlNetconfConstants + .URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0, XmlNetconfConstants.EVENT_TIME).item(0); document.getDocumentElement().removeChild(eventTimeNode); } private static boolean isSupported(XmlElement filter) { - return "subtree".equals(filter.getAttribute("type"))|| - "subtree".equals(filter.getAttribute("type", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); + return "subtree".equals(filter.getAttribute("type")) + || "subtree".equals(filter.getAttribute("type", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0)); } private static Document extractNotificationContent(Document notification) throws DocumentedException { @@ -86,14 +90,15 @@ public class SubtreeFilter { return notification; } - private static Document filteredNotification(XmlElement filter, Document originalNotification) throws DocumentedException { + private static Document filteredNotification(XmlElement filter, + Document originalNotification) throws DocumentedException { Document result = XmlUtil.newDocument(); XmlElement dataSrc = XmlElement.fromDomDocument(originalNotification); Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false); for (XmlElement filterChild : filter.getChildElements()) { addSubtree2(filterChild, dataSrc.getOnlyChildElement(), XmlElement.fromDomElement(dataDst)); } - if(dataDst.getFirstChild() != null) { + if (dataDst.getFirstChild() != null) { result.appendChild(dataDst.getFirstChild()); return result; } else { @@ -107,7 +112,8 @@ public class SubtreeFilter { Element rpcReply = originalReplyDocument.getDocumentElement(); Node rpcReplyDst = result.importNode(rpcReply, false); result.appendChild(rpcReplyDst); - XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data", XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); + XmlElement dataSrc = XmlElement.fromDomElement(rpcReply).getOnlyChildElement("data", + XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0); Element dataDst = (Element) result.importNode(dataSrc.getDomElement(), false); rpcReplyDst.appendChild(dataDst); addSubtree(filter, dataSrc, XmlElement.fromDomElement(dataDst)); @@ -123,7 +129,8 @@ public class SubtreeFilter { } } - private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, XmlElement dstParent) throws DocumentedException { + private static MatchingResult addSubtree2(XmlElement filter, XmlElement src, + XmlElement dstParent) throws DocumentedException { Document document = dstParent.getDomElement().getOwnerDocument(); MatchingResult matches = matches(src, filter); if (matches != MatchingResult.NO_MATCH && matches != MatchingResult.CONTENT_MISMATCH) { @@ -137,7 +144,8 @@ public class SubtreeFilter { int numberOfTextMatchingChildren = 0; for (XmlElement srcChild : src.getChildElements()) { for (XmlElement filterChild : filter.getChildElements()) { - MatchingResult childMatch = addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied)); + MatchingResult childMatch = + addSubtree2(filterChild, srcChild, XmlElement.fromDomElement(copied)); if (childMatch == MatchingResult.CONTENT_MISMATCH) { return MatchingResult.NO_MATCH; } @@ -166,8 +174,8 @@ public class SubtreeFilter { * If filter node has no children and has text content, it also must match. */ private static MatchingResult matches(XmlElement src, XmlElement filter) throws DocumentedException { - boolean tagMatch = src.getName().equals(filter.getName()) && - src.getNamespaceOptionally().equals(filter.getNamespaceOptionally()); + boolean tagMatch = src.getName().equals(filter.getName()) + && src.getNamespaceOptionally().equals(filter.getNamespaceOptionally()); MatchingResult result = null; if (tagMatch) { // match text content @@ -183,7 +191,7 @@ public class SubtreeFilter { if (result == null) { for (Attr attr : filter.getAttributes().values()) { // ignore namespace declarations - if (XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI()) == false ) { + if (XmlUtil.XMLNS_URI.equals(attr.getNamespaceURI()) == false) { // find attr with matching localName(), namespaceURI(), == value() in src String found = src.getAttribute(attr.getLocalName(), attr.getNamespaceURI()); if (attr.getValue().equals(found) && result != MatchingResult.NO_MATCH) { @@ -205,7 +213,8 @@ public class SubtreeFilter { return result; } - private static boolean prefixedContentMatches(final XmlElement filter, final XmlElement src) throws DocumentedException { + private static boolean prefixedContentMatches(final XmlElement filter, + final XmlElement src) throws DocumentedException { final Map.Entry prefixToNamespaceOfFilter; final Map.Entry prefixToNamespaceOfSrc; try { @@ -226,8 +235,10 @@ public class SubtreeFilter { return false; } - final String unprefixedFilterContent = filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1); - final String unprefixedSrcContnet = src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1); + final String unprefixedFilterContent = + filter.getTextContent().substring(prefixToNamespaceOfFilter.getKey().length() + 1); + final String unprefixedSrcContnet = + src.getTextContent().substring(prefixToNamespaceOfSrc.getKey().length() + 1); // Finally compare unprefixed content return unprefixedFilterContent.equals(unprefixedSrcContnet); } diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtil.java index cd74911138..64537f336f 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtil.java @@ -9,7 +9,6 @@ package org.opendaylight.netconf.util.osgi; import java.util.Collection; -import java.util.Optional; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; @@ -30,11 +29,11 @@ public final class NetconfConfigUtil { final Collection> serviceReferences = bundleContext.getServiceReferences(ManagedService.class, null); for (final ServiceReference serviceReference : serviceReferences) { - ManagedService service = bundleContext.getService(serviceReference); - if (service instanceof NetconfConfiguration){ - LOG.debug("Netconf configuration service found"); - return (NetconfConfiguration) service; - } + ManagedService service = bundleContext.getService(serviceReference); + if (service instanceof NetconfConfiguration) { + LOG.debug("Netconf configuration service found"); + return (NetconfConfiguration) service; + } } throw new IllegalStateException("Netconf configuration service not found"); diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfiguration.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfiguration.java index f84d5a1954..c67675a910 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfiguration.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/osgi/NetconfConfiguration.java @@ -55,9 +55,11 @@ public class NetconfConfiguration implements ManagedService { LOG.debug("CSS netconf server configuration cannot be updated as passed dictionary is null"); return; } - final InetSocketAddress sshServerAddress = new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP), - Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP))); - final InetSocketAddress tcpServerAddress = new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP), + final InetSocketAddress sshServerAddress = + new InetSocketAddress((String) dictionaryConfig.get(SSH_ADDRESS_PROP), + Integer.parseInt((String) dictionaryConfig.get(SSH_PORT_PROP))); + final InetSocketAddress tcpServerAddress = + new InetSocketAddress((String) dictionaryConfig.get(TCP_ADDRESS_PROP), Integer.parseInt((String) dictionaryConfig.get(TCP_PORT_PROP))); netconfConfiguration = new NetconfConfigurationHolder(tcpServerAddress, @@ -67,11 +69,11 @@ public class NetconfConfiguration implements ManagedService { LOG.debug("CSS netconf server configuration was updated: {}", dictionaryConfig.toString()); } - public InetSocketAddress getSshServerAddress(){ + public InetSocketAddress getSshServerAddress() { return netconfConfiguration.getSshServerAddress(); } - public InetSocketAddress getTcpServerAddress(){ + public InetSocketAddress getTcpServerAddress() { return netconfConfiguration.getTcpServerAddress(); } diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolver.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolver.java index 9c95ed58ac..a705ea647a 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolver.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolver.java @@ -27,11 +27,11 @@ public class HardcodedNamespaceResolver implements NamespaceContext { } /** - * This method returns the uri for all prefixes needed. Wherever possible it - * uses XMLConstants. + * Returns the URI for all prefixes needed. Wherever possible it + * uses {@code XMLConstants}. * - * @param prefix - * @return uri + * @param prefix prefix + * @return uri uniform resource identifier */ @Override public String getNamespaceURI(String prefix) { diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/XMLNetconfUtil.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/XMLNetconfUtil.java index ebe7bd023b..b3c3da5c26 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/XMLNetconfUtil.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/xml/XMLNetconfUtil.java @@ -24,13 +24,13 @@ public final class XMLNetconfUtil { throw new UnsupportedOperationException("Utility class"); } - public static XPathExpression compileXPath(final String xPath) { - final XPath xpath = FACTORY.newXPath(); - xpath.setNamespaceContext(NS_CONTEXT); + public static XPathExpression compileXPath(final String xpath) { + final XPath newXPath = FACTORY.newXPath(); + newXPath.setNamespaceContext(NS_CONTEXT); try { - return xpath.compile(xPath); + return newXPath.compile(xpath); } catch (final XPathExpressionException e) { - throw new IllegalStateException("Error while compiling xpath expression " + xPath, e); + throw new IllegalStateException("Error while compiling xpath expression " + xpath, e); } } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/CloseableUtilTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/CloseableUtilTest.java index 786395d9b1..907b2b4505 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/CloseableUtilTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/CloseableUtilTest.java @@ -18,6 +18,7 @@ import org.junit.Test; public class CloseableUtilTest { + @SuppressWarnings("checkstyle:IllegalCatch") @Test public void testCloseAllFail() throws Exception { final AutoCloseable failingCloseable = new AutoCloseable() { diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/NetconfUtilTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/NetconfUtilTest.java index 5a7941ad7a..38f5bd039f 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/NetconfUtilTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/NetconfUtilTest.java @@ -44,8 +44,9 @@ public class NetconfUtilTest { @Test public void testConflictingVersionDetection() throws Exception { - final Document document = XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml")); - try{ + final Document document = XmlUtil.readXmlToDocument(getClass() + .getResourceAsStream("/netconfMessages/conflictingversion/conflictingVersionResponse.xml")); + try { NetconfUtil.checkIsMessageOk(document); fail(); } catch (final IllegalStateException e) { @@ -63,7 +64,8 @@ public class NetconfUtilTest { .withValue("admin") .build(); final MapEntryNode session1 = Builders.mapEntryBuilder() - .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifierWithPredicates(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L)) + .withNodeIdentifier(new YangInstanceIdentifier + .NodeIdentifierWithPredicates(Session.QNAME, QName.create(Session.QNAME, "session-id"), 1L)) .withChild(username) .build(); final MapNode sessionList = Builders.mapBuilder() diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperationTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperationTest.java index 1426505c5d..f9de09342a 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperationTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractLastNetconfOperationTest.java @@ -33,7 +33,8 @@ public class AbstractLastNetconfOperationTest { } @Override - protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{ + protected Element handleWithNoSubsequentOperations(Document document, + XmlElement operationElement) throws DocumentedException { handleWithNoSubsequentOperationsRun = true; return null; } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperationTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperationTest.java index 81ccae28f4..75b870f7f6 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperationTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractNetconfOperationTest.java @@ -43,7 +43,8 @@ public class AbstractNetconfOperationTest { } @Override - protected Element handle(Document document, XmlElement message, NetconfOperationChainedExecution subsequentOperation) throws DocumentedException{ + protected Element handle(Document document, XmlElement message, + NetconfOperationChainedExecution subsequentOperation) throws DocumentedException { this.handleRun = true; try { return XmlUtil.readXmlToElement(""); diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractSingletonNetconfOperationTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractSingletonNetconfOperationTest.java index dc48b8b624..9ba35770e4 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractSingletonNetconfOperationTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/mapping/AbstractSingletonNetconfOperationTest.java @@ -25,7 +25,8 @@ public class AbstractSingletonNetconfOperationTest { } @Override - protected Element handleWithNoSubsequentOperations(Document document, XmlElement operationElement) throws DocumentedException{ + protected Element handleWithNoSubsequentOperations(Document document, + XmlElement operationElement) throws DocumentedException { return null; } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/NetconfMessageUtilTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/NetconfMessageUtilTest.java index ad307fe360..53d2c585ef 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/NetconfMessageUtilTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/NetconfMessageUtilTest.java @@ -24,12 +24,14 @@ public class NetconfMessageUtilTest { assertTrue(NetconfMessageUtil.isOKMessage(new NetconfMessage(okMessage))); assertFalse(NetconfMessageUtil.isErrorMessage(new NetconfMessage(okMessage))); - Document errorMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/communicationError/testClientSendsRpcReply_expectedResponse.xml"); + Document errorMessage = XmlFileLoader + .xmlFileToDocument("netconfMessages/communicationError/testClientSendsRpcReply_expectedResponse.xml"); assertTrue(NetconfMessageUtil.isErrorMessage(new NetconfMessage(errorMessage))); assertFalse(NetconfMessageUtil.isOKMessage(new NetconfMessage(errorMessage))); Document helloMessage = XmlFileLoader.xmlFileToDocument("netconfMessages/client_hello.xml"); - Collection caps = NetconfMessageUtil.extractCapabilitiesFromHello(new NetconfMessage(helloMessage).getDocument()); + Collection caps = + NetconfMessageUtil.extractCapabilitiesFromHello(new NetconfMessage(helloMessage).getDocument()); assertTrue(caps.contains("urn:ietf:params:netconf:base:1.0")); assertTrue(caps.contains("urn:ietf:params:netconf:base:1.1")); } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterNotificationTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterNotificationTest.java index ac7d83ce37..96f179a112 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterNotificationTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterNotificationTest.java @@ -50,7 +50,7 @@ public class SubtreeFilterNotificationTest { } @Before - public void setUp(){ + public void setUp() { XMLUnit.setIgnoreWhitespace(true); } @@ -59,8 +59,9 @@ public class SubtreeFilterNotificationTest { XmlElement filter = XmlElement.fromDomDocument(getDocument("filter.xml")); Document preFilterDocument = getDocument("pre-filter.xml"); Document postFilterDocument = getDocument("post-filter.xml"); - Optional actualPostFilterDocumentOpt = SubtreeFilter.applySubtreeNotificationFilter(filter, preFilterDocument); - if(actualPostFilterDocumentOpt.isPresent()) { + Optional actualPostFilterDocumentOpt = + SubtreeFilter.applySubtreeNotificationFilter(filter, preFilterDocument); + if (actualPostFilterDocumentOpt.isPresent()) { Document actualPostFilterDocument = actualPostFilterDocumentOpt.get(); LOG.info("Actual document: {}", XmlUtil.toString(actualPostFilterDocument)); Diff diff = XMLUnit.compareXML(postFilterDocument, actualPostFilterDocument); @@ -71,7 +72,7 @@ public class SubtreeFilterNotificationTest { } public Document getDocument(String fileName) throws SAXException, IOException { - return XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/subtree/notification/" + directoryIndex + "/" + - fileName)); + return XmlUtil.readXmlToDocument(getClass().getResourceAsStream( + "/subtree/notification/" + directoryIndex + "/" + fileName)); } } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterRpcTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterRpcTest.java index e486c75f2e..d5b4a24a84 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterRpcTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/messages/SubtreeFilterRpcTest.java @@ -47,7 +47,7 @@ public class SubtreeFilterRpcTest { } @Before - public void setUp(){ + public void setUp() { XMLUnit.setIgnoreWhitespace(true); } @@ -64,7 +64,7 @@ public class SubtreeFilterRpcTest { } public Document getDocument(String fileName) throws SAXException, IOException { - return XmlUtil.readXmlToDocument(getClass().getResourceAsStream("/subtree/rpc/" + directoryIndex + "/" + - fileName)); + return XmlUtil.readXmlToDocument( + getClass().getResourceAsStream("/subtree/rpc/" + directoryIndex + "/" + fileName)); } } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtilTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtilTest.java index e777bb05f6..64bf74fec5 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtilTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/osgi/NetconfConfigUtilTest.java @@ -8,6 +8,7 @@ package org.opendaylight.netconf.util.osgi; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; @@ -66,7 +67,7 @@ public class NetconfConfigUtilTest { NetconfConfigUtil.getNetconfConfigurationService(context); Assert.fail(IllegalStateException.class + "exception expected"); } catch (IllegalStateException e) { - + assertTrue(e.getMessage().startsWith("Netconf configuration service not found")); } } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/NetconfXmlUnitRecursiveQualifier.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/NetconfXmlUnitRecursiveQualifier.java index 494b96ec43..4e55591271 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/NetconfXmlUnitRecursiveQualifier.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/NetconfXmlUnitRecursiveQualifier.java @@ -16,7 +16,7 @@ import org.w3c.dom.NodeList; /** * Custom xmlunit qualifier that doesn't care about order when deeper in the recursion - * defaults to comparing element name and text content + * defaults to comparing element name and text content. */ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier { @@ -36,6 +36,7 @@ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier { return compareNodes(currentControl, currentTest); } + @SuppressWarnings("checkstyle:IllegalCatch") private boolean compareNodes(Node currentControl, Node currentTest) { try { @@ -54,8 +55,8 @@ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier { return !(currentControl.hasChildNodes() || currentTest.hasChildNodes()); } - return (countNodesWithoutConsecutiveTextNodes(controlNodes) == countNodesWithoutConsecutiveTextNodes(testNodes)) - && checkChildren(controlNodes, testNodes); + return (countNodesWithoutConsecutiveTextNodes(controlNodes) + == countNodesWithoutConsecutiveTextNodes(testNodes)) && checkChildren(controlNodes, testNodes); } catch (Exception e) { return false; @@ -106,16 +107,16 @@ public class NetconfXmlUnitRecursiveQualifier implements ElementQualifier { return builder.toString(); } - private static int countNodesWithoutConsecutiveTextNodes(NodeList l) { + private static int countNodesWithoutConsecutiveTextNodes(NodeList nodeList) { int count = 0; boolean lastNodeWasText = false; - final int length = l.getLength(); + final int length = nodeList.getLength(); for (int i = 0; i < length; i++) { - Node n = l.item(i); - if (!lastNodeWasText || n.getNodeType() != Node.TEXT_NODE) { + Node node = nodeList.item(i); + if (!lastNodeWasText || node.getNodeType() != Node.TEXT_NODE) { count++; } - lastNodeWasText = n.getNodeType() == Node.TEXT_NODE; + lastNodeWasText = node.getNodeType() == Node.TEXT_NODE; } return count; } diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java index e8941445ed..9ce2be2013 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/test/XmlUnitUtil.java @@ -26,7 +26,8 @@ public class XmlUnitUtil { private XmlUnitUtil() {} - public static void assertContainsElementWithText(final Document doc, final String textToFind) throws NodeTestException { + public static void assertContainsElementWithText(final Document doc, + final String textToFind) throws NodeTestException { NodeTest nt = new NodeTest(doc); NodeTester tester = new AbstractNodeTester() { @@ -34,7 +35,7 @@ public class XmlUnitUtil { @Override public void testText(Text text) throws NodeTestException { - if(!textFound) { + if (!textFound) { if (text.getData().equalsIgnoreCase(textToFind)) { textFound = true; } @@ -58,7 +59,7 @@ public class XmlUnitUtil { @Override public void testElement(Element element) throws NodeTestException { if (!elementFound) { - if(element.isEqualNode(testElement)) { + if (element.isEqualNode(testElement)) { elementFound = true; } } @@ -72,7 +73,8 @@ public class XmlUnitUtil { assertNodeTestPasses(nt, tester, new short[]{Node.ELEMENT_NODE}, true); } - public static void assertContainsElementWithName(final Document doc, final String elementName) throws NodeTestException { + public static void assertContainsElementWithName(final Document doc, + final String elementName) throws NodeTestException { NodeTest nt = new NodeTest(doc); NodeTester tester = new AbstractNodeTester() { diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolverTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolverTest.java index dd646df714..c728862068 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolverTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/HardcodedNamespaceResolverTest.java @@ -10,6 +10,7 @@ package org.opendaylight.netconf.util.xml; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; @@ -18,13 +19,16 @@ public class HardcodedNamespaceResolverTest { @Test public void testResolver() throws Exception { - final HardcodedNamespaceResolver hardcodedNamespaceResolver = new HardcodedNamespaceResolver("prefix", "namespace"); + final HardcodedNamespaceResolver hardcodedNamespaceResolver = + new HardcodedNamespaceResolver("prefix", "namespace"); assertEquals("namespace", hardcodedNamespaceResolver.getNamespaceURI("prefix")); - try{ + try { hardcodedNamespaceResolver.getNamespaceURI("unknown"); fail("Unknown namespace lookup should fail"); - } catch(IllegalStateException e) {} + } catch (IllegalStateException e) { + assertTrue(e.getMessage().startsWith("Prefix mapping not found for ")); + } assertNull(hardcodedNamespaceResolver.getPrefix("any")); assertNull(hardcodedNamespaceResolver.getPrefixes("any")); diff --git a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/XMLNetconfUtilTest.java b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/XMLNetconfUtilTest.java index f70406bb2c..3ca07d4dd4 100644 --- a/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/XMLNetconfUtilTest.java +++ b/netconf/netconf-util/src/test/java/org/opendaylight/netconf/util/xml/XMLNetconfUtilTest.java @@ -9,6 +9,7 @@ package org.opendaylight.netconf.util.xml; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import javax.xml.xpath.XPathConstants; @@ -25,8 +26,11 @@ public class XMLNetconfUtilTest { try { XMLNetconfUtil.compileXPath("!@(*&$!"); fail("Incorrect xpath should fail"); - } catch (IllegalStateException e) {} - final Object value = XmlUtil.evaluateXPath(correctXPath, XmlUtil.readXmlToDocument("value"), XPathConstants.NODE); + } catch (IllegalStateException e) { + assertTrue(e.getMessage().startsWith("Error while compiling xpath expression ")); + } + final Object value = XmlUtil.evaluateXPath(correctXPath, + XmlUtil.readXmlToDocument("value"), XPathConstants.NODE); assertEquals("value", ((Element) value).getTextContent()); } diff --git a/restconf/restconf-artifacts/pom.xml b/restconf/restconf-artifacts/pom.xml index 2f52f58685..207331f61d 100644 --- a/restconf/restconf-artifacts/pom.xml +++ b/restconf/restconf-artifacts/pom.xml @@ -70,17 +70,45 @@ ${project.groupId} features-restconf ${project.version} + xml features + + + + + ${project.groupId} + features4-restconf + ${project.version} xml - runtime + features + + + ${project.groupId} + odl-mdsal-apidocs + ${project.version} + xml + features ${project.groupId} odl-restconf ${project.version} + xml + features + + + ${project.groupId} + odl-restconf-all + ${project.version} + xml features + + + ${project.groupId} + odl-restconf-noauth + ${project.version} xml - runtime + features diff --git a/restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java b/restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java index 07e5e92ef4..86dc3d4724 100644 --- a/restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java +++ b/restconf/sal-rest-connector/src/main/java/org/opendaylight/netconf/sal/restconf/impl/BrokerFacade.java @@ -1015,92 +1015,93 @@ public class BrokerFacade { final String insert, final String point) { if (insert == null) { makePut(rWTransaction, datastore, path, payload, schemaContext); - } else { - final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path); - checkItemDoesNotExists(rWTransaction, datastore, path); - switch (insert) { - case "first": - if (schemaNode instanceof ListSchemaNode) { - final OrderedMapNode readList = - (OrderedMapNode) this.readConfigurationData(path.getParent()); - if (readList == null || readList.getValue().isEmpty()) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); - } else { - rWTransaction.delete(datastore, path.getParent()); - simplePut(datastore, path, rWTransaction, schemaContext, payload); - makePut(rWTransaction, datastore, path.getParent(), readList, schemaContext); - } + return; + } + + final DataSchemaNode schemaNode = checkListAndOrderedType(schemaContext, path); + checkItemDoesNotExists(rWTransaction, datastore, path); + switch (insert) { + case "first": + if (schemaNode instanceof ListSchemaNode) { + final OrderedMapNode readList = + (OrderedMapNode) this.readConfigurationData(path.getParent()); + if (readList == null || readList.getValue().isEmpty()) { + simplePut(datastore, path, rWTransaction, schemaContext, payload); } else { - final OrderedLeafSetNode readLeafList = - (OrderedLeafSetNode) readConfigurationData(path.getParent()); - if (readLeafList == null || readLeafList.getValue().isEmpty()) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); - } else { - rWTransaction.delete(datastore, path.getParent()); - simplePut(datastore, path, rWTransaction, schemaContext, payload); - makePut(rWTransaction, datastore, path.getParent(), readLeafList, - schemaContext); - } + rWTransaction.delete(datastore, path.getParent()); + simplePut(datastore, path, rWTransaction, schemaContext, payload); + makePut(rWTransaction, datastore, path.getParent(), readList, schemaContext); } - break; - case "last": - simplePut(datastore, path, rWTransaction, schemaContext, payload); - break; - case "before": - if (schemaNode instanceof ListSchemaNode) { - final OrderedMapNode readList = - (OrderedMapNode) this.readConfigurationData(path.getParent()); - if (readList == null || readList.getValue().isEmpty()) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); - } else { - insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point, - readList, true); - } + } else { + final OrderedLeafSetNode readLeafList = + (OrderedLeafSetNode) readConfigurationData(path.getParent()); + if (readLeafList == null || readLeafList.getValue().isEmpty()) { + simplePut(datastore, path, rWTransaction, schemaContext, payload); } else { - final OrderedLeafSetNode readLeafList = - (OrderedLeafSetNode) readConfigurationData(path.getParent()); - if (readLeafList == null || readLeafList.getValue().isEmpty()) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); - } else { - insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point, - readLeafList, true); - } + rWTransaction.delete(datastore, path.getParent()); + simplePut(datastore, path, rWTransaction, schemaContext, payload); + makePut(rWTransaction, datastore, path.getParent(), readLeafList, + schemaContext); } - break; - case "after": - if (schemaNode instanceof ListSchemaNode) { - final OrderedMapNode readList = - (OrderedMapNode) this.readConfigurationData(path.getParent()); - if (readList == null || readList.getValue().isEmpty()) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); - } else { - insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point, - readList, false); - } + } + break; + case "last": + simplePut(datastore, path, rWTransaction, schemaContext, payload); + break; + case "before": + if (schemaNode instanceof ListSchemaNode) { + final OrderedMapNode readList = + (OrderedMapNode) this.readConfigurationData(path.getParent()); + if (readList == null || readList.getValue().isEmpty()) { + simplePut(datastore, path, rWTransaction, schemaContext, payload); } else { - final OrderedLeafSetNode readLeafList = - (OrderedLeafSetNode) readConfigurationData(path.getParent()); - if (readLeafList == null || readLeafList.getValue().isEmpty()) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); - } else { - insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point, - readLeafList, false); - } + insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point, + readList, true); } - break; - default: - throw new RestconfDocumentedException( - "Used bad value of insert parameter. Possible values are first, last, before or after, " - + "but was: " + insert); - } + } else { + final OrderedLeafSetNode readLeafList = + (OrderedLeafSetNode) readConfigurationData(path.getParent()); + if (readLeafList == null || readLeafList.getValue().isEmpty()) { + simplePut(datastore, path, rWTransaction, schemaContext, payload); + } else { + insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point, + readLeafList, true); + } + } + break; + case "after": + if (schemaNode instanceof ListSchemaNode) { + final OrderedMapNode readList = + (OrderedMapNode) this.readConfigurationData(path.getParent()); + if (readList == null || readList.getValue().isEmpty()) { + simplePut(datastore, path, rWTransaction, schemaContext, payload); + } else { + insertWithPointListPut(rWTransaction, datastore, path, payload, schemaContext, point, + readList, false); + } + } else { + final OrderedLeafSetNode readLeafList = + (OrderedLeafSetNode) readConfigurationData(path.getParent()); + if (readLeafList == null || readLeafList.getValue().isEmpty()) { + simplePut(datastore, path, rWTransaction, schemaContext, payload); + } else { + insertWithPointLeafListPut(rWTransaction, datastore, path, payload, schemaContext, point, + readLeafList, false); + } + } + break; + default: + throw new RestconfDocumentedException( + "Used bad value of insert parameter. Possible values are first, last, before or after, but was: " + + insert); } } - private static void insertWithPointLeafListPut(final DOMDataReadWriteTransaction rWTransaction, + private static void insertWithPointLeafListPut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload, final SchemaContext schemaContext, final String point, final OrderedLeafSetNode readLeafList, final boolean before) { - rWTransaction.delete(datastore, path.getParent()); + tx.delete(datastore, path.getParent()); final InstanceIdentifierContext instanceIdentifier = ControllerContext.getInstance().toInstanceIdentifier(point); int p = 0; @@ -1116,22 +1117,21 @@ public class BrokerFacade { int h = 0; final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent()); - rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree); + tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree); for (final LeafSetEntryNode nodeChild : readLeafList.getValue()) { if (h == p) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); + simplePut(datastore, path, tx, schemaContext, payload); } final YangInstanceIdentifier childPath = path.getParent().node(nodeChild.getIdentifier()); - rWTransaction.put(datastore, childPath, nodeChild); + tx.put(datastore, childPath, nodeChild); h++; } } - private static void insertWithPointListPut(final DOMDataReadWriteTransaction rWTransaction, - final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload, - final SchemaContext schemaContext, final String point, final OrderedMapNode readList, - final boolean before) { - rWTransaction.delete(datastore, path.getParent()); + private static void insertWithPointListPut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore, + final YangInstanceIdentifier path, final NormalizedNode payload, final SchemaContext schemaContext, + final String point, final OrderedMapNode readList, final boolean before) { + tx.delete(datastore, path.getParent()); final InstanceIdentifierContext instanceIdentifier = ControllerContext.getInstance().toInstanceIdentifier(point); int p = 0; @@ -1147,38 +1147,36 @@ public class BrokerFacade { int h = 0; final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path.getParent()); - rWTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree); + tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree); for (final MapEntryNode mapEntryNode : readList.getValue()) { if (h == p) { - simplePut(datastore, path, rWTransaction, schemaContext, payload); + simplePut(datastore, path, tx, schemaContext, payload); } final YangInstanceIdentifier childPath = path.getParent().node(mapEntryNode.getIdentifier()); - rWTransaction.put(datastore, childPath, mapEntryNode); + tx.put(datastore, childPath, mapEntryNode); h++; } } - private static void makePut(final DOMDataReadWriteTransaction writeTransaction, - final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload, - final SchemaContext schemaContext) { + private static void makePut(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore, + final YangInstanceIdentifier path, final NormalizedNode payload, final SchemaContext schemaContext) { if (payload instanceof MapNode) { final NormalizedNode emptySubtree = ImmutableNodes.fromInstanceId(schemaContext, path); - writeTransaction.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree); - ensureParentsByMerge(datastore, path, writeTransaction, schemaContext); + tx.merge(datastore, YangInstanceIdentifier.create(emptySubtree.getIdentifier()), emptySubtree); + ensureParentsByMerge(datastore, path, tx, schemaContext); for (final MapEntryNode child : ((MapNode) payload).getValue()) { final YangInstanceIdentifier childPath = path.node(child.getIdentifier()); - writeTransaction.put(datastore, childPath, child); + tx.put(datastore, childPath, child); } } else { - simplePut(datastore, path, writeTransaction, schemaContext, payload); + simplePut(datastore, path, tx, schemaContext, payload); } } private static void simplePut(final LogicalDatastoreType datastore, final YangInstanceIdentifier path, - final DOMDataReadWriteTransaction writeTransaction, final SchemaContext schemaContext, - final NormalizedNode payload) { - ensureParentsByMerge(datastore, path, writeTransaction, schemaContext); - writeTransaction.put(datastore, path, payload); + final DOMDataWriteTransaction tx, final SchemaContext schemaContext, final NormalizedNode payload) { + ensureParentsByMerge(datastore, path, tx, schemaContext); + tx.put(datastore, path, payload); } private static CheckedFuture deleteDataViaTransaction( @@ -1190,21 +1188,21 @@ public class BrokerFacade { return readWriteTransaction.submit(); } - private static void deleteDataWithinTransaction(final DOMDataWriteTransaction writeTransaction, + private static void deleteDataWithinTransaction(final DOMDataWriteTransaction tx, final LogicalDatastoreType datastore, final YangInstanceIdentifier path) { LOG.trace("Delete {} within Restconf PATCH: {}", datastore.name(), path); - writeTransaction.delete(datastore, path); + tx.delete(datastore, path); } - private static void mergeDataWithinTransaction( - final DOMDataReadWriteTransaction writeTransaction, final LogicalDatastoreType datastore, - final YangInstanceIdentifier path, final NormalizedNode payload, final SchemaContext schemaContext) { + private static void mergeDataWithinTransaction(final DOMDataWriteTransaction tx, + final LogicalDatastoreType datastore, final YangInstanceIdentifier path, final NormalizedNode payload, + final SchemaContext schemaContext) { LOG.trace("Merge {} within Restconf PATCH: {} with payload {}", datastore.name(), path, payload); - ensureParentsByMerge(datastore, path, writeTransaction, schemaContext); + ensureParentsByMerge(datastore, path, tx, schemaContext); // Since YANG Patch provides the option to specify what kind of operation for each edit, // OpenDaylight should not change it. - writeTransaction.merge(datastore, path, payload); + tx.merge(datastore, path, payload); } public void setDomDataBroker(final DOMDataBroker domDataBroker) { @@ -1226,7 +1224,7 @@ public class BrokerFacade { } private static void ensureParentsByMerge(final LogicalDatastoreType store, - final YangInstanceIdentifier normalizedPath, final DOMDataReadWriteTransaction rwTx, + final YangInstanceIdentifier normalizedPath, final DOMDataWriteTransaction tx, final SchemaContext schemaContext) { final List normalizedPathWithoutChildArgs = new ArrayList<>(); YangInstanceIdentifier rootNormalizedPath = null; @@ -1252,7 +1250,7 @@ public class BrokerFacade { final NormalizedNode parentStructure = ImmutableNodes.fromInstanceId(schemaContext, YangInstanceIdentifier.create(normalizedPathWithoutChildArgs)); - rwTx.merge(store, rootNormalizedPath, parentStructure); + tx.merge(store, rootNormalizedPath, parentStructure); } private static final class PATCHStatusContextHelper {