c2774b581248832510b947674089a87cbbd7d2da
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / main / java / org / opendaylight / controller / sal / restconf / impl / RestconfImpl.java
1 /**
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2014 Brocade Communication Systems, Inc.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9 package org.opendaylight.controller.sal.restconf.impl;
10
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
14 import com.google.common.base.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.Iterables;
19 import com.google.common.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
24 import java.math.BigInteger;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.concurrent.CancellationException;
37 import java.util.concurrent.ExecutionException;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.Response.ResponseBuilder;
40 import javax.ws.rs.core.Response.Status;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43 import org.apache.commons.lang3.StringUtils;
44 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
45 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
46 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
47 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
48 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.controller.md.sal.rest.common.RestconfValidationUtils;
54 import org.opendaylight.controller.sal.rest.api.Draft02;
55 import org.opendaylight.controller.sal.rest.api.RestconfService;
56 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
58 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
59 import org.opendaylight.controller.sal.streams.listeners.Notificator;
60 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.common.QNameModule;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
76 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
77 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
78 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
86 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.Module;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.util.EmptyType;
95 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
96 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
97 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
98 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
99 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
100 import org.slf4j.Logger;
101 import org.slf4j.LoggerFactory;
102
103 public class RestconfImpl implements RestconfService {
104
105     private static final RestconfImpl INSTANCE = new RestconfImpl();
106
107     private static final int NOTIFICATION_PORT = 8181;
108
109     private static final int CHAR_NOT_FOUND = -1;
110
111     private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
112
113     private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
114
115     private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
116
117     private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
118
119     private BrokerFacade broker;
120
121     private ControllerContext controllerContext;
122
123     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
124
125     private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
126
127     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
128
129     private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
130
131     private static final String DATASTORE_PARAM_NAME = "datastore";
132
133     private static final String SCOPE_PARAM_NAME = "scope";
134
135     private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
136
137     private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
138
139     private static final QName NETCONF_BASE_QNAME;
140
141     private static final QNameModule SAL_REMOTE_AUGMENT;
142
143     private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
144
145     static {
146         try {
147             final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
148             NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
149             SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
150                     eventSubscriptionAugRevision);
151             SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
152                     QName.create(SAL_REMOTE_AUGMENT, "datastore")));
153         } catch (final ParseException e) {
154             final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
155             LOG.debug(errMsg);
156             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
157         } catch (final URISyntaxException e) {
158             final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
159             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
160         }
161     }
162
163     public void setBroker(final BrokerFacade broker) {
164         this.broker = broker;
165     }
166
167     public void setControllerContext(final ControllerContext controllerContext) {
168         this.controllerContext = controllerContext;
169     }
170
171     private RestconfImpl() {
172     }
173
174     public static RestconfImpl getInstance() {
175         return INSTANCE;
176     }
177
178     @Override
179     public NormalizedNodeContext getModules(final UriInfo uriInfo) {
180         final Set<Module> allModules = controllerContext.getAllModules();
181         final MapNode allModuleMap = makeModuleMapNode(allModules);
182
183         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
184
185         final Module restconfModule = getRestconfModule();
186         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
187                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
188         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
189
190         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
191                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
192         moduleContainerBuilder.withChild(allModuleMap);
193
194         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
195                 null, schemaContext), moduleContainerBuilder.build(),
196                 QueryParametersParser.parseWriterParameters(uriInfo));
197     }
198
199     /**
200      * Valid only for mount point
201      */
202     @Override
203     public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
204         Preconditions.checkNotNull(identifier);
205         if ( ! identifier.contains(ControllerContext.MOUNT)) {
206             final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
207                     + " URI has to end with " + ControllerContext.MOUNT;
208             LOG.debug(errMsg + " for " + identifier);
209             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
210         }
211
212         final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
213         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
214         final Set<Module> modules = controllerContext.getAllModules(mountPoint);
215         final MapNode mountPointModulesMap = makeModuleMapNode(modules);
216
217         final Module restconfModule = getRestconfModule();
218         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
219                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
220         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
221
222         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
223                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
224         moduleContainerBuilder.withChild(mountPointModulesMap);
225
226         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
227                 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
228                 QueryParametersParser.parseWriterParameters(uriInfo));
229     }
230
231     @Override
232     public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
233         Preconditions.checkNotNull(identifier);
234         final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
235         Module module = null;
236         DOMMountPoint mountPoint = null;
237         final SchemaContext schemaContext;
238         if (identifier.contains(ControllerContext.MOUNT)) {
239             final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
240             mountPoint = mountPointIdentifier.getMountPoint();
241             module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
242             schemaContext = mountPoint.getSchemaContext();
243         } else {
244             module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
245             schemaContext = controllerContext.getGlobalSchema();
246         }
247
248         if (module == null) {
249             final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
250                     + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
251             LOG.debug(errMsg);
252             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
253         }
254
255         final Module restconfModule = getRestconfModule();
256         final Set<Module> modules = Collections.singleton(module);
257         final MapNode moduleMap = makeModuleMapNode(modules);
258
259         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
260                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
261         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
262
263         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
264                 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
265     }
266
267     @Override
268     public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
269         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
270         final Set<String> availableStreams = Notificator.getStreamNames();
271         final Module restconfModule = getRestconfModule();
272         final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
273                 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
274         Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
275
276         final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
277                 .mapBuilder((ListSchemaNode) streamSchemaNode);
278
279         for (final String streamName : availableStreams) {
280             listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
281         }
282
283         final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
284                 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
285         Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
286
287         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
288                 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
289         streamsContainerBuilder.withChild(listStreamsBuilder.build());
290
291
292         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
293                 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
294     }
295
296     @Override
297     public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
298         final Set<Module> allModules = controllerContext.getAllModules();
299         return operationsFromModulesToNormalizedContext(allModules, null);
300     }
301
302     @Override
303     public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
304         Set<Module> modules = null;
305         DOMMountPoint mountPoint = null;
306         if (identifier.contains(ControllerContext.MOUNT)) {
307             final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
308             mountPoint = mountPointIdentifier.getMountPoint();
309             modules = controllerContext.getAllModules(mountPoint);
310
311         } else {
312             final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
313             LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
314             throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
315         }
316
317         return operationsFromModulesToNormalizedContext(modules, mountPoint);
318     }
319
320     private static final Predicate<GroupingBuilder> GROUPING_FILTER = new Predicate<GroupingBuilder>() {
321         @Override
322         public boolean apply(final GroupingBuilder g) {
323             return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
324         }
325     };
326
327     private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
328             final DOMMountPoint mountPoint) {
329
330         final Module restconfModule = getRestconfModule();
331         final ModuleBuilder restConfModuleBuilder = new ModuleBuilder(restconfModule);
332         final Set<GroupingBuilder> gropingBuilders = restConfModuleBuilder.getGroupingBuilders();
333         final Iterable<GroupingBuilder> filteredGroups = Iterables.filter(gropingBuilders, GROUPING_FILTER);
334         final GroupingBuilder restconfGroupingBuilder = Iterables.getFirst(filteredGroups, null);
335         final ContainerSchemaNodeBuilder restContainerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restconfGroupingBuilder
336                 .getDataChildByName(Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
337         final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restContainerSchemaNodeBuilder
338                 .getDataChildByName(Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
339
340         final ContainerSchemaNodeBuilder fakeOperationsSchemaNodeBuilder = containerSchemaNodeBuilder;
341         final SchemaPath fakeSchemaPath = fakeOperationsSchemaNodeBuilder.getPath().createChild(QName.create("dummy"));
342
343         final List<LeafNode<Object>> operationsAsData = new ArrayList<>();
344
345         for (final Module module : modules) {
346             final Set<RpcDefinition> rpcs = module.getRpcs();
347             for (final RpcDefinition rpc : rpcs) {
348                 final QName rpcQName = rpc.getQName();
349                 final String name = module.getName();
350
351                 final QName qName = QName.create(restconfModule.getQNameModule(), rpcQName.getLocalName());
352                 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, qName, fakeSchemaPath);
353                 final LeafSchemaNodeBuilder fakeRpcSchemaNodeBuilder = leafSchemaNodeBuilder;
354                 fakeRpcSchemaNodeBuilder.setAugmenting(true);
355
356                 final EmptyType instance = EmptyType.getInstance();
357                 fakeRpcSchemaNodeBuilder.setType(instance);
358                 final LeafSchemaNode fakeRpcSchemaNode = fakeRpcSchemaNodeBuilder.build();
359                 fakeOperationsSchemaNodeBuilder.addChildNode(fakeRpcSchemaNode);
360
361                 final LeafNode<Object> leaf = Builders.leafBuilder(fakeRpcSchemaNode).build();
362                 operationsAsData.add(leaf);
363             }
364         }
365
366         final ContainerSchemaNode operContainerSchemaNode = fakeOperationsSchemaNodeBuilder.build();
367         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> operContainerNode = Builders.containerBuilder(operContainerSchemaNode);
368
369         for (final LeafNode<Object> oper : operationsAsData) {
370             operContainerNode.withChild(oper);
371         }
372
373         final Set<Module> fakeRpcModules = Collections.singleton(restConfModuleBuilder.build());
374
375         final YangParserImpl yangParser = new YangParserImpl();
376         final SchemaContext fakeSchemaCx = yangParser.resolveSchemaContext(fakeRpcModules);
377
378         final InstanceIdentifierContext<?> fakeIICx = new InstanceIdentifierContext<>(null, operContainerSchemaNode, mountPoint, fakeSchemaCx);
379
380         return new NormalizedNodeContext(fakeIICx, operContainerNode.build());
381     }
382
383     private Module getRestconfModule() {
384         final Module restconfModule = controllerContext.getRestconfModule();
385         if (restconfModule == null) {
386             LOG.debug("ietf-restconf module was not found.");
387             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
388                     ErrorTag.OPERATION_NOT_SUPPORTED);
389         }
390
391         return restconfModule;
392     }
393
394     private QName getModuleNameAndRevision(final String identifier) {
395         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
396         String moduleNameAndRevision = "";
397         if (mountIndex >= 0) {
398             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
399         } else {
400             moduleNameAndRevision = identifier;
401         }
402
403         final Splitter splitter = Splitter.on("/").omitEmptyStrings();
404         final Iterable<String> split = splitter.split(moduleNameAndRevision);
405         final List<String> pathArgs = Lists.<String> newArrayList(split);
406         if (pathArgs.size() < 2) {
407             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
408             throw new RestconfDocumentedException(
409                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
410                     ErrorTag.INVALID_VALUE);
411         }
412
413         try {
414             final String moduleName = pathArgs.get(0);
415             final String revision = pathArgs.get(1);
416             final Date moduleRevision = REVISION_FORMAT.parse(revision);
417             return QName.create(null, moduleRevision, moduleName);
418         } catch (final ParseException e) {
419             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
420             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
421                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
422         }
423     }
424
425     @Override
426     public Object getRoot() {
427         return null;
428     }
429
430     @Override
431     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
432         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getSchemaNode() != null);
433         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getSchemaNode() instanceof RpcDefinition);
434         final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
435         final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
436         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
437         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
438         final SchemaContext schemaContext;
439         if (identifier.contains(MOUNT_POINT_MODULE_NAME) && mountPoint != null) {
440             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
441             if ( ! mountRpcServices.isPresent()) {
442                 LOG.debug("Error: Rpc service is missing.");
443                 throw new RestconfDocumentedException("Rpc service is missing.");
444             }
445             schemaContext = mountPoint.getSchemaContext();
446             response = mountRpcServices.get().invokeRpc(type, payload.getData());
447         } else {
448             if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
449                 response = invokeSalRemoteRpcSubscribeRPC(payload);
450             } else {
451                 response = broker.invokeRpc(type, payload.getData());
452             }
453             schemaContext = controllerContext.getGlobalSchema();
454         }
455
456         final DOMRpcResult result = checkRpcResponse(response);
457         final RpcDefinition rpcSchemaNode = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
458
459         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcSchemaNode, mountPoint,
460                 schemaContext), result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
461     }
462
463     private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
464         if (response == null) {
465             return null;
466         }
467         try {
468             final DOMRpcResult retValue = response.get();
469             if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
470                 return retValue;
471             }
472             LOG.debug("RpcError message", retValue.getErrors());
473             throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
474         } catch (final InterruptedException e) {
475             final String errMsg = "The operation was interrupted while executing and did not complete.";
476             LOG.debug("Rpc Interrupt - " + errMsg, e);
477             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
478         } catch (final ExecutionException e) {
479             LOG.debug("Execution RpcError: ", e);
480             Throwable cause = e.getCause();
481             if (cause != null) {
482                 while (cause.getCause() != null) {
483                     cause = cause.getCause();
484                 }
485
486                 if (cause instanceof IllegalArgumentException) {
487                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
488                 }
489                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
490             }
491             throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.", e);
492         } catch (final CancellationException e) {
493             final String errMsg = "The operation was cancelled while executing.";
494             LOG.debug("Cancel RpcExecution: " + errMsg, e);
495             throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
496         }
497     }
498
499     private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
500         if (inputSchema != null && payload.getData() == null) {
501             // expected a non null payload
502             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
503         } else if (inputSchema == null && payload.getData() != null) {
504             // did not expect any input
505             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
506         }
507         // else
508         // {
509         // TODO: Validate "mandatory" and "config" values here??? Or should those be
510         // those be
511         // validate in a more central location inside MD-SAL core.
512         // }
513     }
514
515     private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
516         final ContainerNode value = (ContainerNode) payload.getData();
517         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
518         final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
519                 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
520         final Object pathValue = path.isPresent() ? path.get().getValue() : null;
521
522         if (!(pathValue instanceof YangInstanceIdentifier)) {
523             final String errMsg = "Instance identifier was not normalized correctly ";
524             LOG.debug(errMsg + rpcQName);
525             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
526         }
527
528         final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
529         String streamName = null;
530         if (!pathIdentifier.isEmpty()) {
531             final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
532
533             LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
534             datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
535
536             DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
537             scope = scope == null ? DEFAULT_SCOPE : scope;
538
539             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
540                     + "/scope=" + scope);
541         }
542
543         if (Strings.isNullOrEmpty(streamName)) {
544             final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
545             LOG.debug(errMsg + pathIdentifier);
546             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
547         }
548
549         final RpcDefinition rpcSchemaNode = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
550         RestconfValidationUtils.checkDocumentedError(rpcSchemaNode != null, ErrorType.RPC, ErrorTag.INVALID_VALUE,
551                 "Create stream RPC output can not be null!");
552
553         final QName outputQname = rpcSchemaNode.getOutput().getQName();
554         final QName streamNameQname = QName.create(rpcQName, "stream-name");
555
556         final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
557                 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
558
559         if (!Notificator.existListenerFor(streamName)) {
560             Notificator.createListener(pathIdentifier, streamName);
561         }
562
563         final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
564         return Futures.immediateCheckedFuture(defaultDOMRpcResult);
565     }
566
567     @Override
568     public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
569         if (StringUtils.isNotBlank(noPayload)) {
570             throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
571         }
572
573         String identifierEncoded = null;
574         DOMMountPoint mountPoint = null;
575         final SchemaContext schemaContext;
576         if (identifier.contains(ControllerContext.MOUNT)) {
577             // mounted RPC call - look up mount instance.
578             final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
579             mountPoint = mountPointId.getMountPoint();
580             schemaContext = mountPoint.getSchemaContext();
581             final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
582                     + ControllerContext.MOUNT.length() + 1;
583             final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
584             identifierEncoded = remoteRpcName;
585
586         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
587             final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
588                     + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
589             LOG.debug(slashErrorMsg);
590             throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
591         } else {
592             identifierEncoded = identifier;
593             schemaContext = controllerContext.getGlobalSchema();
594         }
595
596         final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
597
598         RpcDefinition rpc = null;
599         if (mountPoint == null) {
600             rpc = controllerContext.getRpcDefinition(identifierDecoded);
601         } else {
602             rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
603         }
604
605         if (rpc == null) {
606             LOG.debug("RPC " + identifierDecoded + " does not exist.");
607             throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
608         }
609
610         if (rpc.getInput() != null) {
611             LOG.debug("RPC " + rpc + " does not need input value.");
612             // FIXME : find a correct Error from specification
613             throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
614         }
615
616         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
617         if (mountPoint != null) {
618             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
619             if ( ! mountRpcServices.isPresent()) {
620                 throw new RestconfDocumentedException("Rpc service is missing.");
621             }
622             response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
623         } else {
624             response = broker.invokeRpc(rpc.getPath(), null);
625         }
626
627         final DOMRpcResult result = checkRpcResponse(response);
628
629         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
630                 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
631     }
632
633     private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
634         final String[] splittedIdentifier = identifierDecoded.split(":");
635         if (splittedIdentifier.length != 2) {
636             final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
637             LOG.debug(errMsg);
638             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
639         }
640         for (final Module module : schemaContext.getModules()) {
641             if (module.getName().equals(splittedIdentifier[0])) {
642                 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
643                     if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
644                         return rpcDefinition;
645                     }
646                 }
647             }
648         }
649         return null;
650     }
651
652     @Override
653     public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
654         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
655         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
656         NormalizedNode<?, ?> data = null;
657         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
658         if (mountPoint != null) {
659             data = broker.readConfigurationData(mountPoint, normalizedII);
660         } else {
661             data = broker.readConfigurationData(normalizedII);
662         }
663         if(data == null) {
664             final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
665             LOG.debug(errMsg + identifier);
666             throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
667         }
668         return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
669     }
670
671     @Override
672     public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
673         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
674         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
675         NormalizedNode<?, ?> data = null;
676         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
677         if (mountPoint != null) {
678             data = broker.readOperationalData(mountPoint, normalizedII);
679         } else {
680             data = broker.readOperationalData(normalizedII);
681         }
682         if(data == null) {
683             final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
684             LOG.debug(errMsg + identifier);
685             throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
686         }
687         return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
688     }
689
690     @Override
691     public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
692         Preconditions.checkNotNull(identifier);
693         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
694
695         validateInput(iiWithData.getSchemaNode(), payload);
696         validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
697         validateListKeysEqualityInPayloadAndUri(payload);
698
699         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
700         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
701
702         /*
703          * There is a small window where another write transaction could be updating the same data
704          * simultaneously and we get an OptimisticLockFailedException. This error is likely
705          * transient and The WriteTransaction#submit API docs state that a retry will likely
706          * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
707          * probably will never succeed so we'll fail in that case.
708          *
709          * By retrying we're attempting to hide the internal implementation of the data store and
710          * how it handles concurrent updates from the restconf client. The client has instructed us
711          * to put the data and we should make every effort to do so without pushing optimistic lock
712          * failures back to the client and forcing them to handle it via retry (and having to
713          * document the behavior).
714          */
715         int tries = 2;
716         while(true) {
717             try {
718                 if (mountPoint != null) {
719                     broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
720                 } else {
721                     broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
722                 }
723
724                 break;
725             } catch (final TransactionCommitFailedException e) {
726                 if(e instanceof OptimisticLockFailedException) {
727                     if(--tries <= 0) {
728                         LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
729                         throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
730                     }
731
732                     LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
733                 } else {
734                     LOG.debug("Update ConfigDataStore fail " + identifier, e);
735                     throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
736                 }
737             }
738         }
739
740         return Response.status(Status.OK).build();
741     }
742
743     private static void validateTopLevelNodeName(final NormalizedNodeContext node,
744             final YangInstanceIdentifier identifier) {
745
746         final String payloadName = node.getData().getNodeType().getLocalName();
747
748         //no arguments
749         if (identifier.isEmpty()) {
750             //no "data" payload
751             if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
752                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
753                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
754             }
755         //any arguments
756         } else {
757             final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
758             if (!payloadName.equals(identifierName)) {
759                 throw new RestconfDocumentedException("Payload name (" + payloadName
760                         + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
761                         ErrorTag.MALFORMED_MESSAGE);
762             }
763         }
764     }
765
766     /**
767      * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
768      *
769      * @throws RestconfDocumentedException
770      *             if key values or key count in payload and URI isn't equal
771      *
772      */
773     private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
774         Preconditions.checkArgument(payload != null);
775         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
776         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
777         final SchemaNode schemaNode = iiWithData.getSchemaNode();
778         final NormalizedNode<?, ?> data = payload.getData();
779         if (schemaNode instanceof ListSchemaNode) {
780             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
781             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
782                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
783                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
784             }
785         }
786     }
787
788     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
789             final MapEntryNode payload, final List<QName> keyDefinitions) {
790
791         final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
792         for (final QName keyDefinition : keyDefinitions) {
793             final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
794             // should be caught during parsing URI to InstanceIdentifier
795             RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
796                     "Missing key " + keyDefinition + " in URI.");
797
798             final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
799
800             if ( ! uriKeyValue.equals(dataKeyValue)) {
801                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
802                         "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
803                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
804             }
805         }
806     }
807
808     @Override
809     public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
810        return createConfigurationData(payload, uriInfo);
811     }
812
813     // FIXME create RestconfIdetifierHelper and move this method there
814     private YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
815         Preconditions.checkArgument(payload != null);
816         Preconditions.checkArgument(payload.getData() != null);
817         Preconditions.checkArgument(payload.getData().getNodeType() != null);
818         Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
819         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
820
821         final QName payloadNodeQname = payload.getData().getNodeType();
822         final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
823         if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
824             return yangIdent;
825         }
826         final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
827         final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
828         if(parentSchemaNode instanceof DataNodeContainer) {
829             final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
830             for (final DataSchemaNode child : cast.getChildNodes()) {
831                 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
832                     return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
833                 }
834             }
835         }
836         if (parentSchemaNode instanceof RpcDefinition) {
837             return yangIdent;
838         }
839         final String errMsg = "Error parsing input: DataSchemaNode has not children ";
840         LOG.info(errMsg + yangIdent);
841         throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
842     }
843
844     @Override
845     public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
846         if (payload == null) {
847             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
848         }
849
850         // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
851 //        final URI payloadNS = payload.getData().getNodeType().getNamespace();
852 //        if (payloadNS == null) {
853 //            throw new RestconfDocumentedException(
854 //                    "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
855 //                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
856 //        }
857
858         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
859         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
860         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
861         try {
862             if (mountPoint != null) {
863                 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
864             } else {
865                 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
866             }
867         } catch(final RestconfDocumentedException e) {
868             throw e;
869         } catch (final Exception e) {
870             final String errMsg = "Error creating data ";
871             LOG.info(errMsg + uriInfo.getPath(), e);
872             throw new RestconfDocumentedException(errMsg, e);
873         }
874
875         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
876         // FIXME: Provide path to result.
877         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
878         if (location != null) {
879             responseBuilder.location(location);
880         }
881         return responseBuilder.build();
882     }
883
884     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
885         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
886         uriBuilder.path("config");
887         try {
888             uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
889         } catch (final Exception e) {
890             LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
891             return null;
892         }
893         return uriBuilder.build();
894     }
895
896     @Override
897     public Response deleteConfigurationData(final String identifier) {
898         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
899         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
900         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
901
902         try {
903             if (mountPoint != null) {
904                 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
905             } else {
906                 broker.commitConfigurationDataDelete(normalizedII).get();
907             }
908         } catch (final Exception e) {
909             final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
910                     Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
911             if (searchedException.isPresent()) {
912                 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
913             }
914             final String errMsg = "Error while deleting data";
915             LOG.info(errMsg, e);
916             throw new RestconfDocumentedException(errMsg, e);
917         }
918         return Response.status(Status.OK).build();
919     }
920
921     /**
922      * Subscribes to some path in schema context (stream) to listen on changes on this stream.
923      *
924      * Additional parameters for subscribing to stream are loaded via rpc input parameters:
925      * <ul>
926      * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
927      * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
928      * </ul>
929      */
930     @Override
931     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
932         final String streamName = Notificator.createStreamNameFromUri(identifier);
933         if (Strings.isNullOrEmpty(streamName)) {
934             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
935         }
936
937         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
938         if (listener == null) {
939             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
940         }
941
942         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
943         final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
944                 paramToValues.get(DATASTORE_PARAM_NAME));
945         if (datastore == null) {
946             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
947                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
948         }
949         final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
950         if (scope == null) {
951             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
952                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
953         }
954
955         broker.registerToListenDataChanges(datastore, scope, listener);
956
957         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
958         int notificationPort = NOTIFICATION_PORT;
959         try {
960             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
961             notificationPort = webSocketServerInstance.getPort();
962         } catch (final NullPointerException e) {
963             WebSocketServer.createInstance(NOTIFICATION_PORT);
964         }
965         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
966         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
967
968         return Response.status(Status.OK).location(uriToWebsocketServer).build();
969     }
970
971     /**
972      * Load parameter for subscribing to stream from input composite node
973      *
974      * @param compNode
975      *            contains value
976      * @return enum object if its string value is equal to {@code paramName}. In other cases null.
977      */
978     private <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
979             final String paramName) {
980         final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
981         if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
982             return null;
983         }
984         final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
985                 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
986         if (!enumNode.isPresent()) {
987             return null;
988         }
989         final Object rawValue = enumNode.get().getValue();
990         if (!(rawValue instanceof String)) {
991             return null;
992         }
993
994         return resolveAsEnum(classDescriptor, (String) rawValue);
995     }
996
997     /**
998      * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
999      *
1000      * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1001      *         null.
1002      */
1003     private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1004         if (Strings.isNullOrEmpty(value)) {
1005             return null;
1006         }
1007         return resolveAsEnum(classDescriptor, value);
1008     }
1009
1010     private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1011         final T[] enumConstants = classDescriptor.getEnumConstants();
1012         if (enumConstants != null) {
1013             for (final T enm : classDescriptor.getEnumConstants()) {
1014                 if (((Enum<?>) enm).name().equals(value)) {
1015                     return enm;
1016                 }
1017             }
1018         }
1019         return null;
1020     }
1021
1022     private Map<String, String> resolveValuesFromUri(final String uri) {
1023         final Map<String, String> result = new HashMap<>();
1024         final String[] tokens = uri.split("/");
1025         for (int i = 1; i < tokens.length; i++) {
1026             final String[] parameterTokens = tokens[i].split("=");
1027             if (parameterTokens.length == 2) {
1028                 result.put(parameterTokens[0], parameterTokens[1]);
1029             }
1030         }
1031         return result;
1032     }
1033
1034     public BigInteger getOperationalReceived() {
1035         // TODO Auto-generated method stub
1036         return null;
1037     }
1038
1039     private MapNode makeModuleMapNode(final Set<Module> modules) {
1040         Preconditions.checkNotNull(modules);
1041         final Module restconfModule = getRestconfModule();
1042         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1043                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1044         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1045
1046         final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1047                 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1048
1049         for (final Module module : modules) {
1050             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1051         }
1052         return listModuleBuilder.build();
1053     }
1054
1055     protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1056         Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1057                 "moduleSchemaNode has to be of type ListSchemaNode");
1058         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1059         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1060                 .mapEntryBuilder(listModuleSchemaNode);
1061
1062         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1063                 (listModuleSchemaNode), "name");
1064         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1065         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1066         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1067                 .build());
1068
1069         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1070                 (listModuleSchemaNode), "revision");
1071         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1072         Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1073         final String revision = REVISION_FORMAT.format(module.getRevision());
1074         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1075                 .build());
1076
1077         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1078                 (listModuleSchemaNode), "namespace");
1079         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1080         Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1081         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1082                 .withValue(module.getNamespace().toString()).build());
1083
1084         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1085                 (listModuleSchemaNode), "feature");
1086         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1087         Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1088         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1089                 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1090         for (final FeatureDefinition feature : module.getFeatures()) {
1091             featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1092                     .withValue(feature.getQName().getLocalName()).build());
1093         }
1094         moduleNodeValues.withChild(featuresBuilder.build());
1095
1096         return moduleNodeValues.build();
1097     }
1098
1099     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1100         Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1101                 "streamSchemaNode has to be of type ListSchemaNode");
1102         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1103         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1104                 .mapEntryBuilder(listStreamSchemaNode);
1105
1106         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1107                 (listStreamSchemaNode), "name");
1108         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1109         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1110         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1111                 .build());
1112
1113         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1114                 (listStreamSchemaNode), "description");
1115         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1116         Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1117         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1118                 .withValue("DESCRIPTION_PLACEHOLDER").build());
1119
1120         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1121                 (listStreamSchemaNode), "replay-support");
1122         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1123         Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1124         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1125                 .withValue(Boolean.valueOf(true)).build());
1126
1127         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1128                 (listStreamSchemaNode), "replay-log-creation-time");
1129         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1130         Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1131         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1132                 .withValue("").build());
1133
1134         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1135                 (listStreamSchemaNode), "events");
1136         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1137         Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1138         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1139                 .withValue("").build());
1140
1141         return streamNodeValues.build();
1142     }
1143 }