Fix findbugs violations in netconf 02/70202/2
authorTom Pantelis <tompantelis@gmail.com>
Thu, 29 Mar 2018 23:29:44 +0000 (19:29 -0400)
committerTom Pantelis <tompantelis@gmail.com>
Fri, 30 Mar 2018 01:26:35 +0000 (21:26 -0400)
- 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 <tompantelis@gmail.com>
78 files changed:
netconf/callhome-protocol/src/main/java/org/opendaylight/netconf/callhome/protocol/AuthorizedKeysDecoder.java
netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/BaseCallHomeTopology.java
netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/CallHomeAuthProviderImpl.java
netconf/callhome-provider/src/main/java/org/opendaylight/netconf/callhome/mount/Configuration.java
netconf/mdsal-netconf-connector/src/main/java/org/opendaylight/netconf/mdsal/connector/ops/RuntimeRpc.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSource.java
netconf/messagebus-netconf/src/main/java/org/opendaylight/netconf/messagebus/eventsources/netconf/NetconfEventSourceManager.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/NetconfDocumentedException.java
netconf/netconf-api/src/main/java/org/opendaylight/netconf/api/util/NetconfConstants.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientDispatcherImpl.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/NetconfClientSessionNegotiator.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/SimpleNetconfClientSessionListener.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/TcpClientChannelInitializer.java
netconf/netconf-client/src/main/java/org/opendaylight/netconf/client/conf/NetconfClientConfiguration.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfListDevicesCommand.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/commands/NetconfShowDeviceCommand.java
netconf/netconf-console/src/main/java/org/opendaylight/netconf/console/impl/NetconfCommandsImpl.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerSessionNegotiator.java
netconf/netconf-impl/src/test/java/org/opendaylight/netconf/impl/MessageParserTest.java
netconf/netconf-monitoring/src/main/java/org/opendaylight/netconf/monitoring/xml/model/MonitoringSchema.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ChunkedFramingMechanismEncoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/EOMFramingMechanismEncoder.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/MessageParts.java [new file with mode: 0644]
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEOMAggregator.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java
netconf/netconf-netty-util/src/test/java/org/opendaylight/netconf/nettyutil/handler/EOMFramingMechanismEncoderTest.java
netconf/netconf-notifications-api/src/main/java/org/opendaylight/netconf/notifications/NetconfNotification.java
netconf/netconf-notifications-impl/src/main/java/org/opendaylight/netconf/notifications/impl/ops/NotificationsTransformUtil.java
netconf/netconf-parent/pom.xml
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyClientHandler.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/SshProxyServer.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyContext.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/RemoteDeviceConnectorImpl.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/NetconfNodeActor.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/actors/ReadAdapter.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/CreateInitialMasterActorData.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSetupMasterActorData.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/RefreshSlaveActor.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/SchemaPathMessage.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessage.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/rpc/InvokeRpcMessageReply.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionReply.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadTransactionRequest.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewReadWriteTransactionReply.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionReply.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/messages/transactions/NewWriteTransactionRequest.java
netconf/netconf-topology/src/main/java/org/opendaylight/netconf/topology/AbstractNetconfTopology.java
netconf/netconf-util/src/main/java/org/opendaylight/netconf/util/messages/NetconfMessageConstants.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/LibraryModulesSchemas.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfDevice.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/NetconfStateSchemas.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/NetconfDeviceCommunicator.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/listener/UncancellableFuture.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/KeepaliveSalFacade.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceRpc.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/NetconfDeviceTopologyAdapter.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/AbstractWriteTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/sal/tx/WriteCandidateTx.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/NetconfRemoteSchemaYangSourceProvider.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/YangLibrarySchemaYangSourceProvider.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfBaseOps.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/NetconfRpcFutureCallback.java
netconf/sal-netconf-connector/src/main/java/org/opendaylight/netconf/sal/connect/netconf/util/SchemalessRpcStructureTransformer.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/DummyMonitoringService.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Execution.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/Main.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/NetconfDeviceSimulator.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/ScaleUtil.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/TesttoolParameters.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/AsyncExecutionStrategy.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/http/perf/RestPerfClient.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/client/stress/StressClient.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/customrpc/RpcMapping.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/rpc/SimulatedGetConfig.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/scale/util/ScaleUtilParameters.java
netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibProvider.java
netconf/yanglib/src/main/java/org/opendaylight/yanglib/impl/YangLibServiceImpl.java

