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