Remove Optional wrapping 74/103974/3
authorRobert Varga <robert.varga@pantheon.tech>
Tue, 10 Jan 2023 22:57:00 +0000 (23:57 +0100)
committerRobert Varga <nite@hq.sk>
Wed, 11 Jan 2023 21:21:35 +0000 (21:21 +0000)
We are needlessly verbose in what is essentially internal comms. Remove
the indirection, getting right of a weird .map(Function.identity()).

Change-Id: Ibe162079f9eb08b8602b8fa5216c217a9d33e333
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
restconf/restconf-nb/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/CreateStreamUtil.java
restconf/restconf-nb/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/RestconfDataStreamServiceImpl.java
restconf/restconf-nb/src/main/java/org/opendaylight/restconf/nb/rfc8040/rests/services/impl/SubscribeToStreamUtil.java
restconf/restconf-nb/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/WebSocketInitializer.java
restconf/restconf-nb/src/main/java/org/opendaylight/restconf/nb/rfc8040/streams/listeners/ListenersBroker.java

index 17c22a45f9468157da050b6bcfb29a0ae2402fad..e8c228ebfed8fd967fe55b780693799352128ac8 100644 (file)
@@ -11,7 +11,6 @@ import static java.util.Objects.requireNonNull;
 
 import com.google.common.collect.ImmutableSet;
 import java.util.Collection;
 
 import com.google.common.collect.ImmutableSet;
 import java.util.Collection;
-import java.util.Optional;
 import java.util.Set;
 import java.util.stream.Collectors;
 import org.eclipse.jdt.annotation.Nullable;
 import java.util.Set;
 import java.util.stream.Collectors;
 import org.eclipse.jdt.annotation.Nullable;
