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