2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.rests.services.impl;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.collect.ImmutableSet;
13 import java.util.Optional;
14 import org.eclipse.jdt.annotation.Nullable;
15 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
16 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
17 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
18 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
19 import org.opendaylight.restconf.nb.rfc8040.legacy.NormalizedNodePayload;
20 import org.opendaylight.restconf.nb.rfc8040.rests.utils.RestconfStreamsConstants;
21 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.ListenersBroker;
22 import org.opendaylight.restconf.nb.rfc8040.streams.listeners.NotificationListenerAdapter;
23 import org.opendaylight.restconf.nb.rfc8040.utils.parser.IdentifierCodec;
24 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.CreateDataChangeEventSubscriptionInput1.Scope;
25 import org.opendaylight.yang.gen.v1.urn.sal.restconf.event.subscription.rev140708.NotificationOutputTypeGrouping.NotificationOutputType;
26 import org.opendaylight.yangtools.yang.common.ErrorTag;
27 import org.opendaylight.yangtools.yang.common.ErrorType;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.common.QNameModule;
30 import org.opendaylight.yangtools.yang.common.Revision;
31 import org.opendaylight.yangtools.yang.common.XMLNamespace;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
38 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
40 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
41 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
44 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Utility class for creation of data-change-event or YANG notification streams.
51 final class CreateStreamUtil {
52 private static final Logger LOG = LoggerFactory.getLogger(CreateStreamUtil.class);
53 private static final QNameModule SAL_REMOTE_AUGMENT = QNameModule.create(
54 XMLNamespace.of("urn:sal:restconf:event:subscription"), Revision.of("2014-07-08"));
55 private static final QName DATASTORE_QNAME =
56 QName.create(SAL_REMOTE_AUGMENT, RestconfStreamsConstants.DATASTORE_PARAM_NAME).intern();
57 private static final QName SCOPE_QNAME =
58 QName.create(SAL_REMOTE_AUGMENT, RestconfStreamsConstants.SCOPE_PARAM_NAME).intern();
59 private static final QName OUTPUT_TYPE_QNAME =
60 QName.create(SAL_REMOTE_AUGMENT, "notification-output-type").intern();
61 private static final NodeIdentifier DATASTORE_NODEID = NodeIdentifier.create(DATASTORE_QNAME);
62 private static final NodeIdentifier SCOPE_NODEID = NodeIdentifier.create(SCOPE_QNAME);
63 private static final NodeIdentifier OUTPUT_TYPE_NODEID = NodeIdentifier.create(OUTPUT_TYPE_QNAME);
65 private static final AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER = new AugmentationIdentifier(
66 ImmutableSet.of(SCOPE_QNAME, DATASTORE_QNAME, OUTPUT_TYPE_QNAME));
68 private CreateStreamUtil() {
73 * Create data-change-event or notification stream with POST operation via RPC.
75 * @param payload Input of RPC - example in JSON (data-change-event stream):
80 * "path": "/toaster:toaster/toaster:toasterStatus",
81 * "sal-remote-augment:datastore": "OPERATIONAL",
82 * "sal-remote-augment:scope": "ONE"
87 * @param refSchemaCtx Reference to {@link EffectiveModelContext}.
88 * @return {@link DOMRpcResult} - Output of RPC - example in JSON:
93 * "stream-name": "toaster:toaster/toaster:toasterStatus/datastore=OPERATIONAL/scope=ONE"
99 static DOMRpcResult createDataChangeNotifiStream(final NormalizedNodePayload payload,
100 final EffectiveModelContext refSchemaCtx) {
101 // parsing out of container with settings and path
102 final ContainerNode data = (ContainerNode) requireNonNull(payload).getData();
103 final QName qname = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
104 final YangInstanceIdentifier path = preparePath(data, qname);
106 // building of stream name
107 final StringBuilder streamNameBuilder = new StringBuilder(
108 prepareDataChangeNotifiStreamName(path, requireNonNull(refSchemaCtx), data));
109 final NotificationOutputType outputType = prepareOutputType(data);
110 if (outputType.equals(NotificationOutputType.JSON)) {
111 streamNameBuilder.append('/').append(outputType.getName());
113 final String streamName = streamNameBuilder.toString();
115 // registration of the listener
116 ListenersBroker.getInstance().registerDataChangeListener(path, streamName, outputType);
118 // building of output
119 final QName outputQname = QName.create(qname, "output");
120 final QName streamNameQname = QName.create(qname, "stream-name");
122 final ContainerNode output = ImmutableContainerNodeBuilder.create()
123 .withNodeIdentifier(new NodeIdentifier(outputQname))
124 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
125 return new DefaultDOMRpcResult(output);
129 * Prepare {@link NotificationOutputType}.
131 * @param data Container with stream settings (RPC create-stream).
132 * @return Parsed {@link NotificationOutputType}.
134 private static NotificationOutputType prepareOutputType(final ContainerNode data) {
135 final String outputName = extractStringLeaf(data, OUTPUT_TYPE_NODEID);
136 return outputName != null ? NotificationOutputType.valueOf(outputName) : NotificationOutputType.XML;
140 * Prepare stream name.
142 * @param path Path of element from which data-change-event notifications are going to be generated.
143 * @param schemaContext Schema context.
144 * @param data Container with stream settings (RPC create-stream).
145 * @return Parsed stream name.
147 private static String prepareDataChangeNotifiStreamName(final YangInstanceIdentifier path,
148 final EffectiveModelContext schemaContext, final ContainerNode data) {
149 final String datastoreName = extractStringLeaf(data, DATASTORE_NODEID);
150 final LogicalDatastoreType datastoreType = datastoreName != null ? LogicalDatastoreType.valueOf(datastoreName)
151 : LogicalDatastoreType.CONFIGURATION;
153 final String scopeName = extractStringLeaf(data, SCOPE_NODEID);
154 // FIXME: this is not really used
155 final Scope scope = scopeName != null ? Scope.forName(scopeName).orElseThrow() : Scope.BASE;
157 return RestconfStreamsConstants.DATA_SUBSCRIPTION
158 + "/" + ListenersBroker.createStreamNameFromUri(IdentifierCodec.serialize(path, schemaContext)
159 + "/" + RestconfStreamsConstants.DATASTORE_PARAM_NAME + "=" + datastoreType
160 + "/" + RestconfStreamsConstants.SCOPE_PARAM_NAME + "=" + scope);
164 * Prepare {@link YangInstanceIdentifier} of stream source.
166 * @param data Container with stream settings (RPC create-stream).
167 * @param qualifiedName QName of the input RPC context (used only in debugging).
168 * @return Parsed {@link YangInstanceIdentifier} of data element from which the data-change-event notifications
169 * are going to be generated.
171 private static YangInstanceIdentifier preparePath(final ContainerNode data, final QName qualifiedName) {
172 final Object pathValue = data.findChildByArg(new NodeIdentifier(QName.create(qualifiedName, "path")))
173 .map(DataContainerChild::body)
175 if (!(pathValue instanceof YangInstanceIdentifier)) {
176 LOG.debug("Instance identifier {} was not normalized correctly", qualifiedName);
177 throw new RestconfDocumentedException(
178 "Instance identifier was not normalized correctly",
179 ErrorType.APPLICATION,
180 ErrorTag.OPERATION_FAILED);
182 return (YangInstanceIdentifier) pathValue;
185 private static @Nullable String extractStringLeaf(final ContainerNode data, final NodeIdentifier childName) {
186 final DataContainerChild augNode = data.childByArg(SAL_REMOTE_AUG_IDENTIFIER);
187 if (augNode instanceof AugmentationNode) {
188 final DataContainerChild enumNode = ((AugmentationNode) augNode).childByArg(childName);
189 if (enumNode instanceof LeafNode) {
190 final Object value = enumNode.body();
191 if (value instanceof String) {
192 return (String) value;
200 * Create YANG notification stream using notification definition in YANG schema.
202 * @param notificationDefinition YANG notification definition.
203 * @param refSchemaCtx Reference to {@link EffectiveModelContext}
204 * @param outputType Output type (XML or JSON).
205 * @return {@link NotificationListenerAdapter}
207 static NotificationListenerAdapter createYangNotifiStream(final NotificationDefinition notificationDefinition,
208 final EffectiveModelContext refSchemaCtx, final NotificationOutputType outputType) {
209 final String streamName = parseNotificationStreamName(requireNonNull(notificationDefinition),
210 requireNonNull(refSchemaCtx), requireNonNull(outputType.getName()));
211 final Optional<NotificationListenerAdapter> listenerForStreamName = ListenersBroker.getInstance()
212 .getNotificationListenerFor(streamName);
213 return listenerForStreamName.orElseGet(() -> ListenersBroker.getInstance().registerNotificationListener(
214 Absolute.of(notificationDefinition.getQName()), streamName, outputType));
217 private static String parseNotificationStreamName(final NotificationDefinition notificationDefinition,
218 final EffectiveModelContext refSchemaCtx, final String outputType) {
219 final QName notificationDefinitionQName = notificationDefinition.getQName();
220 final Module module = refSchemaCtx.findModule(
221 notificationDefinitionQName.getModule().getNamespace(),
222 notificationDefinitionQName.getModule().getRevision()).orElse(null);
223 requireNonNull(module, String.format("Module for namespace %s does not exist.",
224 notificationDefinitionQName.getModule().getNamespace()));
226 final StringBuilder streamNameBuilder = new StringBuilder();
227 streamNameBuilder.append(RestconfStreamsConstants.NOTIFICATION_STREAM)
229 .append(module.getName())
231 .append(notificationDefinitionQName.getLocalName());
232 if (outputType.equals(NotificationOutputType.JSON.getName())) {
233 streamNameBuilder.append('/').append(NotificationOutputType.JSON.getName());
235 return streamNameBuilder.toString();