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