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