Lower NotificationListenerAdapter
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / streams / listeners / NotificationListenerAdapter.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.restconf.nb.rfc8040.streams.listeners;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.MoreObjects;
15 import java.time.Instant;
16 import java.util.Optional;
17 import javax.xml.xpath.XPathExpressionException;
18 import org.opendaylight.mdsal.dom.api.DOMNotification;
19 import org.opendaylight.mdsal.dom.api.DOMNotificationListener;
20 import org.opendaylight.restconf.common.formatters.JSONNotificationFormatter;
21 import org.opendaylight.restconf.common.formatters.NotificationFormatter;
22 import org.opendaylight.restconf.common.formatters.NotificationFormatterFactory;
23 import org.opendaylight.restconf.common.formatters.XMLNotificationFormatter;
24 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
25 import org.opendaylight.yangtools.yang.data.codec.gson.JSONCodecFactorySupplier;
26 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
27 import org.slf4j.Logger;
28 import org.slf4j.LoggerFactory;
29
30 /**
31  * {@link NotificationListenerAdapter} is responsible to track events on notifications.
32  */
33 public class NotificationListenerAdapter extends AbstractCommonSubscriber implements DOMNotificationListener {
34
35     private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerAdapter.class);
36     private static final NotificationFormatterFactory JSON_FORMATTER_FACTORY = JSONNotificationFormatter.createFactory(
37             JSONCodecFactorySupplier.RFC7951);
38
39     private final String streamName;
40     private final Absolute path;
41     private final NotificationOutputType outputType;
42
43     @VisibleForTesting NotificationFormatter formatter;
44
45
46     /**
47      * Set path of listener and stream name.
48      *
49      * @param path       Schema path of YANG notification.
50      * @param streamName Name of the stream.
51      * @param outputType Type of output on notification (JSON or XML).
52      */
53     NotificationListenerAdapter(final Absolute path, final String streamName, final String outputType) {
54         setLocalNameOfPath(path.lastNodeIdentifier().getLocalName());
55
56         this.outputType = NotificationOutputType.forName(requireNonNull(outputType)).get();
57         this.path = requireNonNull(path);
58         this.streamName = requireNonNull(streamName);
59         checkArgument(!streamName.isEmpty());
60         this.formatter = getFormatterFactory().getFormatter();
61
62         LOG.debug("output type: {}, {}", outputType, this.outputType);
63     }
64
65     private NotificationFormatterFactory getFormatterFactory() {
66         switch (outputType) {
67             case JSON:
68                 return JSON_FORMATTER_FACTORY;
69             case XML:
70                 return XMLNotificationFormatter.FACTORY;
71             default:
72                 throw new IllegalArgumentException("Unsupported outputType " + outputType);
73         }
74     }
75
76     private NotificationFormatter getFormatter(final String filter) throws XPathExpressionException {
77         NotificationFormatterFactory factory = getFormatterFactory();
78         return filter == null || filter.isEmpty() ? factory.getFormatter() : factory.getFormatter(filter);
79     }
80
81     @Override
82     public void setQueryParams(final Instant start, final Instant stop, final String filter,
83                                final boolean leafNodesOnly, final boolean skipNotificationData) {
84         super.setQueryParams(start, stop, filter, leafNodesOnly, skipNotificationData);
85         try {
86             this.formatter = getFormatter(filter);
87         } catch (XPathExpressionException e) {
88             throw new IllegalArgumentException("Failed to get filter", e);
89         }
90     }
91
92     /**
93      * Get output type of this listener.
94      *
95      * @return The configured output type (JSON or XML).
96      */
97     @Override
98     public String getOutputType() {
99         return this.outputType.getName();
100     }
101
102     @Override
103     @SuppressWarnings("checkstyle:IllegalCatch")
104     public void onNotification(final DOMNotification notification) {
105         final Instant now = Instant.now();
106         if (!checkStartStop(now, this)) {
107             return;
108         }
109
110         final Optional<String> maybeOutput;
111         try {
112             maybeOutput = formatter.eventData(schemaHandler.get(), notification, now, getLeafNodesOnly(),
113                     isSkipNotificationData());
114         } catch (Exception e) {
115             LOG.error("Failed to process notification {}", notification, e);
116             return;
117         }
118         if (maybeOutput.isPresent()) {
119             post(maybeOutput.get());
120         }
121     }
122
123     /**
124      * Get stream name of this listener.
125      *
126      * @return The configured stream name.
127      */
128     @Override
129     public String getStreamName() {
130         return this.streamName;
131     }
132
133     /**
134      * Get schema path of notification.
135      *
136      * @return The configured schema path that points to observing YANG notification schema node.
137      */
138     public Absolute getSchemaPath() {
139         return this.path;
140     }
141
142     @Override
143     public String toString() {
144         return MoreObjects.toStringHelper(this)
145                 .add("path", path)
146                 .add("stream-name", streamName)
147                 .add("output-type", outputType)
148                 .toString();
149     }
150 }