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