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