Fix findbugs violations in library 36/69036/8
authorTom Pantelis <tompantelis@gmail.com>
Sat, 3 Mar 2018 15:16:49 +0000 (10:16 -0500)
committerTom Pantelis <tompantelis@gmail.com>
Mon, 12 Mar 2018 22:27:18 +0000 (18:27 -0400)
- Possible null pointer dereference
- Equals method should not assume anything about the type of its argument
- Method ignores exceptional return value
- Equals checks for incompatible operand
- Unusual equals method
- Class is Serializable, but doesn't define serialVersionUID
- Consider using Locale parameterized version of invoked method
- Field isn't final but should be
- Incorrect lazy initialization of static field
- Inefficient use of keySet iterator instead of entrySet iterator
- Should be a static inner class
- Boxing/unboxing to parse a primitive
- Unread field
- Return value of method without side effect is ignored
- Write to static field from instance method
- Load of known null value

Change-Id: I5f7ae7b280919d2f1cfcd86be41cab5d8370a752
Signed-off-by: Tom Pantelis <tompantelis@gmail.com>
17 files changed:
.gitignore
hwvtepsouthbound/hwvtepsouthbound-impl/src/test/java/org/opendaylight/ovsdb/hwvtepsouthbound/DataChangeListenerTestBase.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/MonitorHandle.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/impl/OvsdbConnectionService.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/impl/StalePassiveConnectionService.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/jsonrpc/JsonRpcEndpoint.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/notation/Version.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/notation/json/OvsdbMapSerializer.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/notation/json/OvsdbTypesIdResolver.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/operations/Mutate.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/operations/Operations.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/operations/Update.java
library/impl/src/main/java/org/opendaylight/ovsdb/lib/schema/typed/TyperUtils.java
southbound/southbound-impl/src/test/java/org/opendaylight/ovsdb/southbound/ovsdb/transact/OpenVSwitchBridgeAddCommandTest.java
southbound/southbound-impl/src/test/java/org/opendaylight/ovsdb/southbound/ovsdb/transact/OvsdbNodeUpdateCommandTest.java
southbound/southbound-impl/src/test/java/org/opendaylight/ovsdb/southbound/ovsdb/transact/ProtocolUpdateCommandTest.java
southbound/southbound-impl/src/test/java/org/opendaylight/ovsdb/southbound/ovsdb/transact/TerminationPointUpdateCommandTest.java

index a1b8372c17ded28c985c42fcb968fd5aba2d5dac..9bd34714cd08b2fa551a490f4698676faf6dd0fa 100755 (executable)
@@ -27,6 +27,7 @@ target-ide/
 .DS_Store
 .checkstyle
 .factorypath
+.fbExcludeFilterFile
 .tox
 yang-gen-config
 yang-gen-sal
index 90ae8ce3acd0a2f2b906b8ee587de07f37a5af5c..dc5a7a402ade9c7c94d367f62b6a94963ccd2c3b 100644 (file)
@@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.JsonNode;
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
-
 import java.io.IOException;
 import java.io.InputStream;
 import java.lang.reflect.Field;
@@ -30,7 +29,6 @@ import java.net.InetAddress;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.atomic.AtomicBoolean;
-
 import org.apache.commons.lang3.reflect.FieldUtils;
 import org.junit.After;
 import org.junit.Before;
