2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2014 Brocade Communication Systems, Inc.
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
9 package org.opendaylight.controller.sal.restconf.impl;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import java.math.BigInteger;
23 import java.net.URISyntaxException;
24 import java.text.ParseException;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.Arrays;
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;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.Response.Status;
37 import javax.ws.rs.core.UriBuilder;
38 import javax.ws.rs.core.UriInfo;
39 import org.apache.commons.lang3.StringUtils;
40 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
45 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
46 import org.opendaylight.controller.sal.rest.api.Draft02;
47 import org.opendaylight.controller.sal.rest.api.RestconfService;
48 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
50 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
51 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
52 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
53 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
54 import org.opendaylight.controller.sal.streams.listeners.Notificator;
55 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
56 import org.opendaylight.yangtools.concepts.Codec;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.QNameModule;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
61 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.Node;
63 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
75 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
76 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
77 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
78 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
82 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.util.EmptyType;
98 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
99 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
100 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
101 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
105 public class RestconfImpl implements RestconfService {
107 private enum UriParameters {
108 PRETTY_PRINT("prettyPrint"),
111 private String uriParameterName;
113 UriParameters(final String uriParameterName) {
114 this.uriParameterName = uriParameterName;
118 public String toString() {
119 return uriParameterName;
123 private static class TypeDef {
124 public final TypeDefinition<? extends Object> typedef;
125 public final QName qName;
127 TypeDef(final TypeDefinition<? extends Object> typedef, final QName qName) {
128 this.typedef = typedef;
133 private final static RestconfImpl INSTANCE = new RestconfImpl();
135 private static final int NOTIFICATION_PORT = 8181;
137 private static final int CHAR_NOT_FOUND = -1;
139 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
141 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
143 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
145 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
147 private BrokerFacade broker;
149 private ControllerContext controllerContext;
151 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
153 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
155 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
157 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
159 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
161 private static final String DATASTORE_PARAM_NAME = "datastore";
163 private static final String SCOPE_PARAM_NAME = "scope";
165 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
167 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
169 private static final QName NETCONF_BASE_QNAME;
173 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
174 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
175 } catch (final ParseException e) {
176 throw new RestconfDocumentedException(
177 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
178 ErrorTag.OPERATION_FAILED);
179 } catch (final URISyntaxException e) {
180 throw new RestconfDocumentedException(
181 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
182 ErrorTag.OPERATION_FAILED);
186 public void setBroker(final BrokerFacade broker) {
187 this.broker = broker;
190 public void setControllerContext(final ControllerContext controllerContext) {
191 this.controllerContext = controllerContext;
194 private RestconfImpl() {
197 public static RestconfImpl getInstance() {
202 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
203 final Set<Module> allModules = controllerContext.getAllModules();
204 final MapNode allModuleMap = makeModuleMapNode(allModules);
206 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
208 final Module restconfModule = getRestconfModule();
209 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
210 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
211 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
213 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
214 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
215 moduleContainerBuilder.withChild(allModuleMap);
217 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
218 null, schemaContext), moduleContainerBuilder.build());
222 * Valid only for mount point
225 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
226 Preconditions.checkNotNull(identifier);
227 if ( ! identifier.contains(ControllerContext.MOUNT)) {
228 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
229 + " URI has to end with " + ControllerContext.MOUNT;
230 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
233 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
234 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
235 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
236 final SchemaContext schemaContext = mountPoint.getSchemaContext();
237 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
239 final Module restconfModule = getRestconfModule();
240 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
241 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
242 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
244 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
245 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
246 moduleContainerBuilder.withChild(mountPointModulesMap);
248 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
249 mountPoint, schemaContext), moduleContainerBuilder.build());
253 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
254 Preconditions.checkNotNull(identifier);
255 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
256 Module module = null;
257 DOMMountPoint mountPoint = null;
258 final SchemaContext schemaContext;
259 if (identifier.contains(ControllerContext.MOUNT)) {
260 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
261 mountPoint = mountPointIdentifier.getMountPoint();
262 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
263 schemaContext = mountPoint.getSchemaContext();
265 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
266 schemaContext = controllerContext.getGlobalSchema();
269 if (module == null) {
270 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
271 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
272 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
275 final Module restconfModule = getRestconfModule();
276 final Set<Module> modules = Collections.singleton(module);
277 final MapNode moduleMap = makeModuleMapNode(modules);
279 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
280 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
281 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283 return new NormalizedNodeContext(new InstanceIdentifierContext(null, moduleSchemaNode, mountPoint,
284 schemaContext), moduleMap);
288 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
289 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
290 final Set<String> availableStreams = Notificator.getStreamNames();
291 final Module restconfModule = getRestconfModule();
292 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
293 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
294 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
296 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
297 .mapBuilder((ListSchemaNode) streamSchemaNode);
299 for (final String streamName : availableStreams) {
300 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
303 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
304 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
305 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
307 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
308 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
309 streamsContainerBuilder.withChild(listStreamsBuilder.build());
312 return new NormalizedNodeContext(new InstanceIdentifierContext(null, streamsContainerSchemaNode, null,
313 schemaContext), streamsContainerBuilder.build());
317 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
318 final Set<Module> allModules = controllerContext.getAllModules();
319 return operationsFromModulesToNormalizedContext(allModules, null);
323 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
324 Set<Module> modules = null;
325 DOMMountPoint mountPoint = null;
326 if (identifier.contains(ControllerContext.MOUNT)) {
327 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
328 mountPoint = mountPointIdentifier.getMountPoint();
329 modules = controllerContext.getAllModules(mountPoint);
332 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
333 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
336 return operationsFromModulesToNormalizedContext(modules, mountPoint);
339 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
340 final DOMMountPoint mountPoint) {
342 // FIXME find best way to change restconf-netconf yang schema for provide this functionality
343 final String errMsg = "We are not able support view operations functionality yet.";
344 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
348 * @deprecated method will be removed in Lithium release
351 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
352 final DOMMountPoint mountPoint, final boolean prettyPrint) {
353 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
354 final Module restconfModule = getRestconfModule();
355 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
356 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
357 final QName qName = operationsSchemaNode.getQName();
358 final SchemaPath path = operationsSchemaNode.getPath();
359 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
360 Draft02.RestConfModule.NAME, 0, qName, path);
361 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
362 for (final Module module : modules) {
363 final Set<RpcDefinition> rpcs = module.getRpcs();
364 for (final RpcDefinition rpc : rpcs) {
365 final QName rpcQName = rpc.getQName();
366 final SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
368 operationsAsData.add(immutableSimpleNode);
370 final String name = module.getName();
371 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
372 SchemaPath.create(true, QName.create("dummy")));
373 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
374 fakeRpcSchemaNode.setAugmenting(true);
376 final EmptyType instance = EmptyType.getInstance();
377 fakeRpcSchemaNode.setType(instance);
378 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
382 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
383 final ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
384 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
387 private Module getRestconfModule() {
388 final Module restconfModule = controllerContext.getRestconfModule();
389 if (restconfModule == null) {
390 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
391 ErrorTag.OPERATION_NOT_SUPPORTED);
394 return restconfModule;
397 private QName getModuleNameAndRevision(final String identifier) {
398 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
399 String moduleNameAndRevision = "";
400 if (mountIndex >= 0) {
401 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
403 moduleNameAndRevision = identifier;
406 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
407 final Iterable<String> split = splitter.split(moduleNameAndRevision);
408 final List<String> pathArgs = Lists.<String> newArrayList(split);
409 if (pathArgs.size() < 2) {
410 throw new RestconfDocumentedException(
411 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
412 ErrorTag.INVALID_VALUE);
416 final String moduleName = pathArgs.get(0);
417 final String revision = pathArgs.get(1);
418 final Date moduleRevision = REVISION_FORMAT.parse(revision);
419 return QName.create(null, moduleRevision, moduleName);
420 } catch (final ParseException e) {
421 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
422 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
427 * @deprecated method will be removed for Lithium release
428 * so, please use toStreamEntryNode method
431 * @param streamSchemaNode
435 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
436 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
437 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
438 ((DataNodeContainer) streamSchemaNode), "name");
439 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
441 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
443 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
444 ((DataNodeContainer) streamSchemaNode), "description");
445 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
446 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
447 "DESCRIPTION_PLACEHOLDER"));
449 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
450 ((DataNodeContainer) streamSchemaNode), "replay-support");
451 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
452 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
453 Boolean.valueOf(true)));
455 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
456 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
457 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
458 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
461 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
462 ((DataNodeContainer) streamSchemaNode), "events");
463 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
464 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
466 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
470 * @deprecated method will be removed for Lithium release
471 * so, please use toModuleEntryNode method
474 * @param moduleSchemaNode
478 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
479 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
480 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
481 ((DataNodeContainer) moduleSchemaNode), "name");
482 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
483 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
486 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
487 ((DataNodeContainer) moduleSchemaNode), "revision");
488 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
489 final Date _revision = module.getRevision();
490 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
491 REVISION_FORMAT.format(_revision)));
493 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
494 ((DataNodeContainer) moduleSchemaNode), "namespace");
495 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
496 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
497 module.getNamespace().toString()));
499 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
500 ((DataNodeContainer) moduleSchemaNode), "feature");
501 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
502 for (final FeatureDefinition feature : module.getFeatures()) {
503 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
504 feature.getQName().getLocalName()));
507 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
511 public Object getRoot() {
516 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
517 final RpcExecutor rpc = resolveIdentifierInInvokeRpc(identifier);
518 final QName rpcName = rpc.getRpcDefinition().getQName();
519 final URI rpcNamespace = rpcName.getNamespace();
520 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
521 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
522 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
525 validateInput(rpc.getRpcDefinition().getInput(), payload);
527 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
530 private void validateInput(final DataSchemaNode inputSchema, final NormalizedNodeContext payload) {
531 if (inputSchema != null && payload.getData() == null) {
532 // expected a non null payload
533 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
534 } else if (inputSchema == null && payload.getData() != null) {
535 // did not expect any input
536 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
540 // TODO: Validate "mandatory" and "config" values here??? Or should those be
542 // validate in a more central location inside MD-SAL core.
547 * @deprecated method will be removed for Lithium release
553 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
554 if (inputSchema != null && payload == null) {
555 // expected a non null payload
556 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
557 } else if (inputSchema == null && payload != null) {
558 // did not expect any input
559 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
563 // TODO: Validate "mandatory" and "config" values here??? Or should those be
565 // validate in a more central location inside MD-SAL core.
569 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
570 final boolean prettyPrint) {
571 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
572 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
573 rpc.getQName(), "path"));
574 final Object pathValue = pathNode == null ? null : pathNode.getValue();
576 if (!(pathValue instanceof YangInstanceIdentifier)) {
577 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
578 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
581 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
582 String streamName = null;
583 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
584 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier);
586 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
587 DATASTORE_PARAM_NAME);
588 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
590 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
591 scope = scope == null ? DEFAULT_SCOPE : scope;
593 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
594 + "/scope=" + scope);
597 if (Strings.isNullOrEmpty(streamName)) {
598 throw new RestconfDocumentedException(
599 "Path is empty or contains data node which is not Container or List build-in type.",
600 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
603 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
604 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
605 final List<Node<?>> output = new ArrayList<Node<?>>();
606 output.add(streamNameNode);
608 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
609 null, output, null, null);
611 if (!Notificator.existListenerFor(streamName)) {
612 Notificator.createListener(pathIdentifier, streamName);
615 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
619 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
620 if (StringUtils.isNotBlank(noPayload)) {
621 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
623 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
626 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
627 String identifierEncoded = null;
628 DOMMountPoint mountPoint = null;
629 if (identifier.contains(ControllerContext.MOUNT)) {
630 // mounted RPC call - look up mount instance.
631 final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
632 mountPoint = mountPointId.getMountPoint();
634 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
635 + ControllerContext.MOUNT.length() + 1;
636 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
637 identifierEncoded = remoteRpcName;
639 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
640 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
641 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
642 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
644 identifierEncoded = identifier;
647 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
649 RpcDefinition rpc = null;
650 if (mountPoint == null) {
651 rpc = controllerContext.getRpcDefinition(identifierDecoded);
653 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
657 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
660 if (mountPoint == null) {
661 return new BrokerRpcExecutor(rpc, broker);
663 return new MountPointRpcExecutor(rpc, mountPoint);
668 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
669 final String[] splittedIdentifier = identifierDecoded.split(":");
670 if (splittedIdentifier.length != 2) {
671 throw new RestconfDocumentedException(identifierDecoded
672 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
673 ErrorTag.INVALID_VALUE);
675 for (final Module module : schemaContext.getModules()) {
676 if (module.getName().equals(splittedIdentifier[0])) {
677 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
678 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
679 return rpcDefinition;
687 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
688 if (rpcExecutor == null) {
689 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
692 CompositeNode rpcRequest = null;
693 final RpcDefinition rpc = rpcExecutor.getRpcDefinition();
694 final QName rpcName = rpc.getQName();
696 if (payload == null) {
697 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
699 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
700 final List<Node<?>> input = Collections.<Node<?>> singletonList(value);
701 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
704 final RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
706 checkRpcSuccessAndThrowException(rpcResult);
708 if (rpcResult.getResult() == null) {
712 if (rpc.getOutput() == null) {
713 return null; // no output, nothing to send back.
716 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
719 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
720 if (rpcResult.isSuccessful() == false) {
722 throw new RestconfDocumentedException("The operation was not successful", null,
723 rpcResult.getErrors());
728 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
729 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
730 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
731 NormalizedNode<?, ?> data = null;
732 YangInstanceIdentifier normalizedII;
733 if (mountPoint != null) {
734 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
735 .getInstanceIdentifier());
736 data = broker.readConfigurationData(mountPoint, normalizedII);
738 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
739 data = broker.readConfigurationData(normalizedII);
741 return new NormalizedNodeContext(iiWithData, data);
744 @SuppressWarnings("unchecked")
745 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
750 if (node instanceof CompositeNode) {
751 final ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
753 for (final Node<?> childNode : ((CompositeNode) node).getValue()) {
754 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
758 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
759 } else { // SimpleNode
764 private Integer parseDepthParameter(final UriInfo info) {
765 final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
766 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
771 final Integer depth = Integer.valueOf(param);
773 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
774 "Invalid depth parameter: " + depth, null,
775 "The depth parameter must be an integer > 1 or \"unbounded\""));
779 } catch (final NumberFormatException e) {
780 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
781 "Invalid depth parameter: " + e.getMessage(), null,
782 "The depth parameter must be an integer > 1 or \"unbounded\""));
787 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
788 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
789 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
790 NormalizedNode<?, ?> data = null;
791 YangInstanceIdentifier normalizedII;
792 if (mountPoint != null) {
793 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
794 .getInstanceIdentifier());
795 data = broker.readOperationalData(mountPoint, normalizedII);
797 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
798 data = broker.readOperationalData(normalizedII);
801 return new NormalizedNodeContext(iiWithData, data);
804 private boolean parsePrettyPrintParameter(final UriInfo info) {
805 final String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
806 return Boolean.parseBoolean(param);
810 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
811 Preconditions.checkNotNull(identifier);
812 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
814 validateInput(iiWithData.getSchemaNode(), payload);
815 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
816 validateListKeysEqualityInPayloadAndUri(iiWithData, payload.getData());
818 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
820 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
823 * There is a small window where another write transaction could be updating the same data
824 * simultaneously and we get an OptimisticLockFailedException. This error is likely
825 * transient and The WriteTransaction#submit API docs state that a retry will likely
826 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
827 * probably will never succeed so we'll fail in that case.
829 * By retrying we're attempting to hide the internal implementation of the data store and
830 * how it handles concurrent updates from the restconf client. The client has instructed us
831 * to put the data and we should make every effort to do so without pushing optimistic lock
832 * failures back to the client and forcing them to handle it via retry (and having to
833 * document the behavior).
838 if (mountPoint != null) {
839 broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
841 broker.commitConfigurationDataPut(normalizedII, payload.getData()).checkedGet();
845 } catch (final TransactionCommitFailedException e) {
846 if(e instanceof OptimisticLockFailedException) {
848 LOG.debug("Got OptimisticLockFailedException on last try - failing");
849 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
852 LOG.debug("Got OptimisticLockFailedException - trying again");
854 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
859 return Response.status(Status.OK).build();
862 private void validateTopLevelNodeName(final NormalizedNodeContext node,
863 final YangInstanceIdentifier identifier) {
865 final String payloadName = node.getData().getNodeType().getLocalName();
866 final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
869 if ( ! pathArguments.hasNext()) {
871 if ( ! node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
872 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
873 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
877 final String identifierName = pathArguments.next().getNodeType().getLocalName();
878 if ( ! payloadName.equals(identifierName)) {
879 throw new RestconfDocumentedException("Payload name (" + payloadName
880 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
881 ErrorTag.MALFORMED_MESSAGE);
887 * @deprecated method will be removed for Lithium release
893 private void validateTopLevelNodeName(final Node<?> node,
894 final YangInstanceIdentifier identifier) {
895 final String payloadName = getName(node);
896 final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
899 if (!pathArguments.hasNext()) {
901 if (!node.getNodeType().equals(NETCONF_BASE_QNAME)) {
902 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
903 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
907 final String identifierName = pathArguments.next().getNodeType().getLocalName();
908 if (!payloadName.equals(identifierName)) {
909 throw new RestconfDocumentedException("Payload name (" + payloadName
910 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
911 ErrorTag.MALFORMED_MESSAGE);
917 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
919 * @throws RestconfDocumentedException
920 * if key values or key count in payload and URI isn't equal
923 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
924 final NormalizedNode<?, ?> payload) {
925 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
926 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
927 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
928 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
929 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
931 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
937 * @deprecated method will be removed for Lithium release
939 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
941 * @throws RestconfDocumentedException
942 * if key values or key count in payload and URI isn't equal
946 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
947 final CompositeNode payload) {
948 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
949 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
950 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
951 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
952 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
954 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
959 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final NormalizedNode<?, ?> payload,
960 final List<QName> keyDefinitions) {
961 for (final QName keyDefinition : keyDefinitions) {
962 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
963 // should be caught during parsing URI to InstanceIdentifier
964 if (uriKeyValue == null) {
965 final String errMsg = "Missing key " + keyDefinition + " in URI.";
966 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
968 // TODO thing about the possibility to fix
969 // final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
970 // if (payloadKeyValues.isEmpty()) {
971 // final String errMsg = "Missing key " + keyDefinition.getLocalName() + " in the message body.";
972 // throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
975 // final Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
976 // if (!uriKeyValue.equals(payloadKeyValue)) {
977 // final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
978 // "' specified in the URI doesn't match the value '" + payloadKeyValue + "' specified in the message body. ";
979 // throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
985 * @deprecated method will be removed for Lithium release
987 * @param uriKeyValues
989 * @param keyDefinitions
992 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
993 final List<QName> keyDefinitions) {
994 for (final QName keyDefinition : keyDefinitions) {
995 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
996 // should be caught during parsing URI to InstanceIdentifier
997 if (uriKeyValue == null) {
998 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
999 ErrorTag.DATA_MISSING);
1001 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
1002 if (payloadKeyValues.isEmpty()) {
1003 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
1004 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
1007 final Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
1008 if (!uriKeyValue.equals(payloadKeyValue)) {
1009 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
1010 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
1011 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
1012 ErrorTag.INVALID_VALUE);
1018 public Response createConfigurationData(final String identifier, final Node<?> payload) {
1019 if (payload == null) {
1020 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1023 final URI payloadNS = namespace(payload);
1024 if (payloadNS == null) {
1025 throw new RestconfDocumentedException(
1026 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
1027 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1030 InstanceIdentifierContext iiWithData = null;
1031 CompositeNode value = null;
1032 if (representsMountPointRootData(payload)) {
1033 // payload represents mount point data and URI represents path to the mount point
1035 if (endsWithMountPoint(identifier)) {
1036 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
1037 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
1038 ErrorTag.INVALID_VALUE);
1041 final String completeIdentifier = addMountPointIdentifier(identifier);
1042 iiWithData = controllerContext.toInstanceIdentifier(completeIdentifier);
1044 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
1046 final InstanceIdentifierContext incompleteInstIdWithData = controllerContext
1047 .toInstanceIdentifier(identifier);
1048 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
1049 final DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
1050 final Module module = findModule(mountPoint, payload);
1052 final String payloadName = getName(payload);
1053 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
1054 parentSchema, payloadName, module.getNamespace());
1055 value = this.normalizeNode(payload, schemaNode, mountPoint);
1057 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
1060 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
1061 iiWithData.getSchemaNode());
1062 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1063 YangInstanceIdentifier normalizedII;
1066 if (mountPoint != null) {
1067 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
1068 .getInstanceIdentifier());
1069 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
1071 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1072 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
1074 } catch(final RestconfDocumentedException e) {
1076 } catch (final Exception e) {
1077 throw new RestconfDocumentedException("Error creating data", e);
1080 return Response.status(Status.NO_CONTENT).build();
1084 public Response createConfigurationData(final Node<?> payload) {
1085 if (payload == null) {
1086 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1089 final URI payloadNS = namespace(payload);
1090 if (payloadNS == null) {
1091 throw new RestconfDocumentedException(
1092 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
1093 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1096 final Module module = this.findModule(null, payload);
1098 final String payloadName = getName(payload);
1099 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
1100 payloadName, module.getNamespace());
1101 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
1102 final InstanceIdentifierContext iiWithData = addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
1103 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
1104 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1105 YangInstanceIdentifier normalizedII;
1108 if (mountPoint != null) {
1109 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
1110 .getInstanceIdentifier());
1111 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
1114 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1115 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
1117 } catch(final RestconfDocumentedException e) {
1119 } catch (final Exception e) {
1120 throw new RestconfDocumentedException("Error creating data", e);
1123 return Response.status(Status.NO_CONTENT).build();
1127 public Response deleteConfigurationData(final String identifier) {
1128 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
1129 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1130 YangInstanceIdentifier normalizedII;
1133 if (mountPoint != null) {
1134 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
1135 .getInstanceIdentifier());
1136 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1138 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1139 broker.commitConfigurationDataDelete(normalizedII).get();
1141 } catch (final Exception e) {
1142 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1143 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1144 if (searchedException.isPresent()) {
1145 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
1147 throw new RestconfDocumentedException("Error while deleting data", e);
1149 return Response.status(Status.OK).build();
1153 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1155 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1157 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
1158 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
1162 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1163 final String streamName = Notificator.createStreamNameFromUri(identifier);
1164 if (Strings.isNullOrEmpty(streamName)) {
1165 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1168 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1169 if (listener == null) {
1170 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1173 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1174 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1175 paramToValues.get(DATASTORE_PARAM_NAME));
1176 if (datastore == null) {
1177 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1178 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1180 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1181 if (scope == null) {
1182 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1183 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1186 broker.registerToListenDataChanges(datastore, scope, listener);
1188 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1189 int notificationPort = NOTIFICATION_PORT;
1191 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1192 notificationPort = webSocketServerInstance.getPort();
1193 } catch (final NullPointerException e) {
1194 WebSocketServer.createInstance(NOTIFICATION_PORT);
1196 final UriBuilder port = uriBuilder.port(notificationPort);
1197 final URI uriToWebsocketServer = port.replacePath(streamName).build();
1199 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1203 * Load parameter for subscribing to stream from input composite node
1207 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1209 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1210 final String paramName) {
1211 final QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1212 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1213 final SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1214 if (simpleNode == null) {
1217 final Object rawValue = simpleNode.getValue();
1218 if (!(rawValue instanceof String)) {
1222 return resolveAsEnum(classDescriptor, (String) rawValue);
1226 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1228 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1231 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1232 if (Strings.isNullOrEmpty(value)) {
1235 return resolveAsEnum(classDescriptor, value);
1238 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1239 final T[] enumConstants = classDescriptor.getEnumConstants();
1240 if (enumConstants != null) {
1241 for (final T enm : classDescriptor.getEnumConstants()) {
1242 if (((Enum<?>) enm).name().equals(value)) {
1250 private Map<String, String> resolveValuesFromUri(final String uri) {
1251 final Map<String, String> result = new HashMap<>();
1252 final String[] tokens = uri.split("/");
1253 for (int i = 1; i < tokens.length; i++) {
1254 final String[] parameterTokens = tokens[i].split("=");
1255 if (parameterTokens.length == 2) {
1256 result.put(parameterTokens[0], parameterTokens[1]);
1262 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1263 Module module = null;
1264 if (data instanceof NodeWrapper) {
1265 module = findModule(mountPoint, (NodeWrapper<?>) data);
1266 } else if (data != null) {
1267 final URI namespace = data.getNodeType().getNamespace();
1268 if (mountPoint != null) {
1269 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1271 module = controllerContext.findModuleByNamespace(namespace);
1274 if (module != null) {
1277 throw new RestconfDocumentedException(
1278 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
1279 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1282 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1283 final URI namespace = data.getNamespace();
1284 Preconditions.<URI> checkNotNull(namespace);
1286 Module module = null;
1287 if (mountPoint != null) {
1288 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1289 if (module == null) {
1290 module = controllerContext.findModuleByName(mountPoint, namespace.toString());
1293 module = controllerContext.findModuleByNamespace(namespace);
1294 if (module == null) {
1295 module = controllerContext.findModuleByName(namespace.toString());
1302 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1303 final CompositeNode data, final DataSchemaNode schemaOfData, final SchemaContext schemaContext) {
1304 YangInstanceIdentifier instanceIdentifier = null;
1305 if (identifierWithSchemaNode != null) {
1306 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1309 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1310 InstanceIdentifierBuilder iiBuilder = null;
1311 if (iiOriginal == null) {
1312 iiBuilder = YangInstanceIdentifier.builder();
1314 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1317 if ((schemaOfData instanceof ListSchemaNode)) {
1318 final HashMap<QName, Object> keys = resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1319 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1321 iiBuilder.node(schemaOfData.getQName());
1324 final YangInstanceIdentifier instance = iiBuilder.toInstance();
1325 DOMMountPoint mountPoint = null;
1326 final SchemaContext schemaCtx = null;
1327 if (identifierWithSchemaNode != null) {
1328 mountPoint = identifierWithSchemaNode.getMountPoint();
1331 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1334 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1335 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1336 final List<QName> _keyDefinition = listNode.getKeyDefinition();
1337 for (final QName key : _keyDefinition) {
1338 SimpleNode<? extends Object> head = null;
1339 final String localName = key.getLocalName();
1340 final List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1341 if (simpleNodesByName != null) {
1342 head = Iterables.getFirst(simpleNodesByName, null);
1345 Object dataNodeKeyValueObject = null;
1347 dataNodeKeyValueObject = head.getValue();
1350 if (dataNodeKeyValueObject == null) {
1351 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1352 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1353 ErrorTag.INVALID_VALUE);
1356 keyValues.put(key, dataNodeKeyValueObject);
1362 private boolean endsWithMountPoint(final String identifier) {
1363 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1366 private boolean representsMountPointRootData(final Node<?> data) {
1367 final URI namespace = namespace(data);
1368 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1369 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1372 && SchemaContext.NAME.getLocalName().equals(localName(data));
1375 private String addMountPointIdentifier(final String identifier) {
1376 final boolean endsWith = identifier.endsWith("/");
1378 return (identifier + ControllerContext.MOUNT);
1381 return identifier + "/" + ControllerContext.MOUNT;
1385 * @deprecated method will be removed in Lithium release
1386 * we don't wish to use Node and CompositeNode anywhere
1389 public CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1390 if (schema == null) {
1391 final String localName = node == null ? null :
1392 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1393 node.getNodeType().getLocalName();
1395 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1396 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1399 if (!(schema instanceof DataNodeContainer)) {
1400 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1401 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1404 if ((node instanceof NodeWrapper<?>)) {
1405 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1406 final boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1407 if (isChangeAllowed) {
1408 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1410 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1411 } catch (final IllegalArgumentException e) {
1412 final RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1413 restconfDocumentedException.addSuppressed(e);
1414 throw restconfDocumentedException;
1416 if (nodeWrap instanceof CompositeNodeWrapper) {
1417 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1422 if (node instanceof CompositeNode) {
1423 return (CompositeNode) node;
1426 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1427 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1430 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1431 final QName previousAugment, final DOMMountPoint mountPoint) {
1432 if (schema == null) {
1433 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1434 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1437 QName currentAugment = null;
1438 if (nodeBuilder.getQname() != null) {
1439 currentAugment = previousAugment;
1441 currentAugment = normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1442 if (nodeBuilder.getQname() == null) {
1443 throw new RestconfDocumentedException(
1444 "Data has bad format.\nIf data is in XML format then namespace for \""
1445 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1446 + "\".\n" + "If data is in JSON format then module name for \""
1447 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1448 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1452 if (nodeBuilder instanceof CompositeNodeWrapper) {
1453 if (schema instanceof DataNodeContainer) {
1454 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1456 } else if (schema instanceof AnyXmlSchemaNode) {
1457 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1459 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1460 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1461 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1462 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1466 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1467 final List<NodeWrapper<?>> children = compositeNode.getValues();
1468 for (final NodeWrapper<? extends Object> child : children) {
1469 child.setNamespace(schema.getQName().getNamespace());
1470 if (child instanceof CompositeNodeWrapper) {
1471 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1476 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1477 if ((schema instanceof LeafSchemaNode)) {
1478 emptyNodeBuilder.setComposite(false);
1480 if ((schema instanceof ContainerSchemaNode)) {
1481 // FIXME: Add presence check
1482 emptyNodeBuilder.setComposite(true);
1487 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1488 final DOMMountPoint mountPoint) {
1489 final Object value = simpleNode.getValue();
1490 Object inputValue = value;
1491 final TypeDef typeDef = this.typeDefinition(schema);
1492 TypeDefinition<? extends Object> typeDefinition = typeDef != null ? typeDef.typedef : null;
1494 // For leafrefs, extract the type it is pointing to
1495 if(typeDefinition instanceof LeafrefTypeDefinition) {
1496 if (schema.getQName().equals(typeDef.qName)) {
1497 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema);
1499 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), typeDef.qName);
1503 if (typeDefinition instanceof IdentityrefTypeDefinition) {
1504 inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue);
1507 Object outputValue = inputValue;
1509 if (typeDefinition != null) {
1510 final Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1511 outputValue = codec == null ? null : codec.deserialize(inputValue);
1514 simpleNode.setValue(outputValue);
1517 private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) {
1518 if ((value instanceof String)) {
1519 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1521 } // else value is already instance of IdentityValuesDTO
1525 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1526 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1527 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1528 checkNodeMultiplicityAccordingToSchema(schema, children);
1529 for (final NodeWrapper<? extends Object> child : children) {
1530 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1531 schema, child.getLocalName());
1533 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1534 final StringBuilder builder = new StringBuilder();
1535 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1536 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1539 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1540 + "\" is added as augment from more than one module. "
1541 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1542 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1543 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1546 boolean rightNodeSchemaFound = false;
1547 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1548 if (!rightNodeSchemaFound) {
1549 final QName potentialCurrentAugment = normalizeNodeName(child, potentialSchemaNode,
1550 currentAugment, mountPoint);
1551 if (child.getQname() != null) {
1552 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1553 rightNodeSchemaFound = true;
1558 if (!rightNodeSchemaFound) {
1559 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1560 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1564 if ((schema instanceof ListSchemaNode)) {
1565 final ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1566 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1567 for (final QName listKey : listKeys) {
1568 boolean foundKey = false;
1569 for (final NodeWrapper<? extends Object> child : children) {
1570 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1576 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1577 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1578 ErrorTag.DATA_MISSING);
1584 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1585 final List<NodeWrapper<?>> nodes) {
1586 final Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1587 for (final NodeWrapper<?> child : nodes) {
1588 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1589 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1592 for (final DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1593 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1594 final String localName = childSchemaNode.getQName().getLocalName();
1595 final Integer count = equalNodeNamesToCounts.get(localName);
1596 if (count != null && count > 1) {
1597 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1598 + childSchemaNode.getQName().getLocalName()
1599 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1600 ErrorTag.BAD_ELEMENT);
1606 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1607 final QName previousAugment, final DOMMountPoint mountPoint) {
1608 QName validQName = schema.getQName();
1609 QName currentAugment = previousAugment;
1610 if (schema.isAugmenting()) {
1611 currentAugment = schema.getQName();
1612 } else if (previousAugment != null
1613 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1614 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1617 String moduleName = null;
1618 if (mountPoint == null) {
1619 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1621 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1624 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1625 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1627 * || Note : this check is wrong -
1628 * can never be true as it compares
1629 * a URI with a String not sure what
1630 * the intention is so commented out
1631 * ... Objects . equal ( nodeBuilder
1632 * . getNamespace ( ) ,
1633 * MOUNT_POINT_MODULE_NAME )
1636 nodeBuilder.setQname(validQName);
1639 return currentAugment;
1642 private URI namespace(final Node<?> data) {
1643 if (data instanceof NodeWrapper) {
1644 return ((NodeWrapper<?>) data).getNamespace();
1645 } else if (data != null) {
1646 return data.getNodeType().getNamespace();
1648 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1652 private String localName(final Node<?> data) {
1653 if (data instanceof NodeWrapper) {
1654 return ((NodeWrapper<?>) data).getLocalName();
1655 } else if (data != null) {
1656 return data.getNodeType().getLocalName();
1658 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1663 * @deprecated method will be removed for Lithium release
1669 private String getName(final Node<?> data) {
1670 if (data instanceof NodeWrapper) {
1671 return ((NodeWrapper<?>) data).getLocalName();
1672 } else if (data != null) {
1673 return data.getNodeType().getLocalName();
1675 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1679 private TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
1680 TypeDefinition<?> baseType = type;
1681 QName qName = nodeQName;
1682 while (baseType.getBaseType() != null) {
1683 if (baseType instanceof ExtendedType) {
1684 qName = baseType.getQName();
1686 baseType = baseType.getBaseType();
1689 return new TypeDef(baseType, qName);
1693 private TypeDef typeDefinition(final DataSchemaNode node) {
1694 if (node instanceof LeafListSchemaNode) {
1695 return typeDefinition(((LeafListSchemaNode)node).getType(), node.getQName());
1696 } else if (node instanceof LeafSchemaNode) {
1697 return typeDefinition(((LeafSchemaNode)node).getType(), node.getQName());
1698 } else if (node instanceof AnyXmlSchemaNode) {
1701 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1705 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1706 Node<?> nodes = null;
1707 if (dataNode == null) {
1708 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1709 "No data was found."));
1711 nodes = DataNormalizer.toLegacy(dataNode);
1712 if (nodes != null) {
1713 if (nodes instanceof CompositeNode) {
1714 return (CompositeNode) nodes;
1716 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1719 LOG.error("Top level node isn't of type Container or List schema node but "
1720 + schema.getClass().getSimpleName());
1723 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1724 "It wasn't possible to correctly interpret data."));
1727 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1728 final DataSchemaNode schema) {
1729 final List<Node<?>> lst = new ArrayList<Node<?>>();
1731 if (schema instanceof ContainerSchemaNode) {
1732 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1733 .parse(lst, (ContainerSchemaNode) schema);
1734 } else if (schema instanceof ListSchemaNode) {
1735 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1736 .parse(lst, (ListSchemaNode) schema);
1739 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1741 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1742 "It wasn't possible to translate specified data to datastore readable form."));
1745 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1746 final InstanceIdentifierContext iiWithSchemaNode) {
1747 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1750 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1751 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1752 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1753 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1754 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1757 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1758 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1759 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1760 final List<PathArgument> result = new ArrayList<PathArgument>();
1761 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1762 while (iter.hasNext()) {
1763 final PathArgument pathArgument = iter.next();
1764 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1765 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1767 result.add(pathArgument);
1769 return YangInstanceIdentifier.create(result);
1772 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1773 final DataSchemaNode schemaNode) {
1774 if (node instanceof CompositeNodeWrapper) {
1775 return (CompositeNodeWrapper) node;
1776 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1777 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1778 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1781 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1782 "Top level element has to be composite node or has to represent data container node."));
1785 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1786 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1792 public BigInteger getOperationalReceived() {
1793 // TODO Auto-generated method stub
1797 private MapNode makeModuleMapNode(final Set<Module> modules) {
1798 Preconditions.checkNotNull(modules);
1799 final Module restconfModule = getRestconfModule();
1800 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1801 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1802 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1804 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1805 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1807 for (final Module module : modules) {
1808 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1810 return listModuleBuilder.build();
1813 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1814 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1815 "moduleSchemaNode has to be of type ListSchemaNode");
\r final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
\r final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
\r .mapEntryBuilder(listModuleSchemaNode);
\r\r List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "name");
\r final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
\r .build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "revision");
\r final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
\r final String revision = REVISION_FORMAT.format(module.getRevision());
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
\r .build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "namespace");
\r final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
\r .withValue(module.getNamespace().toString()).build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "feature");
\r final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
\r final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
\r .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
\r for (final FeatureDefinition feature : module.getFeatures()) {
\r featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
\r .withValue(feature.getQName().getLocalName()).build());
\r }
\r moduleNodeValues.withChild(featuresBuilder.build());
1816 \r return moduleNodeValues.build();
\r }
1818 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1819 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1820 "streamSchemaNode has to be of type ListSchemaNode");
1821 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1822 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1823 .mapEntryBuilder(listStreamSchemaNode);
1825 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1826 (listStreamSchemaNode), "name");
1827 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1828 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1829 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1832 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1833 (listStreamSchemaNode), "description");
1834 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1835 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1836 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1837 .withValue("DESCRIPTION_PLACEHOLDER").build());
1839 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1840 (listStreamSchemaNode), "replay-support");
1841 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1842 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1843 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1844 .withValue(Boolean.valueOf(true)).build());
1846 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1847 (listStreamSchemaNode), "replay-log-creation-time");
1848 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1849 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1850 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1851 .withValue("").build());
1853 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1854 (listStreamSchemaNode), "events");
1855 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1856 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1857 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1858 .withValue("").build());
1860 return streamNodeValues.build();