@@ -279,12 +278,14 @@ final class CreateStreamUtil {
      */
     static NotificationListenerAdapter createYangNotifiStream(final NotificationDefinition notificationDefinition,
             final EffectiveModelContext refSchemaCtx, final NotificationOutputType outputType) {
      */
     static NotificationListenerAdapter createYangNotifiStream(final NotificationDefinition notificationDefinition,
             final EffectiveModelContext refSchemaCtx, final NotificationOutputType outputType) {
-        final String streamName = parseNotificationStreamName(requireNonNull(notificationDefinition),
+        final var streamName = parseNotificationStreamName(requireNonNull(notificationDefinition),
                 requireNonNull(refSchemaCtx), requireNonNull(outputType.getName()));
                 requireNonNull(refSchemaCtx), requireNonNull(outputType.getName()));
-        final Optional<NotificationListenerAdapter> listenerForStreamName = ListenersBroker.getInstance()
-                .getNotificationListenerFor(streamName);
-        return listenerForStreamName.orElseGet(() -> ListenersBroker.getInstance().registerNotificationListener(
-                Absolute.of(notificationDefinition.getQName()), streamName, outputType));
+        final var listenersBroker = ListenersBroker.getInstance();
+
+        final var existing = listenersBroker.notificationListenerFor(streamName);
+        return existing != null ? existing
+            : listenersBroker.registerNotificationListener(
+                Absolute.of(notificationDefinition.getQName()), streamName, outputType);
     }
 
     private static String parseNotificationStreamName(final NotificationDefinition notificationDefinition,
     }
 
     private static String parseNotificationStreamName(final NotificationDefinition notificationDefinition,
index 8307f9138e2d504c9380e6df385caca9e8d1397b..9aa37c73cb7cf013bdbebded253eda8ac5b85ad8 100644 (file)
@@ -53,18 +53,17 @@ public class RestconfDataStreamServiceImpl implements RestconfDataStreamService
         final String notificaionType =
             uriInfo.getQueryParameters().getFirst(RestconfStreamsConstants.NOTIFICATION_TYPE);
         if (notificaionType != null && notificaionType.equals(RestconfStreamsConstants.DEVICE)) {
         final String notificaionType =
             uriInfo.getQueryParameters().getFirst(RestconfStreamsConstants.NOTIFICATION_TYPE);
         if (notificaionType != null && notificaionType.equals(RestconfStreamsConstants.DEVICE)) {
-            listener = listenersBroker.getDeviceNotificationListenerFor(streamName)
-                .orElseThrow(() -> {
-                    LOG.debug("Listener for device path with name {} was not found.", streamName);
-                    throw new RestconfDocumentedException("Data missing", ErrorType.APPLICATION,
-                        ErrorTag.DATA_MISSING);
-                });
+            listener = listenersBroker.deviceNotificationListenerFor(streamName);
+            if (listener == null) {
+                LOG.debug("Listener for device path with name {} was not found.", streamName);
+                throw new RestconfDocumentedException("Data missing", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
+            }
         } else {
         } else {
-            listener = listenersBroker.getListenerFor(streamName)
-                .orElseThrow(() -> {
-                    LOG.debug("Listener for stream with name {} was not found.", streamName);
-                    throw new RestconfDocumentedException("Data missing", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
-                });
+            listener = listenersBroker.listenerFor(streamName);
+            if (listener == null) {
+                LOG.debug("Listener for stream with name {} was not found.", streamName);
+                throw new RestconfDocumentedException("Data missing", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
+            }
         }
 
         LOG.debug("Listener for stream with name {} has been found, SSE session handler will be created.", streamName);
         }
 
         LOG.debug("Listener for stream with name {} has been found, SSE session handler will be created.", streamName);
index acbc80e70b6bd107cbf56ac7d1aa59a510b3ab68..c65b834e955e491bacbba059f13ebd6a3594c5f0 100644 (file)
@@ -123,10 +123,11 @@ abstract class SubscribeToStreamUtil {
         }
 
         final NotificationListenerAdapter notificationListenerAdapter = ListenersBroker.getInstance()
         }
 
         final NotificationListenerAdapter notificationListenerAdapter = ListenersBroker.getInstance()
-            .getNotificationListenerFor(streamName)
-            .orElseThrow(() -> new RestconfDocumentedException(
-                String.format("Stream with name %s was not found.", streamName),
-                ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT));
+            .notificationListenerFor(streamName);
+        if (notificationListenerAdapter == null) {
+            throw new RestconfDocumentedException(String.format("Stream with name %s was not found.", streamName),
+                ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
+        }
 
         final EffectiveModelContext schemaContext = handlersHolder.getDatabindProvider().currentContext()
             .modelContext();
 
         final EffectiveModelContext schemaContext = handlersHolder.getDatabindProvider().currentContext()
             .modelContext();
@@ -176,9 +177,12 @@ abstract class SubscribeToStreamUtil {
         }
 
         final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
         }
 
         final String streamName = ListenersBroker.createStreamNameFromUri(identifier);
-        final ListenerAdapter listener = ListenersBroker.getInstance().getDataChangeListenerFor(streamName)
-            .orElseThrow(() -> new RestconfDocumentedException("No listener found for stream " + streamName,
-                ErrorType.APPLICATION, ErrorTag.DATA_MISSING));
+        final ListenerAdapter listener = ListenersBroker.getInstance().dataChangeListenerFor(streamName);
+        if (listener == null) {
+            throw new RestconfDocumentedException("No listener found for stream " + streamName,
+                ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
+        }
+
         listener.setQueryParams(notificationQueryParams);
 
         final DOMDataBroker dataBroker = handlersHolder.getDataBroker();
         listener.setQueryParams(notificationQueryParams);
 
         final DOMDataBroker dataBroker = handlersHolder.getDataBroker();
index 1bf1675fa0b12ea6ebda300bc2dc5386edaddba9..d0f3cefee23d06faa432d8e48dd497f60950e0e3 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.restconf.nb.rfc8040.streams;
 
 import com.google.common.annotations.VisibleForTesting;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 
 import com.google.common.annotations.VisibleForTesting;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import java.util.Optional;
 import java.util.concurrent.ScheduledExecutorService;
 import javax.inject.Inject;
 import javax.inject.Singleton;
 import java.util.concurrent.ScheduledExecutorService;
 import javax.inject.Inject;
 import javax.inject.Singleton;
@@ -20,7 +19,6 @@ import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
 import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
 import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
 import org.eclipse.jetty.websocket.servlet.WebSocketServlet;
 import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory;
 import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
-import org.opendaylight.restconf.nb.rfc8040.streams.listeners.BaseListenerInterface;
 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -47,10 +45,10 @@ public final class WebSocketInitializer extends WebSocketServlet {
      */
     @Inject
     public WebSocketInitializer(final ScheduledThreadPool scheduledThreadPool, final Configuration configuration) {
      */
     @Inject
     public WebSocketInitializer(final ScheduledThreadPool scheduledThreadPool, final Configuration configuration) {
-        this.executorService = scheduledThreadPool.getExecutor();
-        this.maximumFragmentLength = configuration.getMaximumFragmentLength();
-        this.heartbeatInterval = configuration.getHeartbeatInterval();
-        this.idleTimeoutMillis = configuration.getIdleTimeout();
+        executorService = scheduledThreadPool.getExecutor();
+        maximumFragmentLength = configuration.getMaximumFragmentLength();
+        heartbeatInterval = configuration.getHeartbeatInterval();
+        idleTimeoutMillis = configuration.getIdleTimeout();
     }
 
     /**
     }
 
     /**
@@ -104,25 +102,24 @@ public final class WebSocketInitializer extends WebSocketServlet {
         @Override
         public Object createWebSocket(final ServletUpgradeRequest servletUpgradeRequest,
                 final ServletUpgradeResponse servletUpgradeResponse) {
         @Override
         public Object createWebSocket(final ServletUpgradeRequest servletUpgradeRequest,
                 final ServletUpgradeResponse servletUpgradeResponse) {
-            final String requestUri = servletUpgradeRequest.getRequestURI().getRawPath();
-            final String streamName = ListenersBroker.createStreamNameFromUri(requestUri);
+            final var streamName = ListenersBroker.createStreamNameFromUri(
+                servletUpgradeRequest.getRequestURI().getRawPath());
 
 
-            final Optional<BaseListenerInterface> listener = listenersBroker.getListenerFor(streamName);
-            if (listener.isPresent()) {
-                LOG.debug("Listener for stream with name {} has been found, web-socket session handler will be created",
-                        streamName);
-                servletUpgradeResponse.setSuccess(true);
-                servletUpgradeResponse.setStatusCode(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
-                // note: every web-socket manages PING process individually because this approach scales better than
-                //       sending of PING frames at once over all web-socket sessions
-                return new WebSocketSessionHandler(executorService, listener.get(), maximumFragmentLength,
-                        heartbeatInterval);
-            } else {
+            final var listener = listenersBroker.listenerFor(streamName);
+            if (listener == null) {
                 LOG.debug("Listener for stream with name {} was not found.", streamName);
                 servletUpgradeResponse.setSuccess(false);
                 servletUpgradeResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
                 return null;
             }
                 LOG.debug("Listener for stream with name {} was not found.", streamName);
                 servletUpgradeResponse.setSuccess(false);
                 servletUpgradeResponse.setStatusCode(HttpServletResponse.SC_NOT_FOUND);
                 return null;
             }
+
+            LOG.debug("Listener for stream with name {} has been found, web-socket session handler will be created",
+                streamName);
+            servletUpgradeResponse.setSuccess(true);
+            servletUpgradeResponse.setStatusCode(HttpServletResponse.SC_SWITCHING_PROTOCOLS);
+            // note: every web-socket manages PING process individually because this approach scales better than
+            //       sending of PING frames at once over all web-socket sessions
+            return new WebSocketSessionHandler(executorService, listener, maximumFragmentLength, heartbeatInterval);
         }
     }
 }
         }
     }
 }
index 87f43835e74a0d2494c8408b554b422fce21c8bd..3334083e1960a827e29fd9f3100c64ce2465b3c9 100644 (file)
@@ -16,7 +16,7 @@ import java.util.Map;
 import java.util.Optional;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.locks.StampedLock;
 import java.util.Optional;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.locks.StampedLock;
-import java.util.function.Function;
+import org.eclipse.jdt.annotation.Nullable;
 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
@@ -66,13 +66,16 @@ public final class ListenersBroker {
      * Gets {@link ListenerAdapter} specified by stream identification.
      *
      * @param streamName Stream name.
      * Gets {@link ListenerAdapter} specified by stream identification.
      *
      * @param streamName Stream name.
-     * @return {@link ListenerAdapter} specified by stream name wrapped in {@link Optional} or {@link Optional#empty()}
-     *     if listener with specified stream name doesn't exist.
+     * @return {@link ListenerAdapter} specified by stream name or {@code null} if listener with specified stream name
+     *         does not exist.
+     * @throws NullPointerException in {@code streamName} is {@code null}
      */
      */
-    public Optional<ListenerAdapter> getDataChangeListenerFor(final String streamName) {
+    public @Nullable ListenerAdapter dataChangeListenerFor(final String streamName) {
+        requireNonNull(streamName);
+
         final long stamp = dataChangeListenersLock.readLock();
         try {
         final long stamp = dataChangeListenersLock.readLock();
         try {
-            return Optional.ofNullable(dataChangeListeners.get(requireNonNull(streamName)));
+            return dataChangeListeners.get(streamName);
         } finally {
             dataChangeListenersLock.unlockRead(stamp);
         }
         } finally {
             dataChangeListenersLock.unlockRead(stamp);
         }
@@ -82,13 +85,16 @@ public final class ListenersBroker {
      * Gets {@link NotificationListenerAdapter} specified by stream name.
      *
      * @param streamName Stream name.
      * Gets {@link NotificationListenerAdapter} specified by stream name.
      *
      * @param streamName Stream name.
-     * @return {@link NotificationListenerAdapter} specified by stream name wrapped in {@link Optional}
-     *     or {@link Optional#empty()} if listener with specified stream name doesn't exist.
+     * @return {@link NotificationListenerAdapter} specified by stream name or {@code null} if listener with specified
+     *         stream name does not exist.
+     * @throws NullPointerException in {@code streamName} is {@code null}
      */
      */
-    public Optional<NotificationListenerAdapter> getNotificationListenerFor(final String streamName) {
+    public @Nullable NotificationListenerAdapter notificationListenerFor(final String streamName) {
+        requireNonNull(streamName);
+
         final long stamp = notificationListenersLock.readLock();
         try {
         final long stamp = notificationListenersLock.readLock();
         try {
-            return Optional.ofNullable(notificationListeners.get(requireNonNull(streamName)));
+            return notificationListeners.get(streamName);
         } finally {
             notificationListenersLock.unlockRead(stamp);
         }
         } finally {
             notificationListenersLock.unlockRead(stamp);
         }
@@ -98,13 +104,16 @@ public final class ListenersBroker {
      * Get listener for device path.
      *
      * @param path name.
      * Get listener for device path.
      *
      * @param path name.
-     * @return {@link NotificationListenerAdapter} or {@link ListenerAdapter} object wrapped in {@link Optional}
-     *     or {@link Optional#empty()} if listener with specified path doesn't exist.
+     * @return {@link BaseListenerInterface} specified by stream name or {@code null} if listener with specified
+     *         stream name does not exist.
+     * @throws NullPointerException in {@code path} is {@code null}
      */
      */
-    public Optional<BaseListenerInterface> getDeviceNotificationListenerFor(final String path) {
+    public @Nullable BaseListenerInterface deviceNotificationListenerFor(final String path) {
+        requireNonNull(path);
+
         final long stamp = deviceNotificationListenersLock.readLock();
         try {
         final long stamp = deviceNotificationListenersLock.readLock();
         try {
-            return Optional.ofNullable(deviceNotificationListeners.get(requireNonNull(path)));
+            return deviceNotificationListeners.get(path);
         } finally {
             deviceNotificationListenersLock.unlockRead(stamp);
         }
         } finally {
             deviceNotificationListenersLock.unlockRead(stamp);
         }
@@ -117,13 +126,13 @@ public final class ListenersBroker {
      * @return {@link NotificationListenerAdapter} or {@link ListenerAdapter} object wrapped in {@link Optional}
      *     or {@link Optional#empty()} if listener with specified stream name doesn't exist.
      */
      * @return {@link NotificationListenerAdapter} or {@link ListenerAdapter} object wrapped in {@link Optional}
      *     or {@link Optional#empty()} if listener with specified stream name doesn't exist.
      */
-    public Optional<BaseListenerInterface> getListenerFor(final String streamName) {
+    public @Nullable BaseListenerInterface listenerFor(final String streamName) {
         if (streamName.startsWith(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
         if (streamName.startsWith(RestconfStreamsConstants.NOTIFICATION_STREAM)) {
-            return getNotificationListenerFor(streamName).map(Function.identity());
+            return notificationListenerFor(streamName);
         } else if (streamName.startsWith(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
         } else if (streamName.startsWith(RestconfStreamsConstants.DATA_SUBSCRIPTION)) {
-            return getDataChangeListenerFor(streamName).map(Function.identity());
+            return dataChangeListenerFor(streamName);
         } else {
         } else {
-            return Optional.empty();
+            return null;
         }
     }
 
         }
     }