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.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
19 import java.text.ParseException;
20 import java.text.SimpleDateFormat;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.Response.Status;
33 import javax.ws.rs.core.UriBuilder;
34 import javax.ws.rs.core.UriInfo;
35 import org.apache.commons.lang3.StringUtils;
36 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
37 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
40 import org.opendaylight.controller.sal.rest.api.Draft02;
41 import org.opendaylight.controller.sal.rest.api.RestconfService;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
43 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
44 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
45 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
46 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
47 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
48 import org.opendaylight.controller.sal.streams.listeners.Notificator;
49 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
50 import org.opendaylight.yangtools.concepts.Codec;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.QNameModule;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
56 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
57 import org.opendaylight.yangtools.yang.data.api.Node;
58 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
64 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
67 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
68 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer.CnSnFromNormalizedNodeSerializerFactory;
69 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
70 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
71 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
74 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
76 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
78 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.Module;
80 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
81 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
82 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
83 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.util.EmptyType;
86 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
87 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
91 public class RestconfImpl implements RestconfService {
92 private enum UriParameters {
93 PRETTY_PRINT("prettyPrint"),
96 private String uriParameterName;
98 UriParameters(String uriParameterName) {
99 this.uriParameterName = uriParameterName;
103 public String toString() {
104 return uriParameterName;
108 private final static RestconfImpl INSTANCE = new RestconfImpl();
110 private static final int NOTIFICATION_PORT = 8181;
112 private static final int CHAR_NOT_FOUND = -1;
114 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
116 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
118 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
120 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
122 private BrokerFacade broker;
124 private ControllerContext controllerContext;
126 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
128 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
130 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
132 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
134 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
136 private static final String DATASTORE_PARAM_NAME = "datastore";
138 private static final String SCOPE_PARAM_NAME = "scope";
142 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
143 } catch (ParseException e) {
144 throw new RestconfDocumentedException(
145 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
146 ErrorTag.OPERATION_FAILED);
150 public void setBroker(final BrokerFacade broker) {
151 this.broker = broker;
154 public void setControllerContext(final ControllerContext controllerContext) {
155 this.controllerContext = controllerContext;
158 private RestconfImpl() {
161 public static RestconfImpl getInstance() {
166 public StructuredData getModules(final UriInfo uriInfo) {
167 final Module restconfModule = this.getRestconfModule();
169 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
170 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
171 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
173 Set<Module> allModules = this.controllerContext.getAllModules();
174 for (final Module module : allModules) {
175 CompositeNode moduleCompositeNode = this.toModuleCompositeNode(module, moduleSchemaNode);
176 modulesAsData.add(moduleCompositeNode);
179 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
180 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
181 QName qName = modulesSchemaNode.getQName();
182 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
183 return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
187 public StructuredData getAvailableStreams(final UriInfo uriInfo) {
188 Set<String> availableStreams = Notificator.getStreamNames();
190 final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
191 Module restconfModule = this.getRestconfModule();
192 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
193 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
194 for (final String streamName : availableStreams) {
195 streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
198 final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
199 Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
200 QName qName = streamsSchemaNode.getQName();
201 final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
202 return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
206 public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
207 Set<Module> modules = null;
208 DOMMountPoint mountPoint = null;
209 if (identifier.contains(ControllerContext.MOUNT)) {
210 InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
211 mountPoint = mountPointIdentifier.getMountPoint();
212 modules = this.controllerContext.getAllModules(mountPoint);
214 throw new RestconfDocumentedException(
215 "URI has bad format. If modules behind mount point should be showed, URI has to end with "
216 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
219 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
220 Module restconfModule = this.getRestconfModule();
221 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
222 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
224 for (final Module module : modules) {
225 modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
228 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
229 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
230 QName qName = modulesSchemaNode.getQName();
231 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
232 return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
236 public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
237 final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
238 Module module = null;
239 DOMMountPoint mountPoint = null;
240 if (identifier.contains(ControllerContext.MOUNT)) {
241 InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
242 mountPoint = mountPointIdentifier.getMountPoint();
243 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
245 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
248 if (module == null) {
249 throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
250 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
251 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
254 Module restconfModule = this.getRestconfModule();
255 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
256 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
257 final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
258 return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
262 public StructuredData getOperations(final UriInfo uriInfo) {
263 Set<Module> allModules = this.controllerContext.getAllModules();
264 return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
268 public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
269 Set<Module> modules = null;
270 DOMMountPoint mountPoint = null;
271 if (identifier.contains(ControllerContext.MOUNT)) {
272 InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
273 mountPoint = mountPointIdentifier.getMountPoint();
274 modules = this.controllerContext.getAllModules(mountPoint);
276 throw new RestconfDocumentedException(
277 "URI has bad format. If operations behind mount point should be showed, URI has to end with "
278 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
281 return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
284 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
285 final DOMMountPoint mountPoint, boolean prettyPrint) {
286 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
287 Module restconfModule = this.getRestconfModule();
288 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
289 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
290 QName qName = operationsSchemaNode.getQName();
291 SchemaPath path = operationsSchemaNode.getPath();
292 ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
293 Draft02.RestConfModule.NAME, 0, qName, path);
294 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
295 for (final Module module : modules) {
296 Set<RpcDefinition> rpcs = module.getRpcs();
297 for (final RpcDefinition rpc : rpcs) {
298 QName rpcQName = rpc.getQName();
299 SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
301 operationsAsData.add(immutableSimpleNode);
303 String name = module.getName();
304 LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
305 SchemaPath.create(true, QName.create("dummy")));
306 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
307 fakeRpcSchemaNode.setAugmenting(true);
309 EmptyType instance = EmptyType.getInstance();
310 fakeRpcSchemaNode.setType(instance);
311 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
315 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
316 ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
317 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
320 private Module getRestconfModule() {
321 Module restconfModule = controllerContext.getRestconfModule();
322 if (restconfModule == null) {
323 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
324 ErrorTag.OPERATION_NOT_SUPPORTED);
327 return restconfModule;
330 private QName getModuleNameAndRevision(final String identifier) {
331 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
332 String moduleNameAndRevision = "";
333 if (mountIndex >= 0) {
334 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
336 moduleNameAndRevision = identifier;
339 Splitter splitter = Splitter.on("/").omitEmptyStrings();
340 Iterable<String> split = splitter.split(moduleNameAndRevision);
341 final List<String> pathArgs = Lists.<String> newArrayList(split);
342 if (pathArgs.size() < 2) {
343 throw new RestconfDocumentedException(
344 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
345 ErrorTag.INVALID_VALUE);
349 final String moduleName = pathArgs.get(0);
350 String revision = pathArgs.get(1);
351 final Date moduleRevision = REVISION_FORMAT.parse(revision);
352 return QName.create(null, moduleRevision, moduleName);
353 } catch (ParseException e) {
354 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
355 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
359 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
360 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
361 List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
362 ((DataNodeContainer) streamSchemaNode), "name");
363 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
365 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
367 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
368 ((DataNodeContainer) streamSchemaNode), "description");
369 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
370 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
371 "DESCRIPTION_PLACEHOLDER"));
373 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
374 ((DataNodeContainer) streamSchemaNode), "replay-support");
375 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
376 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
377 Boolean.valueOf(true)));
379 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
380 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
381 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
382 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
385 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
386 ((DataNodeContainer) streamSchemaNode), "events");
387 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
388 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
390 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
393 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
394 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
395 List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
396 ((DataNodeContainer) moduleSchemaNode), "name");
397 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
398 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
401 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
402 ((DataNodeContainer) moduleSchemaNode), "revision");
403 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
404 Date _revision = module.getRevision();
405 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
406 REVISION_FORMAT.format(_revision)));
408 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
409 ((DataNodeContainer) moduleSchemaNode), "namespace");
410 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
411 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
412 module.getNamespace().toString()));
414 instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
415 ((DataNodeContainer) moduleSchemaNode), "feature");
416 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
417 for (final FeatureDefinition feature : module.getFeatures()) {
418 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
419 feature.getQName().getLocalName()));
422 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
426 public Object getRoot() {
431 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
432 final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
433 QName rpcName = rpc.getRpcDefinition().getQName();
434 URI rpcNamespace = rpcName.getNamespace();
435 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
436 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
437 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
440 validateInput(rpc.getRpcDefinition().getInput(), payload);
442 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
445 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
446 if (inputSchema != null && payload == null) {
447 // expected a non null payload
448 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
449 } else if (inputSchema == null && payload != null) {
450 // did not expect any input
451 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
455 // TODO: Validate "mandatory" and "config" values here??? Or should those be
457 // validate in a more central location inside MD-SAL core.
461 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
462 final boolean prettyPrint) {
463 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
464 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
465 rpc.getQName(), "path"));
466 final Object pathValue = pathNode == null ? null : pathNode.getValue();
468 if (!(pathValue instanceof YangInstanceIdentifier)) {
469 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
470 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
473 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
474 String streamName = null;
475 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
476 String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
478 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
479 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
481 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
482 scope = scope == null ? DEFAULT_SCOPE : scope;
484 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
485 + "/scope=" + scope);
488 if (Strings.isNullOrEmpty(streamName)) {
489 throw new RestconfDocumentedException(
490 "Path is empty or contains data node which is not Container or List build-in type.",
491 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
494 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
495 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
496 final List<Node<?>> output = new ArrayList<Node<?>>();
497 output.add(streamNameNode);
499 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
500 null, output, null, null);
502 if (!Notificator.existListenerFor(streamName)) {
503 Notificator.createListener(pathIdentifier, streamName);
506 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
510 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
511 if (StringUtils.isNotBlank(noPayload)) {
512 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
514 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
517 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
518 String identifierEncoded = null;
519 DOMMountPoint mountPoint = null;
520 if (identifier.contains(ControllerContext.MOUNT)) {
521 // mounted RPC call - look up mount instance.
522 InstanceIdWithSchemaNode mountPointId = controllerContext.toMountPointIdentifier(identifier);
523 mountPoint = mountPointId.getMountPoint();
525 int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
526 + ControllerContext.MOUNT.length() + 1;
527 String remoteRpcName = identifier.substring(startOfRemoteRpcName);
528 identifierEncoded = remoteRpcName;
530 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
531 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
532 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
533 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
535 identifierEncoded = identifier;
538 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
540 RpcDefinition rpc = null;
541 if (mountPoint == null) {
542 rpc = controllerContext.getRpcDefinition(identifierDecoded);
544 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
548 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
551 if (mountPoint == null) {
552 return new BrokerRpcExecutor(rpc, broker);
554 return new MountPointRpcExecutor(rpc, mountPoint);
559 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
560 final String[] splittedIdentifier = identifierDecoded.split(":");
561 if (splittedIdentifier.length != 2) {
562 throw new RestconfDocumentedException(identifierDecoded
563 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
564 ErrorTag.INVALID_VALUE);
566 for (Module module : schemaContext.getModules()) {
567 if (module.getName().equals(splittedIdentifier[0])) {
568 for (RpcDefinition rpcDefinition : module.getRpcs()) {
569 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
570 return rpcDefinition;
578 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, boolean prettyPrint) {
579 if (rpcExecutor == null) {
580 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
583 CompositeNode rpcRequest = null;
584 RpcDefinition rpc = rpcExecutor.getRpcDefinition();
585 QName rpcName = rpc.getQName();
587 if (payload == null) {
588 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
590 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
591 List<Node<?>> input = Collections.<Node<?>> singletonList(value);
592 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
595 RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
597 checkRpcSuccessAndThrowException(rpcResult);
599 if (rpcResult.getResult() == null) {
603 if (rpc.getOutput() == null) {
604 return null; // no output, nothing to send back.
607 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
610 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
611 if (rpcResult.isSuccessful() == false) {
613 Collection<RpcError> rpcErrors = rpcResult.getErrors();
614 if (rpcErrors == null || rpcErrors.isEmpty()) {
615 throw new RestconfDocumentedException(
616 "The operation was not successful and there were no RPC errors returned", ErrorType.RPC,
617 ErrorTag.OPERATION_FAILED);
620 List<RestconfError> errorList = Lists.newArrayList();
621 for (RpcError rpcError : rpcErrors) {
622 errorList.add(new RestconfError(rpcError));
625 throw new RestconfDocumentedException(errorList);
630 public StructuredData readConfigurationData(final String identifier, final UriInfo uriInfo) {
631 final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode(
632 this.controllerContext.toInstanceIdentifier(identifier), true);
633 DOMMountPoint mountPoint = iiWithData.getMountPoint();
634 NormalizedNode<?, ?> data = null;
635 if (mountPoint != null) {
636 data = broker.readConfigurationData(mountPoint, iiWithData.getInstanceIdentifier());
638 data = broker.readConfigurationData(iiWithData.getInstanceIdentifier());
640 CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode());
642 compositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(uriInfo));
643 boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo);
644 return new StructuredData(compositeNode, iiWithData.getSchemaNode(), iiWithData.getMountPoint(), prettyPrintMode);
647 @SuppressWarnings("unchecked")
648 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
653 if (node instanceof CompositeNode) {
654 ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
656 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
657 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
661 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
662 } else { // SimpleNode
667 private Integer parseDepthParameter(final UriInfo info) {
668 String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
669 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
674 Integer depth = Integer.valueOf(param);
676 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
677 "Invalid depth parameter: " + depth, null,
678 "The depth parameter must be an integer > 1 or \"unbounded\""));
682 } catch (NumberFormatException e) {
683 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
684 "Invalid depth parameter: " + e.getMessage(), null,
685 "The depth parameter must be an integer > 1 or \"unbounded\""));
690 public StructuredData readOperationalData(final String identifier, final UriInfo info) {
691 final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode(
692 this.controllerContext.toInstanceIdentifier(identifier), true);
693 NormalizedNode<?, ?> data = null;
695 DOMMountPoint mountPoint = iiWithData.getMountPoint();
696 if (mountPoint != null) {
697 data = broker.readOperationalData(mountPoint, iiWithData.getInstanceIdentifier());
699 data = broker.readOperationalData(iiWithData.getInstanceIdentifier());
702 final CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode());
703 final CompositeNode prunedCompositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(info));
704 final boolean prettyPrintMode = parsePrettyPrintParameter(info);
705 return new StructuredData(prunedCompositeNode, iiWithData.getSchemaNode(), mountPoint,prettyPrintMode);
708 private boolean parsePrettyPrintParameter(UriInfo info) {
709 String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
710 return Boolean.parseBoolean(param);
714 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
715 final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode(this.controllerContext
716 .toInstanceIdentifier(identifier));
718 validateInput(iiWithData.getSchemaNode(), payload);
720 DOMMountPoint mountPoint = iiWithData.getMountPoint();
721 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
722 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
723 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
724 iiWithData.getSchemaNode());
727 if (mountPoint != null) {
728 broker.commitConfigurationDataPut(mountPoint, iiWithData.getInstanceIdentifier(),
729 datastoreNormalizedNode).get();
731 broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), datastoreNormalizedNode)
734 } catch (Exception e) {
735 throw new RestconfDocumentedException("Error updating data", e);
738 return Response.status(Status.OK).build();
742 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
744 * @throws RestconfDocumentedException
745 * if key values or key count in payload and URI isn't equal
748 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdWithSchemaNode iiWithData,
749 final CompositeNode payload) {
750 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
751 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
752 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
753 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
754 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
756 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
761 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
762 final List<QName> keyDefinitions) {
763 for (QName keyDefinition : keyDefinitions) {
764 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
765 // should be caught during parsing URI to InstanceIdentifier
766 if (uriKeyValue == null) {
767 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
768 ErrorTag.DATA_MISSING);
770 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
771 if (payloadKeyValues.isEmpty()) {
772 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
773 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
776 Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
777 if (!uriKeyValue.equals(payloadKeyValue)) {
778 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
779 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
780 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
781 ErrorTag.INVALID_VALUE);
787 public Response createConfigurationData(final String identifier, final Node<?> payload) {
788 if (payload == null) {
789 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
792 URI payloadNS = this.namespace(payload);
793 if (payloadNS == null) {
794 throw new RestconfDocumentedException(
795 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
796 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
799 InstanceIdWithSchemaNode iiWithData = null;
800 CompositeNode value = null;
801 if (this.representsMountPointRootData(payload)) {
802 // payload represents mount point data and URI represents path to the mount point
804 if (this.endsWithMountPoint(identifier)) {
805 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
806 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
807 ErrorTag.INVALID_VALUE);
810 final String completeIdentifier = this.addMountPointIdentifier(identifier);
811 iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
813 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
815 final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext
816 .toInstanceIdentifier(identifier);
817 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
818 DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
819 final Module module = findModule(mountPoint, payload);
820 if (module == null) {
821 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
822 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
825 String payloadName = this.getName(payload);
826 final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
827 parentSchema, payloadName, module.getNamespace());
828 value = this.normalizeNode(payload, schemaNode, mountPoint);
830 iiWithData = normalizeInstanceIdentifierWithSchemaNode(this.addLastIdentifierFromData(
831 incompleteInstIdWithData, value, schemaNode));
834 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
835 iiWithData.getSchemaNode());
836 DOMMountPoint mountPoint = iiWithData.getMountPoint();
838 if (mountPoint != null) {
839 broker.commitConfigurationDataPost(mountPoint,
840 iiWithData.getInstanceIdentifier(), datastoreNormalizedData);
842 broker.commitConfigurationDataPost(
843 iiWithData.getInstanceIdentifier(), datastoreNormalizedData);
845 } catch (Exception e) {
846 throw new RestconfDocumentedException("Error creating data", e);
849 return Response.status(Status.NO_CONTENT).build();
853 public Response createConfigurationData(final Node<?> payload) {
854 if (payload == null) {
855 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
858 URI payloadNS = this.namespace(payload);
859 if (payloadNS == null) {
860 throw new RestconfDocumentedException(
861 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
862 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
865 final Module module = this.findModule(null, payload);
866 if (module == null) {
867 throw new RestconfDocumentedException(
868 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
869 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
872 String payloadName = this.getName(payload);
873 final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(module,
874 payloadName, module.getNamespace());
875 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
876 final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode);
877 RpcResult<TransactionStatus> status = null;
878 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
879 DOMMountPoint mountPoint = iiWithData.getMountPoint();
882 if (mountPoint != null) {
883 broker.commitConfigurationDataPost(mountPoint,
884 iiWithData.getInstanceIdentifier(), datastoreNormalizedData);
886 broker.commitConfigurationDataPost(
887 iiWithData.getInstanceIdentifier(), datastoreNormalizedData);
889 } catch (Exception e) {
890 throw new RestconfDocumentedException("Error creating data", e);
893 return Response.status(Status.NO_CONTENT).build();
897 public Response deleteConfigurationData(final String identifier) {
898 final InstanceIdWithSchemaNode iiWithData = normalizeInstanceIdentifierWithSchemaNode(this.controllerContext
899 .toInstanceIdentifier(identifier));
900 RpcResult<TransactionStatus> status = null;
901 DOMMountPoint mountPoint = iiWithData.getMountPoint();
904 if (mountPoint != null) {
905 broker.commitConfigurationDataDelete(mountPoint, iiWithData.getInstanceIdentifier()).get();
907 broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get();
909 } catch (Exception e) {
910 throw new RestconfDocumentedException("Error creating data", e);
913 return Response.status(Status.OK).build();
917 * Subscribes to some path in schema context (stream) to listen on changes
920 * Additional parameters for subscribing to stream are loaded via rpc input
923 * <li>datastore</li> - default CONFIGURATION (other values of
924 * {@link LogicalDatastoreType} enum type)
925 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
929 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
930 final String streamName = Notificator.createStreamNameFromUri(identifier);
931 if (Strings.isNullOrEmpty(streamName)) {
932 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
935 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
936 if (listener == null) {
937 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
940 Map<String, String> paramToValues = resolveValuesFromUri(identifier);
941 LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
942 paramToValues.get(DATASTORE_PARAM_NAME));
943 if (datastore == null) {
944 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
945 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
947 DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
949 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
950 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
953 broker.registerToListenDataChanges(datastore, scope, listener);
955 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
956 int notificationPort = NOTIFICATION_PORT;
958 WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
959 notificationPort = webSocketServerInstance.getPort();
960 } catch (NullPointerException e) {
961 WebSocketServer.createInstance(NOTIFICATION_PORT);
963 UriBuilder port = uriBuilder.port(notificationPort);
964 final URI uriToWebsocketServer = port.replacePath(streamName).build();
966 return Response.status(Status.OK).location(uriToWebsocketServer).build();
970 * Load parameter for subscribing to stream from input composite node
974 * @return enum object if its string value is equal to {@code paramName}. In
977 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
978 final String paramName) {
979 QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
980 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
981 SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
982 if (simpleNode == null) {
985 Object rawValue = simpleNode.getValue();
986 if (!(rawValue instanceof String)) {
990 return resolveAsEnum(classDescriptor, (String) rawValue);
994 * Checks whether {@code value} is one of the string representation of
995 * enumeration {@code classDescriptor}
997 * @return enum object if string value of {@code classDescriptor}
998 * enumeration is equal to {@code value}. Other cases null.
1000 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1001 if (Strings.isNullOrEmpty(value)) {
1004 return resolveAsEnum(classDescriptor, value);
1007 private <T> T resolveAsEnum(Class<T> classDescriptor, String value) {
1008 T[] enumConstants = classDescriptor.getEnumConstants();
1009 if (enumConstants != null) {
1010 for (T enm : classDescriptor.getEnumConstants()) {
1011 if (((Enum<?>) enm).name().equals(value)) {
1019 private Map<String, String> resolveValuesFromUri(String uri) {
1020 Map<String, String> result = new HashMap<>();
1021 String[] tokens = uri.split("/");
1022 for (int i = 1; i < tokens.length; i++) {
1023 String[] parameterTokens = tokens[i].split("=");
1024 if (parameterTokens.length == 2) {
1025 result.put(parameterTokens[0], parameterTokens[1]);
1031 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1032 if (data instanceof NodeWrapper) {
1033 return findModule(mountPoint, (NodeWrapper<?>) data);
1034 } else if (data != null) {
1035 URI namespace = data.getNodeType().getNamespace();
1036 if (mountPoint != null) {
1037 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1039 return this.controllerContext.findModuleByNamespace(namespace);
1042 throw new IllegalArgumentException("Unhandled parameter types: "
1043 + Arrays.<Object> asList(mountPoint, data).toString());
1047 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1048 URI namespace = data.getNamespace();
1049 Preconditions.<URI> checkNotNull(namespace);
1051 Module module = null;
1052 if (mountPoint != null) {
1053 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1054 if (module == null) {
1055 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1058 module = this.controllerContext.findModuleByNamespace(namespace);
1059 if (module == null) {
1060 module = this.controllerContext.findModuleByName(namespace.toString());
1067 private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode,
1068 final CompositeNode data, final DataSchemaNode schemaOfData) {
1069 YangInstanceIdentifier instanceIdentifier = null;
1070 if (identifierWithSchemaNode != null) {
1071 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1074 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1075 InstanceIdentifierBuilder iiBuilder = null;
1076 if (iiOriginal == null) {
1077 iiBuilder = YangInstanceIdentifier.builder();
1079 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1082 iiBuilder.node(schemaOfData.getQName());
1084 YangInstanceIdentifier instance = iiBuilder.toInstance();
1085 DOMMountPoint mountPoint = null;
1086 if (identifierWithSchemaNode != null) {
1087 mountPoint = identifierWithSchemaNode.getMountPoint();
1090 return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint);
1093 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1094 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1095 List<QName> _keyDefinition = listNode.getKeyDefinition();
1096 for (final QName key : _keyDefinition) {
1097 SimpleNode<? extends Object> head = null;
1098 String localName = key.getLocalName();
1099 List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1100 if (simpleNodesByName != null) {
1101 head = Iterables.getFirst(simpleNodesByName, null);
1104 Object dataNodeKeyValueObject = null;
1106 dataNodeKeyValueObject = head.getValue();
1109 if (dataNodeKeyValueObject == null) {
1110 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1111 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1112 ErrorTag.INVALID_VALUE);
1115 keyValues.put(key, dataNodeKeyValueObject);
1121 private boolean endsWithMountPoint(final String identifier) {
1122 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1125 private boolean representsMountPointRootData(final Node<?> data) {
1126 URI namespace = this.namespace(data);
1127 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1128 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1131 && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1134 private String addMountPointIdentifier(final String identifier) {
1135 boolean endsWith = identifier.endsWith("/");
1137 return (identifier + ControllerContext.MOUNT);
1140 return identifier + "/" + ControllerContext.MOUNT;
1143 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1144 if (schema == null) {
1145 QName nodeType = node == null ? null : node.getNodeType();
1146 String localName = nodeType == null ? null : nodeType.getLocalName();
1148 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1149 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1152 if (!(schema instanceof DataNodeContainer)) {
1153 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1154 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1157 if ((node instanceof NodeWrapper<?>)) {
1158 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1159 boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1160 if (isChangeAllowed) {
1161 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1163 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1164 } catch (IllegalArgumentException e) {
1165 throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1167 if (nodeWrap instanceof CompositeNodeWrapper) {
1168 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1173 if (node instanceof CompositeNode) {
1174 return (CompositeNode) node;
1177 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1178 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1181 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1182 final QName previousAugment, final DOMMountPoint mountPoint) {
1183 if (schema == null) {
1184 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1185 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1188 QName currentAugment = null;
1189 if (nodeBuilder.getQname() != null) {
1190 currentAugment = previousAugment;
1192 currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1193 if (nodeBuilder.getQname() == null) {
1194 throw new RestconfDocumentedException(
1195 "Data has bad format.\nIf data is in XML format then namespace for \""
1196 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1197 + "\".\n" + "If data is in JSON format then module name for \""
1198 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1199 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1203 if (nodeBuilder instanceof CompositeNodeWrapper) {
1204 if (schema instanceof DataNodeContainer) {
1205 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1207 } else if (schema instanceof AnyXmlSchemaNode) {
1208 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1210 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1211 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1212 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1213 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1217 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1218 List<NodeWrapper<?>> children = compositeNode.getValues();
1219 for (NodeWrapper<? extends Object> child : children) {
1220 child.setNamespace(schema.getQName().getNamespace());
1221 if (child instanceof CompositeNodeWrapper) {
1222 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1227 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1228 if ((schema instanceof LeafSchemaNode)) {
1229 emptyNodeBuilder.setComposite(false);
1231 if ((schema instanceof ContainerSchemaNode)) {
1232 // FIXME: Add presence check
1233 emptyNodeBuilder.setComposite(true);
1238 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1239 final DOMMountPoint mountPoint) {
1240 final Object value = simpleNode.getValue();
1241 Object inputValue = value;
1242 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1243 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1244 if ((value instanceof String)) {
1245 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1247 } // else value is already instance of IdentityValuesDTO
1250 Object outputValue = inputValue;
1252 if (typeDefinition != null) {
1253 Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1254 outputValue = codec == null ? null : codec.deserialize(inputValue);
1257 simpleNode.setValue(outputValue);
1260 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1261 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1262 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1263 checkNodeMultiplicityAccordingToSchema(schema, children);
1264 for (final NodeWrapper<? extends Object> child : children) {
1265 final List<DataSchemaNode> potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName(
1266 schema, child.getLocalName());
1268 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1269 StringBuilder builder = new StringBuilder();
1270 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1271 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1274 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1275 + "\" is added as augment from more than one module. "
1276 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1277 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1278 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1281 boolean rightNodeSchemaFound = false;
1282 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1283 if (!rightNodeSchemaFound) {
1284 final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1285 currentAugment, mountPoint);
1286 if (child.getQname() != null) {
1287 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1288 rightNodeSchemaFound = true;
1293 if (!rightNodeSchemaFound) {
1294 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1295 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1299 if ((schema instanceof ListSchemaNode)) {
1300 ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1301 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1302 for (final QName listKey : listKeys) {
1303 boolean foundKey = false;
1304 for (final NodeWrapper<? extends Object> child : children) {
1305 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1311 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1312 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1313 ErrorTag.DATA_MISSING);
1319 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1320 final List<NodeWrapper<?>> nodes) {
1321 Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1322 for (NodeWrapper<?> child : nodes) {
1323 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1324 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1327 for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1328 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1329 String localName = childSchemaNode.getQName().getLocalName();
1330 Integer count = equalNodeNamesToCounts.get(localName);
1331 if (count != null && count > 1) {
1332 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1333 + childSchemaNode.getQName().getLocalName()
1334 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1335 ErrorTag.BAD_ELEMENT);
1341 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1342 final QName previousAugment, final DOMMountPoint mountPoint) {
1343 QName validQName = schema.getQName();
1344 QName currentAugment = previousAugment;
1345 if (schema.isAugmenting()) {
1346 currentAugment = schema.getQName();
1347 } else if (previousAugment != null
1348 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1349 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1352 String moduleName = null;
1353 if (mountPoint == null) {
1354 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1356 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1359 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1360 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*
1361 * || Note : this check is wrong -
1362 * can never be true as it compares
1363 * a URI with a String not sure what
1364 * the intention is so commented out
1365 * ... Objects . equal ( nodeBuilder
1366 * . getNamespace ( ) ,
1367 * MOUNT_POINT_MODULE_NAME )
1370 nodeBuilder.setQname(validQName);
1373 return currentAugment;
1376 private URI namespace(final Node<?> data) {
1377 if (data instanceof NodeWrapper) {
1378 return ((NodeWrapper<?>) data).getNamespace();
1379 } else if (data != null) {
1380 return data.getNodeType().getNamespace();
1382 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1386 private String localName(final Node<?> data) {
1387 if (data instanceof NodeWrapper) {
1388 return ((NodeWrapper<?>) data).getLocalName();
1389 } else if (data != null) {
1390 return data.getNodeType().getLocalName();
1392 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1396 private String getName(final Node<?> data) {
1397 if (data instanceof NodeWrapper) {
1398 return ((NodeWrapper<?>) data).getLocalName();
1399 } else if (data != null) {
1400 return data.getNodeType().getLocalName();
1402 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1406 private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1407 TypeDefinition<?> baseType = node.getType();
1408 while (baseType.getBaseType() != null) {
1409 baseType = baseType.getBaseType();
1415 private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1416 TypeDefinition<?> baseType = node.getType();
1417 while (baseType.getBaseType() != null) {
1418 baseType = baseType.getBaseType();
1424 private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1425 if (node instanceof LeafListSchemaNode) {
1426 return typeDefinition((LeafListSchemaNode) node);
1427 } else if (node instanceof LeafSchemaNode) {
1428 return _typeDefinition((LeafSchemaNode) node);
1429 } else if (node instanceof AnyXmlSchemaNode) {
1432 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1436 private CompositeNode datastoreNormalizedNodeToCompositeNode(NormalizedNode<?, ?> dataNode, DataSchemaNode schema) {
1437 Iterable<Node<?>> nodes = null;
1438 if (dataNode == null) {
1439 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1440 "No data was found."));
1442 if (schema instanceof ContainerSchemaNode && dataNode instanceof ContainerNode) {
1443 nodes = CnSnFromNormalizedNodeSerializerFactory.getInstance().getContainerNodeSerializer()
1444 .serialize((ContainerSchemaNode) schema, (ContainerNode) dataNode);
1445 } else if (schema instanceof ListSchemaNode && dataNode instanceof MapNode) {
1446 nodes = CnSnFromNormalizedNodeSerializerFactory.getInstance().getMapNodeSerializer()
1447 .serialize((ListSchemaNode) schema, (MapNode) dataNode);
1448 } else if (schema instanceof ListSchemaNode && dataNode instanceof MapEntryNode) {
1449 nodes = CnSnFromNormalizedNodeSerializerFactory.getInstance().getMapEntryNodeSerializer()
1450 .serialize((ListSchemaNode) schema, (MapEntryNode) dataNode);
1452 if (nodes != null) {
1453 if (nodes.iterator().hasNext()) {
1454 Node<?> nodeOldStruct = nodes.iterator().next();
1455 return (CompositeNode) nodeOldStruct;
1457 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1460 LOG.error("Top level node isn't of type Container or List schema node but "
1461 + schema.getClass().getSimpleName());
1464 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1465 "It wasn't possible to correctly interpret data."));
1468 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(CompositeNode compNode, DataSchemaNode schema) {
1469 List<Node<?>> lst = new ArrayList<Node<?>>();
1471 if (schema instanceof ContainerSchemaNode) {
1472 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1473 .parse(lst, (ContainerSchemaNode) schema);
1474 } else if (schema instanceof ListSchemaNode) {
1475 return CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser()
1476 .parse(lst, (ListSchemaNode) schema);
1479 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1481 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1482 "It wasn't possible to translate specified data to datastore readable form."));
1485 private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(InstanceIdWithSchemaNode iiWithSchemaNode) {
1486 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1489 private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(
1490 InstanceIdWithSchemaNode iiWithSchemaNode, boolean unwrapLastListNode) {
1491 return new InstanceIdWithSchemaNode(instanceIdentifierToReadableFormForNormalizeNode(
1492 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1493 iiWithSchemaNode.getMountPoint());
1496 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(YangInstanceIdentifier instIdentifier,
1497 boolean unwrapLastListNode) {
1498 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1499 final List<PathArgument> result = new ArrayList<PathArgument>();
1500 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1501 while (iter.hasNext()) {
1502 final PathArgument pathArgument = iter.next();
1503 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1504 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1506 result.add(pathArgument);
1508 return YangInstanceIdentifier.create(result);
1511 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1512 final DataSchemaNode schemaNode) {
1513 if (node instanceof CompositeNodeWrapper) {
1514 return (CompositeNodeWrapper) node;
1515 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1516 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1517 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1520 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1521 "Top level element has to be composite node or has to represent data container node."));
1524 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1525 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {