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