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