Bug 5679 - implement ietf-restconf-monitoring - cleanup
[netconf.git] / restconf / sal-rest-connector / src / main / java / org / opendaylight / restconf / restful / utils / CreateStreamUtil.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.restful.utils;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.util.concurrent.CheckedFuture;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Iterator;
16 import java.util.List;
17 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
18 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
19 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
20 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
21 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
22 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
23 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
24 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
25 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
26 import org.opendaylight.restconf.common.references.SchemaContextRef;
27 import org.opendaylight.restconf.utils.parser.ParserIdentifier;
28 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
31 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
33 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
36 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
38 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
39 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Util class for streams
49  *
50  * <ul>
51  * <li>create stream
52  * <li>subscribe
53  * </ul>
54  *
55  */
56 public final class CreateStreamUtil {
57
58     private static final Logger LOG = LoggerFactory.getLogger(CreateStreamUtil.class);
59     private static final String OUTPUT_TYPE_PARAM_NAME = "notification-output-type";
60
61     private CreateStreamUtil() {
62         throw new UnsupportedOperationException("Util class");
63     }
64
65     /**
66      * Create stream with POST operation via RPC
67      *
68      * @param payload
69      *            - input of rpc - example in JSON:
70      *
71      *            <pre>
72      *            {@code
73      *            {
74      *                "input": {
75      *                    "path": "/toaster:toaster/toaster:toasterStatus",
76      *                    "sal-remote-augment:datastore": "OPERATIONAL",
77      *                    "sal-remote-augment:scope": "ONE"
78      *                }
79      *            }
80      *            }
81      *            </pre>
82      *
83      * @param refSchemaCtx
84      *            - reference to {@link SchemaContext} -
85      *            {@link SchemaContextRef}
86      * @return {@link CheckedFuture} with {@link DOMRpcResult} - This mean
87      *         output of RPC - example in JSON:
88      *
89      *         <pre>
90      *         {@code
91      *         {
92      *             "output": {
93      *                 "stream-name": "toaster:toaster/toaster:toasterStatus/datastore=OPERATIONAL/scope=ONE"
94      *             }
95      *         }
96      *         }
97      *         </pre>
98      *
99      */
100     public static DOMRpcResult createDataChangeNotifiStream(final NormalizedNodeContext payload,
101             final SchemaContextRef refSchemaCtx) {
102         final ContainerNode data = (ContainerNode) payload.getData();
103         final QName qname = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
104         final YangInstanceIdentifier path = preparePath(data, qname);
105         String streamName = prepareDataChangeNotifiStreamName(path, refSchemaCtx.get(), data);
106
107         final QName outputQname = QName.create(qname, "output");
108         final QName streamNameQname = QName.create(qname, "stream-name");
109
110         final NotificationOutputType outputType = prepareOutputType(data);
111         if(outputType.equals(NotificationOutputType.JSON)){
112             streamName = streamName + "/JSON";
113         }
114
115         if (!Notificator.existListenerFor(streamName)) {
116             Notificator.createListener(path, streamName, outputType);
117         }
118
119         final ContainerNode output =
120                 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
121                         .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
122         return new DefaultDOMRpcResult(output);
123     }
124
125     /**
126      * @param data
127      *            - data of notification
128      * @return output type fo notification
129      */
130     private static NotificationOutputType prepareOutputType(final ContainerNode data) {
131         NotificationOutputType outputType = parseEnum(data, NotificationOutputType.class, OUTPUT_TYPE_PARAM_NAME);
132         return outputType = outputType == null ? NotificationOutputType.XML : outputType;
133     }
134
135     private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path, final SchemaContext schemaContext,
136             final ContainerNode data) {
137         LogicalDatastoreType ds = parseEnum(data, LogicalDatastoreType.class,
138                 RestconfStreamsConstants.DATASTORE_PARAM_NAME);
139         ds = ds == null ? RestconfStreamsConstants.DEFAULT_DS : ds;
140
141         DataChangeScope scope = parseEnum(data, DataChangeScope.class, RestconfStreamsConstants.SCOPE_PARAM_NAME);
142         scope = scope == null ? RestconfStreamsConstants.DEFAULT_SCOPE : scope;
143
144         final String streamName = RestconfStreamsConstants.DATA_SUBSCR + "/"
145                 + Notificator
146                 .createStreamNameFromUri(ParserIdentifier.stringFromYangInstanceIdentifier(path, schemaContext)
147                 + RestconfStreamsConstants.DS_URI + ds + RestconfStreamsConstants.SCOPE_URI + scope);
148         return streamName;
149     }
150
151     private static <T> T parseEnum(final ContainerNode data, final Class<T> clazz, final String paramName) {
152         final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = data
153                 .getChild(RestconfStreamsConstants.SAL_REMOTE_AUG_IDENTIFIER);
154         if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
155             return null;
156         }
157         final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
158                 ((AugmentationNode) augNode.get()).getChild(
159                         new NodeIdentifier(QName.create(RestconfStreamsConstants.SAL_REMOTE_AUGMENT, paramName)));
160         if (!enumNode.isPresent()) {
161             return null;
162         }
163         final Object value = enumNode.get().getValue();
164         if (!(value instanceof String)) {
165             return null;
166         }
167
168         return ResolveEnumUtil.resolveEnum(clazz, (String) value);
169     }
170
171     private static YangInstanceIdentifier preparePath(final ContainerNode data, final QName qName) {
172         final Optional<DataContainerChild<? extends PathArgument, ?>> path = data
173                 .getChild(new YangInstanceIdentifier.NodeIdentifier(QName.create(qName, "path")));
174         Object pathValue = null;
175         if (path.isPresent()) {
176             pathValue = path.get().getValue();
177         }
178         if (!(pathValue instanceof YangInstanceIdentifier)) {
179             final String errMsg = "Instance identifier was not normalized correctly ";
180             LOG.debug(errMsg + qName);
181             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
182         }
183         return (YangInstanceIdentifier) pathValue;
184     }
185
186     /**
187      * Create stream with POST operation via RPC
188      *
189      * @param payload
190      *            - input of RPC
191      * @param refSchemaCtx
192      *            - schemaContext
193      * @return {@link DOMRpcResult}
194      */
195     public static DOMRpcResult createYangNotifiStream(final NormalizedNodeContext payload,
196             final SchemaContextRef refSchemaCtx) {
197         final ContainerNode data = (ContainerNode) payload.getData();
198         LeafSetNode leafSet = null;
199         String outputType = "XML";
200         for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
201             if (dataChild instanceof LeafSetNode) {
202                 leafSet = (LeafSetNode) dataChild;
203             } else if (dataChild instanceof AugmentationNode) {
204                 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
205             }
206         }
207
208         final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
209         final List<SchemaPath> paths = new ArrayList<>();
210         String streamName = RestconfStreamsConstants.CREATE_NOTIFICATION_STREAM + "/";
211
212         final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
213         while (iterator.hasNext()) {
214             final QName valueQName = QName.create((String) iterator.next().getValue());
215             final Module module = refSchemaCtx.findModuleByNamespaceAndRevision(valueQName.getModule().getNamespace(),
216                     valueQName.getModule().getRevision());
217             Preconditions.checkNotNull(module,
218                     "Module for namespace " + valueQName.getModule().getNamespace() + " does not exist");
219             NotificationDefinition notifiDef = null;
220             for (final NotificationDefinition notification : module.getNotifications()) {
221                 if (notification.getQName().equals(valueQName)) {
222                     notifiDef = notification;
223                     break;
224                 }
225             }
226             final String moduleName = module.getName();
227             Preconditions.checkNotNull(notifiDef,
228                     "Notification " + valueQName + "doesn't exist in module " + moduleName);
229             paths.add(notifiDef.getPath());
230             streamName = streamName + moduleName + ":" + valueQName.getLocalName();
231             if (iterator.hasNext()) {
232                 streamName = streamName + ",";
233             }
234         }
235         if (outputType.equals("JSON")) {
236             streamName = streamName + "/JSON";
237         }
238         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
239         final QName outputQname = QName.create(rpcQName, "output");
240         final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
241
242         final ContainerNode output =
243                 ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
244                         .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
245
246         if (!Notificator.existNotificationListenerFor(streamName)) {
247             Notificator.createNotificationListener(paths, streamName, outputType);
248         }
249
250         return new DefaultDOMRpcResult(output);
251     }
252 }