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;
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;
36 import org.apache.commons.lang3.StringUtils;
37 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
38 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
39 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
41 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
42 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
43 import org.opendaylight.controller.sal.rest.api.Draft02;
44 import org.opendaylight.controller.sal.rest.api.RestconfService;
45 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
46 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
47 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
48 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
49 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
50 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
51 import org.opendaylight.controller.sal.streams.listeners.Notificator;
52 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
53 import org.opendaylight.yangtools.concepts.Codec;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.QNameModule;
56 import org.opendaylight.yangtools.yang.common.RpcResult;
57 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
58 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
59 import org.opendaylight.yangtools.yang.data.api.Node;
60 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
65 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
66 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
67 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
68 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
69 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
72 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
74 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
76 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
77 import org.opendaylight.yangtools.yang.model.api.Module;
78 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
79 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
80 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
81 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.util.EmptyType;
84 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
85 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
89 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;
106 private final static RestconfImpl INSTANCE = new RestconfImpl();
108 private static final int NOTIFICATION_PORT = 8181;
110 private static final int CHAR_NOT_FOUND = -1;
112 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
114 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
116 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
118 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
120 private BrokerFacade broker;
122 private ControllerContext controllerContext;
124 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
126 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
128 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
130 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
132 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
134 private static final String DATASTORE_PARAM_NAME = "datastore";
136 private static final String SCOPE_PARAM_NAME = "scope";
140 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
141 } catch (ParseException e) {
142 throw new RestconfDocumentedException(
143 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
144 ErrorTag.OPERATION_FAILED);
148 public void setBroker(final BrokerFacade broker) {
149 this.broker = broker;
152 public void setControllerContext(final ControllerContext controllerContext) {
153 this.controllerContext = controllerContext;
156 private RestconfImpl() {
159 public static RestconfImpl getInstance() {
164 public StructuredData getModules(final UriInfo uriInfo) {
165 final Module restconfModule = this.getRestconfModule();
167 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
168 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
169 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
171 Set<Module> allModules = this.controllerContext.getAllModules();
172 for (final Module module : allModules) {
173 CompositeNode moduleCompositeNode = this.toModuleCompositeNode(module, moduleSchemaNode);
174 modulesAsData.add(moduleCompositeNode);
177 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
178 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
179 QName qName = modulesSchemaNode.getQName();
180 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
181 return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
185 public StructuredData getAvailableStreams(final UriInfo uriInfo) {
186 Set<String> availableStreams = Notificator.getStreamNames();
188 final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
189 Module restconfModule = this.getRestconfModule();
190 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
191 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
192 for (final String streamName : availableStreams) {
193 streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
196 final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
197 Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
198 QName qName = streamsSchemaNode.getQName();
199 final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
200 return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
204 public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
205 Set<Module> modules = null;
206 DOMMountPoint mountPoint = null;
207 if (identifier.contains(ControllerContext.MOUNT)) {
208 InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
209 mountPoint = mountPointIdentifier.getMountPoint();
210 modules = this.controllerContext.getAllModules(mountPoint);
212 throw new RestconfDocumentedException(
213 "URI has bad format. If modules behind mount point should be showed, URI has to end with "
214 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
217 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
218 Module restconfModule = this.getRestconfModule();
219 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
220 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
222 for (final Module module : modules) {
223 modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
226 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
227 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
228 QName qName = modulesSchemaNode.getQName();
229 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
230 return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
234 public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
235 final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
236 Module module = null;
237 DOMMountPoint mountPoint = null;
238 if (identifier.contains(ControllerContext.MOUNT)) {
239 InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
240 mountPoint = mountPointIdentifier.getMountPoint();
241 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
243 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
246 if (module == null) {
247 throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
248 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
249 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
252 Module restconfModule = this.getRestconfModule();
253 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
254 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
255 final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
256 return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
260 public StructuredData getOperations(final UriInfo uriInfo) {
261 Set<Module> allModules = this.controllerContext.getAllModules();
262 return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
266 public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
267 Set<Module> modules = null;
268 DOMMountPoint mountPoint = null;
269 if (identifier.contains(ControllerContext.MOUNT)) {
270 InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
271 mountPoint = mountPointIdentifier.getMountPoint();
272 modules = this.controllerContext.getAllModules(mountPoint);
274 throw new RestconfDocumentedException(
275 "URI has bad format. If operations behind mount point should be showed, URI has to end with "
276 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
279 return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
282 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
283 final DOMMountPoint mountPoint, final boolean prettyPrint) {
284 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
285 Module restconfModule = this.getRestconfModule();
286 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
287 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
288 QName qName = operationsSchemaNode.getQName();
289 SchemaPath path = operationsSchemaNode.getPath();
290 ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
291 Draft02.RestConfModule.NAME, 0, qName, path);
292 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
293 for (final Module module : modules) {
294 Set<RpcDefinition> rpcs = module.getRpcs();
295 for (final RpcDefinition rpc : rpcs) {
296 QName rpcQName = rpc.getQName();
297 SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
299 operationsAsData.add(immutableSimpleNode);
301 String name = module.getName();
302 LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
303 SchemaPath.create(true, QName.create("dummy")));
304 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
305 fakeRpcSchemaNode.setAugmenting(true);
307 EmptyType instance = EmptyType.getInstance();
308 fakeRpcSchemaNode.setType(instance);
309 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
313 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
314 ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
315 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
318 private Module getRestconfModule() {
319 Module restconfModule = controllerContext.getRestconfModule();
320 if (restconfModule == null) {
321 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
322 ErrorTag.OPERATION_NOT_SUPPORTED);
325 return restconfModule;
328 private QName getModuleNameAndRevision(final String identifier) {
329 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
330 String moduleNameAndRevision = "";
331 if (mountIndex >= 0) {
332 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
334 moduleNameAndRevision = identifier;
337 Splitter splitter = Splitter.on("/").omitEmptyStrings();
338 Iterable<String> split = splitter.split(moduleNameAndRevision);
339 final List<String> pathArgs = Lists.<String> newArrayList(split);
340 if (pathArgs.size() < 2) {
341 throw new RestconfDocumentedException(
342 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
343 ErrorTag.INVALID_VALUE);
347 final String moduleName = pathArgs.get(0);
348 String revision = pathArgs.get(1);
349 final Date moduleRevision = REVISION_FORMAT.parse(revision);
350 return QName.create(null, moduleRevision, moduleName);
351 } catch (ParseException e) {
352 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
353 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
357 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
358 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
359 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
360 ((DataNodeContainer) streamSchemaNode), "name");
361 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
363 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
365 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
366 ((DataNodeContainer) streamSchemaNode), "description");
367 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
368 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
369 "DESCRIPTION_PLACEHOLDER"));
371 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
372 ((DataNodeContainer) streamSchemaNode), "replay-support");
373 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
374 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
375 Boolean.valueOf(true)));
377 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
378 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
379 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
380 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
383 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
384 ((DataNodeContainer) streamSchemaNode), "events");
385 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
386 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
388 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
391 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
392 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
393 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
394 ((DataNodeContainer) moduleSchemaNode), "name");
395 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
396 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
399 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
400 ((DataNodeContainer) moduleSchemaNode), "revision");
401 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
402 Date _revision = module.getRevision();
403 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
404 REVISION_FORMAT.format(_revision)));
406 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
407 ((DataNodeContainer) moduleSchemaNode), "namespace");
408 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
409 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
410 module.getNamespace().toString()));
412 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
413 ((DataNodeContainer) moduleSchemaNode), "feature");
414 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
415 for (final FeatureDefinition feature : module.getFeatures()) {
416 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
417 feature.getQName().getLocalName()));
420 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
424 public Object getRoot() {
429 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
430 final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
431 QName rpcName = rpc.getRpcDefinition().getQName();
432 URI rpcNamespace = rpcName.getNamespace();
433 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
434 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
435 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
438 validateInput(rpc.getRpcDefinition().getInput(), payload);
440 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
443 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
444 if (inputSchema != null && payload == null) {
445 // expected a non null payload
446 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
447 } else if (inputSchema == null && payload != null) {
448 // did not expect any input
449 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
453 // TODO: Validate "mandatory" and "config" values here??? Or should those be
455 // validate in a more central location inside MD-SAL core.
459 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
460 final boolean prettyPrint) {
461 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
462 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
463 rpc.getQName(), "path"));
464 final Object pathValue = pathNode == null ? null : pathNode.getValue();
466 if (!(pathValue instanceof YangInstanceIdentifier)) {
467 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
468 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
471 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
472 String streamName = null;
473 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
474 String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
476 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
477 DATASTORE_PARAM_NAME);
478 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
480 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
481 scope = scope == null ? DEFAULT_SCOPE : scope;
483 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
484 + "/scope=" + scope);
487 if (Strings.isNullOrEmpty(streamName)) {
488 throw new RestconfDocumentedException(
489 "Path is empty or contains data node which is not Container or List build-in type.",
490 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
493 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
494 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
495 final List<Node<?>> output = new ArrayList<Node<?>>();
496 output.add(streamNameNode);
498 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
499 null, output, null, null);
501 if (!Notificator.existListenerFor(streamName)) {
502 Notificator.createListener(pathIdentifier, streamName);
505 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
509 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
510 if (StringUtils.isNotBlank(noPayload)) {
511 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
513 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
516 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
517 String identifierEncoded = null;
518 DOMMountPoint mountPoint = null;
519 if (identifier.contains(ControllerContext.MOUNT)) {
520 // mounted RPC call - look up mount instance.
521 InstanceIdWithSchemaNode mountPointId = controllerContext.toMountPointIdentifier(identifier);
522 mountPoint = mountPointId.getMountPoint();
524 int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
525 + ControllerContext.MOUNT.length() + 1;
526 String remoteRpcName = identifier.substring(startOfRemoteRpcName);
527 identifierEncoded = remoteRpcName;
529 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
530 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
531 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
532 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
534 identifierEncoded = identifier;
537 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
539 RpcDefinition rpc = null;
540 if (mountPoint == null) {
541 rpc = controllerContext.getRpcDefinition(identifierDecoded);
543 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
547 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
550 if (mountPoint == null) {
551 return new BrokerRpcExecutor(rpc, broker);
553 return new MountPointRpcExecutor(rpc, mountPoint);
558 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
559 final String[] splittedIdentifier = identifierDecoded.split(":");
560 if (splittedIdentifier.length != 2) {
561 throw new RestconfDocumentedException(identifierDecoded
562 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
563 ErrorTag.INVALID_VALUE);
565 for (Module module : schemaContext.getModules()) {
566 if (module.getName().equals(splittedIdentifier[0])) {
567 for (RpcDefinition rpcDefinition : module.getRpcs()) {
568 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
569 return rpcDefinition;
577 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
578 if (rpcExecutor == null) {
579 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
582 CompositeNode rpcRequest = null;
583 RpcDefinition rpc = rpcExecutor.getRpcDefinition();
584 QName rpcName = rpc.getQName();
586 if (payload == null) {
587 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
589 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
590 List<Node<?>> input = Collections.<Node<?>> singletonList(value);
591 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
594 RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
596 checkRpcSuccessAndThrowException(rpcResult);
598 if (rpcResult.getResult() == null) {
602 if (rpc.getOutput() == null) {
603 return null; // no output, nothing to send back.
606 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
609 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
610 if (rpcResult.isSuccessful() == false) {
612 throw new RestconfDocumentedException("The operation was not successful", null,
613 rpcResult.getErrors());
618 public StructuredData readConfigurationData(final String identifier, final UriInfo uriInfo) {
619 final InstanceIdWithSchemaNode iiWithData = controllerContext.toInstanceIdentifier(identifier);
620 DOMMountPoint mountPoint = iiWithData.getMountPoint();
621 NormalizedNode<?, ?> data = null;
622 YangInstanceIdentifier normalizedII;
623 if (mountPoint != null) {
624 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
625 .getInstanceIdentifier());
626 data = broker.readConfigurationData(mountPoint, normalizedII);
628 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
629 data = broker.readConfigurationData(normalizedII);
632 final CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode());
633 final CompositeNode prunedCompositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(uriInfo));
635 final boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo);
636 return new StructuredData(prunedCompositeNode, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
639 @SuppressWarnings("unchecked")
640 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
645 if (node instanceof CompositeNode) {
646 ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
648 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
649 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
653 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
654 } else { // SimpleNode
659 private Integer parseDepthParameter(final UriInfo info) {
660 String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
661 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
666 Integer depth = Integer.valueOf(param);
668 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
669 "Invalid depth parameter: " + depth, null,
670 "The depth parameter must be an integer > 1 or \"unbounded\""));
674 } catch (NumberFormatException e) {
675 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
676 "Invalid depth parameter: " + e.getMessage(), null,
677 "The depth parameter must be an integer > 1 or \"unbounded\""));
682 public StructuredData readOperationalData(final String identifier, final UriInfo info) {
683 final InstanceIdWithSchemaNode iiWithData = controllerContext.toInstanceIdentifier(identifier);
684 DOMMountPoint mountPoint = iiWithData.getMountPoint();
685 NormalizedNode<?, ?> data = null;
686 YangInstanceIdentifier normalizedII;
687 if (mountPoint != null) {
688 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
689 .getInstanceIdentifier());
690 data = broker.readOperationalData(mountPoint, normalizedII);
692 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
693 data = broker.readOperationalData(normalizedII);
696 final CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode());
697 final CompositeNode prunedCompositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(info));
699 final boolean prettyPrintMode = parsePrettyPrintParameter(info);
700 return new StructuredData(prunedCompositeNode, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
703 private boolean parsePrettyPrintParameter(final UriInfo info) {
704 String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
705 return Boolean.parseBoolean(param);
709 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
710 final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
712 validateInput(iiWithData.getSchemaNode(), payload);
714 DOMMountPoint mountPoint = iiWithData.getMountPoint();
715 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
716 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
717 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
718 iiWithData.getSchemaNode());
720 YangInstanceIdentifier normalizedII;
721 if (mountPoint != null) {
722 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
723 iiWithData.getInstanceIdentifier());
725 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
729 * There is a small window where another write transaction could be updating the same data
730 * simultaneously and we get an OptimisticLockFailedException. This error is likely
731 * transient and The WriteTransaction#submit API docs state that a retry will likely
732 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
733 * probably will never succeed so we'll fail in that case.
735 * By retrying we're attempting to hide the internal implementation of the data store and
736 * how it handles concurrent updates from the restconf client. The client has instructed us
737 * to put the data and we should make every effort to do so without pushing optimistic lock
738 * failures back to the client and forcing them to handle it via retry (and having to
739 * document the behavior).
744 if (mountPoint != null) {
745 broker.commitConfigurationDataPut(mountPoint, normalizedII,
746 datastoreNormalizedNode).checkedGet();
748 broker.commitConfigurationDataPut(normalizedII,
749 datastoreNormalizedNode).checkedGet();
753 } catch (TransactionCommitFailedException e) {
754 if(e instanceof OptimisticLockFailedException) {
756 LOG.debug("Got OptimisticLockFailedException on last try - failing");
757 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
760 LOG.debug("Got OptimisticLockFailedException - trying again");
762 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
767 return Response.status(Status.OK).build();
771 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
773 * @throws RestconfDocumentedException
774 * if key values or key count in payload and URI isn't equal
777 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdWithSchemaNode iiWithData,
778 final CompositeNode payload) {
779 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
780 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
781 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
782 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
783 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
785 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
790 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
791 final List<QName> keyDefinitions) {
792 for (QName keyDefinition : keyDefinitions) {
793 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
794 // should be caught during parsing URI to InstanceIdentifier
795 if (uriKeyValue == null) {
796 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
797 ErrorTag.DATA_MISSING);
799 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
800 if (payloadKeyValues.isEmpty()) {
801 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
802 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
805 Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
806 if (!uriKeyValue.equals(payloadKeyValue)) {
807 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
808 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
809 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
810 ErrorTag.INVALID_VALUE);
816 public Response createConfigurationData(final String identifier, final Node<?> payload) {
817 if (payload == null) {
818 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
821 URI payloadNS = this.namespace(payload);
822 if (payloadNS == null) {
823 throw new RestconfDocumentedException(
824 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
825 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
828 InstanceIdWithSchemaNode iiWithData = null;
829 CompositeNode value = null;
830 if (this.representsMountPointRootData(payload)) {
831 // payload represents mount point data and URI represents path to the mount point
833 if (this.endsWithMountPoint(identifier)) {
834 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
835 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
836 ErrorTag.INVALID_VALUE);
839 final String completeIdentifier = this.addMountPointIdentifier(identifier);
840 iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
842 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
844 final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext
845 .toInstanceIdentifier(identifier);
846 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
847 DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
848 final Module module = findModule(mountPoint, payload);
849 if (module == null) {
850 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
851 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
854 String payloadName = this.getName(payload);
855 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
856 parentSchema, payloadName, module.getNamespace());
857 value = this.normalizeNode(payload, schemaNode, mountPoint);
859 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode);
862 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
863 iiWithData.getSchemaNode());
864 DOMMountPoint mountPoint = iiWithData.getMountPoint();
865 YangInstanceIdentifier normalizedII;
868 if (mountPoint != null) {
869 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
870 .getInstanceIdentifier());
871 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
873 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
874 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
876 } catch(RestconfDocumentedException e) {
878 } catch (Exception e) {
879 throw new RestconfDocumentedException("Error creating data", e);
882 return Response.status(Status.NO_CONTENT).build();
886 public Response createConfigurationData(final Node<?> payload) {
887 if (payload == null) {
888 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
891 URI payloadNS = this.namespace(payload);
892 if (payloadNS == null) {
893 throw new RestconfDocumentedException(
894 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
895 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
898 final Module module = this.findModule(null, payload);
899 if (module == null) {
900 throw new RestconfDocumentedException(
901 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
902 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
905 String payloadName = this.getName(payload);
906 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
907 payloadName, module.getNamespace());
908 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
909 final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode);
910 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
911 DOMMountPoint mountPoint = iiWithData.getMountPoint();
912 YangInstanceIdentifier normalizedII;
915 if (mountPoint != null) {
916 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
917 .getInstanceIdentifier());
918 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
921 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
922 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
924 } catch(RestconfDocumentedException e) {
926 } catch (Exception e) {
927 throw new RestconfDocumentedException("Error creating data", e);
930 return Response.status(Status.NO_CONTENT).build();
934 public Response deleteConfigurationData(final String identifier) {
935 final InstanceIdWithSchemaNode iiWithData = controllerContext.toInstanceIdentifier(identifier);
936 DOMMountPoint mountPoint = iiWithData.getMountPoint();
937 YangInstanceIdentifier normalizedII;
940 if (mountPoint != null) {
941 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
942 .getInstanceIdentifier());
943 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
945 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
946 broker.commitConfigurationDataDelete(normalizedII).get();
948 } catch (Exception e) {
949 throw new RestconfDocumentedException("Error creating data", e);
952 return Response.status(Status.OK).build();
956 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
958 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
960 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
961 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
965 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
966 final String streamName = Notificator.createStreamNameFromUri(identifier);
967 if (Strings.isNullOrEmpty(streamName)) {
968 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
971 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
972 if (listener == null) {
973 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
976 Map<String, String> paramToValues = resolveValuesFromUri(identifier);
977 LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
978 paramToValues.get(DATASTORE_PARAM_NAME));
979 if (datastore == null) {
980 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
981 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
983 DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
985 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
986 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
989 broker.registerToListenDataChanges(datastore, scope, listener);
991 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
992 int notificationPort = NOTIFICATION_PORT;
994 WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
995 notificationPort = webSocketServerInstance.getPort();
996 } catch (NullPointerException e) {
997 WebSocketServer.createInstance(NOTIFICATION_PORT);
999 UriBuilder port = uriBuilder.port(notificationPort);
1000 final URI uriToWebsocketServer = port.replacePath(streamName).build();
1002 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1006 * Load parameter for subscribing to stream from input composite node
1010 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1012 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1013 final String paramName) {
1014 QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1015 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1016 SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1017 if (simpleNode == null) {
1020 Object rawValue = simpleNode.getValue();
1021 if (!(rawValue instanceof String)) {
1025 return resolveAsEnum(classDescriptor, (String) rawValue);
1029 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1031 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1034 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1035 if (Strings.isNullOrEmpty(value)) {
1038 return resolveAsEnum(classDescriptor, value);
1041 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1042 T[] enumConstants = classDescriptor.getEnumConstants();
1043 if (enumConstants != null) {
1044 for (T enm : classDescriptor.getEnumConstants()) {
1045 if (((Enum<?>) enm).name().equals(value)) {
1053 private Map<String, String> resolveValuesFromUri(final String uri) {
1054 Map<String, String> result = new HashMap<>();
1055 String[] tokens = uri.split("/");
1056 for (int i = 1; i < tokens.length; i++) {
1057 String[] parameterTokens = tokens[i].split("=");
1058 if (parameterTokens.length == 2) {
1059 result.put(parameterTokens[0], parameterTokens[1]);
1065 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1066 if (data instanceof NodeWrapper) {
1067 return findModule(mountPoint, (NodeWrapper<?>) data);
1068 } else if (data != null) {
1069 URI namespace = data.getNodeType().getNamespace();
1070 if (mountPoint != null) {
1071 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1073 return this.controllerContext.findModuleByNamespace(namespace);
1076 throw new IllegalArgumentException("Unhandled parameter types: "
1077 + Arrays.<Object> asList(mountPoint, data).toString());
1081 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1082 URI namespace = data.getNamespace();
1083 Preconditions.<URI> checkNotNull(namespace);
1085 Module module = null;
1086 if (mountPoint != null) {
1087 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1088 if (module == null) {
1089 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1092 module = this.controllerContext.findModuleByNamespace(namespace);
1093 if (module == null) {
1094 module = this.controllerContext.findModuleByName(namespace.toString());
1101 private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode,
1102 final CompositeNode data, final DataSchemaNode schemaOfData) {
1103 YangInstanceIdentifier instanceIdentifier = null;
1104 if (identifierWithSchemaNode != null) {
1105 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1108 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1109 InstanceIdentifierBuilder iiBuilder = null;
1110 if (iiOriginal == null) {
1111 iiBuilder = YangInstanceIdentifier.builder();
1113 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1116 if ((schemaOfData instanceof ListSchemaNode)) {
1117 HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1118 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1120 iiBuilder.node(schemaOfData.getQName());
1123 YangInstanceIdentifier instance = iiBuilder.toInstance();
1124 DOMMountPoint mountPoint = null;
1125 if (identifierWithSchemaNode != null) {
1126 mountPoint = identifierWithSchemaNode.getMountPoint();
1129 return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint);
1132 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1133 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1134 List<QName> _keyDefinition = listNode.getKeyDefinition();
1135 for (final QName key : _keyDefinition) {
1136 SimpleNode<? extends Object> head = null;
1137 String localName = key.getLocalName();
1138 List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1139 if (simpleNodesByName != null) {
1140 head = Iterables.getFirst(simpleNodesByName, null);
1143 Object dataNodeKeyValueObject = null;
1145 dataNodeKeyValueObject = head.getValue();
1148 if (dataNodeKeyValueObject == null) {
1149 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1150 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1151 ErrorTag.INVALID_VALUE);
1154 keyValues.put(key, dataNodeKeyValueObject);
1160 private boolean endsWithMountPoint(final String identifier) {
1161 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1164 private boolean representsMountPointRootData(final Node<?> data) {
1165 URI namespace = this.namespace(data);
1166 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1167 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1170 && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1173 private String addMountPointIdentifier(final String identifier) {
1174 boolean endsWith = identifier.endsWith("/");
1176 return (identifier + ControllerContext.MOUNT);
1179 return identifier + "/" + ControllerContext.MOUNT;
1182 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1183 if (schema == null) {
1184 String localName = node == null ? null :
1185 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1186 node.getNodeType().getLocalName();
1188 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1189 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1192 if (!(schema instanceof DataNodeContainer)) {
1193 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1194 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1197 if ((node instanceof NodeWrapper<?>)) {
1198 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1199 boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1200 if (isChangeAllowed) {
1201 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1203 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1204 } catch (IllegalArgumentException e) {
1205 throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1207 if (nodeWrap instanceof CompositeNodeWrapper) {
1208 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1213 if (node instanceof CompositeNode) {
1214 return (CompositeNode) node;
1217 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1218 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1221 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1222 final QName previousAugment, final DOMMountPoint mountPoint) {
1223 if (schema == null) {
1224 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1225 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1228 QName currentAugment = null;
1229 if (nodeBuilder.getQname() != null) {
1230 currentAugment = previousAugment;
1232 currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1233 if (nodeBuilder.getQname() == null) {
1234 throw new RestconfDocumentedException(
1235 "Data has bad format.\nIf data is in XML format then namespace for \""
1236 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1237 + "\".\n" + "If data is in JSON format then module name for \""
1238 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1239 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1243 if (nodeBuilder instanceof CompositeNodeWrapper) {
1244 if (schema instanceof DataNodeContainer) {
1245 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1247 } else if (schema instanceof AnyXmlSchemaNode) {
1248 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1250 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1251 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1252 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1253 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1257 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1258 List<NodeWrapper<?>> children = compositeNode.getValues();
1259 for (NodeWrapper<? extends Object> child : children) {
1260 child.setNamespace(schema.getQName().getNamespace());
1261 if (child instanceof CompositeNodeWrapper) {
1262 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1267 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1268 if ((schema instanceof LeafSchemaNode)) {
1269 emptyNodeBuilder.setComposite(false);
1271 if ((schema instanceof ContainerSchemaNode)) {
1272 // FIXME: Add presence check
1273 emptyNodeBuilder.setComposite(true);
1278 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1279 final DOMMountPoint mountPoint) {
1280 final Object value = simpleNode.getValue();
1281 Object inputValue = value;
1282 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1283 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1284 if ((value instanceof String)) {
1285 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1287 } // else value is already instance of IdentityValuesDTO
1290 Object outputValue = inputValue;
1292 if (typeDefinition != null) {
1293 Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1294 outputValue = codec == null ? null : codec.deserialize(inputValue);
1297 simpleNode.setValue(outputValue);
1300 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1301 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1302 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1303 checkNodeMultiplicityAccordingToSchema(schema, children);
1304 for (final NodeWrapper<? extends Object> child : children) {
1305 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1306 schema, child.getLocalName());
1308 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1309 StringBuilder builder = new StringBuilder();
1310 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1311 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1314 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1315 + "\" is added as augment from more than one module. "
1316 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1317 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1318 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1321 boolean rightNodeSchemaFound = false;
1322 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1323 if (!rightNodeSchemaFound) {
1324 final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1325 currentAugment, mountPoint);
1326 if (child.getQname() != null) {
1327 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1328 rightNodeSchemaFound = true;
1333 if (!rightNodeSchemaFound) {
1334 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1335 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1339 if ((schema instanceof ListSchemaNode)) {
1340 ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1341 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1342 for (final QName listKey : listKeys) {
1343 boolean foundKey = false;
1344 for (final NodeWrapper<? extends Object> child : children) {
1345 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1351 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1352 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1353 ErrorTag.DATA_MISSING);
1359 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1360 final List<NodeWrapper<?>> nodes) {
1361 Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1362 for (NodeWrapper<?> child : nodes) {
1363 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1364 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1367 for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1368 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1369 String localName = childSchemaNode.getQName().getLocalName();
1370 Integer count = equalNodeNamesToCounts.get(localName);
1371 if (count != null && count > 1) {
1372 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1373 + childSchemaNode.getQName().getLocalName()
1374 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1375 ErrorTag.BAD_ELEMENT);
1381 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1382 final QName previousAugment, final DOMMountPoint mountPoint) {
1383 QName validQName = schema.getQName();
1384 QName currentAugment = previousAugment;
1385 if (schema.isAugmenting()) {
1386 currentAugment = schema.getQName();
1387 } else if (previousAugment != null
1388 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1389 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1392 String moduleName = null;
1393 if (mountPoint == null) {
1394 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1396 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1399 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1400 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1402 * || Note : this check is wrong -
1403 * can never be true as it compares
1404 * a URI with a String not sure what
1405 * the intention is so commented out
1406 * ... Objects . equal ( nodeBuilder
1407 * . getNamespace ( ) ,
1408 * MOUNT_POINT_MODULE_NAME )
1411 nodeBuilder.setQname(validQName);
1414 return currentAugment;
1417 private URI namespace(final Node<?> data) {
1418 if (data instanceof NodeWrapper) {
1419 return ((NodeWrapper<?>) data).getNamespace();
1420 } else if (data != null) {
1421 return data.getNodeType().getNamespace();
1423 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1427 private String localName(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 String getName(final Node<?> data) {
1438 if (data instanceof NodeWrapper) {
1439 return ((NodeWrapper<?>) data).getLocalName();
1440 } else if (data != null) {
1441 return data.getNodeType().getLocalName();
1443 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1447 private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1448 TypeDefinition<?> baseType = node.getType();
1449 while (baseType.getBaseType() != null) {
1450 baseType = baseType.getBaseType();
1456 private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1457 TypeDefinition<?> baseType = node.getType();
1458 while (baseType.getBaseType() != null) {
1459 baseType = baseType.getBaseType();
1465 private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1466 if (node instanceof LeafListSchemaNode) {
1467 return typeDefinition((LeafListSchemaNode) node);
1468 } else if (node instanceof LeafSchemaNode) {
1469 return _typeDefinition((LeafSchemaNode) node);
1470 } else if (node instanceof AnyXmlSchemaNode) {
1473 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1477 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1478 Node<?> nodes = null;
1479 if (dataNode == null) {
1480 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1481 "No data was found."));
1483 nodes = DataNormalizer.toLegacy(dataNode);
1484 if (nodes != null) {
1485 if (nodes instanceof CompositeNode) {
1486 return (CompositeNode) nodes;
1488 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1491 LOG.error("Top level node isn't of type Container or List schema node but "
1492 + schema.getClass().getSimpleName());
1495 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1496 "It wasn't possible to correctly interpret data."));
1499 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1500 final DataSchemaNode schema) {
1501 List<Node<?>> lst = new ArrayList<Node<?>>();
1503 if (schema instanceof ContainerSchemaNode) {
1504 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1505 .parse(lst, (ContainerSchemaNode) schema);
1506 } else if (schema instanceof ListSchemaNode) {
1507 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1508 .parse(lst, (ListSchemaNode) schema);
1511 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1513 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1514 "It wasn't possible to translate specified data to datastore readable form."));
1517 private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(
1518 final InstanceIdWithSchemaNode iiWithSchemaNode) {
1519 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1522 private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(
1523 final InstanceIdWithSchemaNode iiWithSchemaNode, final boolean unwrapLastListNode) {
1524 return new InstanceIdWithSchemaNode(instanceIdentifierToReadableFormForNormalizeNode(
1525 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1526 iiWithSchemaNode.getMountPoint());
1529 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1530 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1531 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1532 final List<PathArgument> result = new ArrayList<PathArgument>();
1533 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1534 while (iter.hasNext()) {
1535 final PathArgument pathArgument = iter.next();
1536 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1537 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1539 result.add(pathArgument);
1541 return YangInstanceIdentifier.create(result);
1544 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1545 final DataSchemaNode schemaNode) {
1546 if (node instanceof CompositeNodeWrapper) {
1547 return (CompositeNodeWrapper) node;
1548 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1549 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1550 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1553 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1554 "Top level element has to be composite node or has to represent data container node."));
1557 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1558 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {