2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2014 Brocade Communication Systems, Inc.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.restconf.impl;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
19 import java.text.ParseException;
20 import java.text.SimpleDateFormat;
21 import java.util.ArrayList;
22 import java.util.Arrays;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
31 import javax.ws.rs.core.Response;
32 import javax.ws.rs.core.Response.Status;
33 import javax.ws.rs.core.UriBuilder;
34 import javax.ws.rs.core.UriInfo;
35 import org.apache.commons.lang3.StringUtils;
36 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
37 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
38 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
39 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
40 import org.opendaylight.controller.sal.rest.api.Draft02;
41 import org.opendaylight.controller.sal.rest.api.RestconfService;
42 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
43 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
44 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
45 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
46 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
47 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
48 import org.opendaylight.controller.sal.streams.listeners.Notificator;
49 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
50 import org.opendaylight.yangtools.concepts.Codec;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.QNameModule;
53 import org.opendaylight.yangtools.yang.common.RpcError;
54 import org.opendaylight.yangtools.yang.common.RpcResult;
55 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
56 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
57 import org.opendaylight.yangtools.yang.data.api.Node;
58 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
63 import org.opendaylight.yangtools.yang.data.api.schema.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 InstanceIdWithSchemaNode 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 InstanceIdWithSchemaNode 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 InstanceIdWithSchemaNode 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 = this.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 = this.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 = this.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 = this.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 = this.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 = this.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 = this.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 = this.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 = this.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 InstanceIdWithSchemaNode 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 Collection<RpcError> rpcErrors = rpcResult.getErrors();
611 if (rpcErrors == null || rpcErrors.isEmpty()) {
612 throw new RestconfDocumentedException(
613 "The operation was not successful and there were no RPC errors returned", ErrorType.RPC,
614 ErrorTag.OPERATION_FAILED);
617 List<RestconfError> errorList = Lists.newArrayList();
618 for (RpcError rpcError : rpcErrors) {
619 errorList.add(new RestconfError(rpcError));
622 throw new RestconfDocumentedException(errorList);
627 public StructuredData readConfigurationData(final String identifier, final UriInfo uriInfo) {
628 final InstanceIdWithSchemaNode iiWithData = controllerContext.toInstanceIdentifier(identifier);
629 DOMMountPoint mountPoint = iiWithData.getMountPoint();
630 NormalizedNode<?, ?> data = null;
631 YangInstanceIdentifier normalizedII;
632 if (mountPoint != null) {
633 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData.getInstanceIdentifier());
634 data = broker.readConfigurationData(mountPoint, normalizedII);
636 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
637 data = broker.readConfigurationData(normalizedII);
640 final CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode());
641 final CompositeNode prunedCompositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(uriInfo));
643 final boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo);
644 return new StructuredData(prunedCompositeNode, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
647 @SuppressWarnings("unchecked")
648 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
653 if (node instanceof CompositeNode) {
654 ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
656 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
657 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
661 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
662 } else { // SimpleNode
667 private Integer parseDepthParameter(final UriInfo info) {
668 String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
669 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
674 Integer depth = Integer.valueOf(param);
676 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
677 "Invalid depth parameter: " + depth, null,
678 "The depth parameter must be an integer > 1 or \"unbounded\""));
682 } catch (NumberFormatException e) {
683 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
684 "Invalid depth parameter: " + e.getMessage(), null,
685 "The depth parameter must be an integer > 1 or \"unbounded\""));
690 public StructuredData readOperationalData(final String identifier, final UriInfo info) {
691 final InstanceIdWithSchemaNode iiWithData = controllerContext.toInstanceIdentifier(identifier);
692 DOMMountPoint mountPoint = iiWithData.getMountPoint();
693 NormalizedNode<?, ?> data = null;
694 YangInstanceIdentifier normalizedII;
695 if (mountPoint != null) {
696 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData.getInstanceIdentifier());
697 data = broker.readOperationalData(mountPoint, normalizedII);
699 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
700 data = broker.readOperationalData(normalizedII);
703 final CompositeNode compositeNode = datastoreNormalizedNodeToCompositeNode(data, iiWithData.getSchemaNode());
704 final CompositeNode prunedCompositeNode = pruneDataAtDepth(compositeNode, parseDepthParameter(info));
706 final boolean prettyPrintMode = parsePrettyPrintParameter(info);
707 return new StructuredData(prunedCompositeNode, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
710 private boolean parsePrettyPrintParameter(final UriInfo info) {
711 String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
712 return Boolean.parseBoolean(param);
716 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
717 final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
719 validateInput(iiWithData.getSchemaNode(), payload);
721 DOMMountPoint mountPoint = iiWithData.getMountPoint();
722 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
723 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
724 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
725 iiWithData.getSchemaNode());
727 YangInstanceIdentifier normalizedII;
730 if (mountPoint != null) {
731 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData.getInstanceIdentifier());
732 broker.commitConfigurationDataPut(mountPoint, normalizedII, datastoreNormalizedNode).get();
734 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
735 broker.commitConfigurationDataPut(normalizedII, datastoreNormalizedNode).get();
737 } catch (Exception e) {
738 throw new RestconfDocumentedException("Error updating data", e);
741 return Response.status(Status.OK).build();
745 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
747 * @throws RestconfDocumentedException
748 * if key values or key count in payload and URI isn't equal
751 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdWithSchemaNode iiWithData,
752 final CompositeNode payload) {
753 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
754 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
755 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
756 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
757 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
759 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
764 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
765 final List<QName> keyDefinitions) {
766 for (QName keyDefinition : keyDefinitions) {
767 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
768 // should be caught during parsing URI to InstanceIdentifier
769 if (uriKeyValue == null) {
770 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
771 ErrorTag.DATA_MISSING);
773 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
774 if (payloadKeyValues.isEmpty()) {
775 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
776 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
779 Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
780 if (!uriKeyValue.equals(payloadKeyValue)) {
781 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
782 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
783 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
784 ErrorTag.INVALID_VALUE);
790 public Response createConfigurationData(final String identifier, final Node<?> payload) {
791 if (payload == null) {
792 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
795 URI payloadNS = this.namespace(payload);
796 if (payloadNS == null) {
797 throw new RestconfDocumentedException(
798 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
799 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
802 InstanceIdWithSchemaNode iiWithData = null;
803 CompositeNode value = null;
804 if (this.representsMountPointRootData(payload)) {
805 // payload represents mount point data and URI represents path to the mount point
807 if (this.endsWithMountPoint(identifier)) {
808 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
809 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
810 ErrorTag.INVALID_VALUE);
813 final String completeIdentifier = this.addMountPointIdentifier(identifier);
814 iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
816 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
818 final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext
819 .toInstanceIdentifier(identifier);
820 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
821 DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
822 final Module module = findModule(mountPoint, payload);
823 if (module == null) {
824 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
825 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
828 String payloadName = this.getName(payload);
829 final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
830 parentSchema, payloadName, module.getNamespace());
831 value = this.normalizeNode(payload, schemaNode, mountPoint);
833 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode);
836 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
837 iiWithData.getSchemaNode());
838 DOMMountPoint mountPoint = iiWithData.getMountPoint();
839 YangInstanceIdentifier normalizedII;
842 if (mountPoint != null) {
843 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData.getInstanceIdentifier());
844 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
846 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
847 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
849 } catch (Exception e) {
850 throw new RestconfDocumentedException("Error creating data", e);
853 return Response.status(Status.NO_CONTENT).build();
857 public Response createConfigurationData(final Node<?> payload) {
858 if (payload == null) {
859 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
862 URI payloadNS = this.namespace(payload);
863 if (payloadNS == null) {
864 throw new RestconfDocumentedException(
865 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
866 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
869 final Module module = this.findModule(null, payload);
870 if (module == null) {
871 throw new RestconfDocumentedException(
872 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
873 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
876 String payloadName = this.getName(payload);
877 final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(module,
878 payloadName, module.getNamespace());
879 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
880 final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode);
881 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
882 DOMMountPoint mountPoint = iiWithData.getMountPoint();
883 YangInstanceIdentifier normalizedII;
886 if (mountPoint != null) {
887 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData.getInstanceIdentifier());
888 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
891 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
892 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
894 } catch (Exception e) {
895 throw new RestconfDocumentedException("Error creating data", e);
898 return Response.status(Status.NO_CONTENT).build();
902 public Response deleteConfigurationData(final String identifier) {
903 final InstanceIdWithSchemaNode iiWithData = controllerContext.toInstanceIdentifier(identifier);
904 DOMMountPoint mountPoint = iiWithData.getMountPoint();
905 YangInstanceIdentifier normalizedII;
908 if (mountPoint != null) {
909 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData.getInstanceIdentifier());
910 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
912 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
913 broker.commitConfigurationDataDelete(normalizedII).get();
915 } catch (Exception e) {
916 throw new RestconfDocumentedException("Error creating data", e);
919 return Response.status(Status.OK).build();
923 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
925 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
927 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
928 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
932 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
933 final String streamName = Notificator.createStreamNameFromUri(identifier);
934 if (Strings.isNullOrEmpty(streamName)) {
935 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
938 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
939 if (listener == null) {
940 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
943 Map<String, String> paramToValues = resolveValuesFromUri(identifier);
944 LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
945 paramToValues.get(DATASTORE_PARAM_NAME));
946 if (datastore == null) {
947 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
948 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
950 DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
952 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
953 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
956 broker.registerToListenDataChanges(datastore, scope, listener);
958 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
959 int notificationPort = NOTIFICATION_PORT;
961 WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
962 notificationPort = webSocketServerInstance.getPort();
963 } catch (NullPointerException e) {
964 WebSocketServer.createInstance(NOTIFICATION_PORT);
966 UriBuilder port = uriBuilder.port(notificationPort);
967 final URI uriToWebsocketServer = port.replacePath(streamName).build();
969 return Response.status(Status.OK).location(uriToWebsocketServer).build();
973 * Load parameter for subscribing to stream from input composite node
977 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
979 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
980 final String paramName) {
981 QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
982 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
983 SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
984 if (simpleNode == null) {
987 Object rawValue = simpleNode.getValue();
988 if (!(rawValue instanceof String)) {
992 return resolveAsEnum(classDescriptor, (String) rawValue);
996 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
998 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1001 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1002 if (Strings.isNullOrEmpty(value)) {
1005 return resolveAsEnum(classDescriptor, value);
1008 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1009 T[] enumConstants = classDescriptor.getEnumConstants();
1010 if (enumConstants != null) {
1011 for (T enm : classDescriptor.getEnumConstants()) {
1012 if (((Enum<?>) enm).name().equals(value)) {
1020 private Map<String, String> resolveValuesFromUri(final String uri) {
1021 Map<String, String> result = new HashMap<>();
1022 String[] tokens = uri.split("/");
1023 for (int i = 1; i < tokens.length; i++) {
1024 String[] parameterTokens = tokens[i].split("=");
1025 if (parameterTokens.length == 2) {
1026 result.put(parameterTokens[0], parameterTokens[1]);
1032 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1033 if (data instanceof NodeWrapper) {
1034 return findModule(mountPoint, (NodeWrapper<?>) data);
1035 } else if (data != null) {
1036 URI namespace = data.getNodeType().getNamespace();
1037 if (mountPoint != null) {
1038 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1040 return this.controllerContext.findModuleByNamespace(namespace);
1043 throw new IllegalArgumentException("Unhandled parameter types: "
1044 + Arrays.<Object> asList(mountPoint, data).toString());
1048 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1049 URI namespace = data.getNamespace();
1050 Preconditions.<URI> checkNotNull(namespace);
1052 Module module = null;
1053 if (mountPoint != null) {
1054 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1055 if (module == null) {
1056 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1059 module = this.controllerContext.findModuleByNamespace(namespace);
1060 if (module == null) {
1061 module = this.controllerContext.findModuleByName(namespace.toString());
1068 private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode,
1069 final CompositeNode data, final DataSchemaNode schemaOfData) {
1070 YangInstanceIdentifier instanceIdentifier = null;
1071 if (identifierWithSchemaNode != null) {
1072 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1075 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1076 InstanceIdentifierBuilder iiBuilder = null;
1077 if (iiOriginal == null) {
1078 iiBuilder = YangInstanceIdentifier.builder();
1080 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1083 iiBuilder.node(schemaOfData.getQName());
1085 YangInstanceIdentifier instance = iiBuilder.toInstance();
1086 DOMMountPoint mountPoint = null;
1087 if (identifierWithSchemaNode != null) {
1088 mountPoint = identifierWithSchemaNode.getMountPoint();
1091 return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint);
1094 private boolean endsWithMountPoint(final String identifier) {
1095 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1098 private boolean representsMountPointRootData(final Node<?> data) {
1099 URI namespace = this.namespace(data);
1100 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1101 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1104 && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1107 private String addMountPointIdentifier(final String identifier) {
1108 boolean endsWith = identifier.endsWith("/");
1110 return (identifier + ControllerContext.MOUNT);
1113 return identifier + "/" + ControllerContext.MOUNT;
1116 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1117 if (schema == null) {
1118 QName nodeType = node == null ? null : node.getNodeType();
1119 String localName = nodeType == null ? null : nodeType.getLocalName();
1121 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1122 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1125 if (!(schema instanceof DataNodeContainer)) {
1126 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1127 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1130 if ((node instanceof NodeWrapper<?>)) {
1131 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1132 boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1133 if (isChangeAllowed) {
1134 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1136 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1137 } catch (IllegalArgumentException e) {
1138 throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1140 if (nodeWrap instanceof CompositeNodeWrapper) {
1141 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1146 if (node instanceof CompositeNode) {
1147 return (CompositeNode) node;
1150 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1151 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1154 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1155 final QName previousAugment, final DOMMountPoint mountPoint) {
1156 if (schema == null) {
1157 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1158 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1161 QName currentAugment = null;
1162 if (nodeBuilder.getQname() != null) {
1163 currentAugment = previousAugment;
1165 currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1166 if (nodeBuilder.getQname() == null) {
1167 throw new RestconfDocumentedException(
1168 "Data has bad format.\nIf data is in XML format then namespace for \""
1169 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1170 + "\".\n" + "If data is in JSON format then module name for \""
1171 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1172 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1176 if (nodeBuilder instanceof CompositeNodeWrapper) {
1177 if (schema instanceof DataNodeContainer) {
1178 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1180 } else if (schema instanceof AnyXmlSchemaNode) {
1181 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1183 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1184 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1185 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1186 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1190 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1191 List<NodeWrapper<?>> children = compositeNode.getValues();
1192 for (NodeWrapper<? extends Object> child : children) {
1193 child.setNamespace(schema.getQName().getNamespace());
1194 if (child instanceof CompositeNodeWrapper) {
1195 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1200 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1201 if ((schema instanceof LeafSchemaNode)) {
1202 emptyNodeBuilder.setComposite(false);
1204 if ((schema instanceof ContainerSchemaNode)) {
1205 // FIXME: Add presence check
1206 emptyNodeBuilder.setComposite(true);
1211 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1212 final DOMMountPoint mountPoint) {
1213 final Object value = simpleNode.getValue();
1214 Object inputValue = value;
1215 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1216 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1217 if ((value instanceof String)) {
1218 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1220 } // else value is already instance of IdentityValuesDTO
1223 Object outputValue = inputValue;
1225 if (typeDefinition != null) {
1226 Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1227 outputValue = codec == null ? null : codec.deserialize(inputValue);
1230 simpleNode.setValue(outputValue);
1233 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1234 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1235 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1236 checkNodeMultiplicityAccordingToSchema(schema, children);
1237 for (final NodeWrapper<? extends Object> child : children) {
1238 final List<DataSchemaNode> potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName(
1239 schema, child.getLocalName());
1241 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1242 StringBuilder builder = new StringBuilder();
1243 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1244 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1247 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1248 + "\" is added as augment from more than one module. "
1249 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1250 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1251 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1254 boolean rightNodeSchemaFound = false;
1255 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1256 if (!rightNodeSchemaFound) {
1257 final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1258 currentAugment, mountPoint);
1259 if (child.getQname() != null) {
1260 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1261 rightNodeSchemaFound = true;
1266 if (!rightNodeSchemaFound) {
1267 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1268 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1272 if ((schema instanceof ListSchemaNode)) {
1273 ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1274 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1275 for (final QName listKey : listKeys) {
1276 boolean foundKey = false;
1277 for (final NodeWrapper<? extends Object> child : children) {
1278 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1284 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1285 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1286 ErrorTag.DATA_MISSING);
1292 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1293 final List<NodeWrapper<?>> nodes) {
1294 Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1295 for (NodeWrapper<?> child : nodes) {
1296 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1297 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1300 for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1301 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1302 String localName = childSchemaNode.getQName().getLocalName();
1303 Integer count = equalNodeNamesToCounts.get(localName);
1304 if (count != null && count > 1) {
1305 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1306 + childSchemaNode.getQName().getLocalName()
1307 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1308 ErrorTag.BAD_ELEMENT);
1314 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1315 final QName previousAugment, final DOMMountPoint mountPoint) {
1316 QName validQName = schema.getQName();
1317 QName currentAugment = previousAugment;
1318 if (schema.isAugmenting()) {
1319 currentAugment = schema.getQName();
1320 } else if (previousAugment != null
1321 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1322 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1325 String moduleName = null;
1326 if (mountPoint == null) {
1327 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1329 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1332 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1333 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*
1334 * || Note : this check is wrong -
1335 * can never be true as it compares
1336 * a URI with a String not sure what
1337 * the intention is so commented out
1338 * ... Objects . equal ( nodeBuilder
1339 * . getNamespace ( ) ,
1340 * MOUNT_POINT_MODULE_NAME )
1343 nodeBuilder.setQname(validQName);
1346 return currentAugment;
1349 private URI namespace(final Node<?> data) {
1350 if (data instanceof NodeWrapper) {
1351 return ((NodeWrapper<?>) data).getNamespace();
1352 } else if (data != null) {
1353 return data.getNodeType().getNamespace();
1355 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1359 private String localName(final Node<?> data) {
1360 if (data instanceof NodeWrapper) {
1361 return ((NodeWrapper<?>) data).getLocalName();
1362 } else if (data != null) {
1363 return data.getNodeType().getLocalName();
1365 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1369 private String getName(final Node<?> data) {
1370 if (data instanceof NodeWrapper) {
1371 return ((NodeWrapper<?>) data).getLocalName();
1372 } else if (data != null) {
1373 return data.getNodeType().getLocalName();
1375 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1379 private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1380 TypeDefinition<?> baseType = node.getType();
1381 while (baseType.getBaseType() != null) {
1382 baseType = baseType.getBaseType();
1388 private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1389 TypeDefinition<?> baseType = node.getType();
1390 while (baseType.getBaseType() != null) {
1391 baseType = baseType.getBaseType();
1397 private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1398 if (node instanceof LeafListSchemaNode) {
1399 return typeDefinition((LeafListSchemaNode) node);
1400 } else if (node instanceof LeafSchemaNode) {
1401 return _typeDefinition((LeafSchemaNode) node);
1402 } else if (node instanceof AnyXmlSchemaNode) {
1405 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1409 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1410 Node<?> nodes = null;
1411 if (dataNode == null) {
1412 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1413 "No data was found."));
1415 nodes = DataNormalizer.toLegacy(dataNode);
1416 if (nodes != null) {
1417 if (nodes instanceof CompositeNode) {
1418 return (CompositeNode) nodes;
1420 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1423 LOG.error("Top level node isn't of type Container or List schema node but "
1424 + schema.getClass().getSimpleName());
1427 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1428 "It wasn't possible to correctly interpret data."));
1431 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode, final DataSchemaNode schema) {
1432 List<Node<?>> lst = new ArrayList<Node<?>>();
1434 if (schema instanceof ContainerSchemaNode) {
1435 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1436 .parse(lst, (ContainerSchemaNode) schema);
1437 } else if (schema instanceof ListSchemaNode) {
1438 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1439 .parse(lst, (ListSchemaNode) schema);
1442 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1444 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1445 "It wasn't possible to translate specified data to datastore readable form."));
1448 private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(final InstanceIdWithSchemaNode iiWithSchemaNode) {
1449 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1452 private InstanceIdWithSchemaNode normalizeInstanceIdentifierWithSchemaNode(
1453 final InstanceIdWithSchemaNode iiWithSchemaNode, final boolean unwrapLastListNode) {
1454 return new InstanceIdWithSchemaNode(instanceIdentifierToReadableFormForNormalizeNode(
1455 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1456 iiWithSchemaNode.getMountPoint());
1459 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(final YangInstanceIdentifier instIdentifier,
1460 final boolean unwrapLastListNode) {
1461 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1462 final List<PathArgument> result = new ArrayList<PathArgument>();
1463 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1464 while (iter.hasNext()) {
1465 final PathArgument pathArgument = iter.next();
1466 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1467 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1469 result.add(pathArgument);
1471 return YangInstanceIdentifier.create(result);
1474 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1475 final DataSchemaNode schemaNode) {
1476 if (node instanceof CompositeNodeWrapper) {
1477 return (CompositeNodeWrapper) node;
1478 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1479 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1480 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1483 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1484 "Top level element has to be composite node or has to represent data container node."));
1487 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1488 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {