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.ResponseBuilder;
37 import javax.ws.rs.core.Response.Status;
38 import javax.ws.rs.core.UriBuilder;
39 import javax.ws.rs.core.UriInfo;
40 import org.apache.commons.lang3.StringUtils;
41 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
42 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
43 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
44 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
45 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
46 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
47 import org.opendaylight.controller.sal.rest.api.Draft02;
48 import org.opendaylight.controller.sal.rest.api.RestconfService;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
50 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
51 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
52 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
53 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
54 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
55 import org.opendaylight.controller.sal.streams.listeners.Notificator;
56 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
57 import org.opendaylight.yangtools.concepts.Codec;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.common.QNameModule;
60 import org.opendaylight.yangtools.yang.common.RpcResult;
61 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
63 import org.opendaylight.yangtools.yang.data.api.Node;
64 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
70 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
76 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
77 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
78 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
79 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
83 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
95 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
98 import org.opendaylight.yangtools.yang.model.util.EmptyType;
99 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
100 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
101 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
102 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
103 import org.slf4j.Logger;
104 import org.slf4j.LoggerFactory;
106 public class RestconfImpl implements RestconfService {
108 private enum UriParameters {
109 PRETTY_PRINT("prettyPrint"),
112 private String uriParameterName;
114 UriParameters(final String uriParameterName) {
115 this.uriParameterName = uriParameterName;
119 public String toString() {
120 return uriParameterName;
124 private static class TypeDef {
125 public final TypeDefinition<? extends Object> typedef;
126 public final QName qName;
128 TypeDef(final TypeDefinition<? extends Object> typedef, final QName qName) {
129 this.typedef = typedef;
134 private final static RestconfImpl INSTANCE = new RestconfImpl();
136 private static final int NOTIFICATION_PORT = 8181;
138 private static final int CHAR_NOT_FOUND = -1;
140 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
142 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
144 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
146 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
148 private BrokerFacade broker;
150 private ControllerContext controllerContext;
152 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
154 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
156 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
158 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
160 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
162 private static final String DATASTORE_PARAM_NAME = "datastore";
164 private static final String SCOPE_PARAM_NAME = "scope";
166 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
168 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
170 private static final QName NETCONF_BASE_QNAME;
174 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
175 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
176 } catch (final ParseException e) {
177 throw new RestconfDocumentedException(
178 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
179 ErrorTag.OPERATION_FAILED);
180 } catch (final URISyntaxException e) {
181 throw new RestconfDocumentedException(
182 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
183 ErrorTag.OPERATION_FAILED);
187 public void setBroker(final BrokerFacade broker) {
188 this.broker = broker;
191 public void setControllerContext(final ControllerContext controllerContext) {
192 this.controllerContext = controllerContext;
195 private RestconfImpl() {
198 public static RestconfImpl getInstance() {
203 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
204 final Set<Module> allModules = controllerContext.getAllModules();
205 final MapNode allModuleMap = makeModuleMapNode(allModules);
207 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
209 final Module restconfModule = getRestconfModule();
210 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
211 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
212 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
214 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
215 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
216 moduleContainerBuilder.withChild(allModuleMap);
218 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
219 null, schemaContext), moduleContainerBuilder.build());
223 * Valid only for mount point
226 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
227 Preconditions.checkNotNull(identifier);
228 if ( ! identifier.contains(ControllerContext.MOUNT)) {
229 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
230 + " URI has to end with " + ControllerContext.MOUNT;
231 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
234 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
235 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
236 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
237 final SchemaContext schemaContext = mountPoint.getSchemaContext();
238 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
240 final Module restconfModule = getRestconfModule();
241 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
242 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
243 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
245 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
246 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
247 moduleContainerBuilder.withChild(mountPointModulesMap);
249 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
250 mountPoint, schemaContext), moduleContainerBuilder.build());
254 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
255 Preconditions.checkNotNull(identifier);
256 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
257 Module module = null;
258 DOMMountPoint mountPoint = null;
259 final SchemaContext schemaContext;
260 if (identifier.contains(ControllerContext.MOUNT)) {
261 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
262 mountPoint = mountPointIdentifier.getMountPoint();
263 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
264 schemaContext = mountPoint.getSchemaContext();
266 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
267 schemaContext = controllerContext.getGlobalSchema();
270 if (module == null) {
271 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
272 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
273 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
276 final Module restconfModule = getRestconfModule();
277 final Set<Module> modules = Collections.singleton(module);
278 final MapNode moduleMap = makeModuleMapNode(modules);
280 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
281 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
282 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
284 return new NormalizedNodeContext(new InstanceIdentifierContext(null, moduleSchemaNode, mountPoint,
285 schemaContext), moduleMap);
289 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
290 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
291 final Set<String> availableStreams = Notificator.getStreamNames();
292 final Module restconfModule = getRestconfModule();
293 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
294 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
295 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
297 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
298 .mapBuilder((ListSchemaNode) streamSchemaNode);
300 for (final String streamName : availableStreams) {
301 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
304 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
305 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
306 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
308 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
309 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
310 streamsContainerBuilder.withChild(listStreamsBuilder.build());
313 return new NormalizedNodeContext(new InstanceIdentifierContext(null, streamsContainerSchemaNode, null,
314 schemaContext), streamsContainerBuilder.build());
318 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
319 final Set<Module> allModules = controllerContext.getAllModules();
320 return operationsFromModulesToNormalizedContext(allModules, null);
324 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
325 Set<Module> modules = null;
326 DOMMountPoint mountPoint = null;
327 if (identifier.contains(ControllerContext.MOUNT)) {
328 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
329 mountPoint = mountPointIdentifier.getMountPoint();
330 modules = controllerContext.getAllModules(mountPoint);
333 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
334 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
337 return operationsFromModulesToNormalizedContext(modules, mountPoint);
340 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
341 final DOMMountPoint mountPoint) {
343 // FIXME find best way to change restconf-netconf yang schema for provide this functionality
344 final String errMsg = "We are not able support view operations functionality yet.";
345 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
349 * @deprecated method will be removed in Lithium release
352 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
353 final DOMMountPoint mountPoint, final boolean prettyPrint) {
354 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
355 final Module restconfModule = getRestconfModule();
356 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
357 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
358 final QName qName = operationsSchemaNode.getQName();
359 final SchemaPath path = operationsSchemaNode.getPath();
360 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
361 Draft02.RestConfModule.NAME, 0, qName, path);
362 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
363 for (final Module module : modules) {
364 final Set<RpcDefinition> rpcs = module.getRpcs();
365 for (final RpcDefinition rpc : rpcs) {
366 final QName rpcQName = rpc.getQName();
367 final SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
369 operationsAsData.add(immutableSimpleNode);
371 final String name = module.getName();
372 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
373 SchemaPath.create(true, QName.create("dummy")));
374 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
375 fakeRpcSchemaNode.setAugmenting(true);
377 final EmptyType instance = EmptyType.getInstance();
378 fakeRpcSchemaNode.setType(instance);
379 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
383 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
384 final ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
385 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
388 private Module getRestconfModule() {
389 final Module restconfModule = controllerContext.getRestconfModule();
390 if (restconfModule == null) {
391 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
392 ErrorTag.OPERATION_NOT_SUPPORTED);
395 return restconfModule;
398 private QName getModuleNameAndRevision(final String identifier) {
399 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
400 String moduleNameAndRevision = "";
401 if (mountIndex >= 0) {
402 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
404 moduleNameAndRevision = identifier;
407 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
408 final Iterable<String> split = splitter.split(moduleNameAndRevision);
409 final List<String> pathArgs = Lists.<String> newArrayList(split);
410 if (pathArgs.size() < 2) {
411 throw new RestconfDocumentedException(
412 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
413 ErrorTag.INVALID_VALUE);
417 final String moduleName = pathArgs.get(0);
418 final String revision = pathArgs.get(1);
419 final Date moduleRevision = REVISION_FORMAT.parse(revision);
420 return QName.create(null, moduleRevision, moduleName);
421 } catch (final ParseException e) {
422 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
423 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
428 * @deprecated method will be removed for Lithium release
429 * so, please use toStreamEntryNode method
432 * @param streamSchemaNode
436 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
437 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
438 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
439 ((DataNodeContainer) streamSchemaNode), "name");
440 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
442 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
444 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
445 ((DataNodeContainer) streamSchemaNode), "description");
446 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
447 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
448 "DESCRIPTION_PLACEHOLDER"));
450 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
451 ((DataNodeContainer) streamSchemaNode), "replay-support");
452 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
453 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
454 Boolean.valueOf(true)));
456 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
457 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
458 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
459 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
462 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
463 ((DataNodeContainer) streamSchemaNode), "events");
464 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
465 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
467 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
471 * @deprecated method will be removed for Lithium release
472 * so, please use toModuleEntryNode method
475 * @param moduleSchemaNode
479 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
480 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
481 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
482 ((DataNodeContainer) moduleSchemaNode), "name");
483 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
484 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
487 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
488 ((DataNodeContainer) moduleSchemaNode), "revision");
489 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
490 final Date _revision = module.getRevision();
491 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
492 REVISION_FORMAT.format(_revision)));
494 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
495 ((DataNodeContainer) moduleSchemaNode), "namespace");
496 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
497 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
498 module.getNamespace().toString()));
500 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
501 ((DataNodeContainer) moduleSchemaNode), "feature");
502 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
503 for (final FeatureDefinition feature : module.getFeatures()) {
504 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
505 feature.getQName().getLocalName()));
508 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
512 public Object getRoot() {
517 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
518 final RpcExecutor rpc = resolveIdentifierInInvokeRpc(identifier);
519 final QName rpcName = rpc.getRpcDefinition().getQName();
520 final URI rpcNamespace = rpcName.getNamespace();
521 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
522 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
523 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
526 validateInput(rpc.getRpcDefinition().getInput(), payload);
528 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
531 private void validateInput(final DataSchemaNode inputSchema, final NormalizedNodeContext payload) {
532 if (inputSchema != null && payload.getData() == null) {
533 // expected a non null payload
534 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
535 } else if (inputSchema == null && payload.getData() != null) {
536 // did not expect any input
537 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
541 // TODO: Validate "mandatory" and "config" values here??? Or should those be
543 // validate in a more central location inside MD-SAL core.
548 * @deprecated method will be removed for Lithium release
554 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
555 if (inputSchema != null && payload == null) {
556 // expected a non null payload
557 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
558 } else if (inputSchema == null && payload != null) {
559 // did not expect any input
560 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
564 // TODO: Validate "mandatory" and "config" values here??? Or should those be
566 // validate in a more central location inside MD-SAL core.
570 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
571 final boolean prettyPrint) {
572 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
573 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
574 rpc.getQName(), "path"));
575 final Object pathValue = pathNode == null ? null : pathNode.getValue();
577 if (!(pathValue instanceof YangInstanceIdentifier)) {
578 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
579 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
582 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
583 String streamName = null;
584 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
585 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
587 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
588 DATASTORE_PARAM_NAME);
589 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
591 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
592 scope = scope == null ? DEFAULT_SCOPE : scope;
594 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
595 + "/scope=" + scope);
598 if (Strings.isNullOrEmpty(streamName)) {
599 throw new RestconfDocumentedException(
600 "Path is empty or contains data node which is not Container or List build-in type.",
601 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
604 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
605 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
606 final List<Node<?>> output = new ArrayList<Node<?>>();
607 output.add(streamNameNode);
609 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
610 null, output, null, null);
612 if (!Notificator.existListenerFor(streamName)) {
613 Notificator.createListener(pathIdentifier, streamName);
616 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
620 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
621 if (StringUtils.isNotBlank(noPayload)) {
622 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
624 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
627 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
628 String identifierEncoded = null;
629 DOMMountPoint mountPoint = null;
630 if (identifier.contains(ControllerContext.MOUNT)) {
631 // mounted RPC call - look up mount instance.
632 final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
633 mountPoint = mountPointId.getMountPoint();
635 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
636 + ControllerContext.MOUNT.length() + 1;
637 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
638 identifierEncoded = remoteRpcName;
640 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
641 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
642 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
643 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
645 identifierEncoded = identifier;
648 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
650 RpcDefinition rpc = null;
651 if (mountPoint == null) {
652 rpc = controllerContext.getRpcDefinition(identifierDecoded);
654 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
658 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
661 if (mountPoint == null) {
662 return new BrokerRpcExecutor(rpc, broker);
664 return new MountPointRpcExecutor(rpc, mountPoint);
669 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
670 final String[] splittedIdentifier = identifierDecoded.split(":");
671 if (splittedIdentifier.length != 2) {
672 throw new RestconfDocumentedException(identifierDecoded
673 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
674 ErrorTag.INVALID_VALUE);
676 for (final Module module : schemaContext.getModules()) {
677 if (module.getName().equals(splittedIdentifier[0])) {
678 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
679 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
680 return rpcDefinition;
688 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
689 if (rpcExecutor == null) {
690 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
693 CompositeNode rpcRequest = null;
694 final RpcDefinition rpc = rpcExecutor.getRpcDefinition();
695 final QName rpcName = rpc.getQName();
697 if (payload == null) {
698 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
700 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
701 final List<Node<?>> input = Collections.<Node<?>> singletonList(value);
702 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
705 final RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
707 checkRpcSuccessAndThrowException(rpcResult);
709 if (rpcResult.getResult() == null) {
713 if (rpc.getOutput() == null) {
714 return null; // no output, nothing to send back.
717 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
720 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
721 if (rpcResult.isSuccessful() == false) {
723 throw new RestconfDocumentedException("The operation was not successful", null,
724 rpcResult.getErrors());
729 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
730 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
731 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
732 NormalizedNode<?, ?> data = null;
733 YangInstanceIdentifier normalizedII;
734 if (mountPoint != null) {
735 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
736 .getInstanceIdentifier());
737 data = broker.readConfigurationData(mountPoint, normalizedII);
739 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
740 data = broker.readConfigurationData(normalizedII);
742 return new NormalizedNodeContext(iiWithData, data);
745 @SuppressWarnings("unchecked")
746 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
751 if (node instanceof CompositeNode) {
752 final ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
754 for (final Node<?> childNode : ((CompositeNode) node).getValue()) {
755 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
759 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
760 } else { // SimpleNode
765 private Integer parseDepthParameter(final UriInfo info) {
766 final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
767 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
772 final Integer depth = Integer.valueOf(param);
774 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
775 "Invalid depth parameter: " + depth, null,
776 "The depth parameter must be an integer > 1 or \"unbounded\""));
780 } catch (final NumberFormatException e) {
781 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
782 "Invalid depth parameter: " + e.getMessage(), null,
783 "The depth parameter must be an integer > 1 or \"unbounded\""));
788 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
789 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
790 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
791 NormalizedNode<?, ?> data = null;
792 YangInstanceIdentifier normalizedII;
793 if (mountPoint != null) {
794 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
795 .getInstanceIdentifier());
796 data = broker.readOperationalData(mountPoint, normalizedII);
798 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
799 data = broker.readOperationalData(normalizedII);
802 return new NormalizedNodeContext(iiWithData, data);
805 private boolean parsePrettyPrintParameter(final UriInfo info) {
806 final String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
807 return Boolean.parseBoolean(param);
811 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
812 Preconditions.checkNotNull(identifier);
813 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
815 validateInput(iiWithData.getSchemaNode(), payload);
816 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
817 validateListKeysEqualityInPayloadAndUri(iiWithData, payload.getData());
819 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 NormalizedNodeContext payload, final UriInfo uriInfo) {
1019 if (payload == null) {
1020 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1023 final URI payloadNS = payload.getData().getNodeType().getNamespace();
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 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
1032 final InstanceIdentifierContext iiWithData = mountPoint != null
1033 ? controllerContext.toMountPointIdentifier(identifier)
1034 : controllerContext.toInstanceIdentifier(identifier);
1035 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
1038 if (mountPoint != null) {
1039 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
1041 broker.commitConfigurationDataPost(normalizedII, payload.getData());
1043 } catch(final RestconfDocumentedException e) {
1045 } catch (final Exception e) {
1046 throw new RestconfDocumentedException("Error creating data", e);
1050 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1051 final URI location = resolveLocation(uriInfo, "config", mountPoint, normalizedII);
1052 if (location != null) {
1053 responseBuilder.location(location);
1055 return responseBuilder.build();
1059 public Response createConfigurationData(final Node<?> payload, final UriInfo uriInfo) {
1060 if (payload == null) {
1061 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1064 final URI payloadNS = namespace(payload);
1065 if (payloadNS == null) {
1066 throw new RestconfDocumentedException(
1067 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
1068 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1071 final Module module = this.findModule(null, payload);
1072 if (module == null) {
1073 throw new RestconfDocumentedException(
1074 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
1075 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1078 final String payloadName = getName(payload);
1079 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
1080 payloadName, module.getNamespace());
1081 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
1082 final InstanceIdentifierContext iiWithData = addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
1083 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
1084 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1085 YangInstanceIdentifier normalizedII;
1088 if (mountPoint != null) {
1089 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
1090 .getInstanceIdentifier());
1091 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
1094 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1095 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
1097 } catch(final RestconfDocumentedException e) {
1099 } catch (final Exception e) {
1100 throw new RestconfDocumentedException("Error creating data", e);
1103 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
1104 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
1105 if (location != null) {
1106 responseBuilder.location(location);
1108 return responseBuilder.build();
1111 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
1112 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
1113 uriBuilder.path("config");
1115 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
1116 } catch (final Exception e) {
1117 LOG.debug("Location for instance identifier"+normalizedII+"wasn't created", e);
1120 return uriBuilder.build();
1124 public Response deleteConfigurationData(final String identifier) {
1125 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
1126 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1127 YangInstanceIdentifier normalizedII;
1130 if (mountPoint != null) {
1131 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
1132 .getInstanceIdentifier());
1133 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1135 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1136 broker.commitConfigurationDataDelete(normalizedII).get();
1138 } catch (final Exception e) {
1139 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1140 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1141 if (searchedException.isPresent()) {
1142 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
1144 throw new RestconfDocumentedException("Error while deleting data", e);
1146 return Response.status(Status.OK).build();
1150 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1152 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1154 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
1155 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
1159 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1160 final String streamName = Notificator.createStreamNameFromUri(identifier);
1161 if (Strings.isNullOrEmpty(streamName)) {
1162 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1165 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1166 if (listener == null) {
1167 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1170 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1171 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1172 paramToValues.get(DATASTORE_PARAM_NAME));
1173 if (datastore == null) {
1174 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1175 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1177 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1178 if (scope == null) {
1179 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1180 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1183 broker.registerToListenDataChanges(datastore, scope, listener);
1185 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1186 int notificationPort = NOTIFICATION_PORT;
1188 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1189 notificationPort = webSocketServerInstance.getPort();
1190 } catch (final NullPointerException e) {
1191 WebSocketServer.createInstance(NOTIFICATION_PORT);
1193 final UriBuilder port = uriBuilder.port(notificationPort);
1194 final URI uriToWebsocketServer = port.replacePath(streamName).build();
1196 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1200 * Load parameter for subscribing to stream from input composite node
1204 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1206 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1207 final String paramName) {
1208 final QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1209 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1210 final SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1211 if (simpleNode == null) {
1214 final Object rawValue = simpleNode.getValue();
1215 if (!(rawValue instanceof String)) {
1219 return resolveAsEnum(classDescriptor, (String) rawValue);
1223 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1225 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1228 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1229 if (Strings.isNullOrEmpty(value)) {
1232 return resolveAsEnum(classDescriptor, value);
1235 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1236 final T[] enumConstants = classDescriptor.getEnumConstants();
1237 if (enumConstants != null) {
1238 for (final T enm : classDescriptor.getEnumConstants()) {
1239 if (((Enum<?>) enm).name().equals(value)) {
1247 private Map<String, String> resolveValuesFromUri(final String uri) {
1248 final Map<String, String> result = new HashMap<>();
1249 final String[] tokens = uri.split("/");
1250 for (int i = 1; i < tokens.length; i++) {
1251 final String[] parameterTokens = tokens[i].split("=");
1252 if (parameterTokens.length == 2) {
1253 result.put(parameterTokens[0], parameterTokens[1]);
1259 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1260 Module module = null;
1261 if (data instanceof NodeWrapper) {
1262 module = findModule(mountPoint, (NodeWrapper<?>) data);
1263 } else if (data != null) {
1264 final URI namespace = data.getNodeType().getNamespace();
1265 if (mountPoint != null) {
1266 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1268 module = controllerContext.findModuleByNamespace(namespace);
1271 if (module != null) {
1274 throw new RestconfDocumentedException(
1275 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
1276 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1279 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1280 final URI namespace = data.getNamespace();
1281 Preconditions.<URI> checkNotNull(namespace);
1283 Module module = null;
1284 if (mountPoint != null) {
1285 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1286 if (module == null) {
1287 module = controllerContext.findModuleByName(mountPoint, namespace.toString());
1290 module = controllerContext.findModuleByNamespace(namespace);
1291 if (module == null) {
1292 module = controllerContext.findModuleByName(namespace.toString());
1299 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1300 final CompositeNode data, final DataSchemaNode schemaOfData, final SchemaContext schemaContext) {
1301 YangInstanceIdentifier instanceIdentifier = null;
1302 if (identifierWithSchemaNode != null) {
1303 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1306 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1307 InstanceIdentifierBuilder iiBuilder = null;
1308 if (iiOriginal == null) {
1309 iiBuilder = YangInstanceIdentifier.builder();
1311 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1314 if ((schemaOfData instanceof ListSchemaNode)) {
1315 final HashMap<QName, Object> keys = resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1316 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1318 iiBuilder.node(schemaOfData.getQName());
1321 final YangInstanceIdentifier instance = iiBuilder.toInstance();
1322 DOMMountPoint mountPoint = null;
1323 final SchemaContext schemaCtx = null;
1324 if (identifierWithSchemaNode != null) {
1325 mountPoint = identifierWithSchemaNode.getMountPoint();
1328 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1331 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1332 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1333 final List<QName> _keyDefinition = listNode.getKeyDefinition();
1334 for (final QName key : _keyDefinition) {
1335 SimpleNode<? extends Object> head = null;
1336 final String localName = key.getLocalName();
1337 final List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1338 if (simpleNodesByName != null) {
1339 head = Iterables.getFirst(simpleNodesByName, null);
1342 Object dataNodeKeyValueObject = null;
1344 dataNodeKeyValueObject = head.getValue();
1347 if (dataNodeKeyValueObject == null) {
1348 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1349 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1350 ErrorTag.INVALID_VALUE);
1353 keyValues.put(key, dataNodeKeyValueObject);
1359 private boolean endsWithMountPoint(final String identifier) {
1360 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1363 private boolean representsMountPointRootData(final Node<?> data) {
1364 final URI namespace = namespace(data);
1365 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1366 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1369 && SchemaContext.NAME.getLocalName().equals(localName(data));
1372 private String addMountPointIdentifier(final String identifier) {
1373 final boolean endsWith = identifier.endsWith("/");
1375 return (identifier + ControllerContext.MOUNT);
1378 return identifier + "/" + ControllerContext.MOUNT;
1382 * @deprecated method will be removed in Lithium release
1383 * we don't wish to use Node and CompositeNode anywhere
1386 public CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1387 if (schema == null) {
1388 final String localName = node == null ? null :
1389 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1390 node.getNodeType().getLocalName();
1392 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1393 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1396 if (!(schema instanceof DataNodeContainer)) {
1397 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1398 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1401 if ((node instanceof NodeWrapper<?>)) {
1402 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1403 final boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1404 if (isChangeAllowed) {
1405 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1407 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1408 } catch (final IllegalArgumentException e) {
1409 final RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1410 restconfDocumentedException.addSuppressed(e);
1411 throw restconfDocumentedException;
1413 if (nodeWrap instanceof CompositeNodeWrapper) {
1414 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1419 if (node instanceof CompositeNode) {
1420 return (CompositeNode) node;
1423 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1424 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1427 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1428 final QName previousAugment, final DOMMountPoint mountPoint) {
1429 if (schema == null) {
1430 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1431 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1434 QName currentAugment = null;
1435 if (nodeBuilder.getQname() != null) {
1436 currentAugment = previousAugment;
1438 currentAugment = normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1439 if (nodeBuilder.getQname() == null) {
1440 throw new RestconfDocumentedException(
1441 "Data has bad format.\nIf data is in XML format then namespace for \""
1442 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1443 + "\".\n" + "If data is in JSON format then module name for \""
1444 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1445 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1449 if (nodeBuilder instanceof CompositeNodeWrapper) {
1450 if (schema instanceof DataNodeContainer) {
1451 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1453 } else if (schema instanceof AnyXmlSchemaNode) {
1454 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1456 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1457 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1458 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1459 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1463 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1464 final List<NodeWrapper<?>> children = compositeNode.getValues();
1465 for (final NodeWrapper<? extends Object> child : children) {
1466 child.setNamespace(schema.getQName().getNamespace());
1467 if (child instanceof CompositeNodeWrapper) {
1468 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1473 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1474 if ((schema instanceof LeafSchemaNode)) {
1475 emptyNodeBuilder.setComposite(false);
1477 if ((schema instanceof ContainerSchemaNode)) {
1478 // FIXME: Add presence check
1479 emptyNodeBuilder.setComposite(true);
1484 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1485 final DOMMountPoint mountPoint) {
1486 final Object value = simpleNode.getValue();
1487 Object inputValue = value;
1488 final TypeDef typeDef = this.typeDefinition(schema);
1489 TypeDefinition<? extends Object> typeDefinition = typeDef != null ? typeDef.typedef : null;
1491 // For leafrefs, extract the type it is pointing to
1492 if(typeDefinition instanceof LeafrefTypeDefinition) {
1493 if (schema.getQName().equals(typeDef.qName)) {
1494 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema);
1496 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), typeDef.qName);
1500 if (typeDefinition instanceof IdentityrefTypeDefinition) {
1501 inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue);
1504 Object outputValue = inputValue;
1506 if (typeDefinition != null) {
1507 final Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1508 outputValue = codec == null ? null : codec.deserialize(inputValue);
1511 simpleNode.setValue(outputValue);
1514 private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) {
1515 if ((value instanceof String)) {
1516 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1518 } // else value is already instance of IdentityValuesDTO
1522 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1523 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1524 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1525 checkNodeMultiplicityAccordingToSchema(schema, children);
1526 for (final NodeWrapper<? extends Object> child : children) {
1527 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1528 schema, child.getLocalName());
1530 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1531 final StringBuilder builder = new StringBuilder();
1532 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1533 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1536 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1537 + "\" is added as augment from more than one module. "
1538 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1539 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1540 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1543 boolean rightNodeSchemaFound = false;
1544 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1545 if (!rightNodeSchemaFound) {
1546 final QName potentialCurrentAugment = normalizeNodeName(child, potentialSchemaNode,
1547 currentAugment, mountPoint);
1548 if (child.getQname() != null) {
1549 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1550 rightNodeSchemaFound = true;
1555 if (!rightNodeSchemaFound) {
1556 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1557 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1561 if ((schema instanceof ListSchemaNode)) {
1562 final ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1563 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1564 for (final QName listKey : listKeys) {
1565 boolean foundKey = false;
1566 for (final NodeWrapper<? extends Object> child : children) {
1567 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1573 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1574 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1575 ErrorTag.DATA_MISSING);
1581 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1582 final List<NodeWrapper<?>> nodes) {
1583 final Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1584 for (final NodeWrapper<?> child : nodes) {
1585 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1586 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1589 for (final DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1590 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1591 final String localName = childSchemaNode.getQName().getLocalName();
1592 final Integer count = equalNodeNamesToCounts.get(localName);
1593 if (count != null && count > 1) {
1594 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1595 + childSchemaNode.getQName().getLocalName()
1596 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1597 ErrorTag.BAD_ELEMENT);
1603 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1604 final QName previousAugment, final DOMMountPoint mountPoint) {
1605 QName validQName = schema.getQName();
1606 QName currentAugment = previousAugment;
1607 if (schema.isAugmenting()) {
1608 currentAugment = schema.getQName();
1609 } else if (previousAugment != null
1610 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1611 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1614 String moduleName = null;
1615 if (mountPoint == null) {
1616 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1618 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1621 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1622 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1624 * || Note : this check is wrong -
1625 * can never be true as it compares
1626 * a URI with a String not sure what
1627 * the intention is so commented out
1628 * ... Objects . equal ( nodeBuilder
1629 * . getNamespace ( ) ,
1630 * MOUNT_POINT_MODULE_NAME )
1633 nodeBuilder.setQname(validQName);
1636 return currentAugment;
1639 private URI namespace(final Node<?> data) {
1640 if (data instanceof NodeWrapper) {
1641 return ((NodeWrapper<?>) data).getNamespace();
1642 } else if (data != null) {
1643 return data.getNodeType().getNamespace();
1645 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1649 private String localName(final Node<?> data) {
1650 if (data instanceof NodeWrapper) {
1651 return ((NodeWrapper<?>) data).getLocalName();
1652 } else if (data != null) {
1653 return data.getNodeType().getLocalName();
1655 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1660 * @deprecated method will be removed for Lithium release
1666 private String getName(final Node<?> data) {
1667 if (data instanceof NodeWrapper) {
1668 return ((NodeWrapper<?>) data).getLocalName();
1669 } else if (data != null) {
1670 return data.getNodeType().getLocalName();
1672 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1676 private TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
1677 TypeDefinition<?> baseType = type;
1678 QName qName = nodeQName;
1679 while (baseType.getBaseType() != null) {
1680 if (baseType instanceof ExtendedType) {
1681 qName = baseType.getQName();
1683 baseType = baseType.getBaseType();
1686 return new TypeDef(baseType, qName);
1690 private TypeDef typeDefinition(final DataSchemaNode node) {
1691 if (node instanceof LeafListSchemaNode) {
1692 return typeDefinition(((LeafListSchemaNode)node).getType(), node.getQName());
1693 } else if (node instanceof LeafSchemaNode) {
1694 return typeDefinition(((LeafSchemaNode)node).getType(), node.getQName());
1695 } else if (node instanceof AnyXmlSchemaNode) {
1698 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1702 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1703 Node<?> nodes = null;
1704 if (dataNode == null) {
1705 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1706 "No data was found."));
1708 nodes = DataNormalizer.toLegacy(dataNode);
1709 if (nodes != null) {
1710 if (nodes instanceof CompositeNode) {
1711 return (CompositeNode) nodes;
1713 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1716 LOG.error("Top level node isn't of type Container or List schema node but "
1717 + schema.getClass().getSimpleName());
1720 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1721 "It wasn't possible to correctly interpret data."));
1724 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1725 final DataSchemaNode schema) {
1726 final List<Node<?>> lst = new ArrayList<Node<?>>();
1728 if (schema instanceof ContainerSchemaNode) {
1729 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1730 .parse(lst, (ContainerSchemaNode) schema);
1731 } else if (schema instanceof ListSchemaNode) {
1732 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1733 .parse(lst, (ListSchemaNode) schema);
1736 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1738 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1739 "It wasn't possible to translate specified data to datastore readable form."));
1742 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1743 final InstanceIdentifierContext iiWithSchemaNode) {
1744 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1747 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1748 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1749 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1750 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1751 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1754 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1755 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1756 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1757 final List<PathArgument> result = new ArrayList<PathArgument>();
1758 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1759 while (iter.hasNext()) {
1760 final PathArgument pathArgument = iter.next();
1761 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1762 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1764 result.add(pathArgument);
1766 return YangInstanceIdentifier.create(result);
1769 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1770 final DataSchemaNode schemaNode) {
1771 if (node instanceof CompositeNodeWrapper) {
1772 return (CompositeNodeWrapper) node;
1773 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1774 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1775 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1778 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1779 "Top level element has to be composite node or has to represent data container node."));
1782 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1783 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1789 public BigInteger getOperationalReceived() {
1790 // TODO Auto-generated method stub
1794 private MapNode makeModuleMapNode(final Set<Module> modules) {
1795 Preconditions.checkNotNull(modules);
1796 final Module restconfModule = getRestconfModule();
1797 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1798 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1799 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1801 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1802 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1804 for (final Module module : modules) {
1805 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1807 return listModuleBuilder.build();
1810 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1811 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1812 "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());
1813 \r return moduleNodeValues.build();
\r }
1815 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1816 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1817 "streamSchemaNode has to be of type ListSchemaNode");
1818 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1819 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1820 .mapEntryBuilder(listStreamSchemaNode);
1822 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1823 (listStreamSchemaNode), "name");
1824 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1825 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1826 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1829 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1830 (listStreamSchemaNode), "description");
1831 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1832 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1833 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1834 .withValue("DESCRIPTION_PLACEHOLDER").build());
1836 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1837 (listStreamSchemaNode), "replay-support");
1838 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1839 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1840 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1841 .withValue(Boolean.valueOf(true)).build());
1843 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1844 (listStreamSchemaNode), "replay-log-creation-time");
1845 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1846 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1847 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1848 .withValue("").build());
1850 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1851 (listStreamSchemaNode), "events");
1852 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1853 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1854 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1855 .withValue("").build());
1857 return streamNodeValues.build();