Simplify code using Java 8 features 86/74486/3
authorStephen Kitt <skitt@redhat.com>
Thu, 26 Jul 2018 08:35:02 +0000 (10:35 +0200)
committerStephen Kitt <skitt@redhat.com>
Fri, 27 Jul 2018 12:51:51 +0000 (14:51 +0200)
* method references
* lambda expressions
* Map::computeIfAbsent

Change-Id: Icbfa5c0a76b5b6f2b4339dbbd49b8a44e7b14fb2
Signed-off-by: Stephen Kitt <skitt@redhat.com>
12 files changed:
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/NetconfServerDispatcherImpl.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfCapabilityMonitoringService.java
netconf/netconf-impl/src/main/java/org/opendaylight/netconf/impl/osgi/NetconfSessionMonitoringService.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/AbstractNetconfSessionNegotiator.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/NetconfEXICodec.java
netconf/netconf-netty-util/src/main/java/org/opendaylight/netconf/nettyutil/handler/ssh/client/AsyncSshHandler.java
netconf/netconf-ssh/src/main/java/org/opendaylight/netconf/ssh/RemoteNetconfCommand.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/NetconfTopologyManager.java
netconf/netconf-topology-singleton/src/main/java/org/opendaylight/netconf/topology/singleton/impl/tx/ProxyReadWriteTransaction.java
netconf/tools/netconf-testtool/src/main/java/org/opendaylight/netconf/test/tool/config/Configuration.java
restconf/restconf-common/src/main/java/org/opendaylight/restconf/common/util/MultivaluedHashMap.java
restconf/sal-rest-docgen/src/main/java/org/opendaylight/netconf/sal/rest/doc/util/RestDocgenUtil.java

index 7db8db4f09abcae7d37f6f96d3c887c039d18103..394771b122691f54f1d93648074bc3cf57820709 100644 (file)
@@ -12,9 +12,7 @@ import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.local.LocalAddress;
-import io.netty.channel.local.LocalChannel;
 import io.netty.channel.local.LocalServerChannel;
-import io.netty.channel.socket.SocketChannel;
 import io.netty.util.concurrent.Promise;
 import java.net.InetSocketAddress;
 import org.opendaylight.netconf.api.NetconfServerDispatcher;
@@ -35,23 +33,12 @@ public class NetconfServerDispatcherImpl extends AbstractDispatcher<NetconfServe
 
     @Override
     public ChannelFuture createServer(InetSocketAddress address) {
-        return super.createServer(address, new PipelineInitializer<NetconfServerSession>() {
-            @Override
-            public void initializeChannel(final SocketChannel ch, final Promise<NetconfServerSession> promise) {
-                initializer.initialize(ch, promise);
-            }
-        });
+        return super.createServer(address, initializer::initialize);
     }
 
     @Override
     public ChannelFuture createLocalServer(LocalAddress address) {
-        return super.createServer(address, LocalServerChannel.class, new ChannelPipelineInitializer<LocalChannel,
-                NetconfServerSession>() {
-            @Override
-            public void initializeChannel(final LocalChannel ch, final Promise<NetconfServerSession> promise) {
-                initializer.initialize(ch, promise);
-            }
-        });
+        return super.createServer(address, LocalServerChannel.class, initializer::initialize);
     }
 
     public static class ServerChannelInitializer extends AbstractChannelInitializer<NetconfServerSession> {
index fd520a363e9a4b4b9a9050ca79c70f2bfce03b12..f627f15a7e81902889567ab61fc09a7ae7800dd7 100644 (file)
@@ -106,11 +106,8 @@ class NetconfCapabilityMonitoringService implements CapabilityListener, AutoClos
             }
 
             final String currentModuleName = cap.getModuleName().get();
-            Map<String, String> revisionMap = mappedModulesToRevisionToSchema.get(currentModuleName);
-            if (revisionMap == null) {
-                revisionMap = Maps.newHashMap();
-                mappedModulesToRevisionToSchema.put(currentModuleName, revisionMap);
-            }
+            Map<String, String> revisionMap =
+                mappedModulesToRevisionToSchema.computeIfAbsent(currentModuleName, k -> Maps.newHashMap());
 
             final String currentRevision = cap.getRevision().get();
             revisionMap.put(currentRevision, cap.getCapabilitySchema().get());
index da9a96b6d1de91f638c7ee85af1984925643ad59..639daa803d35a2627f18acb120133e868484d01a 100644 (file)
@@ -99,12 +99,7 @@ class NetconfSessionMonitoringService implements SessionListener, AutoCloseable
         if (!running) {
             startUpdateSessionStats();
         }
-        return new AutoCloseable() {
-            @Override
-            public void close() {
-                listeners.remove(listener);
-            }
-        };
+        return () -> listeners.remove(listener);
     }
 
     @Override
index 065a5bc9c42794d518170b3f9ec052e4dc4ffd85..d9c15ae03578052a079bc157d44d2e7e9dcb6e1e 100644 (file)
@@ -19,7 +19,6 @@ import io.netty.handler.ssl.SslHandler;
 import io.netty.util.Timeout;
 import io.netty.util.Timer;
 import io.netty.util.TimerTask;
