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