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.Collections;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
30 import javax.ws.rs.core.Response;
31 import javax.ws.rs.core.Response.Status;
32 import javax.ws.rs.core.UriBuilder;
33 import javax.ws.rs.core.UriInfo;
34 import org.apache.commons.lang3.StringUtils;
35 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
36 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
37 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
38 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
39 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
40 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
41 import org.opendaylight.controller.sal.rest.api.Draft02;
42 import org.opendaylight.controller.sal.rest.api.RestconfService;
43 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
44 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
45 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
46 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
47 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
48 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
49 import org.opendaylight.controller.sal.streams.listeners.Notificator;
50 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
51 import org.opendaylight.yangtools.concepts.Codec;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.QNameModule;
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.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
65 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
66 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
67 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
70 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
72 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.Module;
76 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
77 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
78 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
79 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.util.EmptyType;
82 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
83 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
84 import org.slf4j.Logger;
85 import org.slf4j.LoggerFactory;
87 public class RestconfImpl implements RestconfService {
88 private enum UriParameters {
89 PRETTY_PRINT("prettyPrint"),
92 private String uriParameterName;
94 UriParameters(final String uriParameterName) {
95 this.uriParameterName = uriParameterName;
99 public String toString() {
100 return uriParameterName;
104 private final static RestconfImpl INSTANCE = new RestconfImpl();
106 private static final int NOTIFICATION_PORT = 8181;
108 private static final int CHAR_NOT_FOUND = -1;
110 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
112 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
114 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
116 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
118 private BrokerFacade broker;
120 private ControllerContext controllerContext;
122 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
124 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
126 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
128 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
130 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
132 private static final String DATASTORE_PARAM_NAME = "datastore";
134 private static final String SCOPE_PARAM_NAME = "scope";
138 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
139 } catch (ParseException e) {
140 throw new RestconfDocumentedException(
141 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
142 ErrorTag.OPERATION_FAILED);
146 public void setBroker(final BrokerFacade broker) {
147 this.broker = broker;
150 public void setControllerContext(final ControllerContext controllerContext) {
151 this.controllerContext = controllerContext;
154 private RestconfImpl() {
157 public static RestconfImpl getInstance() {
162 public StructuredData getModules(final UriInfo uriInfo) {
163 final Module restconfModule = this.getRestconfModule();
165 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
166 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
167 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
169 Set<Module> allModules = this.controllerContext.getAllModules();
170 for (final Module module : allModules) {
171 CompositeNode moduleCompositeNode = this.toModuleCompositeNode(module, moduleSchemaNode);
172 modulesAsData.add(moduleCompositeNode);
175 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
176 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
177 QName qName = modulesSchemaNode.getQName();
178 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
179 return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
183 public StructuredData getAvailableStreams(final UriInfo uriInfo) {
184 Set<String> availableStreams = Notificator.getStreamNames();
186 final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
187 Module restconfModule = this.getRestconfModule();
188 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
189 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
190 for (final String streamName : availableStreams) {
191 streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
194 final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
195 Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
196 QName qName = streamsSchemaNode.getQName();
197 final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
198 return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
202 public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
203 Set<Module> modules = null;
204 DOMMountPoint mountPoint = null;
205 if (identifier.contains(ControllerContext.MOUNT)) {
206 InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
207 mountPoint = mountPointIdentifier.getMountPoint();
208 modules = this.controllerContext.getAllModules(mountPoint);
210 throw new RestconfDocumentedException(
211 "URI has bad format. If modules behind mount point should be showed, URI has to end with "
212 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
215 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
216 Module restconfModule = this.getRestconfModule();
217 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
218 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
220 for (final Module module : modules) {
221 modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
224 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
225 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
226 QName qName = modulesSchemaNode.getQName();
227 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
228 return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
232 public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
233 final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
234 Module module = null;
235 DOMMountPoint mountPoint = null;
236 if (identifier.contains(ControllerContext.MOUNT)) {
237 InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
238 mountPoint = mountPointIdentifier.getMountPoint();
239 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
241 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
244 if (module == null) {
245 throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
246 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
247 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
250 Module restconfModule = this.getRestconfModule();
251 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
252 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
253 final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
254 return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
258 public StructuredData getOperations(final UriInfo uriInfo) {
259 Set<Module> allModules = this.controllerContext.getAllModules();
260 return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
264 public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
265 Set<Module> modules = null;
266 DOMMountPoint mountPoint = null;
267 if (identifier.contains(ControllerContext.MOUNT)) {
268 InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
269 mountPoint = mountPointIdentifier.getMountPoint();
270 modules = this.controllerContext.getAllModules(mountPoint);
272 throw new RestconfDocumentedException(
273 "URI has bad format. If operations behind mount point should be showed, URI has to end with "
274 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
277 return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
280 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
281 final DOMMountPoint mountPoint, final boolean prettyPrint) {
282 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
283 Module restconfModule = this.getRestconfModule();
284 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
285 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
286 QName qName = operationsSchemaNode.getQName();
287 SchemaPath path = operationsSchemaNode.getPath();
288 ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
289 Draft02.RestConfModule.NAME, 0, qName, path);
290 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
291 for (final Module module : modules) {
292 Set<RpcDefinition> rpcs = module.getRpcs();
293 for (final RpcDefinition rpc : rpcs) {
294 QName rpcQName = rpc.getQName();
295 SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
297 operationsAsData.add(immutableSimpleNode);
299 String name = module.getName();
300 LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
301 SchemaPath.create(true, QName.create("dummy")));
302 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
303 fakeRpcSchemaNode.setAugmenting(true);
305 EmptyType instance = EmptyType.getInstance();
306 fakeRpcSchemaNode.setType(instance);
307 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
311 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
312 ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
313 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
316 private Module getRestconfModule() {
317 Module restconfModule = controllerContext.getRestconfModule();
318 if (restconfModule == null) {
319 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
320 ErrorTag.OPERATION_NOT_SUPPORTED);
323 return restconfModule;
326 private QName getModuleNameAndRevision(final String identifier) {
327 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
328 String moduleNameAndRevision = "";
329 if (mountIndex >= 0) {
330 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
332 moduleNameAndRevision = identifier;
335 Splitter splitter = Splitter.on("/").omitEmptyStrings();
336 Iterable<String> split = splitter.split(moduleNameAndRevision);
337 final List<String> pathArgs = Lists.<String> newArrayList(split);
338 if (pathArgs.size() < 2) {
339 throw new RestconfDocumentedException(
340 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
341 ErrorTag.INVALID_VALUE);
345 final String moduleName = pathArgs.get(0);
346 String revision = pathArgs.get(1);
347 final Date moduleRevision = REVISION_FORMAT.parse(revision);
348 return QName.create(null, moduleRevision, moduleName);
349 } catch (ParseException e) {
350 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
351 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
355 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
356 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
357 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
358 ((DataNodeContainer) streamSchemaNode), "name");
359 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
361 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
363 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
364 ((DataNodeContainer) streamSchemaNode), "description");
365 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
366 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
367 "DESCRIPTION_PLACEHOLDER"));
369 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
370 ((DataNodeContainer) streamSchemaNode), "replay-support");
371 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
372 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
373 Boolean.valueOf(true)));
375 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
376 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
377 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
378 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
381 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
382 ((DataNodeContainer) streamSchemaNode), "events");
383 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
384 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
386 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
389 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
390 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
391 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
392 ((DataNodeContainer) moduleSchemaNode), "name");
393 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
394 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
397 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
398 ((DataNodeContainer) moduleSchemaNode), "revision");
399 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
400 Date _revision = module.getRevision();
401 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
402 REVISION_FORMAT.format(_revision)));
404 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
405 ((DataNodeContainer) moduleSchemaNode), "namespace");
406 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
407 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
408 module.getNamespace().toString()));
410 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
411 ((DataNodeContainer) moduleSchemaNode), "feature");
412 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
413 for (final FeatureDefinition feature : module.getFeatures()) {
414 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
415 feature.getQName().getLocalName()));
418 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
422 public Object getRoot() {
427 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
428 final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
429 QName rpcName = rpc.getRpcDefinition().getQName();
430 URI rpcNamespace = rpcName.getNamespace();
431 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
432 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
433 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
436 validateInput(rpc.getRpcDefinition().getInput(), payload);
438 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
441 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
442 if (inputSchema != null && payload == null) {
443 // expected a non null payload
444 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
445 } else if (inputSchema == null && payload != null) {
446 // did not expect any input
447 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
451 // TODO: Validate "mandatory" and "config" values here??? Or should those be
453 // validate in a more central location inside MD-SAL core.
457 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
458 final boolean prettyPrint) {
459 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
460 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
461 rpc.getQName(), "path"));
462 final Object pathValue = pathNode == null ? null : pathNode.getValue();
464 if (!(pathValue instanceof YangInstanceIdentifier)) {
465 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
466 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
469 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
470 String streamName = null;
471 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
472 String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
474 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
475 DATASTORE_PARAM_NAME);
476 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
478 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
479 scope = scope == null ? DEFAULT_SCOPE : scope;
481 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
482 + "/scope=" + scope);
485 if (Strings.isNullOrEmpty(streamName)) {
486 throw new RestconfDocumentedException(
487 "Path is empty or contains data node which is not Container or List build-in type.",
488 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
491 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
492 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
493 final List<Node<?>> output = new ArrayList<Node<?>>();
494 output.add(streamNameNode);
496 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
497 null, output, null, null);
499 if (!Notificator.existListenerFor(streamName)) {
500 Notificator.createListener(pathIdentifier, streamName);
503 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
507 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
508 if (StringUtils.isNotBlank(noPayload)) {
509 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
511 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
514 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
515 String identifierEncoded = null;
516 DOMMountPoint mountPoint = null;
517 if (identifier.contains(ControllerContext.MOUNT)) {
518 // mounted RPC call - look up mount instance.
519 InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
520 mountPoint = mountPointId.getMountPoint();
522 int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
523 + ControllerContext.MOUNT.length() + 1;
524 String remoteRpcName = identifier.substring(startOfRemoteRpcName);
525 identifierEncoded = remoteRpcName;
527 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
528 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
529 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
530 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
532 identifierEncoded = identifier;
535 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
537 RpcDefinition rpc = null;
538 if (mountPoint == null) {
539 rpc = controllerContext.getRpcDefinition(identifierDecoded);
541 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
545 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
548 if (mountPoint == null) {
549 return new BrokerRpcExecutor(rpc, broker);
551 return new MountPointRpcExecutor(rpc, mountPoint);
556 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
557 final String[] splittedIdentifier = identifierDecoded.split(":");
558 if (splittedIdentifier.length != 2) {
559 throw new RestconfDocumentedException(identifierDecoded
560 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
561 ErrorTag.INVALID_VALUE);
563 for (Module module : schemaContext.getModules()) {
564 if (module.getName().equals(splittedIdentifier[0])) {
565 for (RpcDefinition rpcDefinition : module.getRpcs()) {
566 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
567 return rpcDefinition;
575 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
576 if (rpcExecutor == null) {
577 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
580 CompositeNode rpcRequest = null;
581 RpcDefinition rpc = rpcExecutor.getRpcDefinition();
582 QName rpcName = rpc.getQName();
584 if (payload == null) {
585 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
587 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
588 List<Node<?>> input = Collections.<Node<?>> singletonList(value);
589 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
592 RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
594 checkRpcSuccessAndThrowException(rpcResult);
596 if (rpcResult.getResult() == null) {
600 if (rpc.getOutput() == null) {
601 return null; // no output, nothing to send back.
604 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
607 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
608 if (rpcResult.isSuccessful() == false) {
610 throw new RestconfDocumentedException("The operation was not successful", null,
611 rpcResult.getErrors());
616 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
617 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
618 DOMMountPoint mountPoint = iiWithData.getMountPoint();
619 NormalizedNode<?, ?> data = null;
620 YangInstanceIdentifier normalizedII;
621 if (mountPoint != null) {
622 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
623 .getInstanceIdentifier());
624 data = broker.readConfigurationData(mountPoint, normalizedII);
626 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
627 data = broker.readConfigurationData(normalizedII);
629 return new NormalizedNodeContext(iiWithData, data);
632 @SuppressWarnings("unchecked")
633 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
638 if (node instanceof CompositeNode) {
639 ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
641 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
642 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
646 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
647 } else { // SimpleNode
652 private Integer parseDepthParameter(final UriInfo info) {
653 String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
654 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
659 Integer depth = Integer.valueOf(param);
661 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
662 "Invalid depth parameter: " + depth, null,
663 "The depth parameter must be an integer > 1 or \"unbounded\""));
667 } catch (NumberFormatException e) {
668 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
669 "Invalid depth parameter: " + e.getMessage(), null,
670 "The depth parameter must be an integer > 1 or \"unbounded\""));
675 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
676 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
677 DOMMountPoint mountPoint = iiWithData.getMountPoint();
678 NormalizedNode<?, ?> data = null;
679 YangInstanceIdentifier normalizedII;
680 if (mountPoint != null) {
681 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
682 .getInstanceIdentifier());
683 data = broker.readOperationalData(mountPoint, normalizedII);
685 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
686 data = broker.readOperationalData(normalizedII);
689 return new NormalizedNodeContext(iiWithData, data);
692 private boolean parsePrettyPrintParameter(final UriInfo info) {
693 String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
694 return Boolean.parseBoolean(param);
698 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
699 final InstanceIdentifierContext iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
701 validateInput(iiWithData.getSchemaNode(), payload);
703 DOMMountPoint mountPoint = iiWithData.getMountPoint();
704 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
705 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
706 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
707 iiWithData.getSchemaNode());
709 YangInstanceIdentifier normalizedII;
710 if (mountPoint != null) {
711 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
712 iiWithData.getInstanceIdentifier());
714 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
718 * There is a small window where another write transaction could be updating the same data
719 * simultaneously and we get an OptimisticLockFailedException. This error is likely
720 * transient and The WriteTransaction#submit API docs state that a retry will likely
721 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
722 * probably will never succeed so we'll fail in that case.
724 * By retrying we're attempting to hide the internal implementation of the data store and
725 * how it handles concurrent updates from the restconf client. The client has instructed us
726 * to put the data and we should make every effort to do so without pushing optimistic lock
727 * failures back to the client and forcing them to handle it via retry (and having to
728 * document the behavior).
733 if (mountPoint != null) {
734 broker.commitConfigurationDataPut(mountPoint, normalizedII,
735 datastoreNormalizedNode).checkedGet();
737 broker.commitConfigurationDataPut(normalizedII,
738 datastoreNormalizedNode).checkedGet();
742 } catch (TransactionCommitFailedException e) {
743 if(e instanceof OptimisticLockFailedException) {
745 LOG.debug("Got OptimisticLockFailedException on last try - failing");
746 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
749 LOG.debug("Got OptimisticLockFailedException - trying again");
751 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
756 return Response.status(Status.OK).build();
760 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
762 * @throws RestconfDocumentedException
763 * if key values or key count in payload and URI isn't equal
766 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
767 final CompositeNode payload) {
768 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
769 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
770 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
771 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
772 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
774 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
779 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
780 final List<QName> keyDefinitions) {
781 for (QName keyDefinition : keyDefinitions) {
782 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
783 // should be caught during parsing URI to InstanceIdentifier
784 if (uriKeyValue == null) {
785 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
786 ErrorTag.DATA_MISSING);
788 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
789 if (payloadKeyValues.isEmpty()) {
790 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
791 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
794 Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
795 if (!uriKeyValue.equals(payloadKeyValue)) {
796 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
797 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
798 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
799 ErrorTag.INVALID_VALUE);
805 public Response createConfigurationData(final String identifier, final Node<?> payload) {
806 if (payload == null) {
807 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
810 URI payloadNS = this.namespace(payload);
811 if (payloadNS == null) {
812 throw new RestconfDocumentedException(
813 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
814 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
817 InstanceIdentifierContext iiWithData = null;
818 CompositeNode value = null;
819 if (this.representsMountPointRootData(payload)) {
820 // payload represents mount point data and URI represents path to the mount point
822 if (this.endsWithMountPoint(identifier)) {
823 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
824 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
825 ErrorTag.INVALID_VALUE);
828 final String completeIdentifier = this.addMountPointIdentifier(identifier);
829 iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
831 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
833 final InstanceIdentifierContext incompleteInstIdWithData = this.controllerContext
834 .toInstanceIdentifier(identifier);
835 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
836 DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
837 final Module module = findModule(mountPoint, payload);
838 if (module == null) {
839 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
840 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
843 String payloadName = this.getName(payload);
844 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
845 parentSchema, payloadName, module.getNamespace());
846 value = this.normalizeNode(payload, schemaNode, mountPoint);
848 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
851 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
852 iiWithData.getSchemaNode());
853 DOMMountPoint mountPoint = iiWithData.getMountPoint();
854 YangInstanceIdentifier normalizedII;
857 if (mountPoint != null) {
858 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
859 .getInstanceIdentifier());
860 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
862 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
863 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
865 } catch(RestconfDocumentedException e) {
867 } catch (Exception e) {
868 throw new RestconfDocumentedException("Error creating data", e);
871 return Response.status(Status.NO_CONTENT).build();
875 public Response createConfigurationData(final Node<?> payload) {
876 if (payload == null) {
877 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
880 URI payloadNS = this.namespace(payload);
881 if (payloadNS == null) {
882 throw new RestconfDocumentedException(
883 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
884 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
887 final Module module = this.findModule(null, payload);
888 if (module == null) {
889 throw new RestconfDocumentedException(
890 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
891 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
894 String payloadName = this.getName(payload);
895 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
896 payloadName, module.getNamespace());
897 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
898 final InstanceIdentifierContext iiWithData = this.addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
899 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
900 DOMMountPoint mountPoint = iiWithData.getMountPoint();
901 YangInstanceIdentifier normalizedII;
904 if (mountPoint != null) {
905 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
906 .getInstanceIdentifier());
907 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
910 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
911 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
913 } catch(RestconfDocumentedException e) {
915 } catch (Exception e) {
916 throw new RestconfDocumentedException("Error creating data", e);
919 return Response.status(Status.NO_CONTENT).build();
923 public Response deleteConfigurationData(final String identifier) {
924 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
925 DOMMountPoint mountPoint = iiWithData.getMountPoint();
926 YangInstanceIdentifier normalizedII;
929 if (mountPoint != null) {
930 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
931 .getInstanceIdentifier());
932 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
934 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
935 broker.commitConfigurationDataDelete(normalizedII).get();
937 } catch (Exception e) {
938 throw new RestconfDocumentedException("Error creating data", e);
941 return Response.status(Status.OK).build();
945 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
947 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
949 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
950 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
954 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
955 final String streamName = Notificator.createStreamNameFromUri(identifier);
956 if (Strings.isNullOrEmpty(streamName)) {
957 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
960 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
961 if (listener == null) {
962 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
965 Map<String, String> paramToValues = resolveValuesFromUri(identifier);
966 LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
967 paramToValues.get(DATASTORE_PARAM_NAME));
968 if (datastore == null) {
969 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
970 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
972 DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
974 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
975 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
978 broker.registerToListenDataChanges(datastore, scope, listener);
980 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
981 int notificationPort = NOTIFICATION_PORT;
983 WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
984 notificationPort = webSocketServerInstance.getPort();
985 } catch (NullPointerException e) {
986 WebSocketServer.createInstance(NOTIFICATION_PORT);
988 UriBuilder port = uriBuilder.port(notificationPort);
989 final URI uriToWebsocketServer = port.replacePath(streamName).build();
991 return Response.status(Status.OK).location(uriToWebsocketServer).build();
995 * Load parameter for subscribing to stream from input composite node
999 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1001 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1002 final String paramName) {
1003 QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1004 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1005 SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1006 if (simpleNode == null) {
1009 Object rawValue = simpleNode.getValue();
1010 if (!(rawValue instanceof String)) {
1014 return resolveAsEnum(classDescriptor, (String) rawValue);
1018 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1020 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1023 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1024 if (Strings.isNullOrEmpty(value)) {
1027 return resolveAsEnum(classDescriptor, value);
1030 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1031 T[] enumConstants = classDescriptor.getEnumConstants();
1032 if (enumConstants != null) {
1033 for (T enm : classDescriptor.getEnumConstants()) {
1034 if (((Enum<?>) enm).name().equals(value)) {
1042 private Map<String, String> resolveValuesFromUri(final String uri) {
1043 Map<String, String> result = new HashMap<>();
1044 String[] tokens = uri.split("/");
1045 for (int i = 1; i < tokens.length; i++) {
1046 String[] parameterTokens = tokens[i].split("=");
1047 if (parameterTokens.length == 2) {
1048 result.put(parameterTokens[0], parameterTokens[1]);
1054 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1055 if (data instanceof NodeWrapper) {
1056 return findModule(mountPoint, (NodeWrapper<?>) data);
1057 } else if (data != null) {
1058 URI namespace = data.getNodeType().getNamespace();
1059 if (mountPoint != null) {
1060 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1062 return this.controllerContext.findModuleByNamespace(namespace);
1065 throw new IllegalArgumentException("Unhandled parameter types: "
1066 + Arrays.<Object> asList(mountPoint, data).toString());
1070 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1071 URI namespace = data.getNamespace();
1072 Preconditions.<URI> checkNotNull(namespace);
1074 Module module = null;
1075 if (mountPoint != null) {
1076 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1077 if (module == null) {
1078 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1081 module = this.controllerContext.findModuleByNamespace(namespace);
1082 if (module == null) {
1083 module = this.controllerContext.findModuleByName(namespace.toString());
1090 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1091 final CompositeNode data, final DataSchemaNode schemaOfData, SchemaContext schemaContext) {
1092 YangInstanceIdentifier instanceIdentifier = null;
1093 if (identifierWithSchemaNode != null) {
1094 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1097 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1098 InstanceIdentifierBuilder iiBuilder = null;
1099 if (iiOriginal == null) {
1100 iiBuilder = YangInstanceIdentifier.builder();
1102 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1105 if ((schemaOfData instanceof ListSchemaNode)) {
1106 HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1107 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1109 iiBuilder.node(schemaOfData.getQName());
1112 YangInstanceIdentifier instance = iiBuilder.toInstance();
1113 DOMMountPoint mountPoint = null;
1114 SchemaContext schemaCtx = null;
1115 if (identifierWithSchemaNode != null) {
1116 mountPoint = identifierWithSchemaNode.getMountPoint();
1119 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1122 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1123 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1124 List<QName> _keyDefinition = listNode.getKeyDefinition();
1125 for (final QName key : _keyDefinition) {
1126 SimpleNode<? extends Object> head = null;
1127 String localName = key.getLocalName();
1128 List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1129 if (simpleNodesByName != null) {
1130 head = Iterables.getFirst(simpleNodesByName, null);
1133 Object dataNodeKeyValueObject = null;
1135 dataNodeKeyValueObject = head.getValue();
1138 if (dataNodeKeyValueObject == null) {
1139 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1140 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1141 ErrorTag.INVALID_VALUE);
1144 keyValues.put(key, dataNodeKeyValueObject);
1150 private boolean endsWithMountPoint(final String identifier) {
1151 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1154 private boolean representsMountPointRootData(final Node<?> data) {
1155 URI namespace = this.namespace(data);
1156 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1157 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1160 && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1163 private String addMountPointIdentifier(final String identifier) {
1164 boolean endsWith = identifier.endsWith("/");
1166 return (identifier + ControllerContext.MOUNT);
1169 return identifier + "/" + ControllerContext.MOUNT;
1172 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1173 if (schema == null) {
1174 String localName = node == null ? null :
1175 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1176 node.getNodeType().getLocalName();
1178 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1179 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1182 if (!(schema instanceof DataNodeContainer)) {
1183 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1184 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1187 if ((node instanceof NodeWrapper<?>)) {
1188 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1189 boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1190 if (isChangeAllowed) {
1191 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1193 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1194 } catch (IllegalArgumentException e) {
1195 throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1197 if (nodeWrap instanceof CompositeNodeWrapper) {
1198 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1203 if (node instanceof CompositeNode) {
1204 return (CompositeNode) node;
1207 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1208 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1211 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1212 final QName previousAugment, final DOMMountPoint mountPoint) {
1213 if (schema == null) {
1214 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1215 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1218 QName currentAugment = null;
1219 if (nodeBuilder.getQname() != null) {
1220 currentAugment = previousAugment;
1222 currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1223 if (nodeBuilder.getQname() == null) {
1224 throw new RestconfDocumentedException(
1225 "Data has bad format.\nIf data is in XML format then namespace for \""
1226 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1227 + "\".\n" + "If data is in JSON format then module name for \""
1228 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1229 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1233 if (nodeBuilder instanceof CompositeNodeWrapper) {
1234 if (schema instanceof DataNodeContainer) {
1235 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1237 } else if (schema instanceof AnyXmlSchemaNode) {
1238 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1240 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1241 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1242 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1243 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1247 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1248 List<NodeWrapper<?>> children = compositeNode.getValues();
1249 for (NodeWrapper<? extends Object> child : children) {
1250 child.setNamespace(schema.getQName().getNamespace());
1251 if (child instanceof CompositeNodeWrapper) {
1252 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1257 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1258 if ((schema instanceof LeafSchemaNode)) {
1259 emptyNodeBuilder.setComposite(false);
1261 if ((schema instanceof ContainerSchemaNode)) {
1262 // FIXME: Add presence check
1263 emptyNodeBuilder.setComposite(true);
1268 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1269 final DOMMountPoint mountPoint) {
1270 final Object value = simpleNode.getValue();
1271 Object inputValue = value;
1272 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1273 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1274 if ((value instanceof String)) {
1275 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1277 } // else value is already instance of IdentityValuesDTO
1280 Object outputValue = inputValue;
1282 if (typeDefinition != null) {
1283 Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1284 outputValue = codec == null ? null : codec.deserialize(inputValue);
1287 simpleNode.setValue(outputValue);
1290 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1291 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1292 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1293 checkNodeMultiplicityAccordingToSchema(schema, children);
1294 for (final NodeWrapper<? extends Object> child : children) {
1295 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1296 schema, child.getLocalName());
1298 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1299 StringBuilder builder = new StringBuilder();
1300 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1301 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1304 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1305 + "\" is added as augment from more than one module. "
1306 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1307 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1308 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1311 boolean rightNodeSchemaFound = false;
1312 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1313 if (!rightNodeSchemaFound) {
1314 final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1315 currentAugment, mountPoint);
1316 if (child.getQname() != null) {
1317 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1318 rightNodeSchemaFound = true;
1323 if (!rightNodeSchemaFound) {
1324 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1325 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1329 if ((schema instanceof ListSchemaNode)) {
1330 ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1331 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1332 for (final QName listKey : listKeys) {
1333 boolean foundKey = false;
1334 for (final NodeWrapper<? extends Object> child : children) {
1335 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1341 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1342 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1343 ErrorTag.DATA_MISSING);
1349 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1350 final List<NodeWrapper<?>> nodes) {
1351 Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1352 for (NodeWrapper<?> child : nodes) {
1353 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1354 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1357 for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1358 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1359 String localName = childSchemaNode.getQName().getLocalName();
1360 Integer count = equalNodeNamesToCounts.get(localName);
1361 if (count != null && count > 1) {
1362 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1363 + childSchemaNode.getQName().getLocalName()
1364 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1365 ErrorTag.BAD_ELEMENT);
1371 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1372 final QName previousAugment, final DOMMountPoint mountPoint) {
1373 QName validQName = schema.getQName();
1374 QName currentAugment = previousAugment;
1375 if (schema.isAugmenting()) {
1376 currentAugment = schema.getQName();
1377 } else if (previousAugment != null
1378 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1379 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1382 String moduleName = null;
1383 if (mountPoint == null) {
1384 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1386 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1389 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1390 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1392 * || Note : this check is wrong -
1393 * can never be true as it compares
1394 * a URI with a String not sure what
1395 * the intention is so commented out
1396 * ... Objects . equal ( nodeBuilder
1397 * . getNamespace ( ) ,
1398 * MOUNT_POINT_MODULE_NAME )
1401 nodeBuilder.setQname(validQName);
1404 return currentAugment;
1407 private URI namespace(final Node<?> data) {
1408 if (data instanceof NodeWrapper) {
1409 return ((NodeWrapper<?>) data).getNamespace();
1410 } else if (data != null) {
1411 return data.getNodeType().getNamespace();
1413 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1417 private String localName(final Node<?> data) {
1418 if (data instanceof NodeWrapper) {
1419 return ((NodeWrapper<?>) data).getLocalName();
1420 } else if (data != null) {
1421 return data.getNodeType().getLocalName();
1423 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1427 private String getName(final Node<?> data) {
1428 if (data instanceof NodeWrapper) {
1429 return ((NodeWrapper<?>) data).getLocalName();
1430 } else if (data != null) {
1431 return data.getNodeType().getLocalName();
1433 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1437 private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1438 TypeDefinition<?> baseType = node.getType();
1439 while (baseType.getBaseType() != null) {
1440 baseType = baseType.getBaseType();
1446 private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1447 TypeDefinition<?> baseType = node.getType();
1448 while (baseType.getBaseType() != null) {
1449 baseType = baseType.getBaseType();
1455 private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1456 if (node instanceof LeafListSchemaNode) {
1457 return typeDefinition((LeafListSchemaNode) node);
1458 } else if (node instanceof LeafSchemaNode) {
1459 return _typeDefinition((LeafSchemaNode) node);
1460 } else if (node instanceof AnyXmlSchemaNode) {
1463 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1467 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1468 Node<?> nodes = null;
1469 if (dataNode == null) {
1470 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1471 "No data was found."));
1473 nodes = DataNormalizer.toLegacy(dataNode);
1474 if (nodes != null) {
1475 if (nodes instanceof CompositeNode) {
1476 return (CompositeNode) nodes;
1478 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1481 LOG.error("Top level node isn't of type Container or List schema node but "
1482 + schema.getClass().getSimpleName());
1485 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1486 "It wasn't possible to correctly interpret data."));
1489 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1490 final DataSchemaNode schema) {
1491 List<Node<?>> lst = new ArrayList<Node<?>>();
1493 if (schema instanceof ContainerSchemaNode) {
1494 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1495 .parse(lst, (ContainerSchemaNode) schema);
1496 } else if (schema instanceof ListSchemaNode) {
1497 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1498 .parse(lst, (ListSchemaNode) schema);
1501 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1503 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1504 "It wasn't possible to translate specified data to datastore readable form."));
1507 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1508 final InstanceIdentifierContext iiWithSchemaNode) {
1509 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1512 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1513 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1514 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1515 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1516 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1519 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1520 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1521 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1522 final List<PathArgument> result = new ArrayList<PathArgument>();
1523 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1524 while (iter.hasNext()) {
1525 final PathArgument pathArgument = iter.next();
1526 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1527 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1529 result.add(pathArgument);
1531 return YangInstanceIdentifier.create(result);
1534 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1535 final DataSchemaNode schemaNode) {
1536 if (node instanceof CompositeNodeWrapper) {
1537 return (CompositeNodeWrapper) node;
1538 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1539 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1540 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1543 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1544 "Top level element has to be composite node or has to represent data container node."));
1547 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1548 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {