Merge "Option to receive only leaf nodes in websocket notifs"
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / restful / utils / SubscribeToStreamUtil.java
index fddbad9ee1ca8d1811217914eee741e07d9c5ca9..5b8a5255df03dc5ea78b4554486fffeb3f45ea54 100644 (file)
@@ -10,11 +10,13 @@ package org.opendaylight.restconf.restful.utils;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import java.net.URI;
-import java.text.DateFormat;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
+import java.time.Instant;
+import java.time.format.DateTimeFormatter;
+import java.time.format.DateTimeFormatterBuilder;
+import java.time.format.DateTimeParseException;
+import java.time.temporal.ChronoField;
+import java.time.temporal.TemporalAccessor;
 import java.util.ArrayList;
-import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -46,6 +48,7 @@ import org.opendaylight.restconf.restful.services.impl.RestconfStreamsSubscripti
 import org.opendaylight.restconf.utils.RestconfConstants;
 import org.opendaylight.restconf.utils.mapping.RestconfMappingNodeUtil;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DateAndTime;
+import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@@ -68,6 +71,15 @@ import org.slf4j.LoggerFactory;
 public final class SubscribeToStreamUtil {
 
     private static final Logger LOG = LoggerFactory.getLogger(SubscribeToStreamUtil.class);
+    private static final DateTimeFormatter FORMATTER = new DateTimeFormatterBuilder()
+            .appendValue(ChronoField.YEAR, 4).appendLiteral('-')
+            .appendValue(ChronoField.MONTH_OF_YEAR, 2).appendLiteral('-')
+            .appendValue(ChronoField.DAY_OF_MONTH, 2).appendLiteral('T')
+            .appendValue(ChronoField.HOUR_OF_DAY, 2).appendLiteral(':')
+            .appendValue(ChronoField.MINUTE_OF_HOUR, 2).appendLiteral(':')
+            .appendValue(ChronoField.SECOND_OF_MINUTE, 2)
+            .appendFraction(ChronoField.NANO_OF_SECOND, 0, 9, true)
+            .appendOffset("+HH:MM", "Z").toFormatter();
 
     private SubscribeToStreamUtil() {
         throw new UnsupportedOperationException("Util class");
@@ -95,7 +107,12 @@ public final class SubscribeToStreamUtil {
         if (Strings.isNullOrEmpty(streamName)) {
             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
-        final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
+        List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
+        if (identifier.contains(RestconfConstants.SLASH + NotificationOutputType.JSON.getName())) {
+            listeners = pickSpecificListenerByOutput(listeners, NotificationOutputType.JSON.getName());
+        } else {
+            listeners = pickSpecificListenerByOutput(listeners, NotificationOutputType.XML.getName());
+        }
         if ((listeners == null) || listeners.isEmpty()) {
             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
                     ErrorTag.UNKNOWN_ELEMENT);
@@ -110,7 +127,7 @@ public final class SubscribeToStreamUtil {
         for (final NotificationListenerAdapter listener : listeners) {
             registerToListenNotification(listener, handlersHolder.getNotificationServiceHandler());
             listener.setQueryParams(notificationQueryParams.getStart(), notificationQueryParams.getStop(),
-                    notificationQueryParams.getFilter());
+                    notificationQueryParams.getFilter(), false);
             listener.setCloseVars(handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
             final NormalizedNode mapToStreams =
                     RestconfMappingNodeUtil.mapYangNotificationStreamByIetfRestconfMonitoring(listener.getSchemaPath().getLastComponent(),
@@ -124,6 +141,18 @@ public final class SubscribeToStreamUtil {
         return uri;
     }
 
+    static List<NotificationListenerAdapter>
+            pickSpecificListenerByOutput(final List<NotificationListenerAdapter> listeners, final String outputType) {
+        for (final NotificationListenerAdapter notificationListenerAdapter : listeners) {
+            if (notificationListenerAdapter.getOutputType().equals(outputType)) {
+                final List<NotificationListenerAdapter> list = new ArrayList<>();
+                list.add(notificationListenerAdapter);
+                return list;
+            }
+        }
+        return listeners;
+    }
+
     /**
      * Prepare InstanceIdentifierContext for Location leaf
      *
@@ -186,7 +215,7 @@ public final class SubscribeToStreamUtil {
         Preconditions.checkNotNull(listener, "Listener doesn't exist : " + streamName);
 
         listener.setQueryParams(notificationQueryParams.getStart(), notificationQueryParams.getStop(),
-                notificationQueryParams.getFilter());
+                notificationQueryParams.getFilter(), false);
         listener.setCloseVars(handlersHolder.getTransactionChainHandler(), handlersHolder.getSchemaHandler());
 
         registration(ds, scope, listener, handlersHolder.getDomDataBrokerHandler().get());
@@ -216,41 +245,28 @@ public final class SubscribeToStreamUtil {
 
     /**
      * Parse input of query parameters - start-time or stop-time - from
-     * {@link DateAndTime} format to {@link Date} format
+     * {@link DateAndTime} format to {@link Instant} format
      *
      * @param entry
      *            - start-time or stop-time as string in {@link DateAndTime}
      *            format
-     * @return parsed {@link Date} by entry
+     * @return parsed {@link Instant} by entry
      */
-    public static Date parseDateFromQueryParam(final Entry<String, List<String>> entry) {
+    public static Instant parseDateFromQueryParam(final Entry<String, List<String>> entry) {
         final DateAndTime event = new DateAndTime(entry.getValue().iterator().next());
-        String numOf_ms = "";
         final String value = event.getValue();
-        if (value.contains(".")) {
-            numOf_ms = numOf_ms + ".";
-            final int lastChar = value.contains("Z") ? value.indexOf("Z") : (value.contains("+") ? value.indexOf("+")
-                    : (value.contains("-") ? value.indexOf("-") : value.length()));
-            for (int i = 0; i < (lastChar - value.indexOf(".") - 1); i++) {
-                numOf_ms = numOf_ms + "S";
-            }
-        }
-        String zone = "";
-        if (!value.contains("Z")) {
-            zone = zone + "XXX";
-        }
-        final DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" + numOf_ms + zone);
-
+        final TemporalAccessor p;
         try {
-            return dateFormatter.parse(value.contains("Z") ? value.replace('T', ' ').substring(0, value.indexOf("Z"))
-                    : value.replace('T', ' '));
-        } catch (final ParseException e) {
-            throw new RestconfDocumentedException("Cannot parse of value in date: " + value + e);
+            p = FORMATTER.parse(value);
+        } catch (DateTimeParseException e) {
+            throw new RestconfDocumentedException("Cannot parse of value in date: " + value, e);
         }
+        return Instant.from(p);
+
     }
 
     @SuppressWarnings("rawtypes")
-    private static void writeDataToDS(final SchemaContext schemaContext, final String name,
+    static void writeDataToDS(final SchemaContext schemaContext, final String name,
             final DOMDataReadWriteTransaction wTx, final boolean exist, final NormalizedNode mapToStreams) {
         String pathId = "";
         if (exist) {
@@ -262,7 +278,7 @@ public final class SubscribeToStreamUtil {
                 mapToStreams);
     }
 
-    private static void submitData(final DOMDataReadWriteTransaction wTx) {
+    static void submitData(final DOMDataReadWriteTransaction wTx) {
         try {
             wTx.submit().checkedGet();
         } catch (final TransactionCommitFailedException e) {
@@ -279,8 +295,7 @@ public final class SubscribeToStreamUtil {
      */
     public static Map<String, String> mapValuesFromUri(final String identifier) {
         final HashMap<String, String> result = new HashMap<>();
-        final String[] tokens = identifier.split(String.valueOf(RestconfConstants.SLASH));
-        for (final String token : tokens) {
+        for (final String token : RestconfConstants.SLASH_SPLITTER.split(identifier)) {
             final String[] paramToken = token.split(String.valueOf(RestconfStreamsConstants.EQUAL));
             if (paramToken.length == 2) {
                 result.put(paramToken[0], paramToken[1]);
@@ -289,7 +304,7 @@ public final class SubscribeToStreamUtil {
         return result;
     }
 
-    private static URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
+    static URI prepareUriByStreamName(final UriInfo uriInfo, final String streamName) {
         final int port = SubscribeToStreamUtil.prepareNotificationPort();
 
         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
@@ -342,7 +357,7 @@ public final class SubscribeToStreamUtil {
         return port;
     }
 
-    private static boolean checkExist(final SchemaContext schemaContext, final DOMDataReadWriteTransaction wTx) {
+    static boolean checkExist(final SchemaContext schemaContext, final DOMDataReadWriteTransaction wTx) {
         boolean exist;
         try {
             exist = wTx.exists(LogicalDatastoreType.OPERATIONAL,