Merge "BUG 624 - Make netconf TCP port optional."
[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 java.net.URI;
12 import java.text.ParseException;
13 import java.text.SimpleDateFormat;
14 import java.util.ArrayList;
15 import java.util.Arrays;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Date;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.concurrent.Future;
23
24 import javax.ws.rs.core.Response;
25 import javax.ws.rs.core.Response.Status;
26 import javax.ws.rs.core.UriBuilder;
27 import javax.ws.rs.core.UriInfo;
28
29 import org.apache.commons.lang3.StringUtils;
30 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
31 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
32 import org.opendaylight.controller.sal.rest.api.Draft02;
33 import org.opendaylight.controller.sal.rest.api.RestconfService;
34 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
35 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
36 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
37 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
38 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
39 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
40 import org.opendaylight.controller.sal.streams.listeners.Notificator;
41 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
42 import org.opendaylight.yangtools.concepts.Codec;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.common.RpcError;
45 import org.opendaylight.yangtools.yang.common.RpcResult;
46 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
47 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder;
49 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
50 import org.opendaylight.yangtools.yang.data.api.Node;
51 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
52 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
53 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
55 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
57 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.util.EmptyType;
67 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
68 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
69
70 import com.google.common.base.Objects;
71 import com.google.common.base.Preconditions;
72 import com.google.common.base.Splitter;
73 import com.google.common.base.Strings;
74 import com.google.common.collect.Iterables;
75 import com.google.common.collect.Lists;
76
77 public class RestconfImpl implements RestconfService {
78     private final static RestconfImpl INSTANCE = new RestconfImpl();
79
80     private static final int CHAR_NOT_FOUND = -1;
81
82     private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
83
84     private final static SimpleDateFormat REVISION_FORMAT =  new SimpleDateFormat("yyyy-MM-dd");
85
86     private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
87
88     private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
89
90     private BrokerFacade broker;
91
92     private ControllerContext controllerContext;
93
94     public void setBroker(final BrokerFacade broker) {
95         this.broker = broker;
96     }
97
98     public void setControllerContext(final ControllerContext controllerContext) {
99         this.controllerContext = controllerContext;
100     }
101
102     private RestconfImpl() {
103     }
104
105     public static RestconfImpl getInstance() {
106         return INSTANCE;
107     }
108
109     @Override
110     public StructuredData getModules() {
111         final Module restconfModule = this.getRestconfModule();
112
113         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
114         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
115                                         restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
116
117         Set<Module> allModules = this.controllerContext.getAllModules();
118         for (final Module module : allModules) {
119             CompositeNode moduleCompositeNode = this.toModuleCompositeNode(module, moduleSchemaNode);
120             modulesAsData.add(moduleCompositeNode);
121         }
122
123         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
124                                    restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
125         QName qName = modulesSchemaNode.getQName();
126         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
127         return new StructuredData(modulesNode, modulesSchemaNode, null);
128     }
129
130     @Override
131     public StructuredData getAvailableStreams() {
132         Set<String> availableStreams = Notificator.getStreamNames();
133
134         final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
135         Module restconfModule = this.getRestconfModule();
136         final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
137                                              restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
138         for (final String streamName : availableStreams) {
139             streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
140         }
141
142         final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
143                                      restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
144         QName qName = streamsSchemaNode.getQName();
145         final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
146         return new StructuredData(streamsNode, streamsSchemaNode, null);
147     }
148
149     @Override
150     public StructuredData getModules(final String identifier) {
151         Set<Module> modules = null;
152         MountInstance mountPoint = null;
153         if (identifier.contains(ControllerContext.MOUNT)) {
154             InstanceIdWithSchemaNode mountPointIdentifier =
155                                            this.controllerContext.toMountPointIdentifier(identifier);
156             mountPoint = mountPointIdentifier.getMountPoint();
157             modules = this.controllerContext.getAllModules(mountPoint);
158         }
159         else {
160             throw new RestconfDocumentedException(
161                     "URI has bad format. If modules behind mount point should be showed, URI has to end with " +
162                     ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
163         }
164
165         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
166         Module restconfModule = this.getRestconfModule();
167         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
168                                          restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
169
170         for (final Module module : modules) {
171             modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
172         }
173
174         final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
175                                   restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
176         QName qName = modulesSchemaNode.getQName();
177         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
178         return new StructuredData(modulesNode, modulesSchemaNode, mountPoint);
179     }
180
181     @Override
182     public StructuredData getModule(final String identifier) {
183         final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
184         Module module = null;
185         MountInstance mountPoint = null;
186         if (identifier.contains(ControllerContext.MOUNT)) {
187             InstanceIdWithSchemaNode mountPointIdentifier =
188                                             this.controllerContext.toMountPointIdentifier(identifier);
189             mountPoint = mountPointIdentifier.getMountPoint();
190             module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
191         }
192         else {
193             module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
194         }
195
196         if (module == null) {
197             throw new RestconfDocumentedException(
198                     "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" +
199                     moduleNameAndRevision.getRevision() + "' was not found.",
200                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
201         }
202
203         Module restconfModule = this.getRestconfModule();
204         final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
205                                           restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
206         final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
207         return new StructuredData(moduleNode, moduleSchemaNode, mountPoint);
208     }
209
210     @Override
211     public StructuredData getOperations() {
212         Set<Module> allModules = this.controllerContext.getAllModules();
213         return this.operationsFromModulesToStructuredData(allModules, null);
214     }
215
216     @Override
217     public StructuredData getOperations(final String identifier) {
218         Set<Module> modules = null;
219         MountInstance mountPoint = null;
220         if (identifier.contains(ControllerContext.MOUNT)) {
221             InstanceIdWithSchemaNode mountPointIdentifier =
222                                          this.controllerContext.toMountPointIdentifier(identifier);
223             mountPoint = mountPointIdentifier.getMountPoint();
224             modules = this.controllerContext.getAllModules(mountPoint);
225         }
226         else {
227             throw new RestconfDocumentedException(
228                     "URI has bad format. If operations behind mount point should be showed, URI has to end with " +
229                     ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
230         }
231
232         return this.operationsFromModulesToStructuredData(modules, mountPoint);
233     }
234
235     private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
236                                                                  final MountInstance mountPoint) {
237         final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
238         Module restconfModule = this.getRestconfModule();
239         final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
240                               restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
241         QName qName = operationsSchemaNode.getQName();
242         SchemaPath path = operationsSchemaNode.getPath();
243         ContainerSchemaNodeBuilder containerSchemaNodeBuilder =
244                              new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path);
245         final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
246         for (final Module module : modules) {
247             Set<RpcDefinition> rpcs = module.getRpcs();
248             for (final RpcDefinition rpc : rpcs) {
249                 QName rpcQName = rpc.getQName();
250                 SimpleNode<Object> immutableSimpleNode =
251                                      NodeFactory.<Object>createImmutableSimpleNode(rpcQName, null, null);
252                 operationsAsData.add(immutableSimpleNode);
253
254                 String name = module.getName();
255                 LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName, null);
256                 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
257                 fakeRpcSchemaNode.setAugmenting(true);
258
259                 EmptyType instance = EmptyType.getInstance();
260                 fakeRpcSchemaNode.setType(instance);
261                 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
262             }
263         }
264
265         final CompositeNode operationsNode =
266                                   NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
267         ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
268         return new StructuredData(operationsNode, schemaNode, mountPoint);
269     }
270
271     private Module getRestconfModule() {
272         Module restconfModule = controllerContext.getRestconfModule();
273         if (restconfModule == null) {
274             throw new RestconfDocumentedException(
275                     "ietf-restconf module was not found.", ErrorType.APPLICATION,
276                     ErrorTag.OPERATION_NOT_SUPPORTED );
277         }
278
279         return restconfModule;
280     }
281
282     private QName getModuleNameAndRevision(final String identifier) {
283         final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
284         String moduleNameAndRevision = "";
285         if (mountIndex >= 0) {
286             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
287         }
288         else {
289             moduleNameAndRevision = identifier;
290         }
291
292         Splitter splitter = Splitter.on("/").omitEmptyStrings();
293         Iterable<String> split = splitter.split(moduleNameAndRevision);
294         final List<String> pathArgs = Lists.<String>newArrayList(split);
295         if (pathArgs.size() < 2) {
296             throw new RestconfDocumentedException(
297                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'",
298                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
299         }
300
301         try {
302             final String moduleName = pathArgs.get( 0 );
303             String revision = pathArgs.get(1);
304             final Date moduleRevision = REVISION_FORMAT.parse(revision);
305             return QName.create(null, moduleRevision, moduleName);
306         }
307         catch (ParseException e) {
308             throw new RestconfDocumentedException(
309                     "URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
310                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
311         }
312     }
313
314     private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
315         final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
316         List<DataSchemaNode> instanceDataChildrenByName =
317                 this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode),
318                                                                        "name");
319         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
320         streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(), null,
321                                                                            streamName));
322
323         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
324                                                  ((DataNodeContainer) streamSchemaNode), "description");
325         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
326         streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
327                                                                            "DESCRIPTION_PLACEHOLDER"));
328
329         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
330                                                ((DataNodeContainer) streamSchemaNode), "replay-support");
331         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
332         streamNodeValues.add(NodeFactory.<Boolean>createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
333                                                                             Boolean.valueOf(true)));
334
335         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
336                                            ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
337         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
338         streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
339                                                                            null, ""));
340
341         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
342                                                         ((DataNodeContainer) streamSchemaNode), "events");
343         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
344         streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(eventsSchemaNode.getQName(),
345                                                                            null, ""));
346
347         return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
348     }
349
350     private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
351         final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
352         List<DataSchemaNode> instanceDataChildrenByName =
353             this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name");
354         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
355         moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(),
356                                                                            null, module.getName()));
357
358         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
359                                                           ((DataNodeContainer) moduleSchemaNode), "revision");
360         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
361         Date _revision = module.getRevision();
362         moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
363                                                                            REVISION_FORMAT.format(_revision)));
364
365         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
366                                                         ((DataNodeContainer) moduleSchemaNode), "namespace");
367         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
368         moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
369                                                                            module.getNamespace().toString()));
370
371         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
372                                                            ((DataNodeContainer) moduleSchemaNode), "feature");
373         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
374         for (final FeatureDefinition feature : module.getFeatures()) {
375             moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(featureSchemaNode.getQName(), null,
376                                                                                feature.getQName().getLocalName()));
377         }
378
379         return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
380     }
381
382     @Override
383     public Object getRoot() {
384         return null;
385     }
386
387     @Override
388     public StructuredData invokeRpc(final String identifier, final CompositeNode payload) {
389         final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
390         QName rpcName = rpc.getRpcDefinition().getQName();
391         URI rpcNamespace = rpcName.getNamespace();
392         if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) &&
393             Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
394             return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition());
395         }
396
397         validateInput( rpc.getRpcDefinition().getInput(), payload );
398
399         return callRpc(rpc, payload);
400     }
401
402     private void validateInput(DataSchemaNode inputSchema, CompositeNode payload) {
403         if( inputSchema != null && payload == null )
404         {
405             //expected a non null payload
406             throw new RestconfDocumentedException( "Input is required.",
407                                                    ErrorType.PROTOCOL,
408                                                    ErrorTag.MALFORMED_MESSAGE );
409         }
410         else if( inputSchema == null && payload != null )
411         {
412             //did not expect any input
413             throw new RestconfDocumentedException( "No input expected.",
414                                                    ErrorType.PROTOCOL,
415                                                    ErrorTag.MALFORMED_MESSAGE );
416         }
417         //else
418         //{
419             //TODO: Validate "mandatory" and "config" values here??? Or should those be
420         // validate in a more central location inside MD-SAL core.
421         //}
422     }
423
424     private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload,
425                                                           final RpcDefinition rpc) {
426         final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
427         final SimpleNode<? extends Object> pathNode = value == null ? null :
428                                value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") );
429         final Object pathValue = pathNode == null ? null : pathNode.getValue();
430
431         if (!(pathValue instanceof InstanceIdentifier)) {
432             throw new RestconfDocumentedException(
433                     "Instance identifier was not normalized correctly.",
434                     ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED );
435         }
436
437         final InstanceIdentifier pathIdentifier = ((InstanceIdentifier) pathValue);
438         String streamName = null;
439         if (!Iterables.isEmpty(pathIdentifier.getPath())) {
440             String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
441             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier);
442         }
443
444         if (Strings.isNullOrEmpty(streamName)) {
445             throw new RestconfDocumentedException(
446                     "Path is empty or contains data node which is not Container or List build-in type.",
447                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
448         }
449
450         final SimpleNode<String> streamNameNode = NodeFactory.<String>createImmutableSimpleNode(
451                              QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
452         final List<Node<?>> output = new ArrayList<Node<?>>();
453         output.add(streamNameNode);
454
455         final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(
456                                               rpc.getOutput().getQName(), null, output, null, null);
457
458         if (!Notificator.existListenerFor(pathIdentifier)) {
459             Notificator.createListener(pathIdentifier, streamName);
460         }
461
462         return new StructuredData(responseData, rpc.getOutput(), null);
463     }
464
465     @Override
466     public StructuredData invokeRpc(final String identifier, final String noPayload) {
467         if (StringUtils.isNotBlank(noPayload)) {
468             throw new RestconfDocumentedException(
469                     "Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
470         }
471         return invokeRpc( identifier, (CompositeNode)null );
472     }
473
474     private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
475         String identifierEncoded = null;
476         MountInstance mountPoint = null;
477         if (identifier.contains(ControllerContext.MOUNT)) {
478             // mounted RPC call - look up mount instance.
479             InstanceIdWithSchemaNode mountPointId = controllerContext
480                     .toMountPointIdentifier(identifier);
481             mountPoint = mountPointId.getMountPoint();
482
483             int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
484                     + ControllerContext.MOUNT.length() + 1;
485             String remoteRpcName = identifier.substring(startOfRemoteRpcName);
486             identifierEncoded = remoteRpcName;
487
488         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
489             final String slashErrorMsg = String
490                     .format("Identifier %n%s%ncan\'t contain slash "
491                             + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
492                             identifier);
493             throw new RestconfDocumentedException(
494                     slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
495         } else {
496             identifierEncoded = identifier;
497         }
498
499         final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
500         RpcDefinition rpc = controllerContext.getRpcDefinition(identifierDecoded);
501
502         if (rpc == null) {
503             throw new RestconfDocumentedException(
504                     "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
505         }
506
507         if (mountPoint == null) {
508             return new BrokerRpcExecutor(rpc, broker);
509         } else {
510             return new MountPointRpcExecutor(rpc, mountPoint);
511         }
512
513     }
514
515     private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload) {
516         if (rpcExecutor == null) {
517             throw new RestconfDocumentedException(
518                     "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
519         }
520
521         CompositeNode rpcRequest = null;
522         RpcDefinition rpc = rpcExecutor.getRpcDefinition();
523         QName rpcName = rpc.getQName();
524
525         if (payload == null) {
526             rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
527         } else {
528             final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
529             List<Node<?>> input = Collections.<Node<?>> singletonList(value);
530             rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
531         }
532
533         RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
534
535         checkRpcSuccessAndThrowException(rpcResult);
536
537         if (rpcResult.getResult() == null) {
538             return null;
539         }
540
541         if( rpc.getOutput() == null )
542         {
543             return null; //no output, nothing to send back.
544         }
545
546         return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null);
547     }
548
549     private void checkRpcSuccessAndThrowException(RpcResult<CompositeNode> rpcResult) {
550         if (rpcResult.isSuccessful() == false) {
551
552             Collection<RpcError> rpcErrors = rpcResult.getErrors();
553             if( rpcErrors == null || rpcErrors.isEmpty() ) {
554                 throw new RestconfDocumentedException(
555                     "The operation was not successful and there were no RPC errors returned",
556                     ErrorType.RPC, ErrorTag.OPERATION_FAILED );
557             }
558
559             List<RestconfError> errorList = Lists.newArrayList();
560             for( RpcError rpcError: rpcErrors ) {
561                 errorList.add( new RestconfError( rpcError ) );
562             }
563
564             throw new RestconfDocumentedException( errorList );
565         }
566     }
567
568     @Override
569     public StructuredData readConfigurationData(final String identifier) {
570         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
571         CompositeNode data = null;
572         MountInstance mountPoint = iiWithData.getMountPoint();
573         if (mountPoint != null) {
574             data = broker.readConfigurationDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
575         }
576         else {
577             data = broker.readConfigurationData(iiWithData.getInstanceIdentifier());
578         }
579
580         return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
581     }
582
583     @Override
584     public StructuredData readOperationalData(final String identifier) {
585         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
586         CompositeNode data = null;
587         MountInstance mountPoint = iiWithData.getMountPoint();
588         if (mountPoint != null) {
589             data = broker.readOperationalDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
590         }
591         else {
592             data = broker.readOperationalData(iiWithData.getInstanceIdentifier());
593         }
594
595         return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint);
596     }
597
598     @Override
599     public Response updateConfigurationData(final String identifier, final CompositeNode payload) {
600         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
601
602         validateInput(iiWithData.getSchemaNode(), payload);
603
604         MountInstance mountPoint = iiWithData.getMountPoint();
605         final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
606         RpcResult<TransactionStatus> status = null;
607
608         try {
609             if (mountPoint != null) {
610                 status = broker.commitConfigurationDataPutBehindMountPoint(
611                                                 mountPoint, iiWithData.getInstanceIdentifier(), value).get();
612             } else {
613                 status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get();
614             }
615         }
616         catch( Exception e ) {
617             throw new RestconfDocumentedException( "Error updating data", e );
618         }
619
620         if( status.getResult() == TransactionStatus.COMMITED )
621             return Response.status(Status.OK).build();
622
623         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
624     }
625
626     @Override
627     public Response createConfigurationData(final String identifier, final CompositeNode payload) {
628         if( payload == null ) {
629             throw new RestconfDocumentedException( "Input is required.",
630                     ErrorType.PROTOCOL,
631                     ErrorTag.MALFORMED_MESSAGE );
632         }
633
634         URI payloadNS = this.namespace(payload);
635         if (payloadNS == null) {
636             throw new RestconfDocumentedException(
637                  "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
638                  ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
639         }
640
641         InstanceIdWithSchemaNode iiWithData = null;
642         CompositeNode value = null;
643         if (this.representsMountPointRootData(payload)) {
644              // payload represents mount point data and URI represents path to the mount point
645
646             if (this.endsWithMountPoint(identifier)) {
647                 throw new RestconfDocumentedException(
648                         "URI has bad format. URI should be without \"" + ControllerContext.MOUNT +
649                         "\" for POST operation.",
650                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
651             }
652
653             final String completeIdentifier = this.addMountPointIdentifier(identifier);
654             iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
655
656             value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
657         }
658         else {
659             final InstanceIdWithSchemaNode incompleteInstIdWithData =
660                                                this.controllerContext.toInstanceIdentifier(identifier);
661             final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
662             MountInstance mountPoint = incompleteInstIdWithData.getMountPoint();
663             final Module module = this.findModule(mountPoint, payload);
664             if (module == null) {
665                 throw new RestconfDocumentedException(
666                         "Module was not found for \"" + payloadNS + "\"",
667                         ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
668             }
669
670             String payloadName = this.getName(payload);
671             final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
672                                                               parentSchema, payloadName, module.getNamespace());
673             value = this.normalizeNode(payload, schemaNode, mountPoint);
674
675             iiWithData = this.addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode);
676         }
677
678         RpcResult<TransactionStatus> status = null;
679         MountInstance mountPoint = iiWithData.getMountPoint();
680         try {
681             if (mountPoint != null) {
682                 Future<RpcResult<TransactionStatus>> future =
683                                           broker.commitConfigurationDataPostBehindMountPoint(
684                                                        mountPoint, iiWithData.getInstanceIdentifier(), value);
685                 status = future == null ? null : future.get();
686             }
687             else {
688                 Future<RpcResult<TransactionStatus>> future =
689                                broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
690                 status = future == null ? null : future.get();
691             }
692         }
693         catch( Exception e ) {
694             throw new RestconfDocumentedException( "Error creating data", e );
695         }
696
697         if (status == null) {
698             return Response.status(Status.ACCEPTED).build();
699         }
700
701         if( status.getResult() == TransactionStatus.COMMITED )
702             return Response.status(Status.NO_CONTENT).build();
703
704         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
705     }
706
707     @Override
708     public Response createConfigurationData(final CompositeNode payload) {
709         if( payload == null ) {
710             throw new RestconfDocumentedException( "Input is required.",
711                     ErrorType.PROTOCOL,
712                     ErrorTag.MALFORMED_MESSAGE );
713         }
714
715         URI payloadNS = this.namespace(payload);
716         if (payloadNS == null) {
717             throw new RestconfDocumentedException(
718                 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
719                 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
720         }
721
722         final Module module = this.findModule(null, payload);
723         if (module == null) {
724             throw new RestconfDocumentedException(
725                     "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
726                     ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
727         }
728
729         String payloadName = this.getName(payload);
730         final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
731                                                                    module, payloadName, module.getNamespace());
732         final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
733         final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode);
734         RpcResult<TransactionStatus> status = null;
735         MountInstance mountPoint = iiWithData.getMountPoint();
736
737         try {
738             if (mountPoint != null) {
739                 Future<RpcResult<TransactionStatus>> future =
740                                              broker.commitConfigurationDataPostBehindMountPoint(
741                                                           mountPoint, iiWithData.getInstanceIdentifier(), value);
742                 status = future == null ? null : future.get();
743             }
744             else {
745                 Future<RpcResult<TransactionStatus>> future =
746                                  broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
747                 status = future == null ? null : future.get();
748             }
749         }
750         catch( Exception e ) {
751             throw new RestconfDocumentedException( "Error creating data", e );
752         }
753
754         if (status == null) {
755             return Response.status(Status.ACCEPTED).build();
756         }
757
758         if( status.getResult() == TransactionStatus.COMMITED )
759             return Response.status(Status.NO_CONTENT).build();
760
761         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
762     }
763
764     @Override
765     public Response deleteConfigurationData(final String identifier) {
766         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
767         RpcResult<TransactionStatus> status = null;
768         MountInstance mountPoint = iiWithData.getMountPoint();
769
770         try {
771             if (mountPoint != null) {
772                 status = broker.commitConfigurationDataDeleteBehindMountPoint(
773                                         mountPoint, iiWithData.getInstanceIdentifier()).get();
774             }
775             else {
776                 status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get();
777             }
778         }
779         catch( Exception e ) {
780             throw new RestconfDocumentedException( "Error creating data", e );
781         }
782
783         if( status.getResult() == TransactionStatus.COMMITED )
784             return Response.status(Status.OK).build();
785
786         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
787     }
788
789     @Override
790     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
791         final String streamName = Notificator.createStreamNameFromUri(identifier);
792         if (Strings.isNullOrEmpty(streamName)) {
793             throw new RestconfDocumentedException(
794                     "Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
795         }
796
797         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
798         if (listener == null) {
799             throw new RestconfDocumentedException(
800                     "Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
801         }
802
803         broker.registerToListenDataChanges(listener);
804
805         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
806         UriBuilder port = uriBuilder.port(WebSocketServer.PORT);
807         final URI uriToWebsocketServer = port.replacePath(streamName).build();
808
809         return Response.status(Status.OK).location(uriToWebsocketServer).build();
810     }
811
812     private Module findModule(final MountInstance mountPoint, final CompositeNode data) {
813         if (data instanceof CompositeNodeWrapper) {
814             return findModule(mountPoint, (CompositeNodeWrapper)data);
815         }
816         else if (data != null) {
817             URI namespace = data.getNodeType().getNamespace();
818             if (mountPoint != null) {
819                 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
820             }
821             else {
822                 return this.controllerContext.findModuleByNamespace(namespace);
823             }
824         }
825         else {
826             throw new IllegalArgumentException("Unhandled parameter types: " +
827                     Arrays.<Object>asList(mountPoint, data).toString());
828         }
829     }
830
831     private Module findModule(final MountInstance mountPoint, final CompositeNodeWrapper data) {
832         URI namespace = data.getNamespace();
833         Preconditions.<URI>checkNotNull(namespace);
834
835         Module module = null;
836         if (mountPoint != null) {
837             module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
838             if (module == null) {
839                 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
840             }
841         }
842         else {
843             module = this.controllerContext.findModuleByNamespace(namespace);
844             if (module == null) {
845                 module = this.controllerContext.findModuleByName(namespace.toString());
846             }
847         }
848
849         return module;
850     }
851
852     private InstanceIdWithSchemaNode addLastIdentifierFromData(
853                                               final InstanceIdWithSchemaNode identifierWithSchemaNode,
854                                               final CompositeNode data, final DataSchemaNode schemaOfData) {
855         InstanceIdentifier instanceIdentifier = null;
856         if (identifierWithSchemaNode != null) {
857             instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
858         }
859
860         final InstanceIdentifier iiOriginal = instanceIdentifier;
861         InstanceIdentifierBuilder iiBuilder = null;
862         if (iiOriginal == null) {
863             iiBuilder = InstanceIdentifier.builder();
864         }
865         else {
866             iiBuilder = InstanceIdentifier.builder(iiOriginal);
867         }
868
869         if ((schemaOfData instanceof ListSchemaNode)) {
870             HashMap<QName,Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
871             iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
872         }
873         else {
874             iiBuilder.node(schemaOfData.getQName());
875         }
876
877         InstanceIdentifier instance = iiBuilder.toInstance();
878         MountInstance mountPoint = null;
879         if (identifierWithSchemaNode != null) {
880             mountPoint=identifierWithSchemaNode.getMountPoint();
881         }
882
883         return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint);
884     }
885
886     private HashMap<QName,Object> resolveKeysFromData(final ListSchemaNode listNode,
887                                                       final CompositeNode dataNode) {
888         final HashMap<QName,Object> keyValues = new HashMap<QName, Object>();
889         List<QName> _keyDefinition = listNode.getKeyDefinition();
890         for (final QName key : _keyDefinition) {
891             SimpleNode<? extends Object> head = null;
892             String localName = key.getLocalName();
893             List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
894             if (simpleNodesByName != null) {
895                 head = Iterables.getFirst(simpleNodesByName, null);
896             }
897
898             Object dataNodeKeyValueObject = null;
899             if (head != null) {
900                 dataNodeKeyValueObject = head.getValue();
901             }
902
903             if (dataNodeKeyValueObject == null) {
904                 throw new RestconfDocumentedException(
905                         "Data contains list \"" + dataNode.getNodeType().getLocalName() +
906                         "\" which does not contain key: \"" + key.getLocalName() + "\"",
907                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
908             }
909
910             keyValues.put(key, dataNodeKeyValueObject);
911         }
912
913         return keyValues;
914     }
915
916     private boolean endsWithMountPoint(final String identifier) {
917         return identifier.endsWith(ControllerContext.MOUNT) ||
918                identifier.endsWith(ControllerContext.MOUNT + "/");
919     }
920
921     private boolean representsMountPointRootData(final CompositeNode data) {
922         URI namespace = this.namespace(data);
923         return (SchemaContext.NAME.getNamespace().equals( namespace ) /* ||
924                 MOUNT_POINT_MODULE_NAME.equals( namespace.toString() )*/ ) &&
925                 SchemaContext.NAME.getLocalName().equals( this.localName(data) );
926     }
927
928     private String addMountPointIdentifier(final String identifier) {
929         boolean endsWith = identifier.endsWith("/");
930         if (endsWith) {
931             return (identifier + ControllerContext.MOUNT);
932         }
933
934         return identifier + "/" + ControllerContext.MOUNT;
935     }
936
937     private CompositeNode normalizeNode(final CompositeNode node, final DataSchemaNode schema,
938                                         final MountInstance mountPoint) {
939         if (schema == null) {
940             QName nodeType = node == null ? null : node.getNodeType();
941             String localName = nodeType == null ? null : nodeType.getLocalName();
942
943             throw new RestconfDocumentedException(
944                     "Data schema node was not found for " + localName,
945                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
946         }
947
948         if (!(schema instanceof DataNodeContainer)) {
949             throw new RestconfDocumentedException(
950                     "Root element has to be container or list yang datatype.",
951                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
952         }
953
954         if ((node instanceof CompositeNodeWrapper)) {
955             boolean isChangeAllowed = ((CompositeNodeWrapper) node).isChangeAllowed();
956             if (isChangeAllowed) {
957                 try {
958                     this.normalizeNode(((CompositeNodeWrapper) node), schema, null, mountPoint);
959                 }
960                 catch (IllegalArgumentException e) {
961                     throw new RestconfDocumentedException(
962                                     e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
963                 }
964             }
965
966             return ((CompositeNodeWrapper) node).unwrap();
967         }
968
969         return node;
970     }
971
972     private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder,
973                                final DataSchemaNode schema, final QName previousAugment,
974                                final MountInstance mountPoint) {
975         if (schema == null) {
976             throw new RestconfDocumentedException(
977                     "Data has bad format.\n\"" + nodeBuilder.getLocalName() +
978                     "\" does not exist in yang schema.",
979                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
980         }
981
982         QName currentAugment = null;
983         if (nodeBuilder.getQname() != null) {
984             currentAugment = previousAugment;
985         }
986         else {
987             currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
988             if (nodeBuilder.getQname() == null) {
989                 throw new RestconfDocumentedException(
990                         "Data has bad format.\nIf data is in XML format then namespace for \"" +
991                         nodeBuilder.getLocalName() +
992                         "\" should be \"" + schema.getQName().getNamespace() + "\".\n" +
993                         "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() +
994                          "\" should be corresponding to namespace \"" +
995                         schema.getQName().getNamespace() + "\".",
996                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
997             }
998         }
999
1000         if ((nodeBuilder instanceof CompositeNodeWrapper)) {
1001             final List<NodeWrapper<?>> children = ((CompositeNodeWrapper) nodeBuilder).getValues();
1002             for (final NodeWrapper<? extends Object> child : children) {
1003                 final List<DataSchemaNode> potentialSchemaNodes =
1004                         this.controllerContext.findInstanceDataChildrenByName(
1005                                              ((DataNodeContainer) schema), child.getLocalName());
1006
1007                 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1008                     StringBuilder builder = new StringBuilder();
1009                     for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1010                         builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString())
1011                                .append("\n");
1012                     }
1013
1014                     throw new RestconfDocumentedException(
1015                                  "Node \"" + child.getLocalName() +
1016                                  "\" is added as augment from more than one module. " +
1017                                  "Therefore node must have namespace (XML format) or module name (JSON format)." +
1018                                  "\nThe node is added as augment from modules with namespaces:\n" + builder,
1019                                  ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
1020                 }
1021
1022                 boolean rightNodeSchemaFound = false;
1023                 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1024                     if (!rightNodeSchemaFound) {
1025                         final QName potentialCurrentAugment =
1026                                 this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint);
1027                         if (child.getQname() != null ) {
1028                             this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1029                             rightNodeSchemaFound = true;
1030                         }
1031                     }
1032                 }
1033
1034                 if (!rightNodeSchemaFound) {
1035                     throw new RestconfDocumentedException(
1036                                "Schema node \"" + child.getLocalName() + "\" was not found in module.",
1037                                ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT );
1038                 }
1039             }
1040
1041             if ((schema instanceof ListSchemaNode)) {
1042                 final List<QName> listKeys = ((ListSchemaNode) schema).getKeyDefinition();
1043                 for (final QName listKey : listKeys) {
1044                     boolean foundKey = false;
1045                     for (final NodeWrapper<? extends Object> child : children) {
1046                         if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1047                             foundKey = true;
1048                         }
1049                     }
1050
1051                     if (!foundKey) {
1052                         throw new RestconfDocumentedException(
1053                                        "Missing key in URI \"" + listKey.getLocalName() +
1054                                        "\" of list \"" + schema.getQName().getLocalName() + "\"",
1055                                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
1056                     }
1057                 }
1058             }
1059         }
1060         else {
1061             if ((nodeBuilder instanceof SimpleNodeWrapper)) {
1062                 final SimpleNodeWrapper simpleNode = ((SimpleNodeWrapper) nodeBuilder);
1063                 final Object value = simpleNode.getValue();
1064                 Object inputValue = value;
1065                 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1066                 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1067                     if ((value instanceof String)) {
1068                         inputValue = new IdentityValuesDTO( nodeBuilder.getNamespace().toString(),
1069                                                             (String) value, null, (String) value );
1070                     } // else value is already instance of IdentityValuesDTO
1071                 }
1072
1073                 Codec<Object,Object> codec = RestCodec.from(typeDefinition, mountPoint);
1074                 Object outputValue = codec == null ? null : codec.deserialize(inputValue);
1075
1076                 simpleNode.setValue(outputValue);
1077             }
1078             else {
1079                 if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1080                     final EmptyNodeWrapper emptyNodeBuilder = ((EmptyNodeWrapper) nodeBuilder);
1081                     if ((schema instanceof LeafSchemaNode)) {
1082                         emptyNodeBuilder.setComposite(false);
1083                     }
1084                     else {
1085                         if ((schema instanceof ContainerSchemaNode)) {
1086                             // FIXME: Add presence check
1087                             emptyNodeBuilder.setComposite(true);
1088                         }
1089                     }
1090                 }
1091             }
1092         }
1093     }
1094
1095     private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder,
1096                                     final DataSchemaNode schema, final QName previousAugment,
1097                                     final MountInstance mountPoint) {
1098         QName validQName = schema.getQName();
1099         QName currentAugment = previousAugment;
1100         if (schema.isAugmenting()) {
1101             currentAugment = schema.getQName();
1102         }
1103         else if (previousAugment != null &&
1104                  !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1105             validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1106         }
1107
1108         String moduleName = null;
1109         if (mountPoint == null) {
1110             moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1111         }
1112         else {
1113             moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1114         }
1115
1116         if (nodeBuilder.getNamespace() == null ||
1117             Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) ||
1118             Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*||
1119             Note: this check is wrong - can never be true as it compares a URI with a String
1120                   not sure what the intention is so commented out...
1121             Objects.equal(nodeBuilder.getNamespace(), MOUNT_POINT_MODULE_NAME)*/ ) {
1122
1123             nodeBuilder.setQname(validQName);
1124         }
1125
1126         return currentAugment;
1127     }
1128
1129     private URI namespace(final CompositeNode data) {
1130         if (data instanceof CompositeNodeWrapper) {
1131             return ((CompositeNodeWrapper)data).getNamespace();
1132         }
1133         else if (data != null) {
1134             return data.getNodeType().getNamespace();
1135         }
1136         else {
1137             throw new IllegalArgumentException("Unhandled parameter types: " +
1138                     Arrays.<Object>asList(data).toString());
1139         }
1140     }
1141
1142     private String localName(final CompositeNode data) {
1143         if (data instanceof CompositeNodeWrapper) {
1144             return ((CompositeNodeWrapper)data).getLocalName();
1145         }
1146         else if (data != null) {
1147             return data.getNodeType().getLocalName();
1148         }
1149         else {
1150             throw new IllegalArgumentException("Unhandled parameter types: " +
1151                     Arrays.<Object>asList(data).toString());
1152         }
1153     }
1154
1155     private String getName(final CompositeNode data) {
1156         if (data instanceof CompositeNodeWrapper) {
1157             return ((CompositeNodeWrapper)data).getLocalName();
1158         }
1159         else if (data != null) {
1160             return data.getNodeType().getLocalName();
1161         }
1162         else {
1163             throw new IllegalArgumentException("Unhandled parameter types: " +
1164                     Arrays.<Object>asList(data).toString());
1165         }
1166     }
1167
1168     private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1169         TypeDefinition<?> baseType = node.getType();
1170         while (baseType.getBaseType() != null) {
1171             baseType = baseType.getBaseType();
1172         }
1173
1174         return baseType;
1175     }
1176
1177     private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1178         TypeDefinition<?> baseType = node.getType();
1179         while (baseType.getBaseType() != null) {
1180             baseType = baseType.getBaseType();
1181         }
1182
1183         return baseType;
1184     }
1185
1186     private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1187         if (node instanceof LeafListSchemaNode) {
1188             return typeDefinition((LeafListSchemaNode)node);
1189         }
1190         else if (node instanceof LeafSchemaNode) {
1191             return _typeDefinition((LeafSchemaNode)node);
1192         }
1193         else {
1194             throw new IllegalArgumentException("Unhandled parameter types: " +
1195                     Arrays.<Object>asList(node).toString());
1196         }
1197     }
1198 }