index e544195fd8045c32bcc8ffb6d008e45b9fbc6584..7e07568a632e39042c3983686cf48d08ee59defb 100644 (file)
@@ -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());
     }
 }
index 0fcfb82fc79e8268e37228fc2ff3a6fb6bab17d2..d4f9e132b8ed0429de94999b077db6dde98fab7c 100644 (file)
@@ -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;
     }
 }
index 29632c247f1f4caf420b94009db530aab6b7d864..15445eb7460a39943163d5c5c1cae1b776acf607 100644 (file)
@@ -126,7 +126,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider,
         return remoteAddress.toString();
     }
 
-    private class DeviceConfig implements DataTreeChangeListener<Device> {
+    private static class DeviceConfig implements DataTreeChangeListener<Device> {
 
         private final AuthorizedKeysDecoder keyDecoder = new AuthorizedKeysDecoder();
 
@@ -189,7 +189,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider,
         }
     }
 
-    private class DeviceOp implements DataTreeChangeListener<Device> {
+    private static class DeviceOp implements DataTreeChangeListener<Device> {
 
         private final ConcurrentMap<String, Device> byPublicKey = new ConcurrentHashMap<>();
 
@@ -242,7 +242,7 @@ public class CallHomeAuthProviderImpl implements CallHomeAuthorizationProvider,
         }
     }
 