@@ -227,12 +225,20 @@ public class DataChangeListenerTestBase extends AbstractDataBrokerTest {
         doReturn(where).when(delete).where(any());
         Insert insert = mock(Insert.class);
         doReturn(insert).when(insert).withId(any(String.class));
-        Operations.op = PowerMockito.mock(Operations.class);
-        doReturn(insert).when(Operations.op).insert(insertOpCapture.capture());
+        Operations mockOp = PowerMockito.mock(Operations.class);
+        doReturn(insert).when(mockOp).insert(insertOpCapture.capture());
         Update update = mock(Update.class);
-        doReturn(update).when(Operations.op).update(insertOpCapture.capture());
+        doReturn(update).when(mockOp).update(insertOpCapture.capture());
         doReturn(where).when(update).where(any());
-        doReturn(delete).when(Operations.op).delete(any());
+        doReturn(delete).when(mockOp).delete(any());
+
+        Field opField = PowerMockito.field(Operations.class, "op");
+        try {
+            opField.set(Operations.class, mockOp);
+        } catch (IllegalAccessException e) {
+            throw new AssertionError("Set of Operations.op field failed", e);
+        }
+
         ListenableFuture<List<OperationResult>> ft = mock(ListenableFuture.class);
         transactCaptor = ArgumentCaptor.forClass(List.class);
         doReturn(ft).when(ovsdbClient).transact(any(DatabaseSchema.class), transactCaptor.capture());
index b8495fc654452c2a7fa5e435d3aa517a82478081..3b7fb4ebdc983bc0e28e74fcbfb313f491b77fb9 100644 (file)
@@ -11,7 +11,9 @@ package org.opendaylight.ovsdb.lib;
 import java.io.Serializable;
 
 public class MonitorHandle implements Serializable {
-    String id;
+    private static final long serialVersionUID = 1L;
+
+    private final String id;
 
     public MonitorHandle(String id) {
         this.id = id;
index 66bbd150b688a41f58ab08de49b74b954c81a8a9..eb5f1fa7622b5de44007dc6e464ef481ea227802 100644 (file)
@@ -15,6 +15,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.ThreadFactoryBuilder;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.AdaptiveRecvByteBufAllocator;
@@ -38,15 +39,14 @@ import java.net.InetAddress;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import javax.annotation.Nullable;
@@ -84,44 +84,40 @@ import org.slf4j.LoggerFactory;
  * environment. Hence a single instance of the service will be active (via Service Registry in OSGi)
  * and a Singleton object in a non-OSGi environment.
  */
+@SuppressFBWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
 public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
     private static final Logger LOG = LoggerFactory.getLogger(OvsdbConnectionService.class);
-    private static ThreadFactory passiveConnectionThreadFactory = new ThreadFactoryBuilder()
-            .setNameFormat("OVSDBPassiveConnServ-%d").build();
-    private static ScheduledExecutorService executorService
-            = Executors.newScheduledThreadPool(10, passiveConnectionThreadFactory);
-
-    private static ThreadFactory connectionNotifierThreadFactory = new ThreadFactoryBuilder()
-            .setNameFormat("OVSDBConnNotifSer-%d").build();
-    private static ExecutorService connectionNotifierService
-            = Executors.newCachedThreadPool(connectionNotifierThreadFactory);
-
-    private static Set<OvsdbConnectionListener> connectionListeners = new HashSet<>();
-    private static Map<OvsdbClient, Channel> connections = new ConcurrentHashMap<>();
-    private static OvsdbConnection connectionService;
-    private static AtomicBoolean singletonCreated = new AtomicBoolean(false);
     private static final int IDLE_READER_TIMEOUT = 30;
     private static final int READ_TIMEOUT = 180;
     private static final String OVSDB_RPC_TASK_TIMEOUT_PARAM = "ovsdb-rpc-task-timeout";
     private static final String USE_SSL = "use-ssl";
-    private static boolean useSSL = false;
-    private static ICertificateManager certManagerSrv = null;
+    private static final int RETRY_PERIOD = 100; // retry after 100 milliseconds
 
-    private static int jsonRpcDecoderMaxFrameLength = 100000;
-    private static int listenerPort = 6640;
+    private static final ScheduledExecutorService EXECUTOR_SERVICE = Executors.newScheduledThreadPool(10,
+            new ThreadFactoryBuilder().setNameFormat("OVSDBPassiveConnServ-%d").build());
+
+    private static final ExecutorService CONNECTION_NOTIFIER_SERVICE = Executors
+            .newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("OVSDBConnNotifSer-%d").build());
 
     private static final StalePassiveConnectionService STALE_PASSIVE_CONNECTION_SERVICE =
-            new StalePassiveConnectionService(executorService);
-    private static Channel serverChannel = null;
+            new StalePassiveConnectionService(EXECUTOR_SERVICE);
+
+    private static final OvsdbConnection CONNECTION_SERVICE = new OvsdbConnectionService();
+
+    private static final Set<OvsdbConnectionListener> CONNECTION_LISTENERS = ConcurrentHashMap.newKeySet();
+    private static final Map<OvsdbClient, Channel> CONNECTIONS = new ConcurrentHashMap<>();
 
-    private static int retryPeriod = 100; // retry after 100 milliseconds
+    private static volatile boolean useSSL = false;
+    private static volatile ICertificateManager certManagerSrv;
 
+    private static volatile int jsonRpcDecoderMaxFrameLength = 100000;
+    private static volatile Channel serverChannel;
+
+    private final AtomicBoolean singletonCreated = new AtomicBoolean(false);
+    private volatile int listenerPort = 6640;
 
     public static OvsdbConnection getService() {
-        if (connectionService == null) {
-            connectionService = new OvsdbConnectionService();
-        }
-        return connectionService;
+        return CONNECTION_SERVICE;
     }
 
     /**
@@ -185,26 +181,26 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
         if (client == null) {
             return;
         }
-        Channel channel = connections.get(client);
+        Channel channel = CONNECTIONS.get(client);
         if (channel != null) {
             //It's an explicit disconnect from user, so no need to notify back
             //to user about the disconnect.
             client.setConnectionPublished(false);
             channel.disconnect();
         }
-        connections.remove(client);
+        CONNECTIONS.remove(client);
     }
 
     @Override
     public void registerConnectionListener(OvsdbConnectionListener listener) {
         LOG.info("registerConnectionListener: registering {}", listener.getClass().getSimpleName());
-        connectionListeners.add(listener);
+        CONNECTION_LISTENERS.add(listener);
         notifyAlreadyExistingConnectionsToListener(listener);
     }
 
     private void notifyAlreadyExistingConnectionsToListener(final OvsdbConnectionListener listener) {
         for (final OvsdbClient client : getConnections()) {
-            connectionNotifierService.submit(() -> {
+            CONNECTION_NOTIFIER_SERVICE.execute(() -> {
                 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
                 listener.connected(client);
             });
@@ -213,7 +209,7 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
 
     @Override
     public void unregisterConnectionListener(OvsdbConnectionListener listener) {
-        connectionListeners.remove(listener);
+        CONNECTION_LISTENERS.remove(listener);
     }
 
     private static OvsdbClient getChannelClient(Channel channel, ConnectionType type,
@@ -230,7 +226,7 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
         OvsdbRPC rpc = factory.getClient(channel, OvsdbRPC.class);
         OvsdbClientImpl client = new OvsdbClientImpl(rpc, channel, type, socketConnType);
         client.setConnectionPublished(true);
-        connections.put(client, channel);
+        CONNECTIONS.put(client, channel);
         ChannelFuture closeFuture = channel.closeFuture();
         closeFuture.addListener(new ChannelConnectionHandler(client));
         return client;
@@ -274,7 +270,7 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
         final SSLContext sslContext,
         final String[] protocols,
         final String[] cipherSuites) {
-        if (singletonCreated.getAndSet(false) && (serverChannel != null)) {
+        if (singletonCreated.getAndSet(false) && serverChannel != null) {
             serverChannel.close();
             LOG.info("Server channel closed");
         }
@@ -389,7 +385,7 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
                 LOG.error("Probe failed to OVSDB switch. Disconnecting the channel {}", client.getConnectionInfo());
                 client.disconnect();
             }
-        }, connectionNotifierService);
+        }, CONNECTION_NOTIFIER_SERVICE);
     }
 
     private static void handleNewPassiveConnection(final Channel channel) {
@@ -400,19 +396,11 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
         SslHandler sslHandler = (SslHandler) channel.pipeline().get("ssl");
         if (sslHandler != null) {
             class HandleNewPassiveSslRunner implements Runnable {
-                public SslHandler sslHandler;
-                public final Channel channel;
-                private int retryTimes;
-
-                HandleNewPassiveSslRunner(Channel channel, SslHandler sslHandler) {
-                    this.channel = channel;
-                    this.sslHandler = sslHandler;
-                    this.retryTimes = 3;
-                }
+                private int retryTimes = 3;
 
                 private void retry() {
                     if (retryTimes > 0) {
-                        executorService.schedule(this,  retryPeriod, TimeUnit.MILLISECONDS);
+                        EXECUTOR_SERVICE.schedule(this,  RETRY_PERIOD, TimeUnit.MILLISECONDS);
                     } else {
                         LOG.debug("channel closed {}", channel);
                         channel.disconnect();
@@ -482,10 +470,10 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
                 }
             }
 
-            executorService.schedule(new HandleNewPassiveSslRunner(channel, sslHandler),
-                    retryPeriod, TimeUnit.MILLISECONDS);
+            EXECUTOR_SERVICE.schedule(new HandleNewPassiveSslRunner(),
+                    RETRY_PERIOD, TimeUnit.MILLISECONDS);
         } else {
-            executorService.execute(() -> {
+            EXECUTOR_SERVICE.execute(() -> {
                 OvsdbClient client = getChannelClient(channel, ConnectionType.PASSIVE,
                     SocketConnectionType.NON_SSL);
                 handleNewPassiveConnection(client);
@@ -495,9 +483,9 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
 
     public static void channelClosed(final OvsdbClient client) {
         LOG.info("Connection closed {}", client.getConnectionInfo().toString());
-        connections.remove(client);
+        CONNECTIONS.remove(client);
         if (client.isConnectionPublished()) {
-            for (OvsdbConnectionListener listener : connectionListeners) {
+            for (OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
                 listener.disconnected(client);
             }
         }
@@ -506,7 +494,7 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
 
     @Override
     public Collection<OvsdbClient> getConnections() {
-        return connections.keySet();
+        return CONNECTIONS.keySet();
     }
 
     @Override
@@ -517,8 +505,9 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
 
     @Override
     public OvsdbClient getClient(Channel channel) {
-        for (OvsdbClient client : connections.keySet()) {
-            Channel ctx = connections.get(client);
+        for (Entry<OvsdbClient, Channel> entry : CONNECTIONS.entrySet()) {
+            OvsdbClient client = entry.getKey();
+            Channel ctx = entry.getValue();
             if (ctx.equals(channel)) {
                 return client;
             }
@@ -528,7 +517,7 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
 
     private static List<OvsdbClient> getPassiveClientsFromSameNode(OvsdbClient ovsdbClient) {
         List<OvsdbClient> passiveClients = new ArrayList<>();
-        for (OvsdbClient client : connections.keySet()) {
+        for (OvsdbClient client : CONNECTIONS.keySet()) {
             if (!client.equals(ovsdbClient)
                     && client.getConnectionInfo().getRemoteAddress()
                             .equals(ovsdbClient.getConnectionInfo().getRemoteAddress())
@@ -541,8 +530,8 @@ public class OvsdbConnectionService implements AutoCloseable, OvsdbConnection {
 
     public static void notifyListenerForPassiveConnection(final OvsdbClient client) {
         client.setConnectionPublished(true);
-        for (final OvsdbConnectionListener listener : connectionListeners) {
-            connectionNotifierService.submit(() -> {
+        for (final OvsdbConnectionListener listener : CONNECTION_LISTENERS) {
+            CONNECTION_NOTIFIER_SERVICE.execute(() -> {
                 LOG.trace("Connection {} notified to listener {}", client.getConnectionInfo(), listener);
                 listener.connected(client);
             });
index 3563d5156fb770eba984e47bc9ed4ca482b7c979..a74fa1be97544849bbb697da8bb1e9dc7df6894a 100644 (file)
@@ -12,6 +12,7 @@ import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.SettableFuture;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Future;
 import java.util.concurrent.ScheduledExecutorService;
@@ -35,7 +36,7 @@ import org.slf4j.LoggerFactory;
 public class StalePassiveConnectionService implements AutoCloseable {
     private static final Logger LOG = LoggerFactory.getLogger(StalePassiveConnectionService.class);
 
-    private static Map<OvsdbClient, Map<OvsdbClient, SettableFuture>> pendingConnectionClients =
+    private static Map<OvsdbClient, Map<OvsdbClient, SettableFuture<List<String>>>> pendingConnectionClients =
             new ConcurrentHashMap<>();
 
     private final ScheduledExecutorService executorService;
@@ -54,15 +55,16 @@ public class StalePassiveConnectionService implements AutoCloseable {
      */
     public void handleNewPassiveConnection(final OvsdbClient newOvsdbClient,
                                            final List<OvsdbClient> clientsFromSameNode) {
-        final Map<OvsdbClient, SettableFuture> clientFutureMap = new ConcurrentHashMap<>();
+        final Map<OvsdbClient, SettableFuture<List<String>>> clientFutureMap = new ConcurrentHashMap<>();
         pendingConnectionClients.put(newOvsdbClient, clientFutureMap);
 
         // scheduled task for ping response timeout. Connections that don't response to the
         // ping or haven't disconnected after the timeout will be closed
         final ScheduledFuture<?> echoTimeoutFuture =
                 executorService.schedule(() -> {
-                    for (OvsdbClient client : clientFutureMap.keySet()) {
-                        Future<?> clientFuture = clientFutureMap.get(client);
+                    for (Entry<OvsdbClient, SettableFuture<List<String>>> entry : clientFutureMap.entrySet()) {
+                        OvsdbClient client = entry.getKey();
+                        Future<?> clientFuture = entry.getValue();
                         if (!clientFuture.isDone() && !clientFuture.isCancelled()) {
                             clientFuture.cancel(true);
                         }
@@ -79,7 +81,7 @@ public class StalePassiveConnectionService implements AutoCloseable {
         // The future is removed from the 'clientFutureMap' when the onSuccess event for each future arrives
         // If the map is empty we proceed with new connection process
         for (final OvsdbClient client : clientsFromSameNode) {
-            SettableFuture clientFuture = SettableFuture.create();
+            SettableFuture<List<String>> clientFuture = SettableFuture.create();
             clientFutureMap.put(client, clientFuture);
             Futures.addCallback(clientFuture,
                     createStaleConnectionFutureCallback(client, newOvsdbClient, clientFutureMap, echoTimeoutFuture));
@@ -93,13 +95,17 @@ public class StalePassiveConnectionService implements AutoCloseable {
      * @param disconnectedClient the client just disconnected
      */
     public void clientDisconnected(OvsdbClient disconnectedClient) {
-        for (OvsdbClient pendingClient : pendingConnectionClients.keySet()) {
+        for (Entry<OvsdbClient, Map<OvsdbClient, SettableFuture<List<String>>>> entry :
+                pendingConnectionClients.entrySet()) {
+            OvsdbClient pendingClient = entry.getKey();
+
             // set the future result for pending connections that wait for this client to be disconnected
             if (pendingClient.getConnectionInfo().getRemoteAddress()
                     .equals(disconnectedClient.getConnectionInfo().getRemoteAddress())) {
-                Map<OvsdbClient, SettableFuture> clientFutureMap = pendingConnectionClients.get(pendingClient);
-                if (clientFutureMap.containsKey(disconnectedClient)) {
-                    clientFutureMap.get(disconnectedClient).set(null);
+                Map<OvsdbClient, SettableFuture<List<String>>> clientFutureMap = entry.getValue();
+                SettableFuture<List<String>> future = clientFutureMap.get(disconnectedClient);
+                if (future != null) {
+                    future.set(null);
                 }
             }
         }
@@ -111,7 +117,8 @@ public class StalePassiveConnectionService implements AutoCloseable {
 
     private FutureCallback<List<String>> createStaleConnectionFutureCallback(
             final OvsdbClient cbForClient, final OvsdbClient newClient,
-            final Map<OvsdbClient, SettableFuture> clientFutureMap, final ScheduledFuture<?> echoTimeoutFuture) {
+            final Map<OvsdbClient, SettableFuture<List<String>>> clientFutureMap,
+            final ScheduledFuture<?> echoTimeoutFuture) {
         return new FutureCallback<List<String>>() {
             @Override
             public void onSuccess(List<String> result) {
index 5d0e57c6f7634ad1695760e8e0ec7cc5d07a88bb..39c6474bb0fcff2b154fb1b11206a4341cb2306c 100644 (file)
@@ -20,7 +20,6 @@ import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
 import io.netty.channel.Channel;
-
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.HashMap;
@@ -32,7 +31,6 @@ import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.TimeUnit;
-
 import org.opendaylight.ovsdb.lib.error.UnexpectedResultException;
 import org.opendaylight.ovsdb.lib.error.UnsupportedArgumentException;
 import org.opendaylight.ovsdb.lib.message.OvsdbRPC;
@@ -51,7 +49,7 @@ public class JsonRpcEndpoint {
 
     private static int reaperInterval = 1000;
 
-    public class CallContext {
+    public static class CallContext {
         Method method;
         JsonRpc10Request request;
         SettableFuture<Object> future;
@@ -89,7 +87,7 @@ public class JsonRpcEndpoint {
 
         return Reflection.newProxy(klazz, (proxy, method, args) -> {
             if (method.getName().equals(OvsdbRPC.REGISTER_CALLBACK_METHOD)) {
-                if ((args == null) || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
+                if (args == null || args.length != 1 || !(args[0] instanceof OvsdbRPC.Callback)) {
                     return false;
                 }
                 requestCallbacks.put(context, (OvsdbRPC.Callback)args[0]);
@@ -196,12 +194,11 @@ public class JsonRpcEndpoint {
         if (request.getMethod().equals("echo")) {
             JsonRpc10Response response = new JsonRpc10Response(request.getId());
             response.setError(null);
-            String jsonString = null;
             try {
-                jsonString = objectMapper.writeValueAsString(response);
+                String jsonString = objectMapper.writeValueAsString(response);
                 nettyChannel.writeAndFlush(jsonString);
             } catch (JsonProcessingException e) {
-                LOG.error("Exception while processing JSON string {}", jsonString, e);
+                LOG.error("Exception while processing JSON response {}", response, e);
             }
             return;
         }
@@ -210,12 +207,11 @@ public class JsonRpcEndpoint {
         if (request.getMethod().equals("list_dbs")) {
             JsonRpc10Response response = new JsonRpc10Response(request.getId());
             response.setError(null);
-            String jsonString = null;
             try {
-                jsonString = objectMapper.writeValueAsString(response);
+                String jsonString = objectMapper.writeValueAsString(response);
                 nettyChannel.writeAndFlush(jsonString);
             } catch (JsonProcessingException e) {
-                LOG.error("Exception while processing JSON string {}", jsonString, e);
+                LOG.error("Exception while processing JSON response {}", response, e);
             }
             return;
         }
index 58f058e05a845d73c40b484a4ec6985c6f6a03bf..6d6d6827a01f784775345ae85f1f6cddd8742668 100644 (file)
@@ -17,14 +17,13 @@ import java.util.regex.Pattern;
  * @see <a href="http://tools.ietf.org/html/rfc7047#section-3.1">RFC7047 Section 3.1</a>
  */
 public class Version implements Comparable<Version> {
-
-    int major;
-    int minor;
-    int patch;
-
     private static final String FORMAT = "(\\d+)\\.(\\d+)\\.(\\d+)";
     private static final Pattern PATTERN = Pattern.compile(Version.FORMAT);
 
+    private int major;
+    private int minor;
+    private int patch;
+
     public Version(int major, int minor, int patch) {
         this.major = major;
         this.minor = minor;
@@ -39,12 +38,13 @@ public class Version implements Comparable<Version> {
         if (!matcher.find()) {
             throw new IllegalArgumentException("<" + version + "> does not match format " + Version.FORMAT);
         }
-        int major = Integer.valueOf(matcher.group(1));
-        int minor = Integer.valueOf(matcher.group(2));
-        int patch = Integer.valueOf(matcher.group(3));
+        int major = Integer.parseInt(matcher.group(1));
+        int minor = Integer.parseInt(matcher.group(2));
+        int patch = Integer.parseInt(matcher.group(3));
         return new Version(major, minor, patch);
     }
 
+    @Override
     public String toString() {
         return "" + major + "." + minor + "." + patch;
     }
index 54002502cf7addbf2548d024ebaaa6bc7d117266..8ad90722670ad2a06f15f6e0f040f2605d2aece6 100644 (file)
@@ -13,6 +13,7 @@ import com.fasterxml.jackson.databind.JsonSerializer;
 import com.fasterxml.jackson.databind.SerializerProvider;
 import java.io.IOException;
 import java.util.Map;
+import java.util.Map.Entry;
 import org.opendaylight.ovsdb.lib.notation.OvsdbMap;
 
 public class OvsdbMapSerializer extends JsonSerializer<OvsdbMap<?,?>> {
@@ -23,13 +24,14 @@ public class OvsdbMapSerializer extends JsonSerializer<OvsdbMap<?,?>> {
         generator.writeString("map");
         generator.writeStartArray();
         Map<?,?> javaMap = map.delegate();
-        for (Object set : javaMap.keySet()) {
+        for (Entry<?, ?> entry : javaMap.entrySet()) {
+            Object set = entry.getKey();
             generator.writeStartArray();
             generator.writeObject(set);
-            generator.writeObject(javaMap.get(set));
+            generator.writeObject(entry.getValue());
             generator.writeEndArray();
         }
         generator.writeEndArray();
         generator.writeEndArray();
     }
-}
\ No newline at end of file
+}
index 76bd04196c69f4f4e8c19c71f0c6424673abed81..4f7d3e6fa67dd0be5516ee267af74bdf70f00531 100644 (file)
@@ -17,11 +17,8 @@ import org.opendaylight.ovsdb.lib.notation.UUID;
 
 public  class OvsdbTypesIdResolver extends TypeIdResolverBase {
 
-    private JavaType baseType;
-
     @Override
     public void init(JavaType bt) {
-        this.baseType = bt;
     }
 
     @Override
@@ -53,4 +50,4 @@ public  class OvsdbTypesIdResolver extends TypeIdResolverBase {
     public JsonTypeInfo.Id getMechanism() {
         throw new UnsupportedOperationException("not yet done");
     }
-}
\ No newline at end of file
+}
index 3f4b8c07249479a35eb00971ef6e092ac647803e..5a586ce102e1f9163533279bb43167851f368ad1 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.ovsdb.lib.operations;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.ArrayList;
 import java.util.List;
 import org.opendaylight.ovsdb.lib.notation.Condition;
@@ -30,6 +31,7 @@ public class Mutate<E extends TableSchema<E>> extends Operation<E> implements Co
         super(schema, MUTATE);
     }
 
+    @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") // validate call below
     public <T extends TableSchema<T>, D> Mutate<E> addMutation(ColumnSchema<T, D> columnSchema,
                                                                Mutator mutator, D value) {
         columnSchema.validate(value);
@@ -63,4 +65,4 @@ public class Mutate<E extends TableSchema<E>> extends Operation<E> implements Co
     public void setWhere(List<Condition> where) {
         this.where = where;
     }
-}
\ No newline at end of file
+}
index 63f050d26a46bd087715efccdcbd3eb789222f8e..99056cb6261ca58c4eac7fc7e9508601188a1ad1 100644 (file)
@@ -13,7 +13,8 @@ import org.opendaylight.ovsdb.lib.schema.TableSchema;
 import org.opendaylight.ovsdb.lib.schema.typed.TypedBaseTable;
 
 public class Operations {
-    public static Operations op = new Operations();
+    @SuppressWarnings("checkstyle:ConstantName")
+    public static final Operations op = new Operations();
 
     public <E extends TableSchema<E>> Insert<E> insert(TableSchema<E> schema) {
         return new Insert<>(schema);
index 4fe2993a8ecad72efdf2a4a44e12b262e1df6894..054136c4a5c5681062c2638ebfb6bd3cff5cff84 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.ovsdb.lib.operations;
 
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashMap;
@@ -51,6 +52,7 @@ public class Update<E extends TableSchema<E>> extends Operation<E> implements Co
         this(typedTable.getSchema(), typedTable.getRow());
     }
 
+    @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT") // validate call below
     public <T extends TableSchema<T>, D> Update<E> set(ColumnSchema<T, D> columnSchema, D value) {
         columnSchema.validate(value);
         Object untypedValue = columnSchema.getNormalizeData(value);
index c9ef9ebefc2d79c45101139b70515daeea3011ea..dddb8d8734372bcb19731463e47ee98ea3e761dc 100644 (file)
@@ -8,11 +8,14 @@
 
 package org.opendaylight.ovsdb.lib.schema.typed;
 
+import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
 import com.google.common.reflect.Reflection;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import org.opendaylight.ovsdb.lib.error.ColumnSchemaNotFoundException;
 import org.opendaylight.ovsdb.lib.error.SchemaVersionMismatchException;
@@ -85,10 +88,10 @@ public final class TyperUtils {
          */
         int index = GET_STARTS_WITH.length();
         if (isGetData(method) || isSetData(method)) {
-            return method.getName().substring(index, method.getName().length()).toLowerCase();
+            return method.getName().substring(index, method.getName().length()).toLowerCase(Locale.ROOT);
         } else if (isGetColumn(method)) {
             return method.getName().substring(index, method.getName().indexOf(GETCOLUMN_ENDS_WITH,
-                    index)).toLowerCase();
+                    index)).toLowerCase(Locale.ROOT);
         }
 
         return null;
@@ -206,8 +209,8 @@ public final class TyperUtils {
     }
 
     private static void checkVersion(Version schemaVersion, Version fromVersion, Version untilVersion) {
-        if ((!fromVersion.equals(Version.NULL) && schemaVersion.compareTo(fromVersion) < 0) || (!untilVersion.equals(
-                Version.NULL) && schemaVersion.compareTo(untilVersion) > 0)) {
+        if (!fromVersion.equals(Version.NULL) && schemaVersion.compareTo(fromVersion) < 0 || !untilVersion.equals(
+                Version.NULL) && schemaVersion.compareTo(untilVersion) > 0) {
             throw new SchemaVersionMismatchException(schemaVersion, fromVersion, untilVersion);
         }
     }
@@ -345,10 +348,10 @@ public final class TyperUtils {
             }
 
             private Boolean isEqualsMethod(Method method, Object[] args) {
-                return (args != null
+                return args != null
                         && args.length == 1
                         && method.getName().equals("equals")
-                        && Object.class.equals(method.getParameterTypes()[0]));
+                        && Object.class.equals(method.getParameterTypes()[0]);
             }
 
             private Boolean isToStringMethod(Method method, Object[] args) {
@@ -378,18 +381,13 @@ public final class TyperUtils {
             }
 
             @Override
+            @SuppressFBWarnings({"EQ_CHECK_FOR_OPERAND_NOT_COMPATIBLE_WITH_THIS", "EQ_UNUSUAL"})
             public boolean equals(Object obj) {
-                if (obj == null) {
+                if (!(obj instanceof TypedBaseTable)) {
                     return false;
                 }
                 TypedBaseTable<?> typedRowObj = (TypedBaseTable<?>)obj;
-                if (row == null && typedRowObj.getRow() == null) {
-                    return true;
-                }
-                if (row.equals(typedRowObj.getRow())) {
-                    return true;
-                }
-                return false;
+                return Objects.equal(row, typedRowObj.getRow());
             }
 
             @Override public int hashCode() {
index d55066db2be58400ad7935fdbaf17112178b5ba7..7a1021ab456313740b32c7b337094ca0d01fa99a 100644 (file)
@@ -15,7 +15,6 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import java.lang.reflect.Field;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -45,7 +44,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
 
 @RunWith(PowerMockRunner.class)
-@PrepareForTest({TyperUtils.class, TransactUtils.class})
+@PrepareForTest({TyperUtils.class, TransactUtils.class, Operations.class})
 public class OpenVSwitchBridgeAddCommandTest {
     private OpenVSwitchBridgeAddCommand ovsBridgeAddCommand;
 
@@ -82,7 +81,7 @@ public class OpenVSwitchBridgeAddCommandTest {
         doNothing().when(ovs).setBridges(any(Set.class));
 
         Mutate<GenericTableSchema> mutate = mock(Mutate.class);
-        Operations op = (Operations) setField("op");
+        Operations op = OvsdbNodeUpdateCommandTest.setOpField();
         when(op.mutate(any(OpenVSwitch.class))).thenReturn(mutate);
         Column<GenericTableSchema, Set<UUID>> column = mock(Column.class);
         when(ovs.getBridgesColumn()).thenReturn(column);
@@ -95,11 +94,4 @@ public class OpenVSwitchBridgeAddCommandTest {
                 mock(InstanceIdentifierCodec.class));
         verify(transaction).add(any(Operation.class));
     }
-
-    private Object setField(String fieldName) throws Exception {
-        Field field = Operations.class.getDeclaredField(fieldName);
-        field.setAccessible(true);
-        field.set(field.get(Operations.class), mock(Operations.class));
-        return field.get(Operations.class);
-    }
 }
index 4424fd18449511c8fde785bf54e71c7381b52ebf..dcd030bb8718a8c25635f8576bad4f4bda6f7fd0 100644 (file)
@@ -53,7 +53,8 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
 
 @RunWith(PowerMockRunner.class)
-@PrepareForTest({TransactUtils.class, TyperUtils.class, OvsdbNodeUpdateCommand.class, InstanceIdentifier.class})
+@PrepareForTest({TransactUtils.class, TyperUtils.class, OvsdbNodeUpdateCommand.class, InstanceIdentifier.class,
+    Operations.class})
 public class OvsdbNodeUpdateCommandTest {
 
     private static final String EXTERNAL_ID_KEY = "external id key";
@@ -105,7 +106,7 @@ public class OvsdbNodeUpdateCommandTest {
         doNothing().when(ovs).setExternalIds(any(ImmutableMap.class));
 
         Mutate<GenericTableSchema> mutate = mock(Mutate.class);
-        Operations op = (Operations) setField("op");
+        Operations op = setOpField();
         Column<GenericTableSchema, Map<String, String>> column = mock(Column.class);
         when(ovs.getExternalIdsColumn()).thenReturn(column);
         when(column.getSchema()).thenReturn(mock(ColumnSchema.class));
@@ -130,10 +131,10 @@ public class OvsdbNodeUpdateCommandTest {
         verify(transaction, times(2)).add(any(Operation.class));
     }
 
-    private Object setField(String fieldName) throws Exception {
-        Field field = Operations.class.getDeclaredField(fieldName);
-        field.setAccessible(true);
-        field.set(field.get(Operations.class), mock(Operations.class));
-        return field.get(Operations.class);
+    static Operations setOpField() throws Exception {
+        Field opField = PowerMockito.field(Operations.class, "op");
+        Operations mockOp = mock(Operations.class);
+        opField.set(Operations.class, mockOp);
+        return mockOp;
     }
 }
index 6bf34eab84ff93b8f266e8c0fd0e725d7e7befb0..41a40dd738c7729af6f82f3bb30e93a378bd85e8 100644 (file)
@@ -16,7 +16,6 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import com.google.common.base.Optional;
-import java.lang.reflect.Field;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -54,12 +53,12 @@ import org.powermock.core.classloader.annotations.PrepareForTest;
 import org.powermock.modules.junit4.PowerMockRunner;
 
 @RunWith(PowerMockRunner.class)
-@PrepareForTest({InstanceIdentifier.class, ProtocolUpdateCommand.class, TyperUtils.class})
+@PrepareForTest({InstanceIdentifier.class, ProtocolUpdateCommand.class, TyperUtils.class, Operations.class})
 public class ProtocolUpdateCommandTest {
 
     private static final String BRIDGE_NAME_COLUMN = null;
-    private Map<InstanceIdentifier<ProtocolEntry>, ProtocolEntry> protocols = new HashMap<>();
-    private ProtocolUpdateCommand protocolUpdateCommand = new ProtocolUpdateCommand();
+    private final Map<InstanceIdentifier<ProtocolEntry>, ProtocolEntry> protocols = new HashMap<>();
+    private final ProtocolUpdateCommand protocolUpdateCommand = new ProtocolUpdateCommand();
     @Mock private ProtocolEntry protocolEntry;
 
     @SuppressWarnings("unchecked")
@@ -101,7 +100,7 @@ public class ProtocolUpdateCommandTest {
         doNothing().when(bridge).setName(anyString());
         doNothing().when(bridge).setProtocols(any(Set.class));
 
-        Operations op = (Operations) setField("op");
+        Operations op = OvsdbNodeUpdateCommandTest.setOpField();
         Mutate<GenericTableSchema> mutate = mock(Mutate.class);
         when(op.mutate(any(Bridge.class))).thenReturn(mutate);
         Column<GenericTableSchema, Set<String>> column = mock(Column.class);
@@ -126,11 +125,4 @@ public class ProtocolUpdateCommandTest {
         // TODO What are we trying to verify here?
         // verify(transaction).add(any(Operation.class));
     }
-
-    private Object setField(String fieldName) throws Exception {
-        Field field = Operations.class.getDeclaredField(fieldName);
-        field.setAccessible(true);
-        field.set(field.get(Operations.class), mock(Operations.class));
-        return field.get(Operations.class);
-    }
 }
index 8bdc42af078b4419348f9a102d750d8053a48ce6..f62af785ac01053da7b3deedad858629b5339c9c 100644 (file)
@@ -18,7 +18,6 @@ import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import com.google.common.base.Optional;
-import java.lang.reflect.Field;
 import java.util.HashMap;
 import java.util.Map;
 import org.junit.Before;
@@ -53,7 +52,7 @@ import org.powermock.modules.junit4.PowerMockRunner;
 
 @RunWith(PowerMockRunner.class)
 @PrepareForTest({ TerminationPointUpdateCommand.class, TransactUtils.class, TyperUtils.class, VlanMode.class,
-        TerminationPointCreateCommand.class, InstanceIdentifier.class })
+        TerminationPointCreateCommand.class, InstanceIdentifier.class, Operations.class })
 public class TerminationPointUpdateCommandTest {
 
     private static final String TERMINATION_POINT_NAME = "termination point name";
@@ -114,7 +113,7 @@ public class TerminationPointUpdateCommandTest {
         when(TyperUtils.getTypedRowWrapper(any(DatabaseSchema.class), eq(Interface.class))).thenReturn(extraInterface);
         doNothing().when(extraInterface).setName(anyString());
 
-        Operations op = (Operations) setField("op");
+        Operations op = OvsdbNodeUpdateCommandTest.setOpField();
         Update update = mock(Update.class);
         when(op.update(any(Interface.class))).thenReturn(update);
 
@@ -144,11 +143,4 @@ public class TerminationPointUpdateCommandTest {
                 mock(InstanceIdentifierCodec.class));
         verify(transaction, times(1)).add(any(Operation.class));
     }
-
-    private Object setField(String fieldName) throws Exception {
-        Field field = Operations.class.getDeclaredField(fieldName);
-        field.setAccessible(true);
-        field.set(field.get(Operations.class), mock(Operations.class));
-        return field.get(Operations.class);
-    }
 }