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