-    private class GlobalConfig implements DataTreeChangeListener<Global> {
+    private static class GlobalConfig implements DataTreeChangeListener<Global> {
 
         private volatile Global current = null;
 
index 713b7ec4a5837c7dcf1f038f3cf78bc0a41eb90e..14ab22a7f66af1978e4a0cf5a209de0fb9b843ae 100644 (file)
@@ -69,16 +69,13 @@ public class Configuration {
         }
     }
 
-    private final String path;
     private Properties properties;
 
     public Configuration() {
-        path = "<no-path>";
         properties = new Properties();
     }
 
     public Configuration(final String path) throws ConfigurationException {
-        this.path = path;
         try {
             this.properties = readFromPath(path);
         } catch (IOException ioe) {
index 6d4ba4305ae99a1799d5e8ed90f768e76f44172a..d61c249cfd2df18181cba3d8fe01ba3d89a2d98b 100644 (file)
@@ -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;
         }
 
index 26609d21e31196c1291d72e516b6847727ecc28e..a8959888a0d49542566ed8fb492f603e93c1e17a 100644 (file)
@@ -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<String, Stream> availableStreams = getAvailableStreams();
         LOG.debug("Stream configuration compare...");
-        for (String urnPrefix : this.urnPrefixToStreamMap.keySet()) {
-            final String streamName = this.urnPrefixToStreamMap.get(urnPrefix);
+        for (Entry<String, String> 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");
index 91df5f781218707acccf96c1f1319d06627af033..6360136b9fd3f401cf1b6c2e2f0b558ebb8f705a 100644 (file)
@@ -114,22 +114,6 @@ public final class NetconfEventSourceManager implements DataTreeChangeListener<N
         }
     }
 
-    private void nodeUpdated(final InstanceIdentifier<?> 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());
index 8e289fa9e82dc243df9346da319b756ebbff9b83..2adb4984b8a61e32d9ad024352b205460d1d3d56 100644 (file)
@@ -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());
index 3abeeea40c4e0a68f00ebd29e8f8d6ccf3533353..0c7856f84c8a8c3e6e8fc03568876335e80b187b 100644 (file)
@@ -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<String> CONFIG_SERVICE_MARKERS = Sets.newHashSet(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
+    public static final Set<String> CONFIG_SERVICE_MARKERS = ImmutableSet.of(SERVICE_NAME, CONFIG_NETCONF_CONNECTOR,
             NETCONF_MONITORING, NETCONF_NOTIFICATION);
 
     private NetconfConstants() {
index d0dc480299b97192a7a5495daf2e3fed344525c6..780ce7ff59f4103810ba99462b89dbd1ff9f1e30 100644 (file)
@@ -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<NetconfClientSession, NetconfClientSessionListener>
-        implements NetconfClientDispatcher, Closeable {
+        implements NetconfClientDispatcher {
 
     private static final Logger LOG = LoggerFactory.getLogger(NetconfClientDispatcherImpl.class);
 
index 608450225f52d84d71cff3d1443b739905edaa5d..19091f6d60a93c3f7f064ef68adf8cfbd9aff7a1 100644 (file)
@@ -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) {
index 82e72045d44d258f770100980056d5e6e34e4eb8..26f33152dac04473d3c065f1dcab9694ffae8ca2 100644 (file)
@@ -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();
index 2cf0e1a5cd32e04aaabf297a695e786946f8723b..5f25800b4b0c595137485c78fc0bc095c1114e82 100644 (file)
@@ -49,7 +49,7 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer<NetconfClie
 
                 negotiationFutureListener = future -> {
                     if (future.isSuccess()) {
-                        connectPromise.setSuccess();
+                        channelPromise.setSuccess();
                     }
                 };
 
@@ -58,7 +58,7 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer<NetconfClie
                         //complete connection promise with netconf negotiation future
                         negotiationFuture.addListener(negotiationFutureListener);
                     } else {
-                        connectPromise.setFailure(future.cause());
+                        channelPromise.setFailure(future.cause());
                     }
                 });
                 ctx.connect(remoteAddress, localAddress, tcpConnectFuture);
@@ -66,6 +66,10 @@ class TcpClientChannelInitializer extends AbstractChannelInitializer<NetconfClie
 
             @Override
             public void disconnect(final ChannelHandlerContext ctx, final ChannelPromise promise) throws Exception {
+                if (connectPromise == null) {
+                    return;
+                }
+
                 // If we have already succeeded and the session was dropped after, we need to fire inactive to notify
                 // reconnect logic
                 if (connectPromise.isSuccess()) {
index b25071156234e1a02b3a174413cfb6766a1893e7..ee41da8a8d165387d4da477d161c2830ac4e4445 100644 (file)
@@ -85,18 +85,17 @@ public class NetconfClientConfiguration {
         return sslHandlerFactory;
     }
 
-    @SuppressWarnings("checkstyle:FallThrough")
     private void validateConfiguration() {
         Preconditions.checkNotNull(clientProtocol, " ");
         switch (clientProtocol) {
             case TLS:
+                validateTlsConfiguration();
+                validateTcpConfiguration();
+                break;
             case SSH:
-                if (clientProtocol == NetconfClientProtocol.SSH) {
-                    validateSshConfiguration();
-                } else {
-                    validateTlsConfiguration();
-                }
-                // Fall through intentional (ssh or tls validation is a superset of tcp validation)
+                validateSshConfiguration();
+                validateTcpConfiguration();
+                break;
             case TCP:
                 validateTcpConfiguration();
                 break;
@@ -141,4 +140,4 @@ public class NetconfClientConfiguration {
     public enum NetconfClientProtocol {
         TCP, SSH, TLS
     }
-}
\ No newline at end of file
+}
index 874dbc3c1b0db4ffcf8c6e59c295408cc3d769da..f34cbed0014489d34572178e41d8c612440bc635 100644 (file)
@@ -40,8 +40,7 @@ public class NetconfListDevicesCommand extends AbstractAction {
         table.column(NetconfConsoleConstants.NETCONF_PORT).alignLeft();
         table.column(NetconfConsoleConstants.STATUS).alignLeft();
 
-        for (final String nodeIds : allDevices.keySet()) {
-            final Map<String, String> attributes = allDevices.get(nodeIds);
+        for (final Map<String, String> attributes : allDevices.values()) {
             table.addRow().addContent(attributes.get(NetconfConsoleConstants.NETCONF_ID),
                     attributes.get(NetconfConsoleConstants.NETCONF_IP),
                     attributes.get(NetconfConsoleConstants.NETCONF_PORT),
index a6e76350a02299f8fbca45789d3ae81e5ead71ad..8ab84d7257168c3bd6818f5a1307b8064d20015b 100644 (file)
@@ -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<String, List<String>> device = devices.get(nodeId);
+        for (final Entry<String, Map<String, List<String>>> entry : devices.entrySet()) {
+            final String nodeId = entry.getKey();
+            final Map<String, List<String>> 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),
index 9a9fa6e1ee09c7bf665027827c2f1144cc2c428a..8954e4a2947cc3c20a10108447e8d617b315fa83 100644 (file)
@@ -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;
index b3e263a92beadc5f17597abc0eb46340556f3ff2..e32d5c7e451be7f4492b95ad499c11e5dc988627 100644 (file)
@@ -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) {
index 10ef3cd59752704e51aeda6f331acdf4e1637ebf..0b07c774f250ef1db726c2a15b20ad016956f28b 100644 (file)
@@ -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();
index 57ce954dcea21a17abb18d3e11bc3c4df0801e71..37788249450e980f660f9d2b5df80b1f55f648cf 100644 (file)
@@ -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")
index 1d7a3cd5adad2b8b0218e91b1970fb999558b69d..f2592e42304fa62bc1fc9bcf6b149a6c7a7d6364 100644 (file)
@@ -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<ByteBuf> {
     public static final int DEFAULT_CHUNK_SIZE = 8192;
@@ -41,13 +40,13 @@ public class ChunkedFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf
         do {
             final int xfer = Math.min(chunkSize, msg.readableBytes());
 
-            out.writeBytes(NetconfMessageConstants.START_OF_CHUNK);
+            out.writeBytes(MessageParts.START_OF_CHUNK);
             out.writeBytes(String.valueOf(xfer).getBytes(StandardCharsets.US_ASCII));
             out.writeByte('\n');
 
             out.writeBytes(msg, xfer);
         } while (msg.isReadable());
 
-        out.writeBytes(NetconfMessageConstants.END_OF_CHUNK);
+        out.writeBytes(MessageParts.END_OF_CHUNK);
     }
 }
index fdb0aae950e225d5622f4433cd5a59dd39df89ef..74009a7301b87b9546ba26793ce89c99bb9b854d 100644 (file)
@@ -11,12 +11,11 @@ package org.opendaylight.netconf.nettyutil.handler;
 import io.netty.buffer.ByteBuf;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.MessageToByteEncoder;
-import org.opendaylight.netconf.util.messages.NetconfMessageConstants;
 
 public class EOMFramingMechanismEncoder extends MessageToByteEncoder<ByteBuf> {
     @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 (file)
index 0000000..3db8ca6
--- /dev/null
@@ -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);
+}
index 6c0f5a1f6e658043e3fb5c7965def379694fdeca..9c441404d82373d69b41ee302a6ea38cb36d2025 100644 (file)
@@ -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);
index c3ff3496625e0f84f154692f49d71b924d67ca15..2d080ef3fca0e4372937b8bcb11c807fd5a1264a 100644 (file)
@@ -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;
             });
         }
 
index 748e55c47afd3992db4e7fc3616532465b599457..b00de8ad5f0b9d8413b4865eb4117238a2d79c2e 100644 (file)
@@ -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
+}
index 3e7f562434770fe89cb0912e2d76b9c1b92c8836..87de89a5dba7f94488b6ebae6fdafd69923aa874 100644 (file)
@@ -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;
     }
index f45192c3b89d3b74d786f0e52537ec8b132eed81..a657e34a1c2d083095becea200a7b271d1a8f7c1 100644 (file)
@@ -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<RpcDefinition>() {
-                @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);
     }
 
     /**
index ab876da3b91db3a8944a63d44ffd63ac7e3a5866..acb0b824a9e4b7a4529d391ca567daaf6699ec11 100644 (file)
@@ -55,7 +55,6 @@
           <propertyExpansion>checkstyle.violationSeverity=error</propertyExpansion>
         </configuration>
       </plugin>
-<!--
       <plugin>
         <groupId>org.codehaus.mojo</groupId>
         <artifactId>findbugs-maven-plugin</artifactId>
@@ -63,7 +62,6 @@
           <failOnError>true</failOnError>
         </configuration>
       </plugin>
--->
     </plugins>
   </build>
 </project>
index 2a198383a693c91b90b6f3faa7462d64772a2ac9..e8ec506026d24d79255e6788671d28e836b87360 100644 (file)
@@ -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
index 406a28aee4722740fdd04364f851832d2d40a522..f638a2bfbf13e35e53adbdc8f2e800ffeb6e308e 100644 (file)
@@ -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<String, String> getProperties(final SshProxyServerConfiguration sshProxyServerConfiguration) {
-        final Map<String, String> 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 {
index 62508a2c3b1d9ec9ccb0155ca147290217252662..0ac355d6dc0e4b53059e953b43d474cbd21b2ac4 100644 (file)
@@ -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;
     }
 }
index fd1d84168c99ab021024bf158fa8dcae24e62176..40511bf781367eeffe2823de3a336a3251fe8f51 100644 (file)
@@ -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<NetconfSessionPreferences> 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*/);
         }
     }
 }
