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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicates;
15 import com.google.common.base.Splitter;
16 import com.google.common.base.Strings;
17 import com.google.common.base.Throwables;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import java.math.BigInteger;
23 import java.net.URISyntaxException;
24 import java.text.ParseException;
25 import java.text.SimpleDateFormat;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.Date;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.Response.Status;
37 import javax.ws.rs.core.UriBuilder;
38 import javax.ws.rs.core.UriInfo;
39 import org.apache.commons.lang3.StringUtils;
40 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
41 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
42 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
43 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
44 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
45 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
46 import org.opendaylight.controller.sal.rest.api.Draft02;
47 import org.opendaylight.controller.sal.rest.api.RestconfService;
48 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
50 import org.opendaylight.controller.sal.restconf.rpc.impl.BrokerRpcExecutor;
51 import org.opendaylight.controller.sal.restconf.rpc.impl.MountPointRpcExecutor;
52 import org.opendaylight.controller.sal.restconf.rpc.impl.RpcExecutor;
53 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
54 import org.opendaylight.controller.sal.streams.listeners.Notificator;
55 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
56 import org.opendaylight.yangtools.concepts.Codec;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.QNameModule;
59 import org.opendaylight.yangtools.yang.common.RpcResult;
60 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
61 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
62 import org.opendaylight.yangtools.yang.data.api.Node;
63 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
69 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
75 import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
76 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
77 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
78 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
82 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
87 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.Module;
91 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
92 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
95 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
96 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
97 import org.opendaylight.yangtools.yang.model.util.EmptyType;
98 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
99 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
100 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
101 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
105 public class RestconfImpl implements RestconfService {
107 private enum UriParameters {
108 PRETTY_PRINT("prettyPrint"),
111 private String uriParameterName;
113 UriParameters(final String uriParameterName) {
114 this.uriParameterName = uriParameterName;
118 public String toString() {
119 return uriParameterName;
123 private static class TypeDef {
124 public final TypeDefinition<? extends Object> typedef;
125 public final QName qName;
127 TypeDef(final TypeDefinition<? extends Object> typedef, final QName qName) {
128 this.typedef = typedef;
133 private final static RestconfImpl INSTANCE = new RestconfImpl();
135 private static final int NOTIFICATION_PORT = 8181;
137 private static final int CHAR_NOT_FOUND = -1;
139 private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
141 private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
143 private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
145 private final static String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
147 private BrokerFacade broker;
149 private ControllerContext controllerContext;
151 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
153 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
155 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
157 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
159 private static final Date EVENT_SUBSCRIPTION_AUGMENT_REVISION;
161 private static final String DATASTORE_PARAM_NAME = "datastore";
163 private static final String SCOPE_PARAM_NAME = "scope";
165 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
167 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
169 private static final QName NETCONF_BASE_QNAME;
173 EVENT_SUBSCRIPTION_AUGMENT_REVISION = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
174 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
175 } catch (final ParseException e) {
176 throw new RestconfDocumentedException(
177 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
178 ErrorTag.OPERATION_FAILED);
179 } catch (final URISyntaxException e) {
180 throw new RestconfDocumentedException(
181 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
182 ErrorTag.OPERATION_FAILED);
186 public void setBroker(final BrokerFacade broker) {
187 this.broker = broker;
190 public void setControllerContext(final ControllerContext controllerContext) {
191 this.controllerContext = controllerContext;
194 private RestconfImpl() {
197 public static RestconfImpl getInstance() {
202 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
203 final Set<Module> allModules = controllerContext.getAllModules();
204 final MapNode allModuleMap = makeModuleMapNode(allModules);
206 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
208 final Module restconfModule = getRestconfModule();
209 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
210 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
211 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
213 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
214 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
215 moduleContainerBuilder.withChild(allModuleMap);
217 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
218 null, schemaContext), moduleContainerBuilder.build());
222 * Valid only for mount point
225 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
226 Preconditions.checkNotNull(identifier);
227 if ( ! identifier.contains(ControllerContext.MOUNT)) {
228 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
229 + " URI has to end with " + ControllerContext.MOUNT;
230 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
233 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
234 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
235 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
236 final SchemaContext schemaContext = mountPoint.getSchemaContext();
237 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
239 final Module restconfModule = getRestconfModule();
240 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
241 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
242 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
244 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
245 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
246 moduleContainerBuilder.withChild(mountPointModulesMap);
248 return new NormalizedNodeContext(new InstanceIdentifierContext(null, modulesSchemaNode,
249 mountPoint, schemaContext), moduleContainerBuilder.build());
253 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
254 Preconditions.checkNotNull(identifier);
255 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
256 Module module = null;
257 DOMMountPoint mountPoint = null;
258 final SchemaContext schemaContext;
259 if (identifier.contains(ControllerContext.MOUNT)) {
260 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
261 mountPoint = mountPointIdentifier.getMountPoint();
262 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
263 schemaContext = mountPoint.getSchemaContext();
265 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
266 schemaContext = controllerContext.getGlobalSchema();
269 if (module == null) {
270 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
271 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
272 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
275 final Module restconfModule = getRestconfModule();
276 final Set<Module> modules = Collections.singleton(module);
277 final MapNode moduleMap = makeModuleMapNode(modules);
279 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
280 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
281 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
283 return new NormalizedNodeContext(new InstanceIdentifierContext(null, moduleSchemaNode, mountPoint,
284 schemaContext), moduleMap);
288 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
289 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
290 final Set<String> availableStreams = Notificator.getStreamNames();
291 final Module restconfModule = getRestconfModule();
292 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
293 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
294 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
296 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
297 .mapBuilder((ListSchemaNode) streamSchemaNode);
299 for (final String streamName : availableStreams) {
300 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
303 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
304 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
305 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
307 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
308 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
309 streamsContainerBuilder.withChild(listStreamsBuilder.build());
312 return new NormalizedNodeContext(new InstanceIdentifierContext(null, streamsContainerSchemaNode, null,
313 schemaContext), streamsContainerBuilder.build());
317 public StructuredData getOperations(final UriInfo uriInfo) {
318 final Set<Module> allModules = controllerContext.getAllModules();
319 return operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
323 public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
324 Set<Module> modules = null;
325 DOMMountPoint mountPoint = null;
326 if (identifier.contains(ControllerContext.MOUNT)) {
327 final InstanceIdentifierContext mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
328 mountPoint = mountPointIdentifier.getMountPoint();
329 modules = controllerContext.getAllModules(mountPoint);
331 throw new RestconfDocumentedException(
332 "URI has bad format. If operations behind mount point should be showed, URI has to end with "
333 + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
336 return operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
339 private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
340 final DOMMountPoint mountPoint, final boolean prettyPrint) {
341 final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
342 final Module restconfModule = getRestconfModule();
343 final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
344 restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
345 final QName qName = operationsSchemaNode.getQName();
346 final SchemaPath path = operationsSchemaNode.getPath();
347 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
348 Draft02.RestConfModule.NAME, 0, qName, path);
349 final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
350 for (final Module module : modules) {
351 final Set<RpcDefinition> rpcs = module.getRpcs();
352 for (final RpcDefinition rpc : rpcs) {
353 final QName rpcQName = rpc.getQName();
354 final SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
356 operationsAsData.add(immutableSimpleNode);
358 final String name = module.getName();
359 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, rpcQName,
360 SchemaPath.create(true, QName.create("dummy")));
361 final LeafSchemaNodeBuilder fakeRpcSchemaNode = leafSchemaNodeBuilder;
362 fakeRpcSchemaNode.setAugmenting(true);
364 final EmptyType instance = EmptyType.getInstance();
365 fakeRpcSchemaNode.setType(instance);
366 fakeOperationsSchemaNode.addChildNode(fakeRpcSchemaNode.build());
370 final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
371 final ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
372 return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
375 private Module getRestconfModule() {
376 final Module restconfModule = controllerContext.getRestconfModule();
377 if (restconfModule == null) {
378 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
379 ErrorTag.OPERATION_NOT_SUPPORTED);
382 return restconfModule;
385 private QName getModuleNameAndRevision(final String identifier) {
386 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
387 String moduleNameAndRevision = "";
388 if (mountIndex >= 0) {
389 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
391 moduleNameAndRevision = identifier;
394 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
395 final Iterable<String> split = splitter.split(moduleNameAndRevision);
396 final List<String> pathArgs = Lists.<String> newArrayList(split);
397 if (pathArgs.size() < 2) {
398 throw new RestconfDocumentedException(
399 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
400 ErrorTag.INVALID_VALUE);
404 final String moduleName = pathArgs.get(0);
405 final String revision = pathArgs.get(1);
406 final Date moduleRevision = REVISION_FORMAT.parse(revision);
407 return QName.create(null, moduleRevision, moduleName);
408 } catch (final ParseException e) {
409 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
410 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
414 private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
415 final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
416 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
417 ((DataNodeContainer) streamSchemaNode), "name");
418 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
420 .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
422 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
423 ((DataNodeContainer) streamSchemaNode), "description");
424 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
425 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
426 "DESCRIPTION_PLACEHOLDER"));
428 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
429 ((DataNodeContainer) streamSchemaNode), "replay-support");
430 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
431 streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
432 Boolean.valueOf(true)));
434 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
435 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
436 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
437 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
440 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
441 ((DataNodeContainer) streamSchemaNode), "events");
442 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
443 streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
445 return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
448 private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
449 final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
450 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
451 ((DataNodeContainer) moduleSchemaNode), "name");
452 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
453 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
456 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
457 ((DataNodeContainer) moduleSchemaNode), "revision");
458 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
459 final Date _revision = module.getRevision();
460 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
461 REVISION_FORMAT.format(_revision)));
463 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
464 ((DataNodeContainer) moduleSchemaNode), "namespace");
465 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
466 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
467 module.getNamespace().toString()));
469 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
470 ((DataNodeContainer) moduleSchemaNode), "feature");
471 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
472 for (final FeatureDefinition feature : module.getFeatures()) {
473 moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
474 feature.getQName().getLocalName()));
477 return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
481 public Object getRoot() {
486 public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
487 final RpcExecutor rpc = resolveIdentifierInInvokeRpc(identifier);
488 final QName rpcName = rpc.getRpcDefinition().getQName();
489 final URI rpcNamespace = rpcName.getNamespace();
490 if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
491 && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
492 return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
495 validateInput(rpc.getRpcDefinition().getInput(), payload);
497 return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
500 private void validateInput(final DataSchemaNode inputSchema, final Node<?> payload) {
501 if (inputSchema != null && payload == null) {
502 // expected a non null payload
503 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
504 } else if (inputSchema == null && payload != null) {
505 // did not expect any input
506 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
510 // TODO: Validate "mandatory" and "config" values here??? Or should those be
512 // validate in a more central location inside MD-SAL core.
516 private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
517 final boolean prettyPrint) {
518 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
519 final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
520 rpc.getQName(), "path"));
521 final Object pathValue = pathNode == null ? null : pathNode.getValue();
523 if (!(pathValue instanceof YangInstanceIdentifier)) {
524 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
525 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
528 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
529 String streamName = null;
530 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
531 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier);
533 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
534 DATASTORE_PARAM_NAME);
535 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
537 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
538 scope = scope == null ? DEFAULT_SCOPE : scope;
540 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
541 + "/scope=" + scope);
544 if (Strings.isNullOrEmpty(streamName)) {
545 throw new RestconfDocumentedException(
546 "Path is empty or contains data node which is not Container or List build-in type.",
547 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
550 final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
551 QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
552 final List<Node<?>> output = new ArrayList<Node<?>>();
553 output.add(streamNameNode);
555 final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
556 null, output, null, null);
558 if (!Notificator.existListenerFor(streamName)) {
559 Notificator.createListener(pathIdentifier, streamName);
562 return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
566 public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
567 if (StringUtils.isNotBlank(noPayload)) {
568 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
570 return invokeRpc(identifier, (CompositeNode) null, uriInfo);
573 private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
574 String identifierEncoded = null;
575 DOMMountPoint mountPoint = null;
576 if (identifier.contains(ControllerContext.MOUNT)) {
577 // mounted RPC call - look up mount instance.
578 final InstanceIdentifierContext mountPointId = controllerContext.toMountPointIdentifier(identifier);
579 mountPoint = mountPointId.getMountPoint();
581 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
582 + ControllerContext.MOUNT.length() + 1;
583 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
584 identifierEncoded = remoteRpcName;
586 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
587 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
588 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
589 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
591 identifierEncoded = identifier;
594 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
596 RpcDefinition rpc = null;
597 if (mountPoint == null) {
598 rpc = controllerContext.getRpcDefinition(identifierDecoded);
600 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
604 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
607 if (mountPoint == null) {
608 return new BrokerRpcExecutor(rpc, broker);
610 return new MountPointRpcExecutor(rpc, mountPoint);
615 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
616 final String[] splittedIdentifier = identifierDecoded.split(":");
617 if (splittedIdentifier.length != 2) {
618 throw new RestconfDocumentedException(identifierDecoded
619 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
620 ErrorTag.INVALID_VALUE);
622 for (final Module module : schemaContext.getModules()) {
623 if (module.getName().equals(splittedIdentifier[0])) {
624 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
625 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
626 return rpcDefinition;
634 private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, final boolean prettyPrint) {
635 if (rpcExecutor == null) {
636 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
639 CompositeNode rpcRequest = null;
640 final RpcDefinition rpc = rpcExecutor.getRpcDefinition();
641 final QName rpcName = rpc.getQName();
643 if (payload == null) {
644 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, null, null, null);
646 final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
647 final List<Node<?>> input = Collections.<Node<?>> singletonList(value);
648 rpcRequest = NodeFactory.createMutableCompositeNode(rpcName, null, input, null, null);
651 final RpcResult<CompositeNode> rpcResult = rpcExecutor.invokeRpc(rpcRequest);
653 checkRpcSuccessAndThrowException(rpcResult);
655 if (rpcResult.getResult() == null) {
659 if (rpc.getOutput() == null) {
660 return null; // no output, nothing to send back.
663 return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
666 private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
667 if (rpcResult.isSuccessful() == false) {
669 throw new RestconfDocumentedException("The operation was not successful", null,
670 rpcResult.getErrors());
675 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
676 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
677 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
678 NormalizedNode<?, ?> data = null;
679 YangInstanceIdentifier normalizedII;
680 if (mountPoint != null) {
681 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
682 .getInstanceIdentifier());
683 data = broker.readConfigurationData(mountPoint, normalizedII);
685 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
686 data = broker.readConfigurationData(normalizedII);
688 return new NormalizedNodeContext(iiWithData, data);
691 @SuppressWarnings("unchecked")
692 private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
697 if (node instanceof CompositeNode) {
698 final ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
700 for (final Node<?> childNode : ((CompositeNode) node).getValue()) {
701 newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
705 return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
706 } else { // SimpleNode
711 private Integer parseDepthParameter(final UriInfo info) {
712 final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
713 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
718 final Integer depth = Integer.valueOf(param);
720 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
721 "Invalid depth parameter: " + depth, null,
722 "The depth parameter must be an integer > 1 or \"unbounded\""));
726 } catch (final NumberFormatException e) {
727 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
728 "Invalid depth parameter: " + e.getMessage(), null,
729 "The depth parameter must be an integer > 1 or \"unbounded\""));
734 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
735 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
736 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
737 NormalizedNode<?, ?> data = null;
738 YangInstanceIdentifier normalizedII;
739 if (mountPoint != null) {
740 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
741 .getInstanceIdentifier());
742 data = broker.readOperationalData(mountPoint, normalizedII);
744 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
745 data = broker.readOperationalData(normalizedII);
748 return new NormalizedNodeContext(iiWithData, data);
751 private boolean parsePrettyPrintParameter(final UriInfo info) {
752 final String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
753 return Boolean.parseBoolean(param);
757 public Response updateConfigurationData(final String identifier, final Node<?> payload) {
758 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
760 validateInput(iiWithData.getSchemaNode(), payload);
762 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
763 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
764 final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
765 validateListKeysEqualityInPayloadAndUri(iiWithData, value);
766 final NormalizedNode<?, ?> datastoreNormalizedNode = compositeNodeToDatastoreNormalizedNode(value,
767 iiWithData.getSchemaNode());
770 YangInstanceIdentifier normalizedII;
771 if (mountPoint != null) {
772 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(
773 iiWithData.getInstanceIdentifier());
775 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
779 * There is a small window where another write transaction could be updating the same data
780 * simultaneously and we get an OptimisticLockFailedException. This error is likely
781 * transient and The WriteTransaction#submit API docs state that a retry will likely
782 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
783 * probably will never succeed so we'll fail in that case.
785 * By retrying we're attempting to hide the internal implementation of the data store and
786 * how it handles concurrent updates from the restconf client. The client has instructed us
787 * to put the data and we should make every effort to do so without pushing optimistic lock
788 * failures back to the client and forcing them to handle it via retry (and having to
789 * document the behavior).
794 if (mountPoint != null) {
795 broker.commitConfigurationDataPut(mountPoint, normalizedII,
796 datastoreNormalizedNode).checkedGet();
798 broker.commitConfigurationDataPut(normalizedII,
799 datastoreNormalizedNode).checkedGet();
803 } catch (final TransactionCommitFailedException e) {
804 if(e instanceof OptimisticLockFailedException) {
806 LOG.debug("Got OptimisticLockFailedException on last try - failing");
807 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
810 LOG.debug("Got OptimisticLockFailedException - trying again");
812 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
817 return Response.status(Status.OK).build();
820 private void validateTopLevelNodeName(final Node<?> node,
821 final YangInstanceIdentifier identifier) {
822 final String payloadName = getName(node);
823 final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
826 if (!pathArguments.hasNext()) {
828 if (!node.getNodeType().equals(NETCONF_BASE_QNAME)) {
829 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
830 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
834 final String identifierName = pathArguments.next().getNodeType().getLocalName();
835 if (!payloadName.equals(identifierName)) {
836 throw new RestconfDocumentedException("Payload name (" + payloadName
837 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
838 ErrorTag.MALFORMED_MESSAGE);
844 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
846 * @throws RestconfDocumentedException
847 * if key values or key count in payload and URI isn't equal
850 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext iiWithData,
851 final CompositeNode payload) {
852 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
853 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
854 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
855 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
856 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
858 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
863 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
864 final List<QName> keyDefinitions) {
865 for (final QName keyDefinition : keyDefinitions) {
866 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
867 // should be caught during parsing URI to InstanceIdentifier
868 if (uriKeyValue == null) {
869 throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
870 ErrorTag.DATA_MISSING);
872 final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
873 if (payloadKeyValues.isEmpty()) {
874 throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
875 + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
878 final Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
879 if (!uriKeyValue.equals(payloadKeyValue)) {
880 throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
881 + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
882 + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
883 ErrorTag.INVALID_VALUE);
889 public Response createConfigurationData(final String identifier, final Node<?> payload) {
890 if (payload == null) {
891 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
894 final URI payloadNS = namespace(payload);
895 if (payloadNS == null) {
896 throw new RestconfDocumentedException(
897 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
898 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
901 InstanceIdentifierContext iiWithData = null;
902 CompositeNode value = null;
903 if (representsMountPointRootData(payload)) {
904 // payload represents mount point data and URI represents path to the mount point
906 if (endsWithMountPoint(identifier)) {
907 throw new RestconfDocumentedException("URI has bad format. URI should be without \""
908 + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
909 ErrorTag.INVALID_VALUE);
912 final String completeIdentifier = addMountPointIdentifier(identifier);
913 iiWithData = controllerContext.toInstanceIdentifier(completeIdentifier);
915 value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
917 final InstanceIdentifierContext incompleteInstIdWithData = controllerContext
918 .toInstanceIdentifier(identifier);
919 final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
920 final DOMMountPoint mountPoint = incompleteInstIdWithData.getMountPoint();
921 final Module module = findModule(mountPoint, payload);
923 final String payloadName = getName(payload);
924 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(
925 parentSchema, payloadName, module.getNamespace());
926 value = this.normalizeNode(payload, schemaNode, mountPoint);
928 iiWithData = addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode,incompleteInstIdWithData.getSchemaContext());
931 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value,
932 iiWithData.getSchemaNode());
933 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
934 YangInstanceIdentifier normalizedII;
937 if (mountPoint != null) {
938 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
939 .getInstanceIdentifier());
940 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
942 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
943 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
945 } catch(final RestconfDocumentedException e) {
947 } catch (final Exception e) {
948 throw new RestconfDocumentedException("Error creating data", e);
951 return Response.status(Status.NO_CONTENT).build();
955 public Response createConfigurationData(final Node<?> payload) {
956 if (payload == null) {
957 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
960 final URI payloadNS = namespace(payload);
961 if (payloadNS == null) {
962 throw new RestconfDocumentedException(
963 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
964 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
967 final Module module = this.findModule(null, payload);
969 final String payloadName = getName(payload);
970 final DataSchemaNode schemaNode = ControllerContext.findInstanceDataChildByNameAndNamespace(module,
971 payloadName, module.getNamespace());
972 final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
973 final InstanceIdentifierContext iiWithData = addLastIdentifierFromData(null, value, schemaNode,ControllerContext.getInstance().getGlobalSchema());
974 final NormalizedNode<?, ?> datastoreNormalizedData = compositeNodeToDatastoreNormalizedNode(value, schemaNode);
975 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
976 YangInstanceIdentifier normalizedII;
979 if (mountPoint != null) {
980 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
981 .getInstanceIdentifier());
982 broker.commitConfigurationDataPost(mountPoint, normalizedII, datastoreNormalizedData);
985 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
986 broker.commitConfigurationDataPost(normalizedII, datastoreNormalizedData);
988 } catch(final RestconfDocumentedException e) {
990 } catch (final Exception e) {
991 throw new RestconfDocumentedException("Error creating data", e);
994 return Response.status(Status.NO_CONTENT).build();
998 public Response deleteConfigurationData(final String identifier) {
999 final InstanceIdentifierContext iiWithData = controllerContext.toInstanceIdentifier(identifier);
1000 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
1001 YangInstanceIdentifier normalizedII;
1004 if (mountPoint != null) {
1005 normalizedII = new DataNormalizer(mountPoint.getSchemaContext()).toNormalized(iiWithData
1006 .getInstanceIdentifier());
1007 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
1009 normalizedII = controllerContext.toNormalized(iiWithData.getInstanceIdentifier());
1010 broker.commitConfigurationDataDelete(normalizedII).get();
1012 } catch (final Exception e) {
1013 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
1014 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
1015 if (searchedException.isPresent()) {
1016 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
1018 throw new RestconfDocumentedException("Error while deleting data", e);
1020 return Response.status(Status.OK).build();
1024 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
1026 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
1028 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
1029 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
1033 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
1034 final String streamName = Notificator.createStreamNameFromUri(identifier);
1035 if (Strings.isNullOrEmpty(streamName)) {
1036 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1039 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1040 if (listener == null) {
1041 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1044 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1045 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1046 paramToValues.get(DATASTORE_PARAM_NAME));
1047 if (datastore == null) {
1048 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1049 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1051 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1052 if (scope == null) {
1053 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1054 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1057 broker.registerToListenDataChanges(datastore, scope, listener);
1059 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1060 int notificationPort = NOTIFICATION_PORT;
1062 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1063 notificationPort = webSocketServerInstance.getPort();
1064 } catch (final NullPointerException e) {
1065 WebSocketServer.createInstance(NOTIFICATION_PORT);
1067 final UriBuilder port = uriBuilder.port(notificationPort);
1068 final URI uriToWebsocketServer = port.replacePath(streamName).build();
1070 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1074 * Load parameter for subscribing to stream from input composite node
1078 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1080 private <T> T parseEnumTypeParameter(final CompositeNode compNode, final Class<T> classDescriptor,
1081 final String paramName) {
1082 final QNameModule salRemoteAugment = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
1083 EVENT_SUBSCRIPTION_AUGMENT_REVISION);
1084 final SimpleNode<?> simpleNode = compNode.getFirstSimpleByName(QName.create(salRemoteAugment, paramName));
1085 if (simpleNode == null) {
1088 final Object rawValue = simpleNode.getValue();
1089 if (!(rawValue instanceof String)) {
1093 return resolveAsEnum(classDescriptor, (String) rawValue);
1097 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1099 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1102 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1103 if (Strings.isNullOrEmpty(value)) {
1106 return resolveAsEnum(classDescriptor, value);
1109 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1110 final T[] enumConstants = classDescriptor.getEnumConstants();
1111 if (enumConstants != null) {
1112 for (final T enm : classDescriptor.getEnumConstants()) {
1113 if (((Enum<?>) enm).name().equals(value)) {
1121 private Map<String, String> resolveValuesFromUri(final String uri) {
1122 final Map<String, String> result = new HashMap<>();
1123 final String[] tokens = uri.split("/");
1124 for (int i = 1; i < tokens.length; i++) {
1125 final String[] parameterTokens = tokens[i].split("=");
1126 if (parameterTokens.length == 2) {
1127 result.put(parameterTokens[0], parameterTokens[1]);
1133 private Module findModule(final DOMMountPoint mountPoint, final Node<?> data) {
1134 Module module = null;
1135 if (data instanceof NodeWrapper) {
1136 module = findModule(mountPoint, (NodeWrapper<?>) data);
1137 } else if (data != null) {
1138 final URI namespace = data.getNodeType().getNamespace();
1139 if (mountPoint != null) {
1140 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1142 module = controllerContext.findModuleByNamespace(namespace);
1145 if (module != null) {
1148 throw new RestconfDocumentedException(
1149 "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
1150 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
1153 private Module findModule(final DOMMountPoint mountPoint, final NodeWrapper<?> data) {
1154 final URI namespace = data.getNamespace();
1155 Preconditions.<URI> checkNotNull(namespace);
1157 Module module = null;
1158 if (mountPoint != null) {
1159 module = controllerContext.findModuleByNamespace(mountPoint, namespace);
1160 if (module == null) {
1161 module = controllerContext.findModuleByName(mountPoint, namespace.toString());
1164 module = controllerContext.findModuleByNamespace(namespace);
1165 if (module == null) {
1166 module = controllerContext.findModuleByName(namespace.toString());
1173 private InstanceIdentifierContext addLastIdentifierFromData(final InstanceIdentifierContext identifierWithSchemaNode,
1174 final CompositeNode data, final DataSchemaNode schemaOfData, final SchemaContext schemaContext) {
1175 YangInstanceIdentifier instanceIdentifier = null;
1176 if (identifierWithSchemaNode != null) {
1177 instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
1180 final YangInstanceIdentifier iiOriginal = instanceIdentifier;
1181 InstanceIdentifierBuilder iiBuilder = null;
1182 if (iiOriginal == null) {
1183 iiBuilder = YangInstanceIdentifier.builder();
1185 iiBuilder = YangInstanceIdentifier.builder(iiOriginal);
1188 if ((schemaOfData instanceof ListSchemaNode)) {
1189 final HashMap<QName, Object> keys = resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
1190 iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
1192 iiBuilder.node(schemaOfData.getQName());
1195 final YangInstanceIdentifier instance = iiBuilder.toInstance();
1196 DOMMountPoint mountPoint = null;
1197 final SchemaContext schemaCtx = null;
1198 if (identifierWithSchemaNode != null) {
1199 mountPoint = identifierWithSchemaNode.getMountPoint();
1202 return new InstanceIdentifierContext(instance, schemaOfData, mountPoint,schemaContext);
1205 private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
1206 final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
1207 final List<QName> _keyDefinition = listNode.getKeyDefinition();
1208 for (final QName key : _keyDefinition) {
1209 SimpleNode<? extends Object> head = null;
1210 final String localName = key.getLocalName();
1211 final List<SimpleNode<? extends Object>> simpleNodesByName = dataNode.getSimpleNodesByName(localName);
1212 if (simpleNodesByName != null) {
1213 head = Iterables.getFirst(simpleNodesByName, null);
1216 Object dataNodeKeyValueObject = null;
1218 dataNodeKeyValueObject = head.getValue();
1221 if (dataNodeKeyValueObject == null) {
1222 throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
1223 + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
1224 ErrorTag.INVALID_VALUE);
1227 keyValues.put(key, dataNodeKeyValueObject);
1233 private boolean endsWithMountPoint(final String identifier) {
1234 return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
1237 private boolean representsMountPointRootData(final Node<?> data) {
1238 final URI namespace = namespace(data);
1239 return (SchemaContext.NAME.getNamespace().equals(namespace) /*
1240 * || MOUNT_POINT_MODULE_NAME .equals( namespace .
1243 && SchemaContext.NAME.getLocalName().equals(localName(data));
1246 private String addMountPointIdentifier(final String identifier) {
1247 final boolean endsWith = identifier.endsWith("/");
1249 return (identifier + ControllerContext.MOUNT);
1252 return identifier + "/" + ControllerContext.MOUNT;
1255 private CompositeNode normalizeNode(final Node<?> node, final DataSchemaNode schema, final DOMMountPoint mountPoint) {
1256 if (schema == null) {
1257 final String localName = node == null ? null :
1258 node instanceof NodeWrapper ? ((NodeWrapper<?>)node).getLocalName() :
1259 node.getNodeType().getLocalName();
1261 throw new RestconfDocumentedException("Data schema node was not found for " + localName,
1262 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1265 if (!(schema instanceof DataNodeContainer)) {
1266 throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
1267 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1270 if ((node instanceof NodeWrapper<?>)) {
1271 NodeWrapper<?> nodeWrap = (NodeWrapper<?>) node;
1272 final boolean isChangeAllowed = ((NodeWrapper<?>) node).isChangeAllowed();
1273 if (isChangeAllowed) {
1274 nodeWrap = topLevelElementAsCompositeNodeWrapper((NodeWrapper<?>) node, schema);
1276 this.normalizeNode(nodeWrap, schema, null, mountPoint);
1277 } catch (final IllegalArgumentException e) {
1278 final RestconfDocumentedException restconfDocumentedException = new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1279 restconfDocumentedException.addSuppressed(e);
1280 throw restconfDocumentedException;
1282 if (nodeWrap instanceof CompositeNodeWrapper) {
1283 return ((CompositeNodeWrapper) nodeWrap).unwrap();
1288 if (node instanceof CompositeNode) {
1289 return (CompositeNode) node;
1292 throw new RestconfDocumentedException("Top level element is not interpreted as composite node.",
1293 ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
1296 private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1297 final QName previousAugment, final DOMMountPoint mountPoint) {
1298 if (schema == null) {
1299 throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
1300 + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1303 QName currentAugment = null;
1304 if (nodeBuilder.getQname() != null) {
1305 currentAugment = previousAugment;
1307 currentAugment = normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
1308 if (nodeBuilder.getQname() == null) {
1309 throw new RestconfDocumentedException(
1310 "Data has bad format.\nIf data is in XML format then namespace for \""
1311 + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
1312 + "\".\n" + "If data is in JSON format then module name for \""
1313 + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
1314 + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1318 if (nodeBuilder instanceof CompositeNodeWrapper) {
1319 if (schema instanceof DataNodeContainer) {
1320 normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
1322 } else if (schema instanceof AnyXmlSchemaNode) {
1323 normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
1325 } else if (nodeBuilder instanceof SimpleNodeWrapper) {
1326 normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
1327 } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
1328 normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
1332 private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
1333 final List<NodeWrapper<?>> children = compositeNode.getValues();
1334 for (final NodeWrapper<? extends Object> child : children) {
1335 child.setNamespace(schema.getQName().getNamespace());
1336 if (child instanceof CompositeNodeWrapper) {
1337 normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
1342 private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
1343 if ((schema instanceof LeafSchemaNode)) {
1344 emptyNodeBuilder.setComposite(false);
1346 if ((schema instanceof ContainerSchemaNode)) {
1347 // FIXME: Add presence check
1348 emptyNodeBuilder.setComposite(true);
1353 private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
1354 final DOMMountPoint mountPoint) {
1355 final Object value = simpleNode.getValue();
1356 Object inputValue = value;
1357 final TypeDef typeDef = this.typeDefinition(schema);
1358 TypeDefinition<? extends Object> typeDefinition = typeDef != null ? typeDef.typedef : null;
1360 // For leafrefs, extract the type it is pointing to
1361 if(typeDefinition instanceof LeafrefTypeDefinition) {
1362 if (schema.getQName().equals(typeDef.qName)) {
1363 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), schema);
1365 typeDefinition = SchemaContextUtil.getBaseTypeForLeafRef(((LeafrefTypeDefinition) typeDefinition), mountPoint == null ? controllerContext.getGlobalSchema() : mountPoint.getSchemaContext(), typeDef.qName);
1369 if (typeDefinition instanceof IdentityrefTypeDefinition) {
1370 inputValue = parseToIdentityValuesDTO(simpleNode, value, inputValue);
1373 Object outputValue = inputValue;
1375 if (typeDefinition != null) {
1376 final Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
1377 outputValue = codec == null ? null : codec.deserialize(inputValue);
1380 simpleNode.setValue(outputValue);
1383 private Object parseToIdentityValuesDTO(final SimpleNodeWrapper simpleNode, final Object value, Object inputValue) {
1384 if ((value instanceof String)) {
1385 inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
1387 } // else value is already instance of IdentityValuesDTO
1391 private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
1392 final DataNodeContainer schema, final DOMMountPoint mountPoint, final QName currentAugment) {
1393 final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
1394 checkNodeMultiplicityAccordingToSchema(schema, children);
1395 for (final NodeWrapper<? extends Object> child : children) {
1396 final List<DataSchemaNode> potentialSchemaNodes = ControllerContext.findInstanceDataChildrenByName(
1397 schema, child.getLocalName());
1399 if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
1400 final StringBuilder builder = new StringBuilder();
1401 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1402 builder.append(" ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
1405 throw new RestconfDocumentedException("Node \"" + child.getLocalName()
1406 + "\" is added as augment from more than one module. "
1407 + "Therefore node must have namespace (XML format) or module name (JSON format)."
1408 + "\nThe node is added as augment from modules with namespaces:\n" + builder,
1409 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1412 boolean rightNodeSchemaFound = false;
1413 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
1414 if (!rightNodeSchemaFound) {
1415 final QName potentialCurrentAugment = normalizeNodeName(child, potentialSchemaNode,
1416 currentAugment, mountPoint);
1417 if (child.getQname() != null) {
1418 this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
1419 rightNodeSchemaFound = true;
1424 if (!rightNodeSchemaFound) {
1425 throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
1426 + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
1430 if ((schema instanceof ListSchemaNode)) {
1431 final ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
1432 final List<QName> listKeys = listSchemaNode.getKeyDefinition();
1433 for (final QName listKey : listKeys) {
1434 boolean foundKey = false;
1435 for (final NodeWrapper<? extends Object> child : children) {
1436 if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
1442 throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
1443 + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
1444 ErrorTag.DATA_MISSING);
1450 private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
1451 final List<NodeWrapper<?>> nodes) {
1452 final Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
1453 for (final NodeWrapper<?> child : nodes) {
1454 Integer count = equalNodeNamesToCounts.get(child.getLocalName());
1455 equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
1458 for (final DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
1459 if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
1460 final String localName = childSchemaNode.getQName().getLocalName();
1461 final Integer count = equalNodeNamesToCounts.get(localName);
1462 if (count != null && count > 1) {
1463 throw new RestconfDocumentedException("Multiple input data elements were specified for '"
1464 + childSchemaNode.getQName().getLocalName()
1465 + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
1466 ErrorTag.BAD_ELEMENT);
1472 private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
1473 final QName previousAugment, final DOMMountPoint mountPoint) {
1474 QName validQName = schema.getQName();
1475 QName currentAugment = previousAugment;
1476 if (schema.isAugmenting()) {
1477 currentAugment = schema.getQName();
1478 } else if (previousAugment != null
1479 && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
1480 validQName = QName.create(currentAugment, schema.getQName().getLocalName());
1483 String moduleName = null;
1484 if (mountPoint == null) {
1485 moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
1487 moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
1490 if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
1491 || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName)) {
1493 * || Note : this check is wrong -
1494 * can never be true as it compares
1495 * a URI with a String not sure what
1496 * the intention is so commented out
1497 * ... Objects . equal ( nodeBuilder
1498 * . getNamespace ( ) ,
1499 * MOUNT_POINT_MODULE_NAME )
1502 nodeBuilder.setQname(validQName);
1505 return currentAugment;
1508 private URI namespace(final Node<?> data) {
1509 if (data instanceof NodeWrapper) {
1510 return ((NodeWrapper<?>) data).getNamespace();
1511 } else if (data != null) {
1512 return data.getNodeType().getNamespace();
1514 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1518 private String localName(final Node<?> data) {
1519 if (data instanceof NodeWrapper) {
1520 return ((NodeWrapper<?>) data).getLocalName();
1521 } else if (data != null) {
1522 return data.getNodeType().getLocalName();
1524 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1528 private String getName(final Node<?> data) {
1529 if (data instanceof NodeWrapper) {
1530 return ((NodeWrapper<?>) data).getLocalName();
1531 } else if (data != null) {
1532 return data.getNodeType().getLocalName();
1534 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
1538 private TypeDef typeDefinition(final TypeDefinition<?> type, final QName nodeQName) {
1539 TypeDefinition<?> baseType = type;
1540 QName qName = nodeQName;
1541 while (baseType.getBaseType() != null) {
1542 if (baseType instanceof ExtendedType) {
1543 qName = baseType.getQName();
1545 baseType = baseType.getBaseType();
1548 return new TypeDef(baseType, qName);
1552 private TypeDef typeDefinition(final DataSchemaNode node) {
1553 if (node instanceof LeafListSchemaNode) {
1554 return typeDefinition(((LeafListSchemaNode)node).getType(), node.getQName());
1555 } else if (node instanceof LeafSchemaNode) {
1556 return typeDefinition(((LeafSchemaNode)node).getType(), node.getQName());
1557 } else if (node instanceof AnyXmlSchemaNode) {
1560 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
1564 private CompositeNode datastoreNormalizedNodeToCompositeNode(final NormalizedNode<?, ?> dataNode, final DataSchemaNode schema) {
1565 Node<?> nodes = null;
1566 if (dataNode == null) {
1567 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.DATA_MISSING,
1568 "No data was found."));
1570 nodes = DataNormalizer.toLegacy(dataNode);
1571 if (nodes != null) {
1572 if (nodes instanceof CompositeNode) {
1573 return (CompositeNode) nodes;
1575 LOG.error("The node " + dataNode.getNodeType() + " couldn't be transformed to compositenode.");
1578 LOG.error("Top level node isn't of type Container or List schema node but "
1579 + schema.getClass().getSimpleName());
1582 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1583 "It wasn't possible to correctly interpret data."));
1586 private NormalizedNode<?, ?> compositeNodeToDatastoreNormalizedNode(final CompositeNode compNode,
1587 final DataSchemaNode schema) {
1588 final List<Node<?>> lst = new ArrayList<Node<?>>();
1590 if (schema instanceof ContainerSchemaNode) {
1591 return CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
1592 .parse(lst, (ContainerSchemaNode) schema);
1593 } else if (schema instanceof ListSchemaNode) {
1594 return CnSnToNormalizedNodeParserFactory.getInstance().getMapEntryNodeParser()
1595 .parse(lst, (ListSchemaNode) schema);
1598 LOG.error("Top level isn't of type container, list, leaf schema node but " + schema.getClass().getSimpleName());
1600 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1601 "It wasn't possible to translate specified data to datastore readable form."));
1604 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1605 final InstanceIdentifierContext iiWithSchemaNode) {
1606 return normalizeInstanceIdentifierWithSchemaNode(iiWithSchemaNode, false);
1609 private InstanceIdentifierContext normalizeInstanceIdentifierWithSchemaNode(
1610 final InstanceIdentifierContext iiWithSchemaNode, final boolean unwrapLastListNode) {
1611 return new InstanceIdentifierContext(instanceIdentifierToReadableFormForNormalizeNode(
1612 iiWithSchemaNode.getInstanceIdentifier(), unwrapLastListNode), iiWithSchemaNode.getSchemaNode(),
1613 iiWithSchemaNode.getMountPoint(),iiWithSchemaNode.getSchemaContext());
1616 private YangInstanceIdentifier instanceIdentifierToReadableFormForNormalizeNode(
1617 final YangInstanceIdentifier instIdentifier, final boolean unwrapLastListNode) {
1618 Preconditions.checkNotNull(instIdentifier, "Instance identifier can't be null");
1619 final List<PathArgument> result = new ArrayList<PathArgument>();
1620 final Iterator<PathArgument> iter = instIdentifier.getPathArguments().iterator();
1621 while (iter.hasNext()) {
1622 final PathArgument pathArgument = iter.next();
1623 if (pathArgument instanceof NodeIdentifierWithPredicates && (iter.hasNext() || unwrapLastListNode)) {
1624 result.add(new YangInstanceIdentifier.NodeIdentifier(pathArgument.getNodeType()));
1626 result.add(pathArgument);
1628 return YangInstanceIdentifier.create(result);
1631 private CompositeNodeWrapper topLevelElementAsCompositeNodeWrapper(final NodeWrapper<?> node,
1632 final DataSchemaNode schemaNode) {
1633 if (node instanceof CompositeNodeWrapper) {
1634 return (CompositeNodeWrapper) node;
1635 } else if (node instanceof SimpleNodeWrapper && isDataContainerNode(schemaNode)) {
1636 final SimpleNodeWrapper simpleNodeWrapper = (SimpleNodeWrapper) node;
1637 return new CompositeNodeWrapper(namespace(simpleNodeWrapper), localName(simpleNodeWrapper));
1640 throw new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
1641 "Top level element has to be composite node or has to represent data container node."));
1644 private boolean isDataContainerNode(final DataSchemaNode schemaNode) {
1645 if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode) {
1651 public BigInteger getOperationalReceived() {
1652 // TODO Auto-generated method stub
1656 private MapNode makeModuleMapNode(final Set<Module> modules) {
1657 Preconditions.checkNotNull(modules);
1658 final Module restconfModule = getRestconfModule();
1659 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1660 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1661 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1663 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1664 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1666 for (final Module module : modules) {
1667 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1669 return listModuleBuilder.build();
1672 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1673 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1674 "moduleSchemaNode has to be of type ListSchemaNode");
\r final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
\r final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
\r .mapEntryBuilder(listModuleSchemaNode);
\r\r List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "name");
\r final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
\r .build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "revision");
\r final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
\r final String revision = REVISION_FORMAT.format(module.getRevision());
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
\r .build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "namespace");
\r final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
\r moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
\r .withValue(module.getNamespace().toString()).build());
\r\r instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
\r (listModuleSchemaNode), "feature");
\r final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
\r Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
\r final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
\r .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
\r for (final FeatureDefinition feature : module.getFeatures()) {
\r featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
\r .withValue(feature.getQName().getLocalName()).build());
\r }
\r moduleNodeValues.withChild(featuresBuilder.build());
1675 \r return moduleNodeValues.build();
\r }
1677 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1678 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1679 "streamSchemaNode has to be of type ListSchemaNode");
1680 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1681 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1682 .mapEntryBuilder(listStreamSchemaNode);
1684 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1685 (listStreamSchemaNode), "name");
1686 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1687 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1688 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1691 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1692 (listStreamSchemaNode), "description");
1693 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1694 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1695 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1696 .withValue("DESCRIPTION_PLACEHOLDER").build());
1698 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1699 (listStreamSchemaNode), "replay-support");
1700 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1701 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1702 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1703 .withValue(Boolean.valueOf(true)).build());
1705 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1706 (listStreamSchemaNode), "replay-log-creation-time");
1707 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1708 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1709 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1710 .withValue("").build());
1712 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1713 (listStreamSchemaNode), "events");
1714 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1715 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1716 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1717 .withValue("").build());
1719 return streamNodeValues.build();