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;
18 import java.math.BigInteger;
20 import java.text.ParseException;
21 import java.text.SimpleDateFormat;
22 import java.util.ArrayList;
23 import java.util.Arrays;
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.data.AsyncDataBroker.DataChangeScope;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
39 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
40 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
41 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
42 import org.opendaylight.controller.sal.rest.api.Draft02;
43 import org.opendaylight.controller.sal.rest.api.RestconfService;
44 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
45 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
46 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
47 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
48 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
49 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
50 import org.opendaylight.controller.sal.streams.listeners.Notificator;
51 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
52 import org.opendaylight.yangtools.concepts.Codec;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.QNameModule;
55 import org.opendaylight.yangtools.yang.common.RpcResult;
56 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
57 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
58 import org.opendaylight.yangtools.yang.data.api.Node;
59 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
65 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
66 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
67 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
68 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
71 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
73 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.Module;
77 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
78 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
79 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
80 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.util.EmptyType;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
84 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
88 public class RestconfImpl implements RestconfService {
90 private enum UriParameters {
91 PRETTY_PRINT("prettyPrint"),
94 private String uriParameterName;
96 UriParameters(final String uriParameterName) {
97 this.uriParameterName = uriParameterName;
101 public String toString() {
102 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 InstanceIdentifierContext 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 InstanceIdentifierContext 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 InstanceIdentifierContext 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, final 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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 = 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,
479 DATASTORE_PARAM_NAME);
480 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
482 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
483 scope = scope == null ? DEFAULT_SCOPE : scope;
485 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
486 + "/scope=" + scope);
489 if (Strings.isNullOrEmpty(streamName)) {
490 throw new RestconfDocumentedException(
491 "Path is empty or contains data node which is not Container or List build-in type.",
492 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
495 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
496 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
497 final List<Node<?>> output = new ArrayList<Node<?>>();
498 output.add(streamNameNode);
500 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
501 null, output, null, null);
503 if (!Notificator.existListenerFor(streamName)) {
504 Notificator.createListener(pathIdentifier, streamName);
507 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
511 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
512 if (StringUtils.isNotBlank(noPayload)) {
513 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
515 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
518 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
519 String identifierEncoded = null;
520 DOMMountPoint mountPoint = null;
521 if (identifier.contains(ControllerContext.MOUNT)) {
522 // mounted RPC call - look up mount instance.
523 InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
524 mountPoint = mountPointId.getMountPoint();
526 int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
527 + ControllerContext.MOUNT.length() + 1;
528 String remoteRpcName = identifier.substring(startOfRemoteRpcName);
529 identifierEncoded = remoteRpcName;
531 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
532 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
533 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
534 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
536 identifierEncoded = identifier;
539 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
541 RpcDefinition rpc = null;
542 if (mountPoint == null) {
543 rpc = controllerContext.getRpcDefinition(identifierDecoded);
545 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
549 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
552 if (mountPoint == null) {
553 return new BrokerRpcExecutor(rpc, broker);
555 return new MountPointRpcExecutor(rpc, mountPoint);
560 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
561 final String[] splittedIdentifier = identifierDecoded.split(":");
562 if (splittedIdentifier.length != 2) {
563 throw new RestconfDocumentedException(identifierDecoded
564 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
565 ErrorTag.INVALID_VALUE);
567 for (Module module : schemaContext.getModules()) {
568 if (module.getName().equals(splittedIdentifier[0])) {
569 for (RpcDefinition rpcDefinition : module.getRpcs()) {
570 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
571 return rpcDefinition;
579 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
580 if (rpcExecutor == null) {
581 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
584 CompositeNode rpcRequest = null;
585 RpcDefinition rpc = rpcExecutor.getRpcDefinition();
586 QName rpcName = rpc.getQName();
588 if (payload == null) {
589 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
591 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
592 List<Node<?>> input = Collections.<Node<?>> singletonList(value);
593 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
596 RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
598 checkRpcSuccessAndThrowException(rpcResult);
600 if (rpcResult.getResult() == null) {
604 if (rpc.getOutput() == null) {
605 return null; // no output, nothing to send back.
608 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
611 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
612 if (rpcResult.isSuccessful() == false) {
614 throw new RestconfDocumentedException("The operation was not successful", null,
615 rpcResult.getErrors());
620 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
621 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
622 DOMMountPoint mountPoint = iiWithData.getMountPoint();
623 NormalizedNode<?, ?> data = null;
624 YangInstanceIdentifier normalizedII;
625 if (mountPoint != null) {
626 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
627 .getInstanceIdentifier());
628 data = broker.readConfigurationData(mountPoint, normalizedII);
630 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
631 data = broker.readConfigurationData(normalizedII);
633 return new NormalizedNodeContext(iiWithData, data);
636 @SuppressWarnings("unchecked")
637 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
642 if (node instanceof CompositeNode) {
643 ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
645 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
646 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
650 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
651 } else { // SimpleNode
656 private Integer parseDepthParameter(final UriInfo info) {
657 String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
658 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
663 Integer depth = Integer.valueOf(param);
665 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
666 "Invalid depth parameter: " + depth, null,
667 "The depth parameter must be an integer > 1 or \"unbounded\""));
671 } catch (NumberFormatException e) {
672 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
673 "Invalid depth parameter: " + e.getMessage(), null,
674 "The depth parameter must be an integer > 1 or \"unbounded\""));
679 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
680 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
681 DOMMountPoint mountPoint = iiWithData.getMountPoint();
682 NormalizedNode<?, ?> data = null;
683 YangInstanceIdentifier normalizedII;
684 if (mountPoint != null) {
685 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
686 .getInstanceIdentifier());
687 data = broker.readOperationalData(mountPoint, normalizedII);
689 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
690 data = broker.readOperationalData(normalizedII);
693 return new NormalizedNodeContext(iiWithData, data);
696 private boolean parsePrettyPrintParameter(final UriInfo info) {
697 String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
698 return Boolean.parseBoolean(param);
702 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
703 final InstanceIdentifierContext iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
705 validateInput(iiWithData.getSchemaNode(), payload);
707 DOMMountPoint mountPoint = iiWithData.getMountPoint();
708 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
709 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
710 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
711 iiWithData.getSchemaNode());
713 YangInstanceIdentifier normalizedII;
714 if (mountPoint != null) {
715 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
716 iiWithData.getInstanceIdentifier());
718 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
722 * There is a small window where another write transaction could be updating the same data
723 * simultaneously and we get an OptimisticLockFailedException. This error is likely
724 * transient and The WriteTransaction#submit API docs state that a retry will likely
725 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
726 * probably will never succeed so we'll fail in that case.
728 * By retrying we're attempting to hide the internal implementation of the data store and
729 * how it handles concurrent updates from the restconf client. The client has instructed us
730 * to put the data and we should make every effort to do so without pushing optimistic lock
731 * failures back to the client and forcing them to handle it via retry (and having to
732 * document the behavior).
737 if (mountPoint != null) {
738 broker.commitConfigurationDataPut(mountPoint, normalizedII,
739 datastoreNormalizedNode).checkedGet();
741 broker.commitConfigurationDataPut(normalizedII,
742 datastoreNormalizedNode).checkedGet();
746 } catch (TransactionCommitFailedException e) {
747 if(e instanceof OptimisticLockFailedException) {
749 LOG.debug("Got OptimisticLockFailedException on last try - failing");
750 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
753 LOG.debug("Got OptimisticLockFailedException - trying again");
755 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
760 return Response.status(Status.OK).build();
764 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
766 * @throws RestconfDocumentedException
767 * if key values or key count in payload and URI isn't equal
770 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
771 final CompositeNode payload) {
772 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
773 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
774 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
775 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
776 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
778 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
783 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
784 final List<QName> keyDefinitions) {
785 for (QName keyDefinition : keyDefinitions) {
786 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
787 // should be caught during parsing URI to InstanceIdentifier
788 if (uriKeyValue == null) {
789 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
790 ErrorTag.DATA_MISSING);
792 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
793 if (payloadKeyValues.isEmpty()) {
794 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
795 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
798 Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
799 if (!uriKeyValue.equals(payloadKeyValue)) {
800 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
801 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
802 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
803 ErrorTag.INVALID_VALUE);
809 public Response createConfigurationData(final String identifier, final Node<?> payload) {
810 if (payload == null) {
811 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
814 URI payloadNS = this.namespace(payload);
815 if (payloadNS == null) {
816 throw new RestconfDocumentedException(
817 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
818 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
821 InstanceIdentifierContext iiWithData = null;
822 CompositeNode value = null;
823 if (this.representsMountPointRootData(payload)) {
824 // payload represents mount point data and URI represents path to the mount point
826 if (this.endsWithMountPoint(identifier)) {
827 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
828 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
829 ErrorTag.INVALID_VALUE);
832 final String completeIdentifier = this.addMountPointIdentifier(identifier);
833 iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
835 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
837 final InstanceIdentifierContext incompleteInstIdWithData = this.controllerContext
838 .toInstanceIdentifier(identifier);
839 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
840 DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
841 final Module module = findModule(mountPoint, payload);
842 if (module == null) {
843 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
844 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
847 String payloadName = this.getName(payload);
848 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
849 parentSchema, payloadName, module.getNamespace());
850 value = this.normalizeNode(payload, schemaNode, mountPoint);
852 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
855 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
856 iiWithData.getSchemaNode());
857 DOMMountPoint mountPoint = iiWithData.getMountPoint();
858 YangInstanceIdentifier normalizedII;
861 if (mountPoint != null) {
862 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
863 .getInstanceIdentifier());
864 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
866 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
867 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
869 } catch(RestconfDocumentedException e) {
871 } catch (Exception e) {
872 throw new RestconfDocumentedException("Error creating data", e);
875 return Response.status(Status.NO_CONTENT).build();
879 public Response createConfigurationData(final Node<?> payload) {
880 if (payload == null) {
881 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
884 URI payloadNS = this.namespace(payload);
885 if (payloadNS == null) {
886 throw new RestconfDocumentedException(
887 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
888 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
891 final Module module = this.findModule(null, payload);
892 if (module == null) {
893 throw new RestconfDocumentedException(
894 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
895 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
898 String payloadName = this.getName(payload);
899 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
900 payloadName, module.getNamespace());
901 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
902 final InstanceIdentifierContext iiWithData = this.addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
903 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
904 DOMMountPoint mountPoint = iiWithData.getMountPoint();
905 YangInstanceIdentifier normalizedII;
908 if (mountPoint != null) {
909 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
910 .getInstanceIdentifier());
911 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
914 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
915 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
917 } catch(RestconfDocumentedException e) {
919 } catch (Exception e) {
920 throw new RestconfDocumentedException("Error creating data", e);
923 return Response.status(Status.NO_CONTENT).build();
927 public Response deleteConfigurationData(final String identifier) {
928 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
929 DOMMountPoint mountPoint = iiWithData.getMountPoint();
930 YangInstanceIdentifier normalizedII;
933 if (mountPoint != null) {
934 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
935 .getInstanceIdentifier());
936 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
938 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
939 broker.commitConfigurationDataDelete(normalizedII).get();
941 } catch (Exception e) {
942 throw new RestconfDocumentedException("Error creating data", e);
945 return Response.status(Status.OK).build();
949 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
951 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
953 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
954 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
958 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
959 final String streamName = Notificator.createStreamNameFromUri(identifier);
960 if (Strings.isNullOrEmpty(streamName)) {
961 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
964 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
965 if (listener == null) {
966 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
969 Map<String, String> paramToValues = resolveValuesFromUri(identifier);
970 LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
971 paramToValues.get(DATASTORE_PARAM_NAME));
972 if (datastore == null) {
973 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
974 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
976 DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
978 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
979 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
982 broker.registerToListenDataChanges(datastore, scope, listener);
984 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
985 int notificationPort = NOTIFICATION_PORT;
987 WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
988 notificationPort = webSocketServerInstance.getPort();
989 } catch (NullPointerException e) {
990 WebSocketServer.createInstance(NOTIFICATION_PORT);
992 UriBuilder port = uriBuilder.port(notificationPort);
993 final URI uriToWebsocketServer = port.replacePath(streamName).build();
995 return Response.status(Status.OK).location(uriToWebsocketServer).build();
999 * Load parameter for subscribing to stream from input composite node
1003 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1005 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1006 final String paramName) {
1007 QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1008 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1009 SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1010 if (simpleNode == null) {
1013 Object rawValue = simpleNode.getValue();
1014 if (!(rawValue instanceof String)) {
1018 return resolveAsEnum(classDescriptor, (String) rawValue);
1022 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1024 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1027 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1028 if (Strings.isNullOrEmpty(value)) {
1031 return resolveAsEnum(classDescriptor, value);
1034 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1035 T[] enumConstants = classDescriptor.getEnumConstants();
1036 if (enumConstants != null) {
1037 for (T enm : classDescriptor.getEnumConstants()) {
1038 if (((Enum<?>) enm).name().equals(value)) {
1046 private Map<String, String> resolveValuesFromUri(final String uri) {
1047 Map<String, String> result = new HashMap<>();
1048 String[] tokens = uri.split("/");
1049 for (int i = 1; i < tokens.length; i++) {
1050 String[] parameterTokens = tokens[i].split("=");
1051 if (parameterTokens.length == 2) {
1052 result.put(parameterTokens[0], parameterTokens[1]);
1058 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1059 if (data instanceof NodeWrapper) {
1060 return findModule(mountPoint, (NodeWrapper<?>) data);
1061 } else if (data != null) {
1062 URI namespace = data.getNodeType().getNamespace();
1063 if (mountPoint != null) {
1064 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1066 return this.controllerContext.findModuleByNamespace(namespace);
1069 throw new IllegalArgumentException("Unhandled parameter types: "
1070 + Arrays.<Object> asList(mountPoint, data).toString());
1074 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1075 URI namespace = data.getNamespace();
1076 Preconditions.<URI> checkNotNull(namespace);
1078 Module module = null;
1079 if (mountPoint != null) {
1080 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1081 if (module == null) {
1082 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1085 module = this.controllerContext.findModuleByNamespace(namespace);
1086 if (module == null) {
1087 module = this.controllerContext.findModuleByName(namespace.toString());
1094 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1095 final CompositeNode data, final DataSchemaNode schemaOfData, SchemaContext schemaContext) {
1096 YangInstanceIdentifier instanceIdentifier = null;
1097 if (identifierWithSchemaNode != null) {
1098 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1101 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1102 InstanceIdentifierBuilder iiBuilder = null;
1103 if (iiOriginal == null) {
1104 iiBuilder = YangInstanceIdentifier.builder();
1106 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1109 if ((schemaOfData instanceof ListSchemaNode)) {
1110 HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1111 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1113 iiBuilder.node(schemaOfData.getQName());
1116 YangInstanceIdentifier instance = iiBuilder.toInstance();
1117 DOMMountPoint mountPoint = null;
1118 SchemaContext schemaCtx = null;
1119 if (identifierWithSchemaNode != null) {
1120 mountPoint = identifierWithSchemaNode.getMountPoint();
1123 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1126 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1127 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1128 List<QName> _keyDefinition = listNode.getKeyDefinition();
1129 for (final QName key : _keyDefinition) {
1130 SimpleNode<? extends Object> head = null;
1131 String localName = key.getLocalName();
1132 List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1133 if (simpleNodesByName != null) {
1134 head = Iterables.getFirst(simpleNodesByName, null);
1137 Object dataNodeKeyValueObject = null;
1139 dataNodeKeyValueObject = head.getValue();
1142 if (dataNodeKeyValueObject == null) {
1143 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1144 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1145 ErrorTag.INVALID_VALUE);
1148 keyValues.put(key, dataNodeKeyValueObject);
1154 private boolean endsWithMountPoint(final String identifier) {
1155 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1158 private boolean representsMountPointRootData(final Node<?> data) {
1159 URI namespace = this.namespace(data);
1160 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1161 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1164 && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1167 private String addMountPointIdentifier(final String identifier) {
1168 boolean endsWith = identifier.endsWith("/");
1170 return (identifier + ControllerContext.MOUNT);
1173 return identifier + "/" + ControllerContext.MOUNT;
1176 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1177 if (schema == null) {
1178 String localName = node == null ? null :
1179 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1180 node.getNodeType().getLocalName();
1182 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1183 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1186 if (!(schema instanceof DataNodeContainer)) {
1187 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1188 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1191 if ((node instanceof NodeWrapper<?>)) {
1192 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1193 boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1194 if (isChangeAllowed) {
1195 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1197 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1198 } catch (IllegalArgumentException e) {
1199 throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1201 if (nodeWrap instanceof CompositeNodeWrapper) {
1202 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1207 if (node instanceof CompositeNode) {
1208 return (CompositeNode) node;
1211 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1212 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1215 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1216 final QName previousAugment, final DOMMountPoint mountPoint) {
1217 if (schema == null) {
1218 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1219 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1222 QName currentAugment = null;
1223 if (nodeBuilder.getQname() != null) {
1224 currentAugment = previousAugment;
1226 currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1227 if (nodeBuilder.getQname() == null) {
1228 throw new RestconfDocumentedException(
1229 "Data has bad format.\nIf data is in XML format then namespace for \""
1230 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1231 + "\".\n" + "If data is in JSON format then module name for \""
1232 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1233 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1237 if (nodeBuilder instanceof CompositeNodeWrapper) {
1238 if (schema instanceof DataNodeContainer) {
1239 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1241 } else if (schema instanceof AnyXmlSchemaNode) {
1242 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1244 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1245 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1246 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1247 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1251 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1252 List<NodeWrapper<?>> children = compositeNode.getValues();
1253 for (NodeWrapper<? extends Object> child : children) {
1254 child.setNamespace(schema.getQName().getNamespace());
1255 if (child instanceof CompositeNodeWrapper) {
1256 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1261 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1262 if ((schema instanceof LeafSchemaNode)) {
1263 emptyNodeBuilder.setComposite(false);
1265 if ((schema instanceof ContainerSchemaNode)) {
1266 // FIXME: Add presence check
1267 emptyNodeBuilder.setComposite(true);
1272 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1273 final DOMMountPoint mountPoint) {
1274 final Object value = simpleNode.getValue();
1275 Object inputValue = value;
1276 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1277 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1278 if ((value instanceof String)) {
1279 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1281 } // else value is already instance of IdentityValuesDTO
1284 Object outputValue = inputValue;
1286 if (typeDefinition != null) {
1287 Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1288 outputValue = codec == null ? null : codec.deserialize(inputValue);
1291 simpleNode.setValue(outputValue);
1294 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1295 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1296 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1297 checkNodeMultiplicityAccordingToSchema(schema, children);
1298 for (final NodeWrapper<? extends Object> child : children) {
1299 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1300 schema, child.getLocalName());
1302 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1303 StringBuilder builder = new StringBuilder();
1304 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1305 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1308 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1309 + "\" is added as augment from more than one module. "
1310 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1311 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1312 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1315 boolean rightNodeSchemaFound = false;
1316 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1317 if (!rightNodeSchemaFound) {
1318 final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1319 currentAugment, mountPoint);
1320 if (child.getQname() != null) {
1321 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1322 rightNodeSchemaFound = true;
1327 if (!rightNodeSchemaFound) {
1328 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1329 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1333 if ((schema instanceof ListSchemaNode)) {
1334 ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1335 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1336 for (final QName listKey : listKeys) {
1337 boolean foundKey = false;
1338 for (final NodeWrapper<? extends Object> child : children) {
1339 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1345 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1346 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1347 ErrorTag.DATA_MISSING);
1353 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1354 final List<NodeWrapper<?>> nodes) {
1355 Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1356 for (NodeWrapper<?> child : nodes) {
1357 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1358 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1361 for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1362 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1363 String localName = childSchemaNode.getQName().getLocalName();
1364 Integer count = equalNodeNamesToCounts.get(localName);
1365 if (count != null && count > 1) {
1366 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1367 + childSchemaNode.getQName().getLocalName()
1368 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1369 ErrorTag.BAD_ELEMENT);
1375 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1376 final QName previousAugment, final DOMMountPoint mountPoint) {
1377 QName validQName = schema.getQName();
1378 QName currentAugment = previousAugment;
1379 if (schema.isAugmenting()) {
1380 currentAugment = schema.getQName();
1381 } else if (previousAugment != null
1382 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1383 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1386 String moduleName = null;
1387 if (mountPoint == null) {
1388 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1390 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1393 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1394 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1396 * || Note : this check is wrong -
1397 * can never be true as it compares
1398 * a URI with a String not sure what
1399 * the intention is so commented out
1400 * ... Objects . equal ( nodeBuilder
1401 * . getNamespace ( ) ,
1402 * MOUNT_POINT_MODULE_NAME )
1405 nodeBuilder.setQname(validQName);
1408 return currentAugment;
1411 private URI namespace(final Node<?> data) {
1412 if (data instanceof NodeWrapper) {
1413 return ((NodeWrapper<?>) data).getNamespace();
1414 } else if (data != null) {
1415 return data.getNodeType().getNamespace();
1417 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1421 private String localName(final Node<?> data) {
1422 if (data instanceof NodeWrapper) {
1423 return ((NodeWrapper<?>) data).getLocalName();
1424 } else if (data != null) {
1425 return data.getNodeType().getLocalName();
1427 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1431 private String getName(final Node<?> data) {
1432 if (data instanceof NodeWrapper) {
1433 return ((NodeWrapper<?>) data).getLocalName();
1434 } else if (data != null) {
1435 return data.getNodeType().getLocalName();
1437 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1441 private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1442 TypeDefinition<?> baseType = node.getType();
1443 while (baseType.getBaseType() != null) {
1444 baseType = baseType.getBaseType();
1450 private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1451 TypeDefinition<?> baseType = node.getType();
1452 while (baseType.getBaseType() != null) {
1453 baseType = baseType.getBaseType();
1459 private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1460 if (node instanceof LeafListSchemaNode) {
1461 return typeDefinition((LeafListSchemaNode) node);
1462 } else if (node instanceof LeafSchemaNode) {
1463 return _typeDefinition((LeafSchemaNode) node);
1464 } else if (node instanceof AnyXmlSchemaNode) {
1467 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1471 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1472 Node<?> nodes = null;
1473 if (dataNode == null) {
1474 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1475 "No data was found."));
1477 nodes = DataNormalizer.toLegacy(dataNode);
1478 if (nodes != null) {
1479 if (nodes instanceof CompositeNode) {
1480 return (CompositeNode) nodes;
1482 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1485 LOG.error("Top level node isn't of type Container or List schema node but "
1486 + schema.getClass().getSimpleName());
1489 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1490 "It wasn't possible to correctly interpret data."));
1493 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1494 final DataSchemaNode schema) {
1495 List<Node<?>> lst = new ArrayList<Node<?>>();
1497 if (schema instanceof ContainerSchemaNode) {
1498 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1499 .parse(lst, (ContainerSchemaNode) schema);
1500 } else if (schema instanceof ListSchemaNode) {
1501 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1502 .parse(lst, (ListSchemaNode) schema);
1505 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1507 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1508 "It wasn't possible to translate specified data to datastore readable form."));
1511 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1512 final InstanceIdentifierContext iiWithSchemaNode) {
1513 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1516 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1517 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1518 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1519 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1520 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1523 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1524 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1525 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1526 final List<PathArgument> result = new ArrayList<PathArgument>();
1527 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1528 while (iter.hasNext()) {
1529 final PathArgument pathArgument = iter.next();
1530 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1531 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1533 result.add(pathArgument);
1535 return YangInstanceIdentifier.create(result);
1538 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1539 final DataSchemaNode schemaNode) {
1540 if (node instanceof CompositeNodeWrapper) {
1541 return (CompositeNodeWrapper) node;
1542 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1543 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1544 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1547 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1548 "Top level element has to be composite node or has to represent data container node."));
1551 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1552 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1558 public BigInteger getOperationalReceived() {
1559 // TODO Auto-generated method stub