index 89547421c7c50d352ec7f9c4e660709631592f01..3a3fad9ce46a4628a6b8d8b6d717462e02dd2399 100644 (file)
@@ -259,7 +259,7 @@ public final class NetconfNodeActor extends UntypedActor {
 
         Futures.addCallback(remoteSchemaContext, new FutureCallback<SchemaContext>() {
             @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);
             }
index 3d881e65def18fd6ff0a15c21064922e8a2bee45..6b79f621257ad0abcc2a7d19996b41db4ce86325 100644 (file)
@@ -56,7 +56,7 @@ class ReadAdapter {
         Futures.addCallback(read, new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
 
             @Override
-            public void onSuccess(final Optional<NormalizedNode<?, ?>> result) {
+            public void onSuccess(@Nonnull final Optional<NormalizedNode<?, ?>> result) {
                 if (!result.isPresent()) {
                     sender.tell(new EmptyReadResponse(), self);
                     return;
index 45fd4df0f6e66f2e63ba8633a6ec2c7d78af8fd5..b9ce540fd6df321902418a256ffe4d7373e8cd78 100644 (file)
@@ -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<SourceIdentifier> allSourceIdentifiers;
     private final DOMRpcService deviceRpc;
index 2f6e2e250696fb3d44af54c55db094ef28d2c5fb..47befecaad425575634763ee72a848a87347e594 100644 (file)
@@ -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;
 
index 47023f219fd96643c0474ef0d20c00a60e70fcf8..95798f66ac0a883c037e9ce26a3e8ee5b0057dfc 100644 (file)
@@ -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;
index 319b375340262e221b9dc4e0027fbbc88777ec79..a34697885e7d37b1ac3843b1df5c3cc536ce9dd1 100644 (file)
@@ -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
         }
 
index 9a0e5c35e5fe57a32e3765e99f821aadc9e975a0..d540e23f8d6b3dbf066dc5daedcc5c195d1970d4 100644 (file)
@@ -50,7 +50,8 @@ public class InvokeRpcMessage implements Serializable {
 
         private InvokeRpcMessage invokeRpcMessage;
 
-        Proxy() {
+        @SuppressWarnings("checkstyle:RedundantModifier")
+        public Proxy() {
             //due to Externalizable
         }
 
index ba658ba92f83b41db87812160987743a37a4564c..b70582354cc6cd476fd72e93d0303a0211d7babf 100644 (file)
@@ -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<RpcError> 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
         }
 
index 9bc6b59e7e8ccc7788df3144a801c11ee9bfa4a2..e3a84195332f6713962567f1307e7cc4af1a41d4 100644 (file)
@@ -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*/);
         }
     }
 
index 4117918d5322ae79e8cfa9b0e8138c08ddb3ce7e..df5b4bc8d320af34d6444d3352b9a53a357341d0 100644 (file)
@@ -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";
 }
index 68fb36018b7e26cd2a8da7921b0c536b0323efe5..9e62919cf688852953d57c428f2e363d22262c31 100644 (file)
@@ -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<NormalizedNode<?, ?>> 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<String> getValueOfSimpleNode(
             final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> 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
index 2dc16331726e2857897b372bcd55745e3ad36daa..9efd1dfaba5c24d2336bbf1d58d0c7171ce25954 100644 (file)
@@ -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<DeviceSources> resolvedSourceCallback = new FutureCallback<DeviceSources>() {
             @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<NetconfMessage> transformer) {
+    private synchronized void updateTransformer(final MessageTransformer<NetconfMessage> 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) {
index 6ce2d0f145a79ee4de95997792205a6a91ee7e18..822a43a22aace8b4706faf479fb3152193620b3c 100644 (file)
@@ -256,9 +256,8 @@ public final class NetconfStateSchemas implements NetconfDeviceSchemas {
 
         private static Optional<String> getValueOfSimpleNode(
                 final NormalizedNode<? extends YangInstanceIdentifier.PathArgument, ?> 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
index d8eace1fc99c41f0628030281dc593ca72f1ca43..8b67f56db23bdc1bf5bb3cb5d53eec3d8e0f8320 100644 (file)
@@ -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<RpcResult<NetconfMessage>> 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();
index 8f010e778057e7dbd77eed8b0e23e3ad8abfe8fc..77b7d1c142cc3ef4071e9d34a16ed63703700c57 100644 (file)
@@ -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<V> extends AbstractFuture<V> {
-    @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<V> extends AbstractFuture<V> {
         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);
     }
index a92ad42c709044a031e9c65095358a4c16b665fd..590e5e4cdac1944f0d813f5e2cf483243b357340 100644 (file)
@@ -211,11 +211,11 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
             if (result != null && result.getResult() != null) {
                 LOG.debug("{}: Keepalive RPC successful with response: {}", id, result.getResult());
                 scheduleKeepalive();
-            } else if (result != null && result.getErrors() != null) {
+            } else if (result != null && !result.getErrors().isEmpty()) {
                 LOG.warn("{}: Keepalive RPC failed with error: {}", id, result.getErrors());
                 scheduleKeepalive();
             } else {
-                LOG.warn("{} Keepalive RPC returned null with response: {}. Reconnecting netconf session", id, result);
+                LOG.warn("{} Keepalive RPC returned null with response. Reconnecting netconf session", id);
                 reconnect();
             }
         }
@@ -276,7 +276,7 @@ public final class KeepaliveSalFacade implements RemoteDeviceHandler<NetconfSess
     public static final class KeepaliveDOMRpcService implements DOMRpcService {
 
         private final DOMRpcService deviceRpc;
-        private ResetKeepalive resetKeepaliveTask;
+        private final ResetKeepalive resetKeepaliveTask;
         private final long defaultRequestTimeoutMillis;
         private final ScheduledExecutorService executor;
 
index 1b5ae10ec4955b74ecc5660a6ff19deb0cab45ca..897cdaa5c73267039b1438aed9054cb69c37b9d9 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.netconf.sal.connect.netconf.sal;
 
-import com.google.common.base.Function;
 import com.google.common.collect.Collections2;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.Futures;
@@ -68,13 +67,8 @@ public final class NetconfDeviceRpc implements DOMRpcService {
                 }
             }, MoreExecutors.directExecutor());
 
-        return Futures.makeChecked(transformed, new Function<Exception, DOMRpcException>() {
-            @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
index 8fbf058850685e660b9ca639a3355fe0a33ccf30..9e247018e19638d1d169f69a58e648e91b15d9c7 100644 (file)
@@ -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())));
index 8e5c4de458f22a6a6703c9f72db2958fe4cf9dd9..5f31400bec62fdef8adf03d806c3c67635cda0d6 100644 (file)
@@ -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<ListenableFuture<DOMRpcResult>> resultsFutures;
     private final List<TxListener> 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<RpcResult<Void>> result = performCommit();
         Futures.addCallback(result, new FutureCallback<RpcResult<Void>>() {
             @Override
-            public void onSuccess(@Nullable final RpcResult<Void> result) {
-                if (result != null && result.isSuccessful()) {
+            public void onSuccess(@Nonnull final RpcResult<Void> 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<List<DOMRpcResult>>() {
             @Override
-            public void onSuccess(final List<DOMRpcResult> domRpcResults) {
+            public void onSuccess(@Nonnull final List<DOMRpcResult> domRpcResults) {
                 domRpcResults.forEach(domRpcResult -> {
                     if (!domRpcResult.getErrors().isEmpty() && !transformed.isDone()) {
                         final NetconfDocumentedException exception =
index 23803f575129cebf226c0f98f891ef03d695574e..f0bd3949f04831bef59c162155b59daa14b1c400 100644 (file)
@@ -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<DOMRpcResult> lockCandidateCallback = new FutureCallback<DOMRpcResult>() {
             @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");
index 068fc10a5150d0b8065cdc9bf9bcedc89af544a3..0ba6cead958387ab434fd5bd40cbfc03b2cd1411 100644 (file)
@@ -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()) {
 
index d7d4948e4c4efa22b62aeb6ffd54be6588f89f57..4fa5127c6e32f328e08f0d282824443b5986240e 100644 (file)
@@ -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<? extends YangTextSchemaSource> 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));
index 8428a48df63a45d6fb73751b74dffe6f333fa960..e146131d9b0fbd87e4426234e26c6eb942c40149 100644 (file)
@@ -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<NetconfMessage> {
 
@@ -82,7 +85,6 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
         this.strictParsing = strictParsing;
     }
 
-    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public synchronized DOMNotification toNotification(final NetconfMessage message) {
         final Map.Entry<Date, XmlElement> stripped = NetconfMessageTransformUtil.stripNotification(message);
@@ -113,7 +115,8 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
                     notificationAsContainerSchemaNode, strictParsing);
             xmlParser.traverse(new DOMSource(element));
             content = (ContainerNode) resultHolder.getResult();
-        } catch (final Exception e) {
+        } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+                | SAXException | UnsupportedOperationException e) {
             throw new IllegalArgumentException(String.format("Failed to parse notification %s", element), e);
         }
         return new NetconfDeviceNotification(content, stripped.getKey());
@@ -175,7 +178,6 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
                 || rpc.getNamespace().equals(NetconfMessageTransformUtil.CREATE_SUBSCRIPTION_RPC_QNAME.getNamespace());
     }
 
-    @SuppressWarnings("checkstyle:IllegalCatch")
     @Override
     public synchronized DOMRpcResult toRpcResult(final NetconfMessage message, final SchemaPath rpc) {
         final NormalizedNode<?, ?> normalizedNode;
@@ -193,7 +195,8 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
                         strictParsing);
                 xmlParser.traverse(new DOMSource(xmlData));
                 dataNode = (ContainerNode) resultHolder.getResult();
-            } catch (final Exception e) {
+            } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+                    | SAXException e) {
                 throw new IllegalArgumentException(String.format("Failed to parse data response %s", xmlData), e);
             }
 
@@ -232,7 +235,8 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
                             rpcDefinition.getOutput(), strictParsing);
                     xmlParser.traverse(new DOMSource(element));
                     normalizedNode = resultHolder.getResult();
-                } catch (final Exception e) {
+                } catch (XMLStreamException | URISyntaxException | IOException | ParserConfigurationException
+                        | SAXException e) {
                     throw new IllegalArgumentException(String.format("Failed to parse RPC response %s", element), e);
                 }
             }
index 71a60bb18efbe22dfe9269361a105440d19ae626..2c055b9cf18a4349b0b82862d25a4ffe97792b89 100644 (file)
@@ -33,6 +33,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 java.util.Locale;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
 import org.opendaylight.netconf.sal.connect.netconf.sal.KeepaliveSalFacade.KeepaliveDOMRpcService;
@@ -304,7 +305,7 @@ public final class NetconfBaseOps {
 
         // Default operation
         if (defaultOperation.isPresent()) {
-            final String opString = defaultOperation.get().name().toLowerCase();
+            final String opString = defaultOperation.get().name().toLowerCase(Locale.ROOT);
             editBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(toId(NETCONF_DEFAULT_OPERATION_QNAME))
                     .withValue(opString).build());
         }
index e5eaab1d7d92944350067eb6eef3026d489426bc..7e45856e5b7e9d0d0a1b3e8132c98149493bbc1d 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.netconf.sal.connect.netconf.util;
 
 import com.google.common.util.concurrent.FutureCallback;
+import javax.annotation.Nonnull;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.slf4j.Logger;
@@ -29,7 +30,7 @@ public class NetconfRpcFutureCallback implements FutureCallback<DOMRpcResult> {
     }
 
     @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 {
index 28c69e72ab0857d8ef653ec7770c1ca15cb5a83d..98d3d30f91066802cc1ce715caa716ae7da412d3 100644 (file)
@@ -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<QName, Object> keyValues = keyedId.getKeyValues();
-        for (QName qualifiedName : keyValues.keySet()) {
+        for (Entry<QName, Object> entry : keyValues.entrySet()) {
+            QName qualifiedName = entry.getKey();
             final List<XmlElement> 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) {
index 5ece664e179a54113b7824b3bd38327fd491f8e0..e5b30838be6690db8b3776eb6347cd382ba9f6b7 100644 (file)
@@ -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> CAPABILITY_URI_FUNCTION = new Function<Capability, Uri>() {
-        @Nullable
-        @Override
-        public Uri apply(Capability capability) {
-            return new Uri(capability.getCapabilityUri());
-        }
-    };
+    private static final Function<Capability, Uri> CAPABILITY_URI_FUNCTION =
+        capability -> new Uri(capability.getCapabilityUri());
 
     private static final Function<Capability, Schema> CAPABILITY_SCHEMA_FUNCTION = new Function<Capability, Schema>() {
         @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()))
index e55f2de636d679b406ca87de432eb8d7301a8c7c..d4e6683278d10178e5613fe1a81edc273a6c0b1e 100644 (file)
@@ -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<Void> {
     }
 
     private void invokeAsync() {
-        final ArrayList<ListenableFuture<Response>> futures = new ArrayList<>();
         LOG.info("Begin sending async requests");
 
         for (final Request request : payloads) {
@@ -121,7 +119,7 @@ public class Execution implements Callable<Void> {
             } catch (InterruptedException e) {
                 LOG.warn("Semaphore acquire interrupted");
             }
-            futures.add(asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
+            asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
                 @Override
                 public STATE onStatusReceived(HttpResponseStatus status) throws Exception {
                     super.onStatusReceived(status);
@@ -143,7 +141,7 @@ public class Execution implements Callable<Void> {
                     semaphore.release();
                     return response;
                 }
-            }));
+            });
         }
         LOG.info("Requests sent, waiting for responses");
 
index 6ec885d44cb687029c7ac6f8d5fa7d538318b09d..cff30f51bb48348592f004d57315cf1bccf0d743 100644 (file)
@@ -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, "<connection-timeout-millis>",
+                            "%s%s%d%s%n%s%n", configContent, "<connection-timeout-millis>",
                             generateConfigsTimeout, "</connection-timeout-millis>", "</module>");
 
                         builder.append(configContent);
index 42b162b2def8895f543eecc6422ab05cbe1e4e57..5472825edb5d73c1bf7d021a54c765e11c2a229b 100644 (file)
@@ -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);
index 78f5b85434d7833034076069df8599f5e5e95d35..c8929e5132741974efe851d5eeacf2edd7565825 100644 (file)
@@ -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<File> 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<File> 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;
index dde89e478c94064545a7480840103b3a8ff2a8a9..6310eab644e398e7c4e8f85736c3599e561e177f 100644 (file)
@@ -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<File> files = Arrays.asList(schemasDir.listFiles());
+            final File[] filesArray = schemasDir.listFiles();
+            final List<File> 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<Execution.DestToPayload> 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<Execution.DestToPayload> 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;
     }
index 180dad7d120fd42bbc8bc8777f1305a4530ae467..98d38dd475e46d4cafe5f426e301c94d73fe9b82 100644 (file)
@@ -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<ListenableFuture<Response>> 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<Response>() {
+            asyncHttpClient.executeRequest(request, new AsyncCompletionHandler<Response>() {
                 @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");
 
index 334556704b3a946aaebc096bca30c7930d9b3c18..94eff3d25d8e64de4c06bf335651d7622df11ddd 100644 (file)
@@ -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);
     }
index 90728207b05f584864e5bcc167aa0ed7d04028f4..4af92b70181b5465250104dbcef3c0a438e87cd5 100644 (file)
@@ -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();
index a1faa4495069910ee3d0b99a9cf3994a03935033..3b6722f76fb127603c3c85c2a049bca66de819af 100644 (file)
@@ -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) {
index f139a9000d50976943fdc56448377ea8c2cecf9e..f7b942125e532fb2da446e5cf46dd5a2bd0138a7 100644 (file)
@@ -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<XmlElement> xmlElementList = Collections.emptyList();
         try {
             Element element = XmlUtil.readXmlToElement(file);
             XmlElement xmlElement = XmlElement.fromDomElement(element);
-            xmlElementList = xmlElement.getChildElements();
+            List<XmlElement> xmlElementList = xmlElement.getChildElements();
             configData.setConfigList(xmlElementList);
         } catch (IOException e) {
             LOG.info("IO exception loading xml file: {} ", e.getMessage());
index 1cc85ae216af554549e3241f843047a9a3e9253d..cd8d546082b90b3465d1887b3980d3401f0986eb 100644 (file)
@@ -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")
index ba7e22a025bc26bcb5ef251821293bd85f9fdecd..a89233727eef93e82593b0be1ce9cf66bf453ef3 100644 (file)
@@ -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> T getObjectFromBundleContext(final Class<T> type, final String serviceRefName) {
-        final BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
-        final ServiceReference<?> serviceReference = bundleContext.getServiceReference(serviceRefName);
-        return (T) bundleContext.getService(serviceReference);
-    }
 }
index e75776f84b533c6f7baefa94ab5d0b198ffce754..7b942dd0072f38b146772299b20485354584075b 100644 (file)
@@ -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);
         }