2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2014 Brocade Communication Systems, Inc.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.restconf.impl;
11 import com.google.common.base.Objects;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableList;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import java.math.BigInteger;
20 import java.net.URISyntaxException;
21 import java.text.ParseException;
22 import java.text.SimpleDateFormat;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.Collections;
26 import java.util.Date;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
32 import javax.ws.rs.core.Response;
33 import javax.ws.rs.core.Response.Status;
34 import javax.ws.rs.core.UriBuilder;
35 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 {
91 private enum UriParameters {
92 PRETTY_PRINT("prettyPrint"),
95 private String uriParameterName;
97 UriParameters(final String uriParameterName) {
98 this.uriParameterName = uriParameterName;
102 public String toString() {
103 return uriParameterName;
109 private final static RestconfImpl INSTANCE = new RestconfImpl();
111 private static final int NOTIFICATION_PORT = 8181;
113 private static final int CHAR_NOT_FOUND = -1;
115 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
117 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
119 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
121 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
123 private BrokerFacade broker;
125 private ControllerContext controllerContext;
127 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
129 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
131 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
133 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
135 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
137 private static final String DATASTORE_PARAM_NAME = "datastore";
139 private static final String SCOPE_PARAM_NAME = "scope";
141 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
143 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
145 private static final QName NETCONF_BASE_QNAME;
149 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
150 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
151 } catch (ParseException e) {
152 throw new RestconfDocumentedException(
153 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
154 ErrorTag.OPERATION_FAILED);
155 } catch (URISyntaxException e) {
156 throw new RestconfDocumentedException(
157 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
158 ErrorTag.OPERATION_FAILED);
162 public void setBroker(final BrokerFacade broker) {
163 this.broker = broker;
166 public void setControllerContext(final ControllerContext controllerContext) {
167 this.controllerContext = controllerContext;
170 private RestconfImpl() {
173 public static RestconfImpl getInstance() {
178 public StructuredData getModules(final UriInfo uriInfo) {
179 final Module restconfModule = this.getRestconfModule();
181 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
182 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
183 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
185 Set<Module> allModules = this.controllerContext.getAllModules();
186 for (final Module module : allModules) {
187 CompositeNode moduleCompositeNode = this.toModuleCompositeNode(module, moduleSchemaNode);
188 modulesAsData.add(moduleCompositeNode);
191 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
192 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
193 QName qName = modulesSchemaNode.getQName();
194 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
195 return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
199 public StructuredData getAvailableStreams(final UriInfo uriInfo) {
200 Set<String> availableStreams = Notificator.getStreamNames();
202 final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
203 Module restconfModule = this.getRestconfModule();
204 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
205 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
206 for (final String streamName : availableStreams) {
207 streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
210 final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
211 Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
212 QName qName = streamsSchemaNode.getQName();
213 final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
214 return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
218 public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
219 Set<Module> modules = null;
220 DOMMountPoint mountPoint = null;
221 if (identifier.contains(ControllerContext.MOUNT)) {
222 InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
223 mountPoint = mountPointIdentifier.getMountPoint();
224 modules = this.controllerContext.getAllModules(mountPoint);
226 throw new RestconfDocumentedException(
227 "URI has bad format. If modules behind mount point should be showed, URI has to end with "
228 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
231 final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
232 Module restconfModule = this.getRestconfModule();
233 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
234 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
236 for (final Module module : modules) {
237 modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
240 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
241 Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
242 QName qName = modulesSchemaNode.getQName();
243 final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
244 return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
248 public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
249 final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
250 Module module = null;
251 DOMMountPoint mountPoint = null;
252 if (identifier.contains(ControllerContext.MOUNT)) {
253 InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
254 mountPoint = mountPointIdentifier.getMountPoint();
255 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
257 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
260 if (module == null) {
261 throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
262 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
263 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
266 Module restconfModule = this.getRestconfModule();
267 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
268 Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
269 final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
270 return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
274 public StructuredData getOperations(final UriInfo uriInfo) {
275 Set<Module> allModules = this.controllerContext.getAllModules();
276 return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
280 public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
281 Set<Module> modules = null;
282 DOMMountPoint mountPoint = null;
283 if (identifier.contains(ControllerContext.MOUNT)) {
284 InstanceIdentifierContext mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
285 mountPoint = mountPointIdentifier.getMountPoint();
286 modules = this.controllerContext.getAllModules(mountPoint);
288 throw new RestconfDocumentedException(
289 "URI has bad format. If operations behind mount point should be showed, URI has to end with "
290 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
293 return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
296 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
297 final DOMMountPoint mountPoint, final boolean prettyPrint) {
298 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
299 Module restconfModule = this.getRestconfModule();
300 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
301 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
302 QName qName = operationsSchemaNode.getQName();
303 SchemaPath path = operationsSchemaNode.getPath();
304 ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
305 Draft02.RestConfModule.NAME, 0, qName, path);
306 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
307 for (final Module module : modules) {
308 Set<RpcDefinition> rpcs = module.getRpcs();
309 for (final RpcDefinition rpc : rpcs) {
310 QName rpcQName = rpc.getQName();
311 SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
313 operationsAsData.add(immutableSimpleNode);
315 String name = module.getName();
316 LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
317 SchemaPath.create(true, QName.create("dummy")));
318 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
319 fakeRpcSchemaNode.setAugmenting(true);
321 EmptyType instance = EmptyType.getInstance();
322 fakeRpcSchemaNode.setType(instance);
323 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
327 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
328 ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
329 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
332 private Module getRestconfModule() {
333 Module restconfModule = controllerContext.getRestconfModule();
334 if (restconfModule == null) {
335 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
336 ErrorTag.OPERATION_NOT_SUPPORTED);
339 return restconfModule;
342 private QName getModuleNameAndRevision(final String identifier) {
343 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
344 String moduleNameAndRevision = "";
345 if (mountIndex >= 0) {
346 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
348 moduleNameAndRevision = identifier;
351 Splitter splitter = Splitter.on("/").omitEmptyStrings();
352 Iterable<String> split = splitter.split(moduleNameAndRevision);
353 final List<String> pathArgs = Lists.<String> newArrayList(split);
354 if (pathArgs.size() < 2) {
355 throw new RestconfDocumentedException(
356 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
357 ErrorTag.INVALID_VALUE);
361 final String moduleName = pathArgs.get(0);
362 String revision = pathArgs.get(1);
363 final Date moduleRevision = REVISION_FORMAT.parse(revision);
364 return QName.create(null, moduleRevision, moduleName);
365 } catch (ParseException e) {
366 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
367 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
371 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
372 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
373 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
374 ((DataNodeContainer) streamSchemaNode), "name");
375 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
377 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
379 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
380 ((DataNodeContainer) streamSchemaNode), "description");
381 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
382 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
383 "DESCRIPTION_PLACEHOLDER"));
385 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
386 ((DataNodeContainer) streamSchemaNode), "replay-support");
387 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
388 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
389 Boolean.valueOf(true)));
391 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
392 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
393 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
394 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
397 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
398 ((DataNodeContainer) streamSchemaNode), "events");
399 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
400 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
402 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
405 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
406 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
407 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
408 ((DataNodeContainer) moduleSchemaNode), "name");
409 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
410 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
413 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
414 ((DataNodeContainer) moduleSchemaNode), "revision");
415 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
416 Date _revision = module.getRevision();
417 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
418 REVISION_FORMAT.format(_revision)));
420 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
421 ((DataNodeContainer) moduleSchemaNode), "namespace");
422 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
423 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
424 module.getNamespace().toString()));
426 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
427 ((DataNodeContainer) moduleSchemaNode), "feature");
428 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
429 for (final FeatureDefinition feature : module.getFeatures()) {
430 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
431 feature.getQName().getLocalName()));
434 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
438 public Object getRoot() {
443 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
444 final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
445 QName rpcName = rpc.getRpcDefinition().getQName();
446 URI rpcNamespace = rpcName.getNamespace();
447 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
448 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
449 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
452 validateInput(rpc.getRpcDefinition().getInput(), payload);
454 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
457 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
458 if (inputSchema != null && payload == null) {
459 // expected a non null payload
460 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
461 } else if (inputSchema == null && payload != null) {
462 // did not expect any input
463 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
467 // TODO: Validate "mandatory" and "config" values here??? Or should those be
469 // validate in a more central location inside MD-SAL core.
473 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
474 final boolean prettyPrint) {
475 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
476 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
477 rpc.getQName(), "path"));
478 final Object pathValue = pathNode == null ? null : pathNode.getValue();
480 if (!(pathValue instanceof YangInstanceIdentifier)) {
481 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
482 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
485 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
486 String streamName = null;
487 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
488 String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
490 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
491 DATASTORE_PARAM_NAME);
492 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
494 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
495 scope = scope == null ? DEFAULT_SCOPE : scope;
497 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
498 + "/scope=" + scope);
501 if (Strings.isNullOrEmpty(streamName)) {
502 throw new RestconfDocumentedException(
503 "Path is empty or contains data node which is not Container or List build-in type.",
504 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
507 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
508 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
509 final List<Node<?>> output = new ArrayList<Node<?>>();
510 output.add(streamNameNode);
512 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
513 null, output, null, null);
515 if (!Notificator.existListenerFor(streamName)) {
516 Notificator.createListener(pathIdentifier, streamName);
519 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
523 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
524 if (StringUtils.isNotBlank(noPayload)) {
525 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
527 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
530 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
531 String identifierEncoded = null;
532 DOMMountPoint mountPoint = null;
533 if (identifier.contains(ControllerContext.MOUNT)) {
534 // mounted RPC call - look up mount instance.
535 InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
536 mountPoint = mountPointId.getMountPoint();
538 int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
539 + ControllerContext.MOUNT.length() + 1;
540 String remoteRpcName = identifier.substring(startOfRemoteRpcName);
541 identifierEncoded = remoteRpcName;
543 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
544 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
545 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
546 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
548 identifierEncoded = identifier;
551 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
553 RpcDefinition rpc = null;
554 if (mountPoint == null) {
555 rpc = controllerContext.getRpcDefinition(identifierDecoded);
557 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
561 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
564 if (mountPoint == null) {
565 return new BrokerRpcExecutor(rpc, broker);
567 return new MountPointRpcExecutor(rpc, mountPoint);
572 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
573 final String[] splittedIdentifier = identifierDecoded.split(":");
574 if (splittedIdentifier.length != 2) {
575 throw new RestconfDocumentedException(identifierDecoded
576 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
577 ErrorTag.INVALID_VALUE);
579 for (Module module : schemaContext.getModules()) {
580 if (module.getName().equals(splittedIdentifier[0])) {
581 for (RpcDefinition rpcDefinition : module.getRpcs()) {
582 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
583 return rpcDefinition;
591 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
592 if (rpcExecutor == null) {
593 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
596 CompositeNode rpcRequest = null;
597 RpcDefinition rpc = rpcExecutor.getRpcDefinition();
598 QName rpcName = rpc.getQName();
600 if (payload == null) {
601 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
603 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
604 List<Node<?>> input = Collections.<Node<?>> singletonList(value);
605 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
608 RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
610 checkRpcSuccessAndThrowException(rpcResult);
612 if (rpcResult.getResult() == null) {
616 if (rpc.getOutput() == null) {
617 return null; // no output, nothing to send back.
620 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
623 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
624 if (rpcResult.isSuccessful() == false) {
626 throw new RestconfDocumentedException("The operation was not successful", null,
627 rpcResult.getErrors());
632 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
633 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
634 DOMMountPoint mountPoint = iiWithData.getMountPoint();
635 NormalizedNode<?, ?> data = null;
636 YangInstanceIdentifier normalizedII;
637 if (mountPoint != null) {
638 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
639 .getInstanceIdentifier());
640 data = broker.readConfigurationData(mountPoint, normalizedII);
642 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
643 data = broker.readConfigurationData(normalizedII);
645 return new NormalizedNodeContext(iiWithData, data);
648 @SuppressWarnings("unchecked")
649 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
654 if (node instanceof CompositeNode) {
655 ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
657 for (Node<?> childNode : ((CompositeNode) node).getValue()) {
658 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
662 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
663 } else { // SimpleNode
668 private Integer parseDepthParameter(final UriInfo info) {
669 String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
670 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
675 Integer depth = Integer.valueOf(param);
677 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
678 "Invalid depth parameter: " + depth, null,
679 "The depth parameter must be an integer > 1 or \"unbounded\""));
683 } catch (NumberFormatException e) {
684 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
685 "Invalid depth parameter: " + e.getMessage(), null,
686 "The depth parameter must be an integer > 1 or \"unbounded\""));
691 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
692 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
693 DOMMountPoint mountPoint = iiWithData.getMountPoint();
694 NormalizedNode<?, ?> data = null;
695 YangInstanceIdentifier normalizedII;
696 if (mountPoint != null) {
697 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
698 .getInstanceIdentifier());
699 data = broker.readOperationalData(mountPoint, normalizedII);
701 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
702 data = broker.readOperationalData(normalizedII);
705 return new NormalizedNodeContext(iiWithData, data);
708 private boolean parsePrettyPrintParameter(final UriInfo info) {
709 String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
710 return Boolean.parseBoolean(param);
714 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
715 final InstanceIdentifierContext iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
717 validateInput(iiWithData.getSchemaNode(), payload);
719 DOMMountPoint mountPoint = iiWithData.getMountPoint();
720 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
721 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
722 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
723 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
724 iiWithData.getSchemaNode());
727 YangInstanceIdentifier normalizedII;
728 if (mountPoint != null) {
729 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
730 iiWithData.getInstanceIdentifier());
732 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
736 * There is a small window where another write transaction could be updating the same data
737 * simultaneously and we get an OptimisticLockFailedException. This error is likely
738 * transient and The WriteTransaction#submit API docs state that a retry will likely
739 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
740 * probably will never succeed so we'll fail in that case.
742 * By retrying we're attempting to hide the internal implementation of the data store and
743 * how it handles concurrent updates from the restconf client. The client has instructed us
744 * to put the data and we should make every effort to do so without pushing optimistic lock
745 * failures back to the client and forcing them to handle it via retry (and having to
746 * document the behavior).
751 if (mountPoint != null) {
752 broker.commitConfigurationDataPut(mountPoint, normalizedII,
753 datastoreNormalizedNode).checkedGet();
755 broker.commitConfigurationDataPut(normalizedII,
756 datastoreNormalizedNode).checkedGet();
760 } catch (TransactionCommitFailedException e) {
761 if(e instanceof OptimisticLockFailedException) {
763 LOG.debug("Got OptimisticLockFailedException on last try - failing");
764 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
767 LOG.debug("Got OptimisticLockFailedException - trying again");
769 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
774 return Response.status(Status.OK).build();
777 private void validateTopLevelNodeName(final Node<?> node,
778 final YangInstanceIdentifier identifier) {
779 final String payloadName = getName(node);
780 final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
783 if (!pathArguments.hasNext()) {
785 if (!node.getNodeType().equals(NETCONF_BASE_QNAME)) {
786 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
787 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
791 final String identifierName = pathArguments.next().getNodeType().getLocalName();
792 if (!payloadName.equals(identifierName)) {
793 throw new RestconfDocumentedException("Payload name (" + payloadName
794 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
795 ErrorTag.MALFORMED_MESSAGE);
801 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
803 * @throws RestconfDocumentedException
804 * if key values or key count in payload and URI isn't equal
807 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
808 final CompositeNode payload) {
809 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
810 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
811 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
812 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
813 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
815 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
820 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
821 final List<QName> keyDefinitions) {
822 for (QName keyDefinition : keyDefinitions) {
823 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
824 // should be caught during parsing URI to InstanceIdentifier
825 if (uriKeyValue == null) {
826 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
827 ErrorTag.DATA_MISSING);
829 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
830 if (payloadKeyValues.isEmpty()) {
831 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
832 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
835 Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
836 if (!uriKeyValue.equals(payloadKeyValue)) {
837 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
838 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
839 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
840 ErrorTag.INVALID_VALUE);
846 public Response createConfigurationData(final String identifier, final Node<?> payload) {
847 if (payload == null) {
848 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
851 URI payloadNS = this.namespace(payload);
852 if (payloadNS == null) {
853 throw new RestconfDocumentedException(
854 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
855 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
858 InstanceIdentifierContext iiWithData = null;
859 CompositeNode value = null;
860 if (this.representsMountPointRootData(payload)) {
861 // payload represents mount point data and URI represents path to the mount point
863 if (this.endsWithMountPoint(identifier)) {
864 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
865 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
866 ErrorTag.INVALID_VALUE);
869 final String completeIdentifier = this.addMountPointIdentifier(identifier);
870 iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
872 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
874 final InstanceIdentifierContext incompleteInstIdWithData = this.controllerContext
875 .toInstanceIdentifier(identifier);
876 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
877 DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
878 final Module module = findModule(mountPoint, payload);
879 if (module == null) {
880 throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
881 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
884 String payloadName = this.getName(payload);
885 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
886 parentSchema, payloadName, module.getNamespace());
887 value = this.normalizeNode(payload, schemaNode, mountPoint);
889 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
892 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
893 iiWithData.getSchemaNode());
894 DOMMountPoint mountPoint = iiWithData.getMountPoint();
895 YangInstanceIdentifier normalizedII;
898 if (mountPoint != null) {
899 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
900 .getInstanceIdentifier());
901 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
903 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
904 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
906 } catch(RestconfDocumentedException e) {
908 } catch (Exception e) {
909 throw new RestconfDocumentedException("Error creating data", e);
912 return Response.status(Status.NO_CONTENT).build();
916 public Response createConfigurationData(final Node<?> payload) {
917 if (payload == null) {
918 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
921 URI payloadNS = this.namespace(payload);
922 if (payloadNS == null) {
923 throw new RestconfDocumentedException(
924 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
925 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
928 final Module module = this.findModule(null, payload);
929 if (module == null) {
930 throw new RestconfDocumentedException(
931 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
932 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
935 String payloadName = this.getName(payload);
936 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
937 payloadName, module.getNamespace());
938 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
939 final InstanceIdentifierContext iiWithData = this.addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
940 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
941 DOMMountPoint mountPoint = iiWithData.getMountPoint();
942 YangInstanceIdentifier normalizedII;
945 if (mountPoint != null) {
946 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
947 .getInstanceIdentifier());
948 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
951 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
952 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
954 } catch(RestconfDocumentedException e) {
956 } catch (Exception e) {
957 throw new RestconfDocumentedException("Error creating data", e);
960 return Response.status(Status.NO_CONTENT).build();
964 public Response deleteConfigurationData(final String identifier) {
965 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
966 DOMMountPoint mountPoint = iiWithData.getMountPoint();
967 YangInstanceIdentifier normalizedII;
970 if (mountPoint != null) {
971 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
972 .getInstanceIdentifier());
973 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
975 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
976 broker.commitConfigurationDataDelete(normalizedII).get();
978 } catch (Exception e) {
979 throw new RestconfDocumentedException("Error creating data", e);
982 return Response.status(Status.OK).build();
986 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
988 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
990 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
991 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
995 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
996 final String streamName = Notificator.createStreamNameFromUri(identifier);
997 if (Strings.isNullOrEmpty(streamName)) {
998 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1001 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1002 if (listener == null) {
1003 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1006 Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1007 LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1008 paramToValues.get(DATASTORE_PARAM_NAME));
1009 if (datastore == null) {
1010 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1011 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1013 DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1014 if (scope == null) {
1015 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1016 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1019 broker.registerToListenDataChanges(datastore, scope, listener);
1021 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1022 int notificationPort = NOTIFICATION_PORT;
1024 WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1025 notificationPort = webSocketServerInstance.getPort();
1026 } catch (NullPointerException e) {
1027 WebSocketServer.createInstance(NOTIFICATION_PORT);
1029 UriBuilder port = uriBuilder.port(notificationPort);
1030 final URI uriToWebsocketServer = port.replacePath(streamName).build();
1032 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1036 * Load parameter for subscribing to stream from input composite node
1040 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1042 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1043 final String paramName) {
1044 QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1045 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1046 SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1047 if (simpleNode == null) {
1050 Object rawValue = simpleNode.getValue();
1051 if (!(rawValue instanceof String)) {
1055 return resolveAsEnum(classDescriptor, (String) rawValue);
1059 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1061 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1064 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1065 if (Strings.isNullOrEmpty(value)) {
1068 return resolveAsEnum(classDescriptor, value);
1071 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1072 T[] enumConstants = classDescriptor.getEnumConstants();
1073 if (enumConstants != null) {
1074 for (T enm : classDescriptor.getEnumConstants()) {
1075 if (((Enum<?>) enm).name().equals(value)) {
1083 private Map<String, String> resolveValuesFromUri(final String uri) {
1084 Map<String, String> result = new HashMap<>();
1085 String[] tokens = uri.split("/");
1086 for (int i = 1; i < tokens.length; i++) {
1087 String[] parameterTokens = tokens[i].split("=");
1088 if (parameterTokens.length == 2) {
1089 result.put(parameterTokens[0], parameterTokens[1]);
1095 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1096 if (data instanceof NodeWrapper) {
1097 return findModule(mountPoint, (NodeWrapper<?>) data);
1098 } else if (data != null) {
1099 URI namespace = data.getNodeType().getNamespace();
1100 if (mountPoint != null) {
1101 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1103 return this.controllerContext.findModuleByNamespace(namespace);
1106 throw new IllegalArgumentException("Unhandled parameter types: "
1107 + Arrays.<Object> asList(mountPoint, data).toString());
1111 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1112 URI namespace = data.getNamespace();
1113 Preconditions.<URI> checkNotNull(namespace);
1115 Module module = null;
1116 if (mountPoint != null) {
1117 module = this.controllerContext.findModuleByNamespace(mountPoint, namespace);
1118 if (module == null) {
1119 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
1122 module = this.controllerContext.findModuleByNamespace(namespace);
1123 if (module == null) {
1124 module = this.controllerContext.findModuleByName(namespace.toString());
1131 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1132 final CompositeNode data, final DataSchemaNode schemaOfData, SchemaContext schemaContext) {
1133 YangInstanceIdentifier instanceIdentifier = null;
1134 if (identifierWithSchemaNode != null) {
1135 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1138 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1139 InstanceIdentifierBuilder iiBuilder = null;
1140 if (iiOriginal == null) {
1141 iiBuilder = YangInstanceIdentifier.builder();
1143 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1146 if ((schemaOfData instanceof ListSchemaNode)) {
1147 HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1148 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1150 iiBuilder.node(schemaOfData.getQName());
1153 YangInstanceIdentifier instance = iiBuilder.toInstance();
1154 DOMMountPoint mountPoint = null;
1155 SchemaContext schemaCtx = null;
1156 if (identifierWithSchemaNode != null) {
1157 mountPoint = identifierWithSchemaNode.getMountPoint();
1160 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1163 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1164 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1165 List<QName> _keyDefinition = listNode.getKeyDefinition();
1166 for (final QName key : _keyDefinition) {
1167 SimpleNode<? extends Object> head = null;
1168 String localName = key.getLocalName();
1169 List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1170 if (simpleNodesByName != null) {
1171 head = Iterables.getFirst(simpleNodesByName, null);
1174 Object dataNodeKeyValueObject = null;
1176 dataNodeKeyValueObject = head.getValue();
1179 if (dataNodeKeyValueObject == null) {
1180 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1181 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1182 ErrorTag.INVALID_VALUE);
1185 keyValues.put(key, dataNodeKeyValueObject);
1191 private boolean endsWithMountPoint(final String identifier) {
1192 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1195 private boolean representsMountPointRootData(final Node<?> data) {
1196 URI namespace = this.namespace(data);
1197 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1198 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1201 && SchemaContext.NAME.getLocalName().equals(this.localName(data));
1204 private String addMountPointIdentifier(final String identifier) {
1205 boolean endsWith = identifier.endsWith("/");
1207 return (identifier + ControllerContext.MOUNT);
1210 return identifier + "/" + ControllerContext.MOUNT;
1213 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1214 if (schema == null) {
1215 String localName = node == null ? null :
1216 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1217 node.getNodeType().getLocalName();
1219 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1220 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1223 if (!(schema instanceof DataNodeContainer)) {
1224 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1225 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1228 if ((node instanceof NodeWrapper<?>)) {
1229 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1230 boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1231 if (isChangeAllowed) {
1232 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1234 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1235 } catch (IllegalArgumentException e) {
1236 throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1238 if (nodeWrap instanceof CompositeNodeWrapper) {
1239 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1244 if (node instanceof CompositeNode) {
1245 return (CompositeNode) node;
1248 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1249 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1252 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1253 final QName previousAugment, final DOMMountPoint mountPoint) {
1254 if (schema == null) {
1255 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1256 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1259 QName currentAugment = null;
1260 if (nodeBuilder.getQname() != null) {
1261 currentAugment = previousAugment;
1263 currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1264 if (nodeBuilder.getQname() == null) {
1265 throw new RestconfDocumentedException(
1266 "Data has bad format.\nIf data is in XML format then namespace for \""
1267 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1268 + "\".\n" + "If data is in JSON format then module name for \""
1269 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1270 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1274 if (nodeBuilder instanceof CompositeNodeWrapper) {
1275 if (schema instanceof DataNodeContainer) {
1276 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1278 } else if (schema instanceof AnyXmlSchemaNode) {
1279 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1281 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1282 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1283 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1284 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1288 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1289 List<NodeWrapper<?>> children = compositeNode.getValues();
1290 for (NodeWrapper<? extends Object> child : children) {
1291 child.setNamespace(schema.getQName().getNamespace());
1292 if (child instanceof CompositeNodeWrapper) {
1293 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1298 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1299 if ((schema instanceof LeafSchemaNode)) {
1300 emptyNodeBuilder.setComposite(false);
1302 if ((schema instanceof ContainerSchemaNode)) {
1303 // FIXME: Add presence check
1304 emptyNodeBuilder.setComposite(true);
1309 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1310 final DOMMountPoint mountPoint) {
1311 final Object value = simpleNode.getValue();
1312 Object inputValue = value;
1313 TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
1314 if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
1315 if ((value instanceof String)) {
1316 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1318 } // else value is already instance of IdentityValuesDTO
1321 Object outputValue = inputValue;
1323 if (typeDefinition != null) {
1324 Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1325 outputValue = codec == null ? null : codec.deserialize(inputValue);
1328 simpleNode.setValue(outputValue);
1331 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1332 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1333 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1334 checkNodeMultiplicityAccordingToSchema(schema, children);
1335 for (final NodeWrapper<? extends Object> child : children) {
1336 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1337 schema, child.getLocalName());
1339 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1340 StringBuilder builder = new StringBuilder();
1341 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1342 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1345 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1346 + "\" is added as augment from more than one module. "
1347 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1348 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1349 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1352 boolean rightNodeSchemaFound = false;
1353 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1354 if (!rightNodeSchemaFound) {
1355 final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
1356 currentAugment, mountPoint);
1357 if (child.getQname() != null) {
1358 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1359 rightNodeSchemaFound = true;
1364 if (!rightNodeSchemaFound) {
1365 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1366 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1370 if ((schema instanceof ListSchemaNode)) {
1371 ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1372 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1373 for (final QName listKey : listKeys) {
1374 boolean foundKey = false;
1375 for (final NodeWrapper<? extends Object> child : children) {
1376 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1382 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1383 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1384 ErrorTag.DATA_MISSING);
1390 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1391 final List<NodeWrapper<?>> nodes) {
1392 Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1393 for (NodeWrapper<?> child : nodes) {
1394 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1395 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1398 for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1399 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1400 String localName = childSchemaNode.getQName().getLocalName();
1401 Integer count = equalNodeNamesToCounts.get(localName);
1402 if (count != null && count > 1) {
1403 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1404 + childSchemaNode.getQName().getLocalName()
1405 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1406 ErrorTag.BAD_ELEMENT);
1412 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1413 final QName previousAugment, final DOMMountPoint mountPoint) {
1414 QName validQName = schema.getQName();
1415 QName currentAugment = previousAugment;
1416 if (schema.isAugmenting()) {
1417 currentAugment = schema.getQName();
1418 } else if (previousAugment != null
1419 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1420 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1423 String moduleName = null;
1424 if (mountPoint == null) {
1425 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1427 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1430 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1431 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1433 * || Note : this check is wrong -
1434 * can never be true as it compares
1435 * a URI with a String not sure what
1436 * the intention is so commented out
1437 * ... Objects . equal ( nodeBuilder
1438 * . getNamespace ( ) ,
1439 * MOUNT_POINT_MODULE_NAME )
1442 nodeBuilder.setQname(validQName);
1445 return currentAugment;
1448 private URI namespace(final Node<?> data) {
1449 if (data instanceof NodeWrapper) {
1450 return ((NodeWrapper<?>) data).getNamespace();
1451 } else if (data != null) {
1452 return data.getNodeType().getNamespace();
1454 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1458 private String localName(final Node<?> data) {
1459 if (data instanceof NodeWrapper) {
1460 return ((NodeWrapper<?>) data).getLocalName();
1461 } else if (data != null) {
1462 return data.getNodeType().getLocalName();
1464 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1468 private String getName(final Node<?> data) {
1469 if (data instanceof NodeWrapper) {
1470 return ((NodeWrapper<?>) data).getLocalName();
1471 } else if (data != null) {
1472 return data.getNodeType().getLocalName();
1474 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1478 private TypeDefinition<? extends Object> _typeDefinition(final LeafSchemaNode node) {
1479 TypeDefinition<?> baseType = node.getType();
1480 while (baseType.getBaseType() != null) {
1481 baseType = baseType.getBaseType();
1487 private TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
1488 TypeDefinition<?> baseType = node.getType();
1489 while (baseType.getBaseType() != null) {
1490 baseType = baseType.getBaseType();
1496 private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
1497 if (node instanceof LeafListSchemaNode) {
1498 return typeDefinition((LeafListSchemaNode) node);
1499 } else if (node instanceof LeafSchemaNode) {
1500 return _typeDefinition((LeafSchemaNode) node);
1501 } else if (node instanceof AnyXmlSchemaNode) {
1504 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1508 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1509 Node<?> nodes = null;
1510 if (dataNode == null) {
1511 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1512 "No data was found."));
1514 nodes = DataNormalizer.toLegacy(dataNode);
1515 if (nodes != null) {
1516 if (nodes instanceof CompositeNode) {
1517 return (CompositeNode) nodes;
1519 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1522 LOG.error("Top level node isn't of type Container or List schema node but "
1523 + schema.getClass().getSimpleName());
1526 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1527 "It wasn't possible to correctly interpret data."));
1530 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1531 final DataSchemaNode schema) {
1532 List<Node<?>> lst = new ArrayList<Node<?>>();
1534 if (schema instanceof ContainerSchemaNode) {
1535 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1536 .parse(lst, (ContainerSchemaNode) schema);
1537 } else if (schema instanceof ListSchemaNode) {
1538 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1539 .parse(lst, (ListSchemaNode) schema);
1542 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1544 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1545 "It wasn't possible to translate specified data to datastore readable form."));
1548 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1549 final InstanceIdentifierContext iiWithSchemaNode) {
1550 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1553 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1554 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1555 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1556 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1557 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1560 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1561 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1562 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1563 final List<PathArgument> result = new ArrayList<PathArgument>();
1564 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1565 while (iter.hasNext()) {
1566 final PathArgument pathArgument = iter.next();
1567 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1568 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1570 result.add(pathArgument);
1572 return YangInstanceIdentifier.create(result);
1575 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1576 final DataSchemaNode schemaNode) {
1577 if (node instanceof CompositeNodeWrapper) {
1578 return (CompositeNodeWrapper) node;
1579 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1580 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1581 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1584 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1585 "Top level element has to be composite node or has to represent data container node."));
1588 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1589 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1595 public BigInteger getOperationalReceived() {
1596 // TODO Auto-generated method stub