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