-import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GenericFutureListener;
 import io.netty.util.concurrent.Promise;
 import java.util.concurrent.TimeUnit;
@@ -84,14 +83,10 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
         } else {
             final Optional<SslHandler> sslHandler = getSslHandler(channel);
             if (sslHandler.isPresent()) {
-                Future<Channel> future = sslHandler.get().handshakeFuture();
-                future.addListener(new GenericFutureListener<Future<? super Channel>>() {
-                    @Override
-                    public void operationComplete(final Future<? super Channel> future) {
-                        Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
-                        LOG.debug("Ssl handshake complete");
-                        start();
-                    }
+                sslHandler.get().handshakeFuture().addListener(future -> {
+                    Preconditions.checkState(future.isSuccess(), "Ssl handshake was not successful");
+                    LOG.debug("Ssl handshake complete");
+                    start();
                 });
             } else {
                 start();
@@ -139,14 +134,11 @@ public abstract class AbstractNetconfSessionNegotiator<P extends NetconfSessionP
                             LOG.warn("Netconf session was not established after {}", connectionTimeoutMillis);
                             changeState(State.FAILED);
 
-                            channel.close().addListener(new GenericFutureListener<ChannelFuture>() {
-                                @Override
-                                public void operationComplete(final ChannelFuture future) {
-                                    if (future.isSuccess()) {
-                                        LOG.debug("Channel {} closed: success", future.channel());
-                                    } else {
-                                        LOG.warn("Channel {} closed: fail", future.channel());
-                                    }
+                            channel.close().addListener((GenericFutureListener<ChannelFuture>) future -> {
+                                if (future.isSuccess()) {
+                                    LOG.debug("Channel {} closed: success", future.channel());
+                                } else {
+                                    LOG.warn("Channel {} closed: fail", future.channel());
                                 }
                             });
                         }
index 383e8b7d50d2eb87e3ffeb5cbfe9e8b5d9703991..44d07209e7271efd8db7ff06a067839fd52307e6 100644 (file)
@@ -26,12 +26,7 @@ public final class NetconfEXICodec {
      * OpenEXI does not allow us to directly prevent resolution of external entities. In order
      * to prevent XXE attacks, we reuse a single no-op entity resolver.
      */
-    private static final EntityResolver ENTITY_RESOLVER = new EntityResolver() {
-        @Override
-        public InputSource resolveEntity(final String publicId, final String systemId) {
-            return new InputSource();
-        }
-    };
+    private static final EntityResolver ENTITY_RESOLVER = (publicId, systemId) -> new InputSource();
 
     /**
      * Since we have a limited number of options we can have, instantiating a weak cache
index fa59b344b86ad1ca29c26c3cf7a3d2f971207523..149ccf16f9910dfbf38a866f5c0d89fbda50c7b6 100644 (file)
@@ -164,7 +164,7 @@ public class AsyncSshHandler extends ChannelOutboundHandlerAdapter {
 
         ClientChannel localChannel = channel;
         sshReadAsyncListener = new AsyncSshHandlerReader(() -> AsyncSshHandler.this.disconnect(ctx, ctx.newPromise()),
-            msg -> ctx.fireChannelRead(msg), localChannel.toString(), localChannel.getAsyncOut());
+            ctx::fireChannelRead, localChannel.toString(), localChannel.getAsyncOut());
 
         // if readAsyncListener receives immediate close,
         // it will close this handler and closing this handler sets channel variable to null
index c016dc395949f3e172f9707f258107d6da101d89..733d81af1ffc11b7676767ad07e6cade8a1ecc9f 100644 (file)
@@ -16,7 +16,6 @@ import io.netty.channel.ChannelInitializer;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.local.LocalAddress;
 import io.netty.channel.local.LocalChannel;
-import io.netty.util.concurrent.GenericFutureListener;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.InetSocketAddress;
@@ -118,19 +117,15 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
             }
         });
         clientChannelFuture = clientBootstrap.connect(localAddress);
-        clientChannelFuture.addListener(new GenericFutureListener<ChannelFuture>() {
-
-            @Override
-            public void operationComplete(final ChannelFuture future) {
-                if (future.isSuccess()) {
-                    clientChannel = clientChannelFuture.channel();
-                } else {
-                    LOG.warn("Unable to establish internal connection to netconf server for client: {}",
-                            getClientAddress());
-                    Preconditions.checkNotNull(callback, "Exit callback must be set");
-                    callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
-                            + getClientAddress());
-                }
+        clientChannelFuture.addListener(future -> {
+            if (future.isSuccess()) {
+                clientChannel = clientChannelFuture.channel();
+            } else {
+                LOG.warn("Unable to establish internal connection to netconf server for client: {}",
+                        getClientAddress());
+                Preconditions.checkNotNull(callback, "Exit callback must be set");
+                callback.onExit(1, "Unable to establish internal connection to netconf server for client: "
+                        + getClientAddress());
             }
         });
     }
@@ -142,14 +137,10 @@ public class RemoteNetconfCommand implements AsyncCommand, SessionAware {
 
         clientChannelFuture.cancel(true);
         if (clientChannel != null) {
-            clientChannel.close().addListener(new GenericFutureListener<ChannelFuture>() {
-
-                @Override
-                public void operationComplete(final ChannelFuture future) {
-                    if (!future.isSuccess()) {
-                        LOG.warn("Unable to release internal connection to netconf server on channel: {}",
-                                clientChannel);
-                    }
+            clientChannel.close().addListener(future -> {
+                if (!future.isSuccess()) {
+                    LOG.warn("Unable to release internal connection to netconf server on channel: {}",
+                            clientChannel);
                 }
             });
         }
index a87f77c2e9da1b2dc4bc805e5a10239dcbf38818..a71f7cb23f832a284c72b14867a6672691855a37 100644 (file)
@@ -209,10 +209,8 @@ public class NetconfTopologyManager
             dataChangeListenerRegistration = null;
         }
 
-        contexts.values().forEach(netconfTopologyContext -> close(netconfTopologyContext));
-
-        clusterRegistrations.values().forEach(
-            clusterSingletonServiceRegistration -> close(clusterSingletonServiceRegistration));
+        contexts.values().forEach(NetconfTopologyManager::close);
+        clusterRegistrations.values().forEach(NetconfTopologyManager::close);
 
         contexts.clear();
         clusterRegistrations.clear();
index 82fbc41e05cc9b553c9859e6c59b1ea34d62a7fb..bfe776e79ebc8ae03aec06b36acbce7b12f726b6 100644 (file)
@@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Consumer;
 import javax.annotation.concurrent.GuardedBy;
 import org.eclipse.jdt.annotation.NonNull;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncWriteTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
@@ -79,7 +80,7 @@ public class ProxyReadWriteTransaction implements DOMDataReadWriteTransaction {
             return false;
         }
 
-        processTransactionOperation(facade -> facade.cancel());
+        processTransactionOperation(AsyncWriteTransaction::cancel);
         return true;
     }
 
index 665442535ce7c5bf9be6cf2d5d45d0a3df2ce10d..390be4b4163b02df0875a5b627c1ac9a8f94b08e 100644 (file)
@@ -9,11 +9,9 @@ package org.opendaylight.netconf.test.tool.config;
 
 import com.google.common.collect.ImmutableSet;
 import java.io.File;
-import java.security.PublicKey;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
 import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
-import org.apache.sshd.server.session.ServerSession;
 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.netconf.auth.AuthProvider;
 import org.opendaylight.netconf.test.tool.operations.OperationsCreator;
@@ -53,12 +51,9 @@ public class Configuration {
         return true;
     };
 
-    public static final PublickeyAuthenticator DEFAULT_PUBLIC_KEY_AUTHENTICATOR = new PublickeyAuthenticator() {
-        @Override
-        public boolean authenticate(final String username, final PublicKey key, final ServerSession session) {
-            LOG.info("Auth with public key: {}", key);
-            return true;
-        }
+    public static final PublickeyAuthenticator DEFAULT_PUBLIC_KEY_AUTHENTICATOR = (username, key, session) -> {
+        LOG.info("Auth with public key: {}", key);
+        return true;
     };
 
     private int generateConfigsTimeout = (int) TimeUnit.MINUTES.toMillis(30);
index 1036757f498ef4957da1daf40ca19522914f1f7c..4eedb93245726b268e183bb1d26eee4962ed75bb 100644 (file)
@@ -177,12 +177,6 @@ public class MultivaluedHashMap<K, V> implements MultivaluedMap<K, V> {
     }
 
     private List<V> getValues(K key) {
-        List<V> list = store.get(key);
-        if (list == null) {
-            list = new LinkedList<>();
-            store.put(key, list);
-        }
-
-        return list;
+        return store.computeIfAbsent(key, k -> new LinkedList<>());
     }
 }
index 1fa3a01dc3922a7f478c54756580d5b0222b26e7..ee96a376db8f750a6e930d3c57bd843aba4328ee 100644 (file)
@@ -55,16 +55,10 @@ public final class RestDocgenUtil {
         final URI namespace = node.getQName().getNamespace();
         final Optional<Revision> revision = node.getQName().getRevision();
 
-        Map<Optional<Revision>, Module> revisionToModule = NAMESPACE_AND_REVISION_TO_MODULE.get(namespace);
-        if (revisionToModule == null) {
-            revisionToModule = new HashMap<>();
-            NAMESPACE_AND_REVISION_TO_MODULE.put(namespace, revisionToModule);
-        }
-        Module module = revisionToModule.get(revision);
-        if (module == null) {
-            module = schemaContext.findModule(namespace, revision).orElse(null);
-            revisionToModule.put(revision, module);
-        }
+        Map<Optional<Revision>, Module> revisionToModule =
+            NAMESPACE_AND_REVISION_TO_MODULE.computeIfAbsent(namespace, k -> new HashMap<>());
+        Module module =
+            revisionToModule.computeIfAbsent(revision, k -> schemaContext.findModule(namespace, k).orElse(null));
         if (module != null) {
             return module.getName() + ":" + node.getQName().getLocalName();
         }