From 47c1b8e3d9835d336c79d6b4ca4e61417a05039e Mon Sep 17 00:00:00 2001 From: Tom Pantelis Date: Thu, 29 Mar 2018 19:29:44 -0400 Subject: [PATCH] Fix findbugs violations in netconf - Field is a mutable collection which should be package protected - Unchecked/unconfirmed cast of return value from method - May expose internal representation by returning reference to mutable object - May expose internal representation by incorporating reference to mutable object - Field should be package protected - Parameter must be non-null but is marked as nullable - Nullcheck of value previously dereferenced - Inconsistent synchronization - Method ignores return value - Boxing/unboxing to parse a primitive - Boxed value is unboxed and then immediately reboxed - Unchecked/unconfirmed cast - Class implements same interface as superclass - Switch statement found where one case falls through to the next case - Field not initialized in constructor but dereferenced without null check - Reliance on default encoding - Private method is never called - Method invokes toString() method on a String - Possible null pointer dereference - Consider using Locale parameterized version of invoked method - Field not guarded against concurrent access - Method does not release lock on all exception paths - Inefficient use of keySet iterator instead of entrySet iterator - Load of known null value - Redundant nullcheck of value known to be non-null - Non-transient non-serializable instance field in serializable class - Class is Externalizable but doesn't define a void constructor - Class is Serializable, but doesn't define serialVersionUID - Class defines field that masks a superclass field - Should be a static inner class - Repeated conditional tests - Format string should use %n rather than \n - Method may fail to close stream - Unconditional wait - Wait not in loop - Method concatenates strings using + in a loop - Dead store to local variable - Possible null pointer dereference due to return value of called method - Useless object created Change-Id: If4b7fe5431a4b957f344ecc4307982a40241c97b Signed-off-by: Tom Pantelis --- .../protocol/AuthorizedKeysDecoder.java | 31 ++++++------ .../callhome/mount/BaseCallHomeTopology.java | 4 -- .../mount/CallHomeAuthProviderImpl.java | 6 +-- .../netconf/callhome/mount/Configuration.java | 3 -- .../mdsal/connector/ops/RuntimeRpc.java | 2 +- .../netconf/NetconfEventSource.java | 6 ++- .../netconf/NetconfEventSourceManager.java | 16 ------ .../api/NetconfDocumentedException.java | 2 + .../netconf/api/util/NetconfConstants.java | 4 +- .../client/NetconfClientDispatcherImpl.java | 3 +- .../NetconfClientSessionNegotiator.java | 11 +++-- .../SimpleNetconfClientSessionListener.java | 2 + .../client/TcpClientChannelInitializer.java | 8 ++- .../conf/NetconfClientConfiguration.java | 15 +++--- .../commands/NetconfListDevicesCommand.java | 3 +- .../commands/NetconfShowDeviceCommand.java | 8 +-- .../console/impl/NetconfCommandsImpl.java | 4 +- .../impl/NetconfServerSessionNegotiator.java | 2 + .../netconf/impl/MessageParserTest.java | 21 ++++---- .../xml/model/MonitoringSchema.java | 2 +- .../ChunkedFramingMechanismEncoder.java | 5 +- .../handler/EOMFramingMechanismEncoder.java | 3 +- .../nettyutil/handler/MessageParts.java | 23 +++++++++ .../handler/NetconfEOMAggregator.java | 3 +- .../handler/ssh/client/AsyncSshHandler.java | 17 ++++--- .../EOMFramingMechanismEncoderTest.java | 5 +- .../notifications/NetconfNotification.java | 3 ++ .../impl/ops/NotificationsTransformUtil.java | 8 +-- netconf/netconf-parent/pom.xml | 2 - .../netconf/ssh/SshProxyClientHandler.java | 39 +++++++-------- .../netconf/ssh/SshProxyServer.java | 11 ----- .../impl/NetconfTopologyContext.java | 8 +-- .../impl/RemoteDeviceConnectorImpl.java | 11 ++--- .../impl/actors/NetconfNodeActor.java | 2 +- .../singleton/impl/actors/ReadAdapter.java | 2 +- .../CreateInitialMasterActorData.java | 5 +- .../messages/RefreshSetupMasterActorData.java | 5 +- .../singleton/messages/RefreshSlaveActor.java | 3 +- .../singleton/messages/SchemaPathMessage.java | 7 ++- .../messages/rpc/InvokeRpcMessage.java | 3 +- .../messages/rpc/InvokeRpcMessageReply.java | 5 +- .../transactions/NewReadTransactionReply.java | 1 + .../NewReadTransactionRequest.java | 1 + .../NewReadWriteTransactionReply.java | 1 + .../NewWriteTransactionReply.java | 1 + .../NewWriteTransactionRequest.java | 1 + .../topology/AbstractNetconfTopology.java | 11 ++--- .../messages/NetconfMessageConstants.java | 17 +++---- .../netconf/LibraryModulesSchemas.java | 22 ++++++--- .../sal/connect/netconf/NetconfDevice.java | 7 +-- .../connect/netconf/NetconfStateSchemas.java | 5 +- .../listener/NetconfDeviceCommunicator.java | 21 ++++---- .../netconf/listener/UncancellableFuture.java | 12 ++--- .../netconf/sal/KeepaliveSalFacade.java | 6 +-- .../connect/netconf/sal/NetconfDeviceRpc.java | 10 +--- .../sal/NetconfDeviceTopologyAdapter.java | 5 -- .../netconf/sal/tx/AbstractWriteTx.java | 12 ++--- .../netconf/sal/tx/WriteCandidateTx.java | 3 +- ...NetconfRemoteSchemaYangSourceProvider.java | 3 +- .../YangLibrarySchemaYangSourceProvider.java | 3 +- .../mapping/NetconfMessageTransformer.java | 14 ++++-- .../connect/netconf/util/NetconfBaseOps.java | 3 +- .../util/NetconfRpcFutureCallback.java | 3 +- .../SchemalessRpcStructureTransformer.java | 9 ++-- .../test/tool/DummyMonitoringService.java | 12 ++--- .../netconf/test/tool/Execution.java | 6 +-- .../opendaylight/netconf/test/tool/Main.java | 18 ++++--- .../test/tool/NetconfDeviceSimulator.java | 2 + .../netconf/test/tool/ScaleUtil.java | 49 +++++++++---------- .../netconf/test/tool/TesttoolParameters.java | 34 +++++++------ .../http/perf/AsyncExecutionStrategy.java | 6 +-- .../tool/client/http/perf/RestPerfClient.java | 4 +- .../test/tool/client/stress/StressClient.java | 4 +- .../test/tool/customrpc/RpcMapping.java | 2 +- .../test/tool/rpc/SimulatedGetConfig.java | 4 +- .../tool/scale/util/ScaleUtilParameters.java | 2 + .../yanglib/impl/YangLibProvider.java | 9 ---- .../yanglib/impl/YangLibServiceImpl.java | 3 +- 78 files changed, 317 insertions(+), 332 deletions(-) create mode 100644 netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java diff --git a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java index e544195fd8..7e07568a63 100644 --- a/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java +++ b/netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java @@ -11,6 +11,7 @@ import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.math.BigInteger; +import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PublicKey; @@ -63,7 +64,7 @@ public class AuthorizedKeysDecoder { // look for the Base64 encoded part of the line to decode // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes - bytes = Base64.getDecoder().decode(keyLine.getBytes()); + bytes = Base64.getDecoder().decode(keyLine.getBytes(StandardCharsets.UTF_8)); if (bytes.length == 0) { throw new IllegalArgumentException("No Base64 part to decode in " + keyLine); } @@ -121,7 +122,7 @@ public class AuthorizedKeysDecoder { private String decodeType() { int len = decodeInt(); - String type = new String(bytes, pos, len); + String type = new String(bytes, pos, len, StandardCharsets.UTF_8); pos += len; return type; } @@ -140,23 +141,22 @@ public class AuthorizedKeysDecoder { } public static String encodePublicKey(final PublicKey publicKey) throws IOException { - String publicKeyEncoded; ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); - if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA)) { + if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_RSA) && publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; DataOutputStream dout = new DataOutputStream(byteOs); - dout.writeInt(KEY_TYPE_RSA.getBytes().length); - dout.write(KEY_TYPE_RSA.getBytes()); + dout.writeInt(KEY_TYPE_RSA.getBytes(StandardCharsets.UTF_8).length); + dout.write(KEY_TYPE_RSA.getBytes(StandardCharsets.UTF_8)); dout.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dout.write(rsaPublicKey.getPublicExponent().toByteArray()); dout.writeInt(rsaPublicKey.getModulus().toByteArray().length); dout.write(rsaPublicKey.getModulus().toByteArray()); - } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA)) { + } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_DSA) && publicKey instanceof DSAPublicKey) { DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey; DSAParams dsaParams = dsaPublicKey.getParams(); DataOutputStream dout = new DataOutputStream(byteOs); - dout.writeInt(KEY_TYPE_DSA.getBytes().length); - dout.write(KEY_TYPE_DSA.getBytes()); + dout.writeInt(KEY_TYPE_DSA.getBytes(StandardCharsets.UTF_8).length); + dout.write(KEY_TYPE_DSA.getBytes(StandardCharsets.UTF_8)); dout.writeInt(dsaParams.getP().toByteArray().length); dout.write(dsaParams.getP().toByteArray()); dout.writeInt(dsaParams.getQ().toByteArray().length); @@ -165,13 +165,13 @@ public class AuthorizedKeysDecoder { dout.write(dsaParams.getG().toByteArray()); dout.writeInt(dsaPublicKey.getY().toByteArray().length); dout.write(dsaPublicKey.getY().toByteArray()); - } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA)) { + } else if (publicKey.getAlgorithm().equals(KEY_FACTORY_TYPE_ECDSA) && publicKey instanceof BCECPublicKey) { BCECPublicKey ecPublicKey = (BCECPublicKey) publicKey; DataOutputStream dout = new DataOutputStream(byteOs); - dout.writeInt(KEY_TYPE_ECDSA.getBytes().length); - dout.write(KEY_TYPE_ECDSA.getBytes()); - dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes().length); - dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes()); + dout.writeInt(KEY_TYPE_ECDSA.getBytes(StandardCharsets.UTF_8).length); + dout.write(KEY_TYPE_ECDSA.getBytes(StandardCharsets.UTF_8)); + dout.writeInt(ECDSA_SUPPORTED_CURVE_NAME.getBytes(StandardCharsets.UTF_8).length); + dout.write(ECDSA_SUPPORTED_CURVE_NAME.getBytes(StandardCharsets.UTF_8)); byte[] coordX = ecPublicKey.getQ().getAffineXCoord().getEncoded(); byte[] coordY = ecPublicKey.getQ().getAffineYCoord().getEncoded(); @@ -182,7 +182,6 @@ public class AuthorizedKeysDecoder { } else { throw new IllegalArgumentException("Unknown public key encoding: " + publicKey.getAlgorithm()); } - publicKeyEncoded = new String(Base64.getEncoder().encodeToString(byteOs.toByteArray())); - return publicKeyEncoded; + return Base64.getEncoder().encodeToString(byteOs.toByteArray()); } } diff --git a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/BaseCallHomeTopology.java b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/BaseCallHomeTopology.java index 0fcfb82fc7..d4f9e132b8 100644 --- a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/BaseCallHomeTopology.java +++ b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/BaseCallHomeTopology.java @@ -19,9 +19,6 @@ import org.opendaylight.netconf.topology.AbstractNetconfTopology; import org.opendaylight.netconf.topology.api.SchemaRepositoryProvider; abstract class BaseCallHomeTopology extends AbstractNetconfTopology { - - protected DOMMountPointService mountPointService = null; - BaseCallHomeTopology(final String topologyId, final NetconfClientDispatcher clientDispatcher, final EventExecutor eventExecutor, final ScheduledThreadPool keepaliveExecutor, @@ -33,6 +30,5 @@ abstract class BaseCallHomeTopology extends AbstractNetconfTopology { super(topologyId, clientDispatcher, eventExecutor, keepaliveExecutor, processingExecutor, schemaRepositoryProvider, dataBroker, mountPointService, encryptionService); - this.mountPointService = mountPointService; } } diff --git a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeAuthProviderImpl.java b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeAuthProviderImpl.java index 29632c247f..15445eb746 100644 --- a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeAuthProviderImpl.java +++ b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeAuthProviderImpl.java @@ -126,7 +126,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, return remoteAddress.toString(); } - private class DeviceConfig implements DataTreeChangeListener { + private static class DeviceConfig implements DataTreeChangeListener { private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder(); @@ -189,7 +189,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, } } - private class DeviceOp implements DataTreeChangeListener { + private static class DeviceOp implements DataTreeChangeListener { private final ConcurrentMap byPublicKey = new ConcurrentHashMap<>(); @@ -242,7 +242,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider, } } - private class GlobalConfig implements DataTreeChangeListener { + private static class GlobalConfig implements DataTreeChangeListener { private volatile Global current = null; diff --git a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java index 713b7ec4a5..14ab22a7f6 100644 --- a/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java +++ b/netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java @@ -69,16 +69,13 @@ public class Configuration { } } - private final String path; private Properties properties; public Configuration() { - path = ""; properties = new Properties(); } public Configuration(final String path) throws ConfigurationException { - this.path = path; try { this.properties = readFromPath(path); } catch (IOException ioe) { diff --git a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java index 6d4ba4305a..d61c249cfd 100644 --- a/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java +++ b/netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java @@ -259,7 +259,7 @@ public class RuntimeRpc extends AbstractSingletonNetconfOperation { @Nullable private NormalizedNode rpcToNNode(final XmlElement element, @Nullable final ContainerSchemaNode input) throws DocumentedException { - if (input.getChildNodes().isEmpty()) { + if (input == null || input.getChildNodes().isEmpty()) { return null; } diff --git a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java index 26609d21e3..a8959888a0 100644 --- a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java +++ b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java @@ -23,6 +23,7 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Future; import java.util.regex.Pattern; @@ -122,8 +123,9 @@ public class NetconfEventSource implements EventSource, DOMNotificationListener .put(cntr.getNotificationUrnPrefix(), cntr); Map availableStreams = getAvailableStreams(); LOG.debug("Stream configuration compare..."); - for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) { - final String streamName = this.urnPrefixToStreamMap.get(urnPrefix); + for (Entry entry : this.urnPrefixToStreamMap.entrySet()) { + String urnPrefix = entry.getKey(); + final String streamName = entry.getValue(); LOG.debug("urnPrefix: {} streamName: {}", urnPrefix, streamName); if (availableStreams.containsKey(streamName)) { LOG.debug("Stream containig on device"); diff --git a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManager.java b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManager.java index 91df5f7812..6360136b9f 100644 --- a/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManager.java +++ b/netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManager.java @@ -114,22 +114,6 @@ public final class NetconfEventSourceManager implements DataTreeChangeListener key, final Node node) { - Preconditions.checkNotNull(key); - if (!validateNode(node)) { - LOG.warn("NodeUpdated event : Node [{}] is null or not valid.", key.toString()); - return; - } - - LOG.info("Netconf event source [{}] is updating...", key.toString()); - NetconfEventSourceRegistration nesr = registrationMap.get(key); - if (nesr != null) { - nesr.updateStatus(); - } else { - nodeCreated(key, node); - } - } - private void nodeRemoved(final InstanceIdentifier key) { Preconditions.checkNotNull(key); LOG.info("Netconf event source [{}] is removing...", key.toString()); diff --git a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDocumentedException.java b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDocumentedException.java index 8e289fa9e8..2adb4984b8 100644 --- a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDocumentedException.java +++ b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDocumentedException.java @@ -8,6 +8,7 @@ package org.opendaylight.netconf.api; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.util.Map; import org.opendaylight.controller.config.util.xml.DocumentedException; import org.w3c.dom.Document; @@ -43,6 +44,7 @@ public class NetconfDocumentedException extends DocumentedException { super(message, cause, errorType, errorTag, errorSeverity, errorInfo); } + @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE") public NetconfDocumentedException(final DocumentedException exception) { super(exception.getMessage(), (Exception) exception.getCause(), exception.getErrorType(), exception.getErrorTag(), exception.getErrorSeverity(), exception.getErrorInfo()); diff --git a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java index 3abeeea40c..0c7856f84c 100644 --- a/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java +++ b/netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java @@ -8,7 +8,7 @@ package org.opendaylight.netconf.api.util; -import com.google.common.collect.Sets; +import com.google.common.collect.ImmutableSet; import java.util.Set; /** @@ -25,7 +25,7 @@ public final class NetconfConstants { public static final String NETCONF_MONITORING = "ietf-netconf-monitoring"; public static final String NETCONF_NOTIFICATION = "ietf-netconf-notifications"; - public static final Set CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR, + public static final Set CONFIG_SERVICE_MARKERS = ImmutableSet.of(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR, NETCONF_MONITORING, NETCONF_NOTIFICATION); private NetconfConstants() { diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcherImpl.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcherImpl.java index d0dc480299..780ce7ff59 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcherImpl.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcherImpl.java @@ -11,7 +11,6 @@ package org.opendaylight.netconf.client; import io.netty.channel.EventLoopGroup; import io.netty.util.Timer; import io.netty.util.concurrent.Future; -import java.io.Closeable; import org.opendaylight.netconf.client.conf.NetconfClientConfiguration; import org.opendaylight.netconf.client.conf.NetconfReconnectingClientConfiguration; import org.opendaylight.protocol.framework.AbstractDispatcher; @@ -19,7 +18,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class NetconfClientDispatcherImpl extends AbstractDispatcher - implements NetconfClientDispatcher, Closeable { + implements NetconfClientDispatcher { private static final Logger LOG = LoggerFactory.getLogger(NetconfClientDispatcherImpl.class); diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java index 608450225f..19091f6d60 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java @@ -12,6 +12,7 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Interner; import com.google.common.collect.Interners; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; @@ -64,16 +65,17 @@ public class NetconfClientSessionNegotiator extends } @Override + @SuppressFBWarnings("BC_UNCONFIRMED_CAST") protected void handleMessage(final NetconfHelloMessage netconfMessage) throws NetconfDocumentedException { final NetconfClientSession session = getSessionForHelloMessage(netconfMessage); replaceHelloMessageInboundHandler(session); // If exi should be used, try to initiate exi communication // Call negotiationSuccessFul after exi negotiation is finished successfully or not - if (shouldUseExi(netconfMessage)) { + final NetconfMessage startExiMessage = sessionPreferences.getStartExiMessage(); + if (shouldUseExi(netconfMessage) && startExiMessage instanceof NetconfStartExiMessage) { LOG.debug("Netconf session {} should use exi.", session); - NetconfStartExiMessage startExiMessage = (NetconfStartExiMessage) sessionPreferences.getStartExiMessage(); - tryToInitiateExi(session, startExiMessage); + tryToInitiateExi(session, (NetconfStartExiMessage) startExiMessage); } else { // Exi is not supported, release session immediately LOG.debug("Netconf session {} isn't capable of using exi.", session); @@ -105,6 +107,7 @@ public class NetconfClientSessionNegotiator extends }); } + @SuppressFBWarnings("BC_UNCONFIRMED_CAST") private boolean shouldUseExi(final NetconfHelloMessage helloMsg) { return containsExi10Capability(helloMsg.getDocument()) && containsExi10Capability(sessionPreferences.getHelloMessage().getDocument()); @@ -130,7 +133,7 @@ public class NetconfClientSessionNegotiator extends } } - return Long.valueOf(textContent); + return Long.parseLong(textContent); } private static String getSessionIdWithXPath(final Document doc, final XPathExpression sessionIdXPath) { diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java index 82e72045d4..26f33152da 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java @@ -9,6 +9,7 @@ package org.opendaylight.netconf.client; import com.google.common.base.Preconditions; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.concurrent.Promise; @@ -40,6 +41,7 @@ public class SimpleNetconfClientSessionListener implements NetconfClientSessionL private NetconfClientSession clientSession; @GuardedBy("this") + @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED") private void dispatchRequest() { while (!requests.isEmpty()) { final RequestEntry e = requests.peek(); diff --git a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/TcpClientChannelInitializer.java b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/TcpClientChannelInitializer.java index 2cf0e1a5cd..5f25800b4b 100644 --- a/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/TcpClientChannelInitializer.java +++ b/netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/TcpClientChannelInitializer.java @@ -49,7 +49,7 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer { if (future.isSuccess()) { - connectPromise.setSuccess(); + channelPromise.setSuccess(); } }; @@ -58,7 +58,7 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer attributes = allDevices.get(nodeIds); + for (final Map attributes : allDevices.values()) { table.addRow().addContent(attributes.get(NetconfConsoleConstants.NETCONF_ID), attributes.get(NetconfConsoleConstants.NETCONF_IP), attributes.get(NetconfConsoleConstants.NETCONF_PORT), diff --git a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfShowDeviceCommand.java b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfShowDeviceCommand.java index a6e76350a0..8ab84d7257 100644 --- a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfShowDeviceCommand.java +++ b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfShowDeviceCommand.java @@ -12,6 +12,7 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import javax.annotation.Nonnull; import org.apache.karaf.shell.commands.Command; import org.apache.karaf.shell.commands.Option; @@ -75,7 +76,7 @@ public class NetconfShowDeviceCommand extends AbstractAction { } if (!NetconfCommandUtils.isIpValid(deviceIp) - || (devicePort != null && !NetconfCommandUtils.isPortValid(devicePort))) { + || devicePort != null && !NetconfCommandUtils.isPortValid(devicePort)) { return "Invalid IP:" + deviceIp + " or Port:" + devicePort + "Please enter a valid entry to proceed."; } @@ -93,8 +94,9 @@ public class NetconfShowDeviceCommand extends AbstractAction { table.column(NetconfConsoleConstants.STATUS).alignLeft(); table.column(NetconfConsoleConstants.AVAILABLE_CAPABILITIES).alignLeft(); - for (final String nodeId : devices.keySet()) { - final Map> device = devices.get(nodeId); + for (final Entry>> entry : devices.entrySet()) { + final String nodeId = entry.getKey(); + final Map> device = entry.getValue(); table.addRow().addContent(nodeId, device.get(NetconfConsoleConstants.NETCONF_IP).get(NetconfConsoleConstants.DEFAULT_INDEX), device.get(NetconfConsoleConstants.NETCONF_PORT).get(NetconfConsoleConstants.DEFAULT_INDEX), diff --git a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/impl/NetconfCommandsImpl.java b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/impl/NetconfCommandsImpl.java index 9a9fa6e1ee..8954e4a294 100644 --- a/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/impl/NetconfCommandsImpl.java +++ b/netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/impl/NetconfCommandsImpl.java @@ -17,6 +17,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; @@ -73,7 +74,8 @@ public class NetconfCommandsImpl implements NetconfCommands { attributes.put(NetconfConsoleConstants.NETCONF_IP, netconfNode.getHost().getIpAddress().getIpv4Address().getValue()); attributes.put(NetconfConsoleConstants.NETCONF_PORT, netconfNode.getPort().getValue().toString()); - attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name().toLowerCase()); + attributes.put(NetconfConsoleConstants.STATUS, netconfNode.getConnectionStatus().name() + .toLowerCase(Locale.ROOT)); netconfNodes.put(node.getNodeId().getValue(), attributes); } return netconfNodes; diff --git a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiator.java b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiator.java index b3e263a92b..e32d5c7e45 100644 --- a/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiator.java +++ b/netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiator.java @@ -9,6 +9,7 @@ package org.opendaylight.netconf.impl; import com.google.common.base.Optional; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.Channel; import io.netty.channel.local.LocalAddress; import io.netty.util.Timer; @@ -52,6 +53,7 @@ public class NetconfServerSessionNegotiator } @Override + @SuppressFBWarnings("BC_UNCONFIRMED_CAST_OF_RETURN_VALUE") protected NetconfServerSession getSession( NetconfServerSessionListener sessionListener, Channel channel, NetconfHelloMessage message) { diff --git a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/MessageParserTest.java b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/MessageParserTest.java index 10ef3cd597..0b07c774f2 100644 --- a/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/MessageParserTest.java +++ b/netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/MessageParserTest.java @@ -62,18 +62,19 @@ public class MessageParserTest { int msgLength = out.readableBytes(); int chunkCount = msgLength / ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE; - if ((msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE) != 0) { + if (msgLength % ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE != 0) { chunkCount++; } + + byte[] endOfChunkBytes = NetconfMessageConstants.END_OF_CHUNK.getBytes(StandardCharsets.UTF_8); for (int i = 1; i <= chunkCount; i++) { ByteBuf recievedOutbound = (ByteBuf) messages.poll(); int exptHeaderLength = ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE; if (i == chunkCount) { - exptHeaderLength = msgLength - (ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1)); - byte[] eom = new byte[NetconfMessageConstants.END_OF_CHUNK.length]; - recievedOutbound - .getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_CHUNK.length, eom); - assertArrayEquals(NetconfMessageConstants.END_OF_CHUNK, eom); + exptHeaderLength = msgLength - ChunkedFramingMechanismEncoder.DEFAULT_CHUNK_SIZE * (i - 1); + byte[] eom = new byte[endOfChunkBytes.length]; + recievedOutbound.getBytes(recievedOutbound.readableBytes() - endOfChunkBytes.length, eom); + assertArrayEquals(endOfChunkBytes, eom); } byte[] header = new byte[String.valueOf(exptHeaderLength).length() @@ -99,10 +100,10 @@ public class MessageParserTest { testChunkChannel.writeOutbound(this.msg); ByteBuf recievedOutbound = (ByteBuf) testChunkChannel.readOutbound(); - byte[] eom = new byte[NetconfMessageConstants.END_OF_MESSAGE.length]; - recievedOutbound.getBytes(recievedOutbound.readableBytes() - NetconfMessageConstants.END_OF_MESSAGE.length, - eom); - assertArrayEquals(NetconfMessageConstants.END_OF_MESSAGE, eom); + byte[] endOfMsgBytes = NetconfMessageConstants.END_OF_MESSAGE.getBytes(StandardCharsets.UTF_8); + byte[] eom = new byte[endOfMsgBytes.length]; + recievedOutbound.getBytes(recievedOutbound.readableBytes() - endOfMsgBytes.length, eom); + assertArrayEquals(endOfMsgBytes, eom); testChunkChannel.writeInbound(recievedOutbound); NetconfMessage receivedMessage = (NetconfMessage) testChunkChannel.readInbound(); diff --git a/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSchema.java b/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSchema.java index 57ce954dce..3778824945 100644 --- a/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSchema.java +++ b/netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSchema.java @@ -30,7 +30,7 @@ final class MonitoringSchema { @XmlElement(name = "namespace") public String getNamespace() { - return schema.getNamespace().getValue().toString(); + return schema.getNamespace().getValue(); } @XmlElement(name = "location") diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java index 1d7a3cd5ad..f2592e4230 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java @@ -13,7 +13,6 @@ import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.MessageToByteEncoder; import java.nio.charset.StandardCharsets; -import org.opendaylight.netconf.util.messages.NetconfMessageConstants; public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder { public static final int DEFAULT_CHUNK_SIZE = 8192; @@ -41,13 +40,13 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, ByteBuf out) { out.writeBytes(msg); - out.writeBytes(NetconfMessageConstants.END_OF_MESSAGE); + out.writeBytes(MessageParts.END_OF_MESSAGE); } } diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java new file mode 100644 index 0000000000..3db8ca6af0 --- /dev/null +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java @@ -0,0 +1,23 @@ +/* + * Copyright (c) 2018 Inocybe Technologies 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.nettyutil.handler; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import org.opendaylight.netconf.util.messages.NetconfMessageConstants; + +/** + * netconf message part constants as bytes. + * + * @author Thomas Pantelis + */ +interface MessageParts { + byte[] END_OF_MESSAGE = NetconfMessageConstants.END_OF_MESSAGE.getBytes(UTF_8); + byte[] START_OF_CHUNK = NetconfMessageConstants.START_OF_CHUNK.getBytes(UTF_8); + byte[] END_OF_CHUNK = NetconfMessageConstants.END_OF_CHUNK.getBytes(UTF_8); +} diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEOMAggregator.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEOMAggregator.java index 6c0f5a1f6e..9c441404d8 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEOMAggregator.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEOMAggregator.java @@ -11,11 +11,10 @@ package org.opendaylight.netconf.nettyutil.handler; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.handler.codec.DelimiterBasedFrameDecoder; -import org.opendaylight.netconf.util.messages.NetconfMessageConstants; public class NetconfEOMAggregator extends DelimiterBasedFrameDecoder { - public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(NetconfMessageConstants.END_OF_MESSAGE); + public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(MessageParts.END_OF_MESSAGE); public NetconfEOMAggregator() { super(Integer.MAX_VALUE, DELIMITER); diff --git a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java index c3ff349662..2d080ef3fc 100644 --- a/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java +++ b/netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java @@ -119,9 +119,10 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { session = future.getSession(); final AuthFuture authenticateFuture = authenticationHandler.authenticate(session); + final ClientSession localSession = session; authenticateFuture.addListener(future1 -> { if (future1.isSuccess()) { - handleSshAuthenticated(session, ctx); + handleSshAuthenticated(localSession, ctx); } else { // Exception does not have to be set in the future, add simple exception in such case final Throwable exception = future1.getException() == null @@ -164,8 +165,9 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { // TODO we should also read from error stream and at least log from that + ClientChannel localChannel = channel; sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()), - msg -> ctx.fireChannelRead(msg), channel.toString(), channel.getAsyncOut()); + msg -> ctx.fireChannelRead(msg), localChannel.toString(), localChannel.getAsyncOut()); // if readAsyncListener receives immediate close, // it will close this handler and closing this handler sets channel variable to null @@ -198,10 +200,9 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { this.connectPromise = promise; if (negotiationFuture != null) { - negotiationFutureListener = future -> { if (future.isSuccess()) { - connectPromise.setSuccess(); + promise.setSuccess(); } }; //complete connection promise with netconf negotiation future @@ -249,10 +250,12 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter { if (session != null && !session.isClosed() && !session.isClosing()) { session.close(false).addListener(future -> { - if (!future.isClosed()) { - session.close(true); + synchronized (this) { + if (!future.isClosed()) { + session.close(true); + } + session = null; } - session = null; }); } diff --git a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java index 748e55c47a..b00de8ad5f 100644 --- a/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java +++ b/netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java @@ -13,7 +13,6 @@ import static org.junit.Assert.assertEquals; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.junit.Test; -import org.opendaylight.netconf.util.messages.NetconfMessageConstants; public class EOMFramingMechanismEncoderTest { @@ -24,6 +23,6 @@ public class EOMFramingMechanismEncoderTest { final ByteBuf destination = Unpooled.buffer(); new EOMFramingMechanismEncoder().encode(null, source, destination); - assertEquals(Unpooled.wrappedBuffer(source.array(), NetconfMessageConstants.END_OF_MESSAGE), destination); + assertEquals(Unpooled.wrappedBuffer(source.array(), MessageParts.END_OF_MESSAGE), destination); } -} \ No newline at end of file +} diff --git a/netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotification.java b/netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotification.java index 3e7f562434..87de89a5db 100644 --- a/netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotification.java +++ b/netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotification.java @@ -9,6 +9,7 @@ package org.opendaylight.netconf.notifications; import com.google.common.base.Preconditions; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.text.ParsePosition; import java.time.Instant; import java.time.LocalDateTime; @@ -179,6 +180,7 @@ public final class NetconfNotification extends NetconfMessage { /** * Create new notification with provided timestamp. */ + @SuppressFBWarnings("EI_EXPOSE_REP2") // stores a reference to an externally mutable Date object public NetconfNotification(final Document notificationContent, final Date eventTime) { super(wrapNotification(notificationContent, eventTime)); this.eventTime = eventTime; @@ -189,6 +191,7 @@ public final class NetconfNotification extends NetconfMessage { * * @return notification event time */ + @SuppressFBWarnings("EI_EXPOSE_REP") public Date getEventTime() { return eventTime; } diff --git a/netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtil.java b/netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtil.java index f45192c3b8..a657e34a1c 100644 --- a/netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtil.java +++ b/netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtil.java @@ -10,7 +10,6 @@ package org.opendaylight.netconf.notifications.impl.ops; import com.google.common.base.Optional; import com.google.common.base.Preconditions; -import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Iterables; import java.io.IOException; @@ -69,12 +68,7 @@ public final class NotificationsTransformUtil { private static RpcDefinition findCreateSubscriptionRpc() { return Iterables.getFirst(Collections2.filter(NOTIFICATIONS_SCHEMA_CTX.getOperations(), - new Predicate() { - @Override - public boolean apply(final RpcDefinition input) { - return input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION); - } - }), null); + input -> input.getQName().getLocalName().equals(CreateSubscription.CREATE_SUBSCRIPTION)), null); } /** diff --git a/netconf/netconf-parent/pom.xml b/netconf/netconf-parent/pom.xml index ab876da3b9..acb0b824a9 100644 --- a/netconf/netconf-parent/pom.xml +++ b/netconf/netconf-parent/pom.xml @@ -55,7 +55,6 @@ checkstyle.violationSeverity=error - 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 2a198383a6..e8ec506026 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 @@ -8,10 +8,10 @@ package org.opendaylight.netconf.ssh; -import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; +import java.nio.charset.StandardCharsets; import org.apache.sshd.common.io.IoInputStream; import org.apache.sshd.common.io.IoOutputStream; import org.apache.sshd.server.ExitCallback; @@ -52,27 +52,21 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { writeAdditionalHeader(ctx); asyncSshHandlerWriter = new AsyncSshHandlerWriter(out); - asyncSshHandlerReader = new AsyncSshHandlerReader(new AutoCloseable() { - @Override - public void close() throws Exception { - // Close both sessions (delegate server and remote client) - ctx.fireChannelInactive(); - ctx.disconnect(); - ctx.close(); - asyncSshHandlerReader.close(); - asyncSshHandlerWriter.close(); - } - }, new AsyncSshHandlerReader.ReadMsgHandler() { - @Override - public void onMessageRead(final ByteBuf msg) { - if (LOG.isTraceEnabled()) { - LOG.trace("Forwarding message for client: {} on channel: {}, message: {}", - netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), - AsyncSshHandlerWriter.byteBufToString(msg)); - } - // Just forward to delegate - ctx.writeAndFlush(msg); + asyncSshHandlerReader = new AsyncSshHandlerReader(() -> { + // Close both sessions (delegate server and remote client) + ctx.fireChannelInactive(); + ctx.disconnect(); + ctx.close(); + asyncSshHandlerReader.close(); + asyncSshHandlerWriter.close(); + }, msg -> { + if (LOG.isTraceEnabled()) { + LOG.trace("Forwarding message for client: {} on channel: {}, message: {}", + netconfHelloMessageAdditionalHeader.getAddress(), ctx.channel(), + AsyncSshHandlerWriter.byteBufToString(msg)); } + // Just forward to delegate + ctx.writeAndFlush(msg); }, "ssh" + netconfHelloMessageAdditionalHeader.getAddress(), in); @@ -80,7 +74,8 @@ final class SshProxyClientHandler extends ChannelInboundHandlerAdapter { } private void writeAdditionalHeader(final ChannelHandlerContext ctx) { - ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString().getBytes())); + ctx.writeAndFlush(Unpooled.copiedBuffer(netconfHelloMessageAdditionalHeader.toFormattedString() + .getBytes(StandardCharsets.UTF_8))); } @Override 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 406a28aee4..f638a2bfbf 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 @@ -12,9 +12,7 @@ import com.google.common.collect.ImmutableList; import io.netty.channel.EventLoopGroup; import java.io.IOException; import java.nio.channels.AsynchronousChannelGroup; -import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; @@ -84,15 +82,6 @@ public class SshProxyServer implements AutoCloseable { sshServer.start(); } - private static Map getProperties(final SshProxyServerConfiguration sshProxyServerConfiguration) { - final Map ret = new HashMap<>(); - ret.put(ServerFactoryManager.IDLE_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout())); - // TODO make auth timeout configurable on its own - ret.put(ServerFactoryManager.AUTH_TIMEOUT, String.valueOf(sshProxyServerConfiguration.getIdleTimeout())); - - return ret; - } - @Override public void close() throws IOException { try { diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyContext.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyContext.java index 62508a2c3b..0ac355d6dc 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyContext.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyContext.java @@ -18,6 +18,7 @@ import akka.util.Timeout; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; +import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nonnull; import org.opendaylight.controller.md.sal.dom.api.DOMMountPointService; import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService; @@ -47,7 +48,7 @@ class NetconfTopologyContext implements ClusterSingletonService { private NetconfNodeManager netconfNodeManager; private ActorRef masterActorRef; private boolean finalClose = false; - private boolean closed = false; + private final AtomicBoolean closed = new AtomicBoolean(false); private boolean isMaster; NetconfTopologyContext(final NetconfTopologySetup netconfTopologyDeviceSetup, @@ -164,8 +165,8 @@ class NetconfTopologyContext implements ClusterSingletonService { } } - private synchronized void stopDeviceConnectorAndActor() { - if (closed) { + private void stopDeviceConnectorAndActor() { + if (!closed.compareAndSet(false, true)) { return; } if (remoteDeviceConnector != null) { @@ -176,6 +177,5 @@ class NetconfTopologyContext implements ClusterSingletonService { netconfTopologyDeviceSetup.getActorSystem().stop(masterActorRef); masterActorRef = null; } - closed = true; } } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImpl.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImpl.java index fd1d84168c..40511bf781 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImpl.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImpl.java @@ -153,11 +153,11 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector { NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node, final ActorRef deviceContextActorRef) { //setup default values since default value is not supported in mdsal - final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null + final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? NetconfTopologyUtils.DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis(); - final Long keepaliveDelay = node.getKeepaliveDelay() == null + final long keepaliveDelay = node.getKeepaliveDelay() == null ? NetconfTopologyUtils.DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay(); - final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null + final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? NetconfTopologyUtils.DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema(); RemoteDeviceHandler salFacade = new MasterSalFacade(remoteDeviceId, @@ -352,11 +352,8 @@ public class RemoteDeviceConnectorImpl implements RemoteDeviceConnector { @Override public ReconnectStrategy createReconnectStrategy() { - final Long maxSleep = null; - final Long deadline = null; - return new TimedReconnectStrategy(executor, minSleep, - minSleep, sleepFactor, maxSleep, connectionAttempts, deadline); + minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/); } } } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java index 89547421c7..3a3fad9ce4 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java @@ -259,7 +259,7 @@ public final class NetconfNodeActor extends UntypedActor { Futures.addCallback(remoteSchemaContext, new FutureCallback() { @Override - public void onSuccess(final SchemaContext result) { + public void onSuccess(@Nonnull final SchemaContext result) { LOG.info("{}: Schema context resolved: {}", id, result.getModules()); slaveSalManager.registerSlaveMountPoint(result, deviceRpcService, masterReference); } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java index 3d881e65de..6b79f62125 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java @@ -56,7 +56,7 @@ class ReadAdapter { Futures.addCallback(read, new FutureCallback>>() { @Override - public void onSuccess(final Optional> result) { + public void onSuccess(@Nonnull final Optional> result) { if (!result.isPresent()) { sender.tell(new EmptyReadResponse(), self); return; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/CreateInitialMasterActorData.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/CreateInitialMasterActorData.java index 45fd4df0f6..b9ce540fd6 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/CreateInitialMasterActorData.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/CreateInitialMasterActorData.java @@ -8,7 +8,6 @@ package org.opendaylight.netconf.topology.singleton.messages; -import java.io.Serializable; import java.util.List; import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker; import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; @@ -17,9 +16,7 @@ import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier; /** * Master sends this message to the own actor to set necessary parameters. */ -public class CreateInitialMasterActorData implements Serializable { - private static final long serialVersionUID = 1L; - +public class CreateInitialMasterActorData { private final DOMDataBroker deviceDataBroker; private final List allSourceIdentifiers; private final DOMRpcService deviceRpc; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSetupMasterActorData.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSetupMasterActorData.java index 2f6e2e2506..47befecaad 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSetupMasterActorData.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSetupMasterActorData.java @@ -8,16 +8,13 @@ package org.opendaylight.netconf.topology.singleton.messages; -import java.io.Serializable; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup; /** * Master sends this message to the own actor to refresh setup data. */ -public class RefreshSetupMasterActorData implements Serializable { - private static final long serialVersionUID = 1L; - +public class RefreshSetupMasterActorData { private final NetconfTopologySetup netconfTopologyDeviceSetup; private final RemoteDeviceId remoteDeviceId; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSlaveActor.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSlaveActor.java index 47023f219f..95798f66ac 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSlaveActor.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSlaveActor.java @@ -9,13 +9,12 @@ package org.opendaylight.netconf.topology.singleton.messages; import akka.util.Timeout; -import java.io.Serializable; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.netconf.topology.singleton.impl.utils.NetconfTopologySetup; import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository; import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry; -public class RefreshSlaveActor implements Serializable { +public class RefreshSlaveActor { private final SchemaRepository schemaRepository; private final RemoteDeviceId id; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/SchemaPathMessage.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/SchemaPathMessage.java index 319b375340..a34697885e 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/SchemaPathMessage.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/SchemaPathMessage.java @@ -9,6 +9,7 @@ package org.opendaylight.netconf.topology.singleton.messages; import com.google.common.collect.Iterables; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; @@ -20,7 +21,8 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath; public class SchemaPathMessage implements Serializable { private static final long serialVersionUID = 1L; - private SchemaPath schemaPath; + @SuppressFBWarnings("SE_BAD_FIELD") + private final SchemaPath schemaPath; public SchemaPathMessage(final SchemaPath schemaPath) { this.schemaPath = schemaPath; @@ -39,7 +41,8 @@ public class SchemaPathMessage implements Serializable { private SchemaPathMessage schemaPathMessage; - Proxy() { + @SuppressWarnings("checkstyle:RedundantModifier") + public Proxy() { //due to Externalizable } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessage.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessage.java index 9a0e5c35e5..d540e23f8d 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessage.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessage.java @@ -50,7 +50,8 @@ public class InvokeRpcMessage implements Serializable { private InvokeRpcMessage invokeRpcMessage; - Proxy() { + @SuppressWarnings("checkstyle:RedundantModifier") + public Proxy() { //due to Externalizable } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessageReply.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessageReply.java index ba658ba92f..b70582354c 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessageReply.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessageReply.java @@ -8,6 +8,7 @@ package org.opendaylight.netconf.topology.singleton.messages.rpc; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; @@ -21,6 +22,7 @@ import org.opendaylight.yangtools.yang.common.RpcError; public class InvokeRpcMessageReply implements Serializable { private static final long serialVersionUID = 1L; + @SuppressFBWarnings("SE_BAD_FIELD") private final Collection rpcErrors; private final NormalizedNodeMessage normalizedNodeMessage; @@ -47,7 +49,8 @@ public class InvokeRpcMessageReply implements Serializable { private InvokeRpcMessageReply invokeRpcMessageReply; - Proxy() { + @SuppressWarnings("checkstyle:RedundantModifier") + public Proxy() { //due to Externalizable } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionReply.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionReply.java index a787a9f469..f2fcd0c55b 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionReply.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionReply.java @@ -12,6 +12,7 @@ import akka.actor.ActorRef; import java.io.Serializable; public class NewReadTransactionReply implements Serializable { + private static final long serialVersionUID = 1L; private final ActorRef txActor; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionRequest.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionRequest.java index 0c6bb3b8c2..c1490f2f85 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionRequest.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionRequest.java @@ -11,5 +11,6 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions; import java.io.Serializable; public class NewReadTransactionRequest implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java index 141ecccdd3..08e293059e 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java @@ -12,6 +12,7 @@ import akka.actor.ActorRef; import java.io.Serializable; public class NewReadWriteTransactionReply implements Serializable { + private static final long serialVersionUID = 1L; private final ActorRef txActor; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionReply.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionReply.java index 8e356a8162..8d5e8181fc 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionReply.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionReply.java @@ -12,6 +12,7 @@ import akka.actor.ActorRef; import java.io.Serializable; public class NewWriteTransactionReply implements Serializable { + private static final long serialVersionUID = 1L; private final ActorRef txActor; diff --git a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionRequest.java b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionRequest.java index 8b7e914f3c..34184be483 100644 --- a/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionRequest.java +++ b/netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionRequest.java @@ -11,5 +11,6 @@ package org.opendaylight.netconf.topology.singleton.messages.transactions; import java.io.Serializable; public class NewWriteTransactionRequest implements Serializable { + private static final long serialVersionUID = 1L; } diff --git a/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java b/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java index 9bc6b59e7e..e3a8419533 100644 --- a/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java +++ b/netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java @@ -278,11 +278,11 @@ public abstract class AbstractNetconfTopology implements NetconfTopology { protected NetconfConnectorDTO createDeviceCommunicator(final NodeId nodeId, final NetconfNode node) { //setup default values since default value is not supported in mdsal - final Long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null + final long defaultRequestTimeoutMillis = node.getDefaultRequestTimeoutMillis() == null ? DEFAULT_REQUEST_TIMEOUT_MILLIS : node.getDefaultRequestTimeoutMillis(); - final Long keepaliveDelay = node.getKeepaliveDelay() == null + final long keepaliveDelay = node.getKeepaliveDelay() == null ? DEFAULT_KEEPALIVE_DELAY : node.getKeepaliveDelay(); - final Boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null + final boolean reconnectOnChangedSchema = node.isReconnectOnChangedSchema() == null ? DEFAULT_RECONNECT_ON_CHANGED_SCHEMA : node.isReconnectOnChangedSchema(); final IpAddress ipAddress = node.getHost().getIpAddress(); @@ -579,11 +579,8 @@ public abstract class AbstractNetconfTopology implements NetconfTopology { @Override public ReconnectStrategy createReconnectStrategy() { - final Long maxSleep = null; - final Long deadline = null; - return new TimedReconnectStrategy(executor, minSleep, - minSleep, sleepFactor, maxSleep, connectionAttempts, deadline); + minSleep, sleepFactor, null /*maxSleep*/, connectionAttempts, null /*deadline*/); } } diff --git a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageConstants.java b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageConstants.java index 4117918d53..df5b4bc8d3 100644 --- a/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageConstants.java +++ b/netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageConstants.java @@ -8,27 +8,22 @@ package org.opendaylight.netconf.util.messages; -import static java.nio.charset.StandardCharsets.UTF_8; - -public final class NetconfMessageConstants { - - private NetconfMessageConstants(){} +public interface NetconfMessageConstants { /** * The NETCONF 1.0 old-style message separator. This is framing mechanism * is used by default. */ - public static final byte[] END_OF_MESSAGE = "]]>]]>".getBytes(UTF_8); + String END_OF_MESSAGE = "]]>]]>"; // bytes - public static final int MIN_HEADER_LENGTH = 4; + int MIN_HEADER_LENGTH = 4; // bytes - public static final int MAX_HEADER_LENGTH = 13; - - public static final byte[] START_OF_CHUNK = "\n#".getBytes(UTF_8); - public static final byte[] END_OF_CHUNK = "\n##\n".getBytes(UTF_8); + int MAX_HEADER_LENGTH = 13; + String START_OF_CHUNK = "\n#"; + String END_OF_CHUNK = "\n##\n"; } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java index 68fb36018b..9e62919cf6 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java @@ -24,16 +24,22 @@ import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; +import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.AbstractMap; import java.util.Collections; +import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.stream.XMLStreamException; import javax.xml.transform.dom.DOMSource; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; import org.opendaylight.mdsal.binding.generator.impl.ModuleInfoBackedContext; @@ -67,6 +73,7 @@ import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; +import org.xml.sax.SAXException; /** * Holds URLs with YANG schema resources for all yang modules reported in @@ -130,7 +137,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas { if (connection instanceof HttpURLConnection) { connection.setRequestProperty("Accept", "application/xml"); final String userpass = username + ":" + password; - final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes()); + final String basicAuth = "Basic " + printBase64Binary(userpass.getBytes(StandardCharsets.UTF_8)); connection.setRequestProperty("Authorization", basicAuth); } @@ -291,7 +298,7 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas { String extension = ""; final int i = fileName.lastIndexOf(46); if (i != -1) { - extension = fileName.substring(i).toLowerCase(); + extension = fileName.substring(i).toLowerCase(Locale.ROOT); } return extension.equals(".json"); @@ -302,14 +309,13 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas { final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder); final JsonParserStream jsonParser = JsonParserStream.create(writer, LIBRARY_CONTEXT); - final JsonReader reader = new JsonReader(new InputStreamReader(in)); + final JsonReader reader = new JsonReader(new InputStreamReader(in, Charset.defaultCharset())); jsonParser.parse(reader); return resultHolder.isFinished() ? Optional.of(resultHolder.getResult()) : Optional.empty(); } - @SuppressWarnings("checkstyle:IllegalCatch") private static Optional> readXml(final InputStream in) { try { final DocumentBuilder docBuilder = UntrustedXML.newDocumentBuilder(); @@ -338,7 +344,8 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas { xmlParser.traverse(new DOMSource(doc.getDocumentElement())); final NormalizedNode parsed = resultHolder.getResult(); return Optional.of(parsed); - } catch (final Exception e) { + } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException + | SAXException e) { LOG.warn("Unable to parse yang library xml content", e); } @@ -394,9 +401,8 @@ public final class LibraryModulesSchemas implements NetconfDeviceSchemas { private static Optional getValueOfSimpleNode( final NormalizedNode node) { - final Object value = node.getValue(); - return value == null || Strings.isNullOrEmpty(value.toString()) ? Optional.empty() - : Optional.of(value.toString().trim()); + final String valueStr = node.getValue().toString(); + return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim()); } @Override diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java index 2dc1633172..9efd1dfaba 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java @@ -29,6 +29,7 @@ import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.stream.Collectors; +import javax.annotation.Nonnull; import javax.annotation.concurrent.GuardedBy; import org.opendaylight.controller.md.sal.dom.api.DOMNotification; import org.opendaylight.controller.md.sal.dom.api.DOMRpcException; @@ -149,7 +150,7 @@ public class NetconfDevice final FutureCallback resolvedSourceCallback = new FutureCallback() { @Override - public void onSuccess(final DeviceSources result) { + public void onSuccess(@Nonnull final DeviceSources result) { addProvidedSourcesToSchemaRegistry(result); setUpSchema(result); } @@ -250,7 +251,7 @@ public class NetconfDevice updateTransformer(null); } - private void updateTransformer(final MessageTransformer transformer) { + private synchronized void updateTransformer(final MessageTransformer transformer) { messageTransformer = transformer; } @@ -511,7 +512,7 @@ public class NetconfDevice if (cause instanceof MissingSchemaSourceException) { requiredSources = handleMissingSchemaSourceException( - requiredSources, (MissingSchemaSourceException) e.getCause()); + requiredSources, (MissingSchemaSourceException) cause); continue; } if (cause instanceof SchemaResolutionException) { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java index 6ce2d0f145..822a43a22a 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java @@ -256,9 +256,8 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas { private static Optional getValueOfSimpleNode( final NormalizedNode node) { - final Object value = node.getValue(); - return value == null || Strings.isNullOrEmpty(value.toString()) - ? Optional.empty() : Optional.of(value.toString().trim()); + final String valueStr = node.getValue().toString(); + return Strings.isNullOrEmpty(valueStr) ? Optional.empty() : Optional.of(valueStr.trim()); } @Override diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java index d8eace1fc9..8b67f56db2 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java @@ -275,7 +275,7 @@ public class NetconfDeviceCommunicator try { request = requests.peek(); if (request != null && request.future.isUncancellable()) { - requests.poll(); + request = requests.poll(); // we have just removed one request from the queue // we can also release one permit if (semaphore != null) { @@ -343,18 +343,15 @@ public class NetconfDeviceCommunicator @Override public ListenableFuture> sendRequest(final NetconfMessage message, final QName rpc) { sessionLock.lock(); - - if (semaphore != null && !semaphore.tryAcquire()) { - LOG.warn("Limit of concurrent rpc messages was reached (limit :" - + concurentRpcMsgs + "). Rpc reply message is needed. Discarding request of Netconf device with id" - + id.getName()); - sessionLock.unlock(); - return Futures.immediateFailedFuture(new NetconfDocumentedException( - "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs - + ") waiting for emptying the queue of Netconf device with id" + id.getName())); - } - try { + if (semaphore != null && !semaphore.tryAcquire()) { + LOG.warn("Limit of concurrent rpc messages was reached (limit :" + concurentRpcMsgs + + "). Rpc reply message is needed. Discarding request of Netconf device with id" + id.getName()); + return Futures.immediateFailedFuture(new NetconfDocumentedException( + "Limit of rpc messages was reached (Limit :" + concurentRpcMsgs + + ") waiting for emptying the queue of Netconf device with id" + id.getName())); + } + return sendRequestWithLock(message, rpc); } finally { sessionLock.unlock(); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java index 8f010e7780..77b7d1c142 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java @@ -10,17 +10,15 @@ package org.opendaylight.netconf.sal.connect.netconf.listener; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.AbstractFuture; import javax.annotation.Nullable; -import javax.annotation.concurrent.GuardedBy; final class UncancellableFuture extends AbstractFuture { - @GuardedBy("this") - private boolean uncancellable = false; + private volatile boolean uncancellable = false; UncancellableFuture(final boolean uncancellable) { this.uncancellable = uncancellable; } - public synchronized boolean setUncancellable() { + public boolean setUncancellable() { if (isCancelled()) { return false; } @@ -29,17 +27,17 @@ final class UncancellableFuture extends AbstractFuture { return true; } - public synchronized boolean isUncancellable() { + public boolean isUncancellable() { return uncancellable; } @Override - public synchronized boolean cancel(final boolean mayInterruptIfRunning) { + public boolean cancel(final boolean mayInterruptIfRunning) { return !uncancellable && super.cancel(mayInterruptIfRunning); } @Override - public synchronized boolean set(@Nullable final V value) { + public boolean set(@Nullable final V value) { Preconditions.checkState(uncancellable); return super.set(value); } diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java index a92ad42c70..590e5e4cda 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java @@ -211,11 +211,11 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler() { - @Nullable - @Override - public DOMRpcException apply(@Nullable final Exception exception) { - return new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type); - } - }); + return Futures.makeChecked(transformed, exception -> + new DOMRpcImplementationNotAvailableException(exception, "Unable to invoke rpc %s", type)); } @Nonnull diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java index 8fbf058850..9e247018e1 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java @@ -248,11 +248,6 @@ public final class NetconfDeviceTopologyAdapter implements AutoCloseable { }, MoreExecutors.directExecutor()); } - private static Node getNodeWithId(final RemoteDeviceId id) { - final NodeBuilder builder = getNodeIdBuilder(id); - return builder.build(); - } - private static NodeBuilder getNodeIdBuilder(final RemoteDeviceId id) { final NodeBuilder nodeBuilder = new NodeBuilder(); nodeBuilder.setKey(new NodeKey(new NodeId(id.getName()))); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java index 8e5c4de458..5f31400bec 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java @@ -18,7 +18,7 @@ import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -import javax.annotation.Nullable; +import javax.annotation.Nonnull; import org.opendaylight.controller.config.util.xml.DocumentedException; import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType; import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; @@ -48,7 +48,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { protected final List> resultsFutures; private final List listeners = new CopyOnWriteArrayList<>(); // Allow commit to be called only once - protected boolean finished = false; + protected volatile boolean finished = false; public AbstractWriteTx(final NetconfBaseOps netOps, final RemoteDeviceId id, final boolean rollbackSupport) { this.netOps = netOps; @@ -153,13 +153,13 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { final ListenableFuture> result = performCommit(); Futures.addCallback(result, new FutureCallback>() { @Override - public void onSuccess(@Nullable final RpcResult result) { - if (result != null && result.isSuccessful()) { + public void onSuccess(@Nonnull final RpcResult rpcResult) { + if (rpcResult.isSuccessful()) { listeners.forEach(txListener -> txListener.onTransactionSuccessful(AbstractWriteTx.this)); } else { final TransactionCommitFailedException cause = new TransactionCommitFailedException("Transaction failed", - result.getErrors().toArray(new RpcError[result.getErrors().size()])); + rpcResult.getErrors().toArray(new RpcError[rpcResult.getErrors().size()])); listeners.forEach(listener -> listener.onTransactionFailed(AbstractWriteTx.this, cause)); } } @@ -189,7 +189,7 @@ public abstract class AbstractWriteTx implements DOMDataWriteTransaction { Futures.addCallback(Futures.allAsList(resultsFutures), new FutureCallback>() { @Override - public void onSuccess(final List domRpcResults) { + public void onSuccess(@Nonnull final List domRpcResults) { domRpcResults.forEach(domRpcResult -> { if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) { final NetconfDocumentedException exception = diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java index 23803f5751..f0bd3949f0 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java @@ -16,6 +16,7 @@ import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; @@ -68,7 +69,7 @@ public class WriteCandidateTx extends AbstractWriteTx { private void lock() { final FutureCallback lockCandidateCallback = new FutureCallback() { @Override - public void onSuccess(final DOMRpcResult result) { + public void onSuccess(@Nonnull final DOMRpcResult result) { if (isSuccess(result)) { if (LOG.isTraceEnabled()) { LOG.trace("Lock candidate successful"); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java index 068fc10a51..0ba6cead95 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java @@ -22,6 +22,7 @@ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; +import javax.annotation.Nonnull; import javax.xml.transform.dom.DOMSource; import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult; import org.opendaylight.controller.md.sal.dom.api.DOMRpcService; @@ -144,7 +145,7 @@ public final class NetconfRemoteSchemaYangSourceProvider implements SchemaSource } @Override - public YangTextSchemaSource apply(final DOMRpcResult input) { + public YangTextSchemaSource apply(@Nonnull final DOMRpcResult input) { if (input.getErrors().isEmpty()) { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java index d7d4948e4c..4fa5127c6e 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java @@ -15,6 +15,7 @@ import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.nio.charset.Charset; import java.util.Map; import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId; import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException; @@ -51,7 +52,7 @@ public final class YangLibrarySchemaYangSourceProvider implements SchemaSourcePr private ListenableFuture download(final SourceIdentifier sourceIdentifier) { final URL url = availableSources.get(sourceIdentifier); try (InputStream in = url.openStream()) { - final String schemaContent = new String(ByteStreams.toByteArray(in)); + final String schemaContent = new String(ByteStreams.toByteArray(in), Charset.defaultCharset()); final NetconfRemoteSchemaYangSourceProvider.NetconfYangTextSchemaSource yangSource = new NetconfRemoteSchemaYangSourceProvider .NetconfYangTextSchemaSource(id, sourceIdentifier, Optional.of(schemaContent)); diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java index 8428a48df6..e146131d9b 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java @@ -16,11 +16,13 @@ import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import java.io.IOException; +import java.net.URISyntaxException; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.Map; import javax.annotation.Nonnull; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.stream.XMLStreamException; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; @@ -54,6 +56,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; +import org.xml.sax.SAXException; public class NetconfMessageTransformer implements MessageTransformer { @@ -82,7 +85,6 @@ public class NetconfMessageTransformer implements MessageTransformer stripped = NetconfMessageTransformUtil.stripNotification(message); @@ -113,7 +115,8 @@ public class NetconfMessageTransformer implements MessageTransformer normalizedNode; @@ -193,7 +195,8 @@ public class NetconfMessageTransformer implements MessageTransformer { } @Override - public void onSuccess(final DOMRpcResult result) { + public void onSuccess(@Nonnull final DOMRpcResult result) { if (result.getErrors().isEmpty()) { LOG.trace("{}: {} invoked successfully", id, type); } else { diff --git a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java index 28c69e72ab..98d3d30f91 100644 --- a/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java +++ b/netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java @@ -13,7 +13,9 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; import java.util.Collections; import java.util.List; +import java.util.Locale; import java.util.Map; +import java.util.Map.Entry; import javax.xml.transform.dom.DOMSource; import org.opendaylight.controller.config.util.xml.DocumentedException; import org.opendaylight.controller.config.util.xml.XmlElement; @@ -156,7 +158,8 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer { final YangInstanceIdentifier.NodeIdentifierWithPredicates keyedId = (YangInstanceIdentifier.NodeIdentifierWithPredicates) lastPathArgument; final Map keyValues = keyedId.getKeyValues(); - for (QName qualifiedName : keyValues.keySet()) { + for (Entry entry : keyValues.entrySet()) { + QName qualifiedName = entry.getKey(); final List key = dataElement.getChildElementsWithinNamespace(qualifiedName.getLocalName(), qualifiedName.getNamespace().toString()); @@ -172,7 +175,7 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer { } catch (DocumentedException e) { throw new IllegalStateException("Key value not present in key element", e); } - if (!keyValues.get(qualifiedName).equals(textContent)) { + if (!entry.getValue().equals(textContent)) { throw new IllegalStateException("Key value in path not equal to key value in xml"); } } @@ -225,7 +228,7 @@ class SchemalessRpcStructureTransformer implements RpcStructureTransformer { } private static String toOperationString(final ModifyAction operation) { - return operation.name().toLowerCase(); + return operation.name().toLowerCase(Locale.ROOT); } private static Element getSourceElement(final DOMSource source) { diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/DummyMonitoringService.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/DummyMonitoringService.java index 5ece664e17..e5b30838be 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/DummyMonitoringService.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/DummyMonitoringService.java @@ -16,6 +16,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Collections; import java.util.Set; +import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.opendaylight.controller.config.util.capability.Capability; import org.opendaylight.netconf.api.monitoring.NetconfManagementSession; @@ -39,18 +40,13 @@ import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.netconf.mon public class DummyMonitoringService implements NetconfMonitoringService { private static final Sessions EMPTY_SESSIONS = new SessionsBuilder().setSession(Collections.emptyList()).build(); - private static final Function CAPABILITY_URI_FUNCTION = new Function() { - @Nullable - @Override - public Uri apply(Capability capability) { - return new Uri(capability.getCapabilityUri()); - } - }; + private static final Function CAPABILITY_URI_FUNCTION = + capability -> new Uri(capability.getCapabilityUri()); private static final Function CAPABILITY_SCHEMA_FUNCTION = new Function() { @Nullable @Override - public Schema apply(@Nullable Capability capability) { + public Schema apply(@Nonnull Capability capability) { return new SchemaBuilder() .setIdentifier(capability.getModuleName().get()) .setNamespace(new Uri(capability.getModuleNamespace().get())) diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Execution.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Execution.java index e55f2de636..d4e6683278 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Execution.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Execution.java @@ -13,7 +13,6 @@ import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.HttpResponseStatus; -import com.ning.http.client.ListenableFuture; import com.ning.http.client.Realm; import com.ning.http.client.Request; import com.ning.http.client.Response; @@ -112,7 +111,6 @@ public class Execution implements Callable { } private void invokeAsync() { - final ArrayList> futures = new ArrayList<>(); LOG.info("Begin sending async requests"); for (final Request request : payloads) { @@ -121,7 +119,7 @@ public class Execution implements Callable { } catch (InterruptedException e) { LOG.warn("Semaphore acquire interrupted"); } - futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler() { + asyncHttpClient.executeRequest(request, new AsyncCompletionHandler() { @Override public STATE onStatusReceived(HttpResponseStatus status) throws Exception { super.onStatusReceived(status); @@ -143,7 +141,7 @@ public class Execution implements Callable { semaphore.release(); return response; } - })); + }); } LOG.info("Requests sent, waiting for responses"); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java index 6ec885d44c..cff30f51bb 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java @@ -17,6 +17,7 @@ import com.google.common.collect.Lists; import com.google.common.io.ByteStreams; import com.google.common.io.CharStreams; import com.google.common.io.Files; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.FileWriter; import java.io.IOException; @@ -42,6 +43,7 @@ import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressFBWarnings("DM_DEFAULT_ENCODING") public final class Main { private static final Logger LOG = LoggerFactory.getLogger(Main.class); @@ -50,6 +52,7 @@ public final class Main { } @SuppressWarnings("checkstyle:IllegalCatch") + @SuppressFBWarnings({"UW_UNCOND_WAIT", "WA_NOT_IN_LOOP"}) public static void main(final String[] args) { final TesttoolParameters params = TesttoolParameters.parseArgs(args, TesttoolParameters.getParser()); params.validate(); @@ -84,7 +87,7 @@ public final class Main { } else { try { future.get(); - } catch (final ExecutionException e) { + } catch (final ExecutionException | InterruptedException e) { LOG.info("{}. thread failed.", threadNum, e); } } @@ -102,7 +105,7 @@ public final class Main { configGenerator.updateFeatureFile(generated); configGenerator.changeLoadOrder(); } - } catch (final Exception e) { + } catch (RuntimeException | InterruptedException e) { LOG.error("Unhandled exception", e); netconfDeviceSimulator.close(); System.exit(1); @@ -150,9 +153,12 @@ public final class Main { Preconditions.checkState(configDir.mkdirs(), "Unable to create directory " + configDir); } - for (final File file : configDir.listFiles(pathname -> - !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX))) { - Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file); + final File[] files = configDir.listFiles(pathname -> + !pathname.isDirectory() && pathname.getName().startsWith(SIM_DEVICE_CFG_PREFIX)); + if (files != null) { + for (final File file : files) { + Preconditions.checkState(file.delete(), "Unable to clean previous generated file %s", file); + } } try (InputStream stream = Main.class.getResourceAsStream(NETCONF_CONNECTOR_XML)) { @@ -183,7 +189,7 @@ public final class Main { String configContent = String.format( middleBlueprint, name, address, String.valueOf(openDevice), String.valueOf(!useSsh)); configContent = String.format( - "%s%s%d%s\n%s\n", configContent, "", + "%s%s%d%s%n%s%n", configContent, "", generateConfigsTimeout, "", ""); builder.append(configContent); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java index 42b162b2de..5472825edb 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java @@ -15,6 +15,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ThreadFactoryBuilder; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.local.LocalAddress; @@ -75,6 +76,7 @@ import org.opendaylight.yangtools.yang.parser.rfc7950.repo.TextToASTTransformer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressFBWarnings("DM_DEFAULT_ENCODING") public class NetconfDeviceSimulator implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(NetconfDeviceSimulator.class); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/ScaleUtil.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/ScaleUtil.java index 78f5b85434..c8929e5132 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/ScaleUtil.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/ScaleUtil.java @@ -15,6 +15,7 @@ import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig.Builder; import com.ning.http.client.Request; import com.ning.http.client.Response; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.BufferedReader; import java.io.File; import java.io.IOException; @@ -30,13 +31,12 @@ import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; -import net.sourceforge.argparse4j.inf.ArgumentParser; -import net.sourceforge.argparse4j.inf.ArgumentParserException; import org.opendaylight.netconf.test.tool.config.Configuration; import org.opendaylight.netconf.test.tool.config.ConfigurationBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"}) public final class ScaleUtil { private static final ScheduledExecutorService EXECUTOR = new LoggingWrapperExecutor(4); private static final Semaphore SEMAPHORE = new Semaphore(0); @@ -73,16 +73,20 @@ public final class ScaleUtil { root.error("Failed to start any simulated devices, exiting..."); System.exit(1); } - if (params.distroFolder != null) { - final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator( - params.distroFolder, openDevices); - final List generated = configGenerator.generate( - params.ssh, params.generateConfigBatchSize, - params.generateConfigsTimeout, params.generateConfigsAddress, - params.devicesPerPort); - configGenerator.updateFeatureFile(generated); - configGenerator.changeLoadOrder(); + + if (params.distroFolder == null) { + root.error("Distro folder is not set, exiting..."); + System.exit(1); } + + final Main.ConfigGenerator configGenerator = new Main.ConfigGenerator( + params.distroFolder, openDevices); + final List generated = configGenerator.generate( + params.ssh, params.generateConfigBatchSize, + params.generateConfigsTimeout, params.generateConfigsAddress, + params.devicesPerPort); + configGenerator.updateFeatureFile(generated); + configGenerator.changeLoadOrder(); } catch (final Exception e) { root.error("Unhandled exception", e); netconfDeviceSimulator.close(); @@ -181,24 +185,15 @@ public final class ScaleUtil { if (f.isDirectory()) { deleteFolder(f); } else { - f.delete(); + if (!f.delete()) { + root.warn("Failed to delete {}", f); + } } } } - folder.delete(); - } - - private static TesttoolParameters parseArgs(final String[] args, final ArgumentParser parser) { - final TesttoolParameters parameters = new TesttoolParameters(); - try { - parser.parseArgs(args, parameters); - return parameters; - } catch (ArgumentParserException e) { - parser.handleError(e); + if (!folder.delete()) { + root.warn("Failed to delete {}", folder); } - - System.exit(1); - return null; } private static class ScaleVerifyCallable implements Callable { @@ -287,8 +282,8 @@ public final class ScaleUtil { return new LogOnExceptionCallable(callable); } - private class LogOnExceptionCallable implements Callable { - private Callable theCallable; + private static class LogOnExceptionCallable implements Callable { + private final Callable theCallable; LogOnExceptionCallable(Callable theCallable) { this.theCallable = theCallable; diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java index dde89e478c..6310eab644 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java @@ -13,6 +13,7 @@ import static com.google.common.base.Preconditions.checkArgument; import com.google.common.base.Preconditions; import com.google.common.io.CharStreams; import com.google.common.io.Files; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; @@ -23,6 +24,7 @@ import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.StringJoiner; @@ -34,6 +36,7 @@ import net.sourceforge.argparse4j.annotation.Arg; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; +@SuppressFBWarnings({"DM_EXIT", "DM_DEFAULT_ENCODING"}) public class TesttoolParameters { private static final String HOST_KEY = "{HOST}"; @@ -303,13 +306,12 @@ public class TesttoolParameters { checkArgument(schemasDir.isDirectory(), "Schemas dir has to be a directory"); checkArgument(schemasDir.canRead(), "Schemas dir has to be readable"); - final List files = Arrays.asList(schemasDir.listFiles()); + final File[] filesArray = schemasDir.listFiles(); + final List files = filesArray != null ? Arrays.asList(filesArray) : Collections.emptyList(); for (final File file : files) { final Matcher matcher = YANG_FILENAME_PATTERN.matcher(file.getName()); if (!matcher.matches()) { - final BufferedReader reader; - try { - reader = new BufferedReader(new FileReader(file)); + try (BufferedReader reader = new BufferedReader(new FileReader(file))) { String line = reader.readLine(); while (!DATE_PATTERN.matcher(line).find()) { line = reader.readLine(); @@ -324,7 +326,9 @@ public class TesttoolParameters { final String revision = m.group(1); final String correctName = moduleName + "@" + revision + ".yang"; final File correctNameFile = new File(correctName); - file.renameTo(correctNameFile); + if (!file.renameTo(correctNameFile)) { + System.err.println("Failed to rename " + file); + } } } catch (final IOException e) { // print error to console (test tool is running from console) @@ -361,8 +365,8 @@ public class TesttoolParameters { final int batchedRequests = openDevices.size() / generateConfigBatchSize; final int batchedRequestsPerThread = batchedRequests / threadAmount; - final int leftoverBatchedRequests = (batchedRequests) % threadAmount; - final int leftoverRequests = openDevices.size() - (batchedRequests * generateConfigBatchSize); + final int leftoverBatchedRequests = batchedRequests % threadAmount; + final int leftoverRequests = openDevices.size() - batchedRequests * generateConfigBatchSize; final StringBuilder destBuilder = new StringBuilder(DEST); destBuilder.replace(destBuilder.indexOf(ADDRESS_PORT), @@ -370,16 +374,16 @@ public class TesttoolParameters { controllerDestination); for (int l = 0; l < threadAmount; l++) { - from = l * (batchedRequests * batchedRequestsPerThread); - to = from + (batchedRequests * batchedRequestsPerThread); + from = l * batchedRequests * batchedRequestsPerThread; + to = from + batchedRequests * batchedRequestsPerThread; iterator = openDevices.subList(from, to).iterator(); allThreadsPayloads.add(createBatchedPayloads(batchedRequestsPerThread, iterator, editContentString, destBuilder.toString())); } ArrayList payloads = null; if (leftoverBatchedRequests > 0) { - from = threadAmount * (batchedRequests * batchedRequestsPerThread); - to = from + (batchedRequests * batchedRequestsPerThread); + from = threadAmount * batchedRequests * batchedRequestsPerThread; + to = from + batchedRequests * batchedRequestsPerThread; iterator = openDevices.subList(from, to).iterator(); payloads = createBatchedPayloads(leftoverBatchedRequests, iterator, editContentString, destBuilder.toString()); @@ -413,7 +417,7 @@ public class TesttoolParameters { } if (leftoverRequests > 0) { - from = (threadAmount) * requestPerThreads; + from = threadAmount * requestPerThreads; to = from + leftoverRequests; iterator = openDevices.subList(from, to).iterator(); allThreadsPayloads.add(createPayloads(iterator, editContentString)); @@ -464,13 +468,13 @@ public class TesttoolParameters { final ArrayList payloads = new ArrayList<>(); for (int i = 0; i < batchedRequestsCount; i++) { - String payload = ""; + StringBuilder payload = new StringBuilder(); for (int j = 0; j < generateConfigBatchSize; j++) { final StringBuilder payloadBuilder = new StringBuilder( prepareMessage(openDevices.next(), editContentString)); - payload += modifyMessage(payloadBuilder, j, generateConfigBatchSize); + payload.append(modifyMessage(payloadBuilder, j, generateConfigBatchSize)); } - payloads.add(new Execution.DestToPayload(destination, payload)); + payloads.add(new Execution.DestToPayload(destination, payload.toString())); } return payloads; } diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/AsyncExecutionStrategy.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/AsyncExecutionStrategy.java index 180dad7d12..98d38dd475 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/AsyncExecutionStrategy.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/AsyncExecutionStrategy.java @@ -11,7 +11,6 @@ package org.opendaylight.netconf.test.tool.client.http.perf; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.HttpResponseStatus; -import com.ning.http.client.ListenableFuture; import com.ning.http.client.Request; import com.ning.http.client.Response; import java.util.ArrayList; @@ -39,7 +38,6 @@ public class AsyncExecutionStrategy implements ExecutionStrategy { @Override public void invoke() { - final ArrayList> futures = new ArrayList<>(); LOG.info("Begin sending async requests"); for (final Request request : payloads) { @@ -48,7 +46,7 @@ public class AsyncExecutionStrategy implements ExecutionStrategy { } catch (InterruptedException e) { LOG.warn("Semaphore acquire interrupted"); } - futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler() { + asyncHttpClient.executeRequest(request, new AsyncCompletionHandler() { @Override public STATE onStatusReceived(HttpResponseStatus status) throws Exception { super.onStatusReceived(status); @@ -64,7 +62,7 @@ public class AsyncExecutionStrategy implements ExecutionStrategy { semaphore.release(); return response; } - })); + }); } LOG.info("Requests sent, waiting for responses"); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java index 334556704b..94eff3d25d 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java @@ -10,6 +10,7 @@ package org.opendaylight.netconf.test.tool.client.http.perf; import com.google.common.base.Stopwatch; import com.google.common.io.Files; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; @@ -25,6 +26,7 @@ import org.opendaylight.netconf.test.tool.TestToolUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +@SuppressFBWarnings("DM_EXIT") public final class RestPerfClient { private static final Logger LOG = LoggerFactory.getLogger(RestPerfClient.class); @@ -188,7 +190,7 @@ public final class RestPerfClient { // and do not log it if (allThreadsCompleted) { LOG.info( - "Requests per second: {}", (parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); + "Requests per second: {}", parameters.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)); } System.exit(0); } diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java index 90728207b0..4af92b7018 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java @@ -11,6 +11,7 @@ package org.opendaylight.netconf.test.tool.client.stress; import ch.qos.logback.classic.Level; import com.google.common.base.Stopwatch; import com.google.common.io.Files; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.util.HashedWheelTimer; import io.netty.util.Timer; @@ -44,6 +45,7 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; +@SuppressFBWarnings("DM_EXIT") public final class StressClient { private static final Logger LOG = LoggerFactory.getLogger(StressClient.class); @@ -183,7 +185,7 @@ public final class StressClient { started.stop(); LOG.info("FINISHED. Execution time: {}", started); - LOG.info("Requests per second: {}", (params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS))); + LOG.info("Requests per second: {}", params.editCount * 1000.0 / started.elapsed(TimeUnit.MILLISECONDS)); // Cleanup timer.stop(); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java index a1faa44950..3b6722f76f 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java @@ -125,7 +125,7 @@ class RpcMapping { } } - if (e1Children.isEmpty() && e1Children.isEmpty()) { + if (e1Children.isEmpty() && e2Children.isEmpty()) { try { return e1.getTextContent().equals(e2.getTextContent()); } catch (final DocumentedException e) { diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java index f139a9000d..f7b942125e 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java @@ -11,7 +11,6 @@ package org.opendaylight.netconf.test.tool.rpc; import com.google.common.base.Optional; import java.io.File; import java.io.IOException; -import java.util.Collections; import java.util.List; import org.opendaylight.controller.config.util.xml.DocumentedException; import org.opendaylight.controller.config.util.xml.XmlElement; @@ -46,11 +45,10 @@ public class SimulatedGetConfig extends AbstractConfigNetconfOperation { private static DataList loadInitialConfigXMLFile(final File file) { LOG.info("Loading initial config xml file: {}", file.getName()); DataList configData = new DataList(); - List xmlElementList = Collections.emptyList(); try { Element element = XmlUtil.readXmlToElement(file); XmlElement xmlElement = XmlElement.fromDomElement(element); - xmlElementList = xmlElement.getChildElements(); + List xmlElementList = xmlElement.getChildElements(); configData.setConfigList(xmlElementList); } catch (IOException e) { LOG.info("IO exception loading xml file: {} ", e.getMessage()); diff --git a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/scale/util/ScaleUtilParameters.java b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/scale/util/ScaleUtilParameters.java index 1cc85ae216..cd8d546082 100644 --- a/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/scale/util/ScaleUtilParameters.java +++ b/netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/scale/util/ScaleUtilParameters.java @@ -8,12 +8,14 @@ package org.opendaylight.netconf.test.tool.scale.util; +import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import net.sourceforge.argparse4j.ArgumentParsers; import net.sourceforge.argparse4j.annotation.Arg; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.ArgumentParserException; +@SuppressFBWarnings("DM_EXIT") public class ScaleUtilParameters { @Arg(dest = "distro-folder") diff --git a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java index ba7e22a025..a89233727e 100644 --- a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java +++ b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java @@ -41,9 +41,6 @@ import org.opendaylight.yangtools.yang.model.repo.spi.SchemaListenerRegistration import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceListener; import org.opendaylight.yangtools.yang.model.repo.util.FilesystemSchemaSourceCache; import org.opendaylight.yangtools.yang.parser.repo.SharedSchemaRepository; -import org.osgi.framework.BundleContext; -import org.osgi.framework.FrameworkUtil; -import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -192,10 +189,4 @@ public class YangLibProvider implements AutoCloseable, SchemaSourceListener { return sourceIdentifier.getRevision().map(rev -> new OptionalRevision(new RevisionIdentifier(rev.toString()))) .orElse(NO_REVISION); } - - private T getObjectFromBundleContext(final Class type, final String serviceRefName) { - final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext(); - final ServiceReference serviceReference = bundleContext.getServiceReference(serviceRefName); - return (T) bundleContext.getService(serviceReference); - } } diff --git a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java index e75776f84b..7b942dd007 100644 --- a/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java +++ b/netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java @@ -12,6 +12,7 @@ import com.google.common.base.Preconditions; import com.google.common.io.ByteStreams; import com.google.common.util.concurrent.ListenableFuture; import java.io.IOException; +import java.nio.charset.Charset; import java.util.concurrent.ExecutionException; import org.opendaylight.yanglib.api.YangLibService; import org.opendaylight.yangtools.yang.common.Revision; @@ -51,7 +52,7 @@ public class YangLibServiceImpl implements YangLibService { try { final YangTextSchemaSource source = sourceFuture.get(); - return new String(ByteStreams.toByteArray(source.openStream())); + return new String(ByteStreams.toByteArray(source.openStream()), Charset.defaultCharset()); } catch (InterruptedException | ExecutionException | IOException e) { throw new IllegalStateException("Unable to get schema " + sourceId, e); } -- 2.36.6