08ba91fe8553970542440d36710112774bd659f9
[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.Iterator;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.Set;
37 import java.util.concurrent.CancellationException;
38 import java.util.concurrent.ExecutionException;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.Response.ResponseBuilder;
41 import javax.ws.rs.core.Response.Status;
42 import javax.ws.rs.core.UriBuilder;
43 import javax.ws.rs.core.UriInfo;
44 import org.apache.commons.lang3.StringUtils;
45 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
46 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
47 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
48 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
49 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
53 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
54 import org.opendaylight.controller.md.sal.rest.common.RestconfValidationUtils;
55 import org.opendaylight.controller.sal.rest.api.Draft02;
56 import org.opendaylight.controller.sal.rest.api.RestconfService;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
58 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
59 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
60 import org.opendaylight.controller.sal.streams.listeners.Notificator;
61 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.common.QNameModule;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
68 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
77 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
78 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
94 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
95 import org.opendaylight.yangtools.yang.model.util.EmptyType;
96 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
97 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
98 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
99 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
100 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
101 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
104
105 public class RestconfImpl implements RestconfService {
106
107     private enum UriParameters {
108         PRETTY_PRINT("prettyPrint"),
109         DEPTH("depth");
110
111         private String uriParameterName;
112
113         UriParameters(final String uriParameterName) {
114             this.uriParameterName = uriParameterName;
115         }
116
117         @Override
118         public String toString() {
119             return uriParameterName;
120         }
121     }
122
123     private static final RestconfImpl INSTANCE = new RestconfImpl();
124
125     private static final int NOTIFICATION_PORT = 8181;
126
127     private static final int CHAR_NOT_FOUND = -1;
128
129     private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
130
131     private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
132
133     private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
134
135     private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
136
137     private BrokerFacade broker;
138
139     private ControllerContext controllerContext;
140
141     private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
142
143     private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
144
145     private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
146
147     private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
148
149     private static final String DATASTORE_PARAM_NAME = "datastore";
150
151     private static final String SCOPE_PARAM_NAME = "scope";
152
153     private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
154
155     private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
156
157     private static final QName NETCONF_BASE_QNAME;
158
159     private static final QNameModule SAL_REMOTE_AUGMENT;
160
161     private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
162
163     static {
164         try {
165             final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
166             NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
167             SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
168                     eventSubscriptionAugRevision);
169             SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
170                     QName.create(SAL_REMOTE_AUGMENT, "datastore")));
171         } catch (final ParseException e) {
172             throw new RestconfDocumentedException(
173                     "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
174                     ErrorTag.OPERATION_FAILED);
175         } catch (final URISyntaxException e) {
176             throw new RestconfDocumentedException(
177                     "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
178                     ErrorTag.OPERATION_FAILED);
179         }
180     }
181
182     public void setBroker(final BrokerFacade broker) {
183         this.broker = broker;
184     }
185
186     public void setControllerContext(final ControllerContext controllerContext) {
187         this.controllerContext = controllerContext;
188     }
189
190     private RestconfImpl() {
191     }
192
193     public static RestconfImpl getInstance() {
194         return INSTANCE;
195     }
196
197     @Override
198     public NormalizedNodeContext getModules(final UriInfo uriInfo) {
199         final Set<Module> allModules = controllerContext.getAllModules();
200         final MapNode allModuleMap = makeModuleMapNode(allModules);
201
202         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
203
204         final Module restconfModule = getRestconfModule();
205         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
206                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
207         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
208
209         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
210                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
211         moduleContainerBuilder.withChild(allModuleMap);
212
213         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
214                 null, schemaContext), moduleContainerBuilder.build());
215     }
216
217     /**
218      * Valid only for mount point
219      */
220     @Override
221     public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
222         Preconditions.checkNotNull(identifier);
223         if ( ! identifier.contains(ControllerContext.MOUNT)) {
224             final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
225                     + " URI has to end with " + ControllerContext.MOUNT;
226             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
227         }
228
229         final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
230         final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
231         final Set<Module> modules = controllerContext.getAllModules(mountPoint);
232         final MapNode mountPointModulesMap = makeModuleMapNode(modules);
233
234         final Module restconfModule = getRestconfModule();
235         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
236                 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
237         Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
238
239         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
240                 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
241         moduleContainerBuilder.withChild(mountPointModulesMap);
242
243         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
244                 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build());
245     }
246
247     @Override
248     public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
249         Preconditions.checkNotNull(identifier);
250         final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
251         Module module = null;
252         DOMMountPoint mountPoint = null;
253         final SchemaContext schemaContext;
254         if (identifier.contains(ControllerContext.MOUNT)) {
255             final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
256             mountPoint = mountPointIdentifier.getMountPoint();
257             module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
258             schemaContext = mountPoint.getSchemaContext();
259         } else {
260             module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
261             schemaContext = controllerContext.getGlobalSchema();
262         }
263
264         if (module == null) {
265             final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
266                     + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
267             throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
268         }
269
270         final Module restconfModule = getRestconfModule();
271         final Set<Module> modules = Collections.singleton(module);
272         final MapNode moduleMap = makeModuleMapNode(modules);
273
274         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
275                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
276         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
277
278         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
279                 schemaContext), moduleMap);
280     }
281
282     @Override
283     public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
284         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
285         final Set<String> availableStreams = Notificator.getStreamNames();
286         final Module restconfModule = getRestconfModule();
287         final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
288                 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
289         Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
290
291         final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
292                 .mapBuilder((ListSchemaNode) streamSchemaNode);
293
294         for (final String streamName : availableStreams) {
295             listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
296         }
297
298         final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
299                 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
300         Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
301
302         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
303                 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
304         streamsContainerBuilder.withChild(listStreamsBuilder.build());
305
306
307         return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
308                 schemaContext), streamsContainerBuilder.build());
309     }
310
311     @Override
312     public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
313         final Set<Module> allModules = controllerContext.getAllModules();
314         return operationsFromModulesToNormalizedContext(allModules, null);
315     }
316
317     @Override
318     public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
319         Set<Module> modules = null;
320         DOMMountPoint mountPoint = null;
321         if (identifier.contains(ControllerContext.MOUNT)) {
322             final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
323             mountPoint = mountPointIdentifier.getMountPoint();
324             modules = controllerContext.getAllModules(mountPoint);
325
326         } else {
327             final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
328             throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
329         }
330
331         return operationsFromModulesToNormalizedContext(modules, mountPoint);
332     }
333
334     private static final Predicate<GroupingBuilder> GROUPING_FILTER = new Predicate<GroupingBuilder>() {
335         @Override
336         public boolean apply(final GroupingBuilder g) {
337             return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
338         }
339     };
340
341     private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
342             final DOMMountPoint mountPoint) {
343
344         final Module restconfModule = getRestconfModule();
345         final ModuleBuilder restConfModuleBuilder = new ModuleBuilder(restconfModule);
346         final Set<GroupingBuilder> gropingBuilders = restConfModuleBuilder.getGroupingBuilders();
347         final Iterable<GroupingBuilder> filteredGroups = Iterables.filter(gropingBuilders, GROUPING_FILTER);
348         final GroupingBuilder restconfGroupingBuilder = Iterables.getFirst(filteredGroups, null);
349         final ContainerSchemaNodeBuilder restContainerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restconfGroupingBuilder
350                 .getDataChildByName(Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
351         final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restContainerSchemaNodeBuilder
352                 .getDataChildByName(Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
353
354         final ContainerSchemaNodeBuilder fakeOperationsSchemaNodeBuilder = containerSchemaNodeBuilder;
355         final SchemaPath fakeSchemaPath = fakeOperationsSchemaNodeBuilder.getPath().createChild(QName.create("dummy"));
356
357         final List<LeafNode<Object>> operationsAsData = new ArrayList<>();
358
359         for (final Module module : modules) {
360             final Set<RpcDefinition> rpcs = module.getRpcs();
361             for (final RpcDefinition rpc : rpcs) {
362                 final QName rpcQName = rpc.getQName();
363                 final String name = module.getName();
364
365                 final QName qName = QName.create(restconfModule.getQNameModule(), rpcQName.getLocalName());
366                 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, qName, fakeSchemaPath);
367                 final LeafSchemaNodeBuilder fakeRpcSchemaNodeBuilder = leafSchemaNodeBuilder;
368                 fakeRpcSchemaNodeBuilder.setAugmenting(true);
369
370                 final EmptyType instance = EmptyType.getInstance();
371                 fakeRpcSchemaNodeBuilder.setType(instance);
372                 final LeafSchemaNode fakeRpcSchemaNode = fakeRpcSchemaNodeBuilder.build();
373                 fakeOperationsSchemaNodeBuilder.addChildNode(fakeRpcSchemaNode);
374
375                 final LeafNode<Object> leaf = Builders.leafBuilder(fakeRpcSchemaNode).build();
376                 operationsAsData.add(leaf);
377             }
378         }
379
380         final ContainerSchemaNode operContainerSchemaNode = fakeOperationsSchemaNodeBuilder.build();
381         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> operContainerNode = Builders.containerBuilder(operContainerSchemaNode);
382
383         for (final LeafNode<Object> oper : operationsAsData) {
384             operContainerNode.withChild(oper);
385         }
386
387         final Set<Module> fakeRpcModules = Collections.singleton(restConfModuleBuilder.build());
388
389         final YangParserImpl yangParser = new YangParserImpl();
390         final SchemaContext fakeSchemaCx = yangParser.resolveSchemaContext(fakeRpcModules);
391
392         final InstanceIdentifierContext<?> fakeIICx = new InstanceIdentifierContext<>(null, operContainerSchemaNode, mountPoint, fakeSchemaCx);
393
394         return new NormalizedNodeContext(fakeIICx, operContainerNode.build());
395     }
396
397     private Module getRestconfModule() {
398         final Module restconfModule = controllerContext.getRestconfModule();
399         if (restconfModule == null) {
400             throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
401                     ErrorTag.OPERATION_NOT_SUPPORTED);
402         }
403
404         return restconfModule;
405     }
406
407     private QName getModuleNameAndRevision(final String identifier) {
408         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
409         String moduleNameAndRevision = "";
410         if (mountIndex >= 0) {
411             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
412         } else {
413             moduleNameAndRevision = identifier;
414         }
415
416         final Splitter splitter = Splitter.on("/").omitEmptyStrings();
417         final Iterable<String> split = splitter.split(moduleNameAndRevision);
418         final List<String> pathArgs = Lists.<String> newArrayList(split);
419         if (pathArgs.size() < 2) {
420             throw new RestconfDocumentedException(
421                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
422                     ErrorTag.INVALID_VALUE);
423         }
424
425         try {
426             final String moduleName = pathArgs.get(0);
427             final String revision = pathArgs.get(1);
428             final Date moduleRevision = REVISION_FORMAT.parse(revision);
429             return QName.create(null, moduleRevision, moduleName);
430         } catch (final ParseException e) {
431             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
432                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
433         }
434     }
435
436     @Override
437     public Object getRoot() {
438         return null;
439     }
440
441     @Override
442     public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
443         final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
444         final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
445         final CheckedFuture<DOMRpcResult, DOMRpcException> response;
446         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
447         final SchemaContext schemaContext;
448         if (identifier.contains(MOUNT_POINT_MODULE_NAME) && mountPoint != null) {
449             final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
450             if ( ! mountRpcServices.isPresent()) {
451                 throw new RestconfDocumentedException("Rpc service is missing.");
452             }
453             schemaContext = mountPoint.getSchemaContext();
454             response = mountRpcServices.get().invokeRpc(type, payload.getData());
455         } else {
456             if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
457                 response = invokeSalRemoteRpcSubscribeRPC(payload);
458             } else {
459                 response = broker.invokeRpc(type, payload.getData());
460             }
461             schemaContext = controllerContext.getGlobalSchema();
462         }
463
464         final DOMRpcResult result = checkRpcResponse(response);
465
466         RpcDefinition resultNodeSchema = null;
467         final NormalizedNode<?, ?> resultData = result.getResult();
468         if (result != null && result.getResult() != null) {
469             resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
470         }
471
472         return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
473                 resultNodeSchema, mountPoint, schemaContext), resultData);
474     }
475
476     private DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
477         if (response == null) {
478             return null;
479         }
480         try {
481             final DOMRpcResult retValue = response.get();
482             if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
483                 return retValue;
484             }
485             throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
486         } catch (final InterruptedException e) {
487             throw new RestconfDocumentedException(
488                     "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
489                     ErrorTag.PARTIAL_OPERATION);
490         } catch (final ExecutionException e) {
491             Throwable cause = e.getCause();
492             if (cause != null) {
493                 while (cause.getCause() != null) {
494                     cause = cause.getCause();
495                 }
496
497                 if (cause instanceof IllegalArgumentException) {
498                     throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
499                             ErrorTag.INVALID_VALUE);
500                 }
501
502                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
503                         cause);
504             } else {
505                 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
506                         e);
507             }
508         } catch (final CancellationException e) {
509             throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
510                     ErrorTag.PARTIAL_OPERATION);
511         }
512     }
513
514     private void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
515         if (inputSchema != null && payload.getData() == null) {
516             // expected a non null payload
517             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
518         } else if (inputSchema == null && payload.getData() != null) {
519             // did not expect any input
520             throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
521         }
522         // else
523         // {
524         // TODO: Validate "mandatory" and "config" values here??? Or should those be
525         // those be
526         // validate in a more central location inside MD-SAL core.
527         // }
528     }
529
530     private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
531         final ContainerNode value = (ContainerNode) payload.getData();
532         final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
533         final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
534                 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
535         final Object pathValue = path.isPresent() ? path.get().getValue() : null;
536
537         if (!(pathValue instanceof YangInstanceIdentifier)) {
538             throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
539                     ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
540         }
541
542         final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
543         String streamName = null;
544         if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
545             final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
546
547             LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
548                     DATASTORE_PARAM_NAME);
549             datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
550
551             DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
552             scope = scope == null ? DEFAULT_SCOPE : scope;
553
554             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
555                     + "/scope=" + scope);
556         }
557
558         if (Strings.isNullOrEmpty(streamName)) {
559             throw new RestconfDocumentedException(
560                     "Path is empty or contains value node which is not Container or List build-in type.",
561                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
562         }
563
564         final QName outputQname = QName.create(rpcQName, "output");
565         final QName streamNameQname = QName.create(rpcQName, "stream-name");
566
567         final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
568                 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
569
570         if (!Notificator.existListenerFor(streamName)) {
571             Notificator.createListener(pathIdentifier, 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         final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
789
790         //no arguments
791         if ( ! pathArguments.hasNext()) {
792             //no "data" payload
793             if ( ! node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
794                 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
795                         ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
796             }
797         //any arguments
798         } else {
799             final String identifierName = pathArguments.next().getNodeType().getLocalName();
800             if ( ! payloadName.equals(identifierName)) {
801                 throw new RestconfDocumentedException("Payload name (" + payloadName
802                         + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
803                         ErrorTag.MALFORMED_MESSAGE);
804             }
805         }
806     }
807
808     /**
809      * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
810      *
811      * @throws RestconfDocumentedException
812      *             if key values or key count in payload and URI isn't equal
813      *
814      */
815     private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
816         Preconditions.checkArgument(payload != null);
817         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
818         final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
819         final SchemaNode schemaNode = iiWithData.getSchemaNode();
820         final NormalizedNode<?, ?> data = payload.getData();
821         if (schemaNode instanceof ListSchemaNode) {
822             final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
823             if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
824                 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
825                 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
826             }
827         }
828     }
829
830     private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
831             final MapEntryNode payload, final List<QName> keyDefinitions) {
832
833         final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
834         for (final QName keyDefinition : keyDefinitions) {
835             final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
836             // should be caught during parsing URI to InstanceIdentifier
837             RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
838                     "Missing key " + keyDefinition + " in URI.");
839
840             final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
841
842             if ( ! uriKeyValue.equals(dataKeyValue)) {
843                 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
844                         "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
845                 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
846             }
847         }
848     }
849
850     @Override
851     public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
852        return createConfigurationData(payload, uriInfo);
853     }
854
855     // FIXME create RestconfIdetifierHelper and move this method there
856     private YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
857         Preconditions.checkArgument(payload != null);
858         Preconditions.checkArgument(payload.getData() != null);
859         Preconditions.checkArgument(payload.getData().getNodeType() != null);
860         Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
861         Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
862
863         final QName payloadNodeQname = payload.getData().getNodeType();
864         final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
865         if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
866             return yangIdent;
867         }
868         final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
869         final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
870         if(parentSchemaNode instanceof DataNodeContainer) {
871             final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
872             for (final DataSchemaNode child : cast.getChildNodes()) {
873                 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
874                     return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
875                 }
876             }
877         }
878         if (parentSchemaNode instanceof RpcDefinition) {
879             return yangIdent;
880         }
881         final String errMsg = "Error parsing input: DataSchemaNode has not children";
882         throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
883     }
884
885     @Override
886     public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
887         if (payload == null) {
888             throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
889         }
890
891         // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
892 //        final URI payloadNS = payload.getData().getNodeType().getNamespace();
893 //        if (payloadNS == null) {
894 //            throw new RestconfDocumentedException(
895 //                    "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
896 //                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
897 //        }
898
899         final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
900         final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
901         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
902         try {
903             if (mountPoint != null) {
904                 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
905             } else {
906                 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
907             }
908         } catch(final RestconfDocumentedException e) {
909             throw e;
910         } catch (final Exception e) {
911             throw new RestconfDocumentedException("Error creating data", e);
912         }
913
914         final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
915         // FIXME: Provide path to result.
916         final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
917         if (location != null) {
918             responseBuilder.location(location);
919         }
920         return responseBuilder.build();
921     }
922
923     private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
924         final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
925         uriBuilder.path("config");
926         try {
927             uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
928         } catch (final Exception e) {
929             LOG.debug("Location for instance identifier"+normalizedII+"wasn't created", e);
930             return null;
931         }
932         return uriBuilder.build();
933     }
934
935     @Override
936     public Response deleteConfigurationData(final String identifier) {
937         final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
938         final DOMMountPoint mountPoint = iiWithData.getMountPoint();
939         final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
940
941         try {
942             if (mountPoint != null) {
943                 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
944             } else {
945                 broker.commitConfigurationDataDelete(normalizedII).get();
946             }
947         } catch (final Exception e) {
948             final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
949                     Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
950             if (searchedException.isPresent()) {
951                 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
952             }
953             throw new RestconfDocumentedException("Error while deleting data", e);
954         }
955         return Response.status(Status.OK).build();
956     }
957
958     /**
959      * Subscribes to some path in schema context (stream) to listen on changes on this stream.
960      *
961      * Additional parameters for subscribing to stream are loaded via rpc input parameters:
962      * <ul>
963      * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
964      * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
965      * </ul>
966      */
967     @Override
968     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
969         final String streamName = Notificator.createStreamNameFromUri(identifier);
970         if (Strings.isNullOrEmpty(streamName)) {
971             throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
972         }
973
974         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
975         if (listener == null) {
976             throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
977         }
978
979         final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
980         final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
981                 paramToValues.get(DATASTORE_PARAM_NAME));
982         if (datastore == null) {
983             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
984                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
985         }
986         final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
987         if (scope == null) {
988             throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
989                     ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
990         }
991
992         broker.registerToListenDataChanges(datastore, scope, listener);
993
994         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
995         int notificationPort = NOTIFICATION_PORT;
996         try {
997             final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
998             notificationPort = webSocketServerInstance.getPort();
999         } catch (final NullPointerException e) {
1000             WebSocketServer.createInstance(NOTIFICATION_PORT);
1001         }
1002         final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1003         final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1004
1005         return Response.status(Status.OK).location(uriToWebsocketServer).build();
1006     }
1007
1008     /**
1009      * Load parameter for subscribing to stream from input composite node
1010      *
1011      * @param compNode
1012      *            contains value
1013      * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1014      */
1015     private <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1016             final String paramName) {
1017         final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1018         if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1019             return null;
1020         }
1021         final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1022                 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1023         if (!enumNode.isPresent()) {
1024             return null;
1025         }
1026         final Object rawValue = enumNode.get().getValue();
1027         if (!(rawValue instanceof String)) {
1028             return null;
1029         }
1030
1031         return resolveAsEnum(classDescriptor, (String) rawValue);
1032     }
1033
1034     /**
1035      * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1036      *
1037      * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1038      *         null.
1039      */
1040     private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1041         if (Strings.isNullOrEmpty(value)) {
1042             return null;
1043         }
1044         return resolveAsEnum(classDescriptor, value);
1045     }
1046
1047     private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1048         final T[] enumConstants = classDescriptor.getEnumConstants();
1049         if (enumConstants != null) {
1050             for (final T enm : classDescriptor.getEnumConstants()) {
1051                 if (((Enum<?>) enm).name().equals(value)) {
1052                     return enm;
1053                 }
1054             }
1055         }
1056         return null;
1057     }
1058
1059     private Map<String, String> resolveValuesFromUri(final String uri) {
1060         final Map<String, String> result = new HashMap<>();
1061         final String[] tokens = uri.split("/");
1062         for (int i = 1; i < tokens.length; i++) {
1063             final String[] parameterTokens = tokens[i].split("=");
1064             if (parameterTokens.length == 2) {
1065                 result.put(parameterTokens[0], parameterTokens[1]);
1066             }
1067         }
1068         return result;
1069     }
1070
1071     public BigInteger getOperationalReceived() {
1072         // TODO Auto-generated method stub
1073         return null;
1074     }
1075
1076     private MapNode makeModuleMapNode(final Set<Module> modules) {
1077         Preconditions.checkNotNull(modules);
1078         final Module restconfModule = getRestconfModule();
1079         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1080                 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1081         Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1082
1083         final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1084                 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1085
1086         for (final Module module : modules) {
1087             listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1088         }
1089         return listModuleBuilder.build();
1090     }
1091
1092     protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1093         Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1094                 "moduleSchemaNode has to be of type ListSchemaNode");
1095         final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1096         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1097                 .mapEntryBuilder(listModuleSchemaNode);
1098
1099         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1100                 (listModuleSchemaNode), "name");
1101         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1102         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1103         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1104                 .build());
1105
1106         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1107                 (listModuleSchemaNode), "revision");
1108         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1109         Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1110         final String revision = REVISION_FORMAT.format(module.getRevision());
1111         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1112                 .build());
1113
1114         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1115                 (listModuleSchemaNode), "namespace");
1116         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1117         Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1118         moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1119                 .withValue(module.getNamespace().toString()).build());
1120
1121         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1122                 (listModuleSchemaNode), "feature");
1123         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1124         Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1125         final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1126                 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1127         for (final FeatureDefinition feature : module.getFeatures()) {
1128             featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1129                     .withValue(feature.getQName().getLocalName()).build());
1130         }
1131         moduleNodeValues.withChild(featuresBuilder.build());
1132
1133         return moduleNodeValues.build();
1134     }
1135
1136     protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1137         Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1138                 "streamSchemaNode has to be of type ListSchemaNode");
1139         final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1140         final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1141                 .mapEntryBuilder(listStreamSchemaNode);
1142
1143         List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1144                 (listStreamSchemaNode), "name");
1145         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1146         Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1147         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1148                 .build());
1149
1150         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1151                 (listStreamSchemaNode), "description");
1152         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1153         Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1154         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1155                 .withValue("DESCRIPTION_PLACEHOLDER").build());
1156
1157         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1158                 (listStreamSchemaNode), "replay-support");
1159         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1160         Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1161         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1162                 .withValue(Boolean.valueOf(true)).build());
1163
1164         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1165                 (listStreamSchemaNode), "replay-log-creation-time");
1166         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1167         Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1168         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1169                 .withValue("").build());
1170
1171         instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1172                 (listStreamSchemaNode), "events");
1173         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1174         Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1175         streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1176                 .withValue("").build());
1177
1178         return streamNodeValues.build();
1179     }
1180 }