2 * Copyright (c) 2014, 2015 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * 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.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicate;
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.Iterables;
19 import com.google.common.collect.Lists;
20 import com.google.common.collect.Maps;
21 import com.google.common.collect.Sets;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
24 import java.math.BigInteger;
26 import java.net.URISyntaxException;
27 import java.text.ParseException;
28 import java.text.SimpleDateFormat;
29 import java.util.ArrayList;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.List;
36 import java.util.concurrent.CancellationException;
37 import java.util.concurrent.ExecutionException;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.Response.ResponseBuilder;
40 import javax.ws.rs.core.Response.Status;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43 import org.apache.commons.lang3.StringUtils;
44 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
45 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
46 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
47 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
48 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.controller.md.sal.rest.common.RestconfValidationUtils;
54 import org.opendaylight.controller.sal.rest.api.Draft02;
55 import org.opendaylight.controller.sal.rest.api.RestconfService;
56 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
57 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
58 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
59 import org.opendaylight.controller.sal.streams.listeners.Notificator;
60 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.common.QNameModule;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
76 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
77 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
78 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
82 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
84 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
86 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.Module;
90 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
91 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
92 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
94 import org.opendaylight.yangtools.yang.model.util.EmptyType;
95 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
96 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
97 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
98 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
99 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
100 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
101 import org.slf4j.Logger;
102 import org.slf4j.LoggerFactory;
104 public class RestconfImpl implements RestconfService {
106 private static final RestconfImpl INSTANCE = new RestconfImpl();
108 private static final int NOTIFICATION_PORT = 8181;
110 private static final int CHAR_NOT_FOUND = -1;
112 private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
114 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
116 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
118 private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
120 private BrokerFacade broker;
122 private ControllerContext controllerContext;
124 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
126 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
128 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
130 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
132 private static final String DATASTORE_PARAM_NAME = "datastore";
134 private static final String SCOPE_PARAM_NAME = "scope";
136 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
138 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
140 private static final QName NETCONF_BASE_QNAME;
142 private static final QNameModule SAL_REMOTE_AUGMENT;
144 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
148 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
149 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
150 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
151 eventSubscriptionAugRevision);
152 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
153 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
154 } catch (final ParseException e) {
155 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
157 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
158 } catch (final URISyntaxException e) {
159 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
160 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
164 public void setBroker(final BrokerFacade broker) {
165 this.broker = broker;
168 public void setControllerContext(final ControllerContext controllerContext) {
169 this.controllerContext = controllerContext;
172 private RestconfImpl() {
175 public static RestconfImpl getInstance() {
180 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
181 final Set<Module> allModules = controllerContext.getAllModules();
182 final MapNode allModuleMap = makeModuleMapNode(allModules);
184 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
186 final Module restconfModule = getRestconfModule();
187 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
188 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
189 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
191 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
192 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
193 moduleContainerBuilder.withChild(allModuleMap);
195 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
196 null, schemaContext), moduleContainerBuilder.build(),
197 QueryParametersParser.parseWriterParameters(uriInfo));
201 * Valid only for mount point
204 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
205 Preconditions.checkNotNull(identifier);
206 if ( ! identifier.contains(ControllerContext.MOUNT)) {
207 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
208 + " URI has to end with " + ControllerContext.MOUNT;
209 LOG.debug(errMsg + " for " + identifier);
210 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
213 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
214 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
215 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
216 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
218 final Module restconfModule = getRestconfModule();
219 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
220 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
221 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
223 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
224 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
225 moduleContainerBuilder.withChild(mountPointModulesMap);
227 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
228 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
229 QueryParametersParser.parseWriterParameters(uriInfo));
233 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
234 Preconditions.checkNotNull(identifier);
235 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
236 Module module = null;
237 DOMMountPoint mountPoint = null;
238 final SchemaContext schemaContext;
239 if (identifier.contains(ControllerContext.MOUNT)) {
240 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
241 mountPoint = mountPointIdentifier.getMountPoint();
242 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
243 schemaContext = mountPoint.getSchemaContext();
245 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
246 schemaContext = controllerContext.getGlobalSchema();
249 if (module == null) {
250 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
251 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
253 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
256 final Module restconfModule = getRestconfModule();
257 final Set<Module> modules = Collections.singleton(module);
258 final MapNode moduleMap = makeModuleMapNode(modules);
260 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
261 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
262 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
264 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
265 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
269 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
270 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
271 final Set<String> availableStreams = Notificator.getStreamNames();
272 final Module restconfModule = getRestconfModule();
273 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
274 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
275 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
277 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
278 .mapBuilder((ListSchemaNode) streamSchemaNode);
280 for (final String streamName : availableStreams) {
281 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
284 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
285 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
286 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
288 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
289 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
290 streamsContainerBuilder.withChild(listStreamsBuilder.build());
293 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
294 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
298 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
299 final Set<Module> allModules = controllerContext.getAllModules();
300 return operationsFromModulesToNormalizedContext(allModules, null);
304 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
305 Set<Module> modules = null;
306 DOMMountPoint mountPoint = null;
307 if (identifier.contains(ControllerContext.MOUNT)) {
308 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
309 mountPoint = mountPointIdentifier.getMountPoint();
310 modules = controllerContext.getAllModules(mountPoint);
313 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
314 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
315 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
318 return operationsFromModulesToNormalizedContext(modules, mountPoint);
321 private static final Predicate<GroupingBuilder> GROUPING_FILTER = new Predicate<GroupingBuilder>() {
323 public boolean apply(final GroupingBuilder g) {
324 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
328 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
329 final DOMMountPoint mountPoint) {
331 final Module restconfModule = getRestconfModule();
332 final ModuleBuilder restConfModuleBuilder = new ModuleBuilder(restconfModule);
333 final Set<GroupingBuilder> gropingBuilders = restConfModuleBuilder.getGroupingBuilders();
334 final Iterable<GroupingBuilder> filteredGroups = Iterables.filter(gropingBuilders, GROUPING_FILTER);
335 final GroupingBuilder restconfGroupingBuilder = Iterables.getFirst(filteredGroups, null);
336 final ContainerSchemaNodeBuilder restContainerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restconfGroupingBuilder
337 .getDataChildByName(Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
338 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restContainerSchemaNodeBuilder
339 .getDataChildByName(Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
341 final ContainerSchemaNodeBuilder fakeOperationsSchemaNodeBuilder = containerSchemaNodeBuilder;
342 final SchemaPath fakeSchemaPath = fakeOperationsSchemaNodeBuilder.getPath().createChild(QName.create("dummy"));
344 final List<LeafNode<Object>> operationsAsData = new ArrayList<>();
346 for (final Module module : modules) {
347 final Set<RpcDefinition> rpcs = module.getRpcs();
348 for (final RpcDefinition rpc : rpcs) {
349 final QName rpcQName = rpc.getQName();
350 final String name = module.getName();
352 final QName qName = QName.create(restconfModule.getQNameModule(), rpcQName.getLocalName());
353 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, qName, fakeSchemaPath);
354 final LeafSchemaNodeBuilder fakeRpcSchemaNodeBuilder = leafSchemaNodeBuilder;
355 fakeRpcSchemaNodeBuilder.setAugmenting(true);
357 final EmptyType instance = EmptyType.getInstance();
358 fakeRpcSchemaNodeBuilder.setType(instance);
359 final LeafSchemaNode fakeRpcSchemaNode = fakeRpcSchemaNodeBuilder.build();
360 fakeOperationsSchemaNodeBuilder.addChildNode(fakeRpcSchemaNode);
362 final LeafNode<Object> leaf = Builders.leafBuilder(fakeRpcSchemaNode).build();
363 operationsAsData.add(leaf);
367 final ContainerSchemaNode operContainerSchemaNode = fakeOperationsSchemaNodeBuilder.build();
368 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> operContainerNode = Builders.containerBuilder(operContainerSchemaNode);
370 for (final LeafNode<Object> oper : operationsAsData) {
371 operContainerNode.withChild(oper);
374 final Set<Module> fakeRpcModules = Collections.singleton(restConfModuleBuilder.build());
376 final YangParserImpl yangParser = new YangParserImpl();
377 final SchemaContext fakeSchemaCx = yangParser.resolveSchemaContext(fakeRpcModules);
379 final InstanceIdentifierContext<?> fakeIICx = new InstanceIdentifierContext<>(null, operContainerSchemaNode, mountPoint, fakeSchemaCx);
381 return new NormalizedNodeContext(fakeIICx, operContainerNode.build());
384 private Module getRestconfModule() {
385 final Module restconfModule = controllerContext.getRestconfModule();
386 if (restconfModule == null) {
387 LOG.debug("ietf-restconf module was not found.");
388 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
389 ErrorTag.OPERATION_NOT_SUPPORTED);
392 return restconfModule;
395 private QName getModuleNameAndRevision(final String identifier) {
396 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
397 String moduleNameAndRevision = "";
398 if (mountIndex >= 0) {
399 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
401 moduleNameAndRevision = identifier;
404 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
405 final Iterable<String> split = splitter.split(moduleNameAndRevision);
406 final List<String> pathArgs = Lists.<String> newArrayList(split);
407 if (pathArgs.size() < 2) {
408 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
409 throw new RestconfDocumentedException(
410 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
411 ErrorTag.INVALID_VALUE);
415 final String moduleName = pathArgs.get(0);
416 final String revision = pathArgs.get(1);
417 final Date moduleRevision = REVISION_FORMAT.parse(revision);
418 return QName.create(null, moduleRevision, moduleName);
419 } catch (final ParseException e) {
420 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
421 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
422 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
427 public Object getRoot() {
432 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
433 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
434 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
435 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
436 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
437 final SchemaContext schemaContext;
438 if (identifier.contains(MOUNT_POINT_MODULE_NAME) && mountPoint != null) {
439 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
440 if ( ! mountRpcServices.isPresent()) {
441 LOG.debug("Error: Rpc service is missing.");
442 throw new RestconfDocumentedException("Rpc service is missing.");
444 schemaContext = mountPoint.getSchemaContext();
445 response = mountRpcServices.get().invokeRpc(type, payload.getData());
447 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
448 response = invokeSalRemoteRpcSubscribeRPC(payload);
450 response = broker.invokeRpc(type, payload.getData());
452 schemaContext = controllerContext.getGlobalSchema();
455 final DOMRpcResult result = checkRpcResponse(response);
457 RpcDefinition resultNodeSchema = null;
458 final NormalizedNode<?, ?> resultData = result.getResult();
459 if (result != null && result.getResult() != null) {
460 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
463 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
464 resultNodeSchema, mountPoint, schemaContext), resultData,
465 QueryParametersParser.parseWriterParameters(uriInfo));
468 private DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
469 if (response == null) {
473 final DOMRpcResult retValue = response.get();
474 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
477 LOG.debug("RpcError message", retValue.getErrors());
478 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
479 } catch (final InterruptedException e) {
480 final String errMsg = "The operation was interrupted while executing and did not complete.";
481 LOG.debug("Rpc Interrupt - " + errMsg, e);
482 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
483 } catch (final ExecutionException e) {
484 LOG.debug("Execution RpcError: ", e);
485 Throwable cause = e.getCause();
487 while (cause.getCause() != null) {
488 cause = cause.getCause();
491 if (cause instanceof IllegalArgumentException) {
492 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
493 ErrorTag.INVALID_VALUE);
495 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
497 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
499 } catch (final CancellationException e) {
500 final String errMsg = "The operation was cancelled while executing.";
501 LOG.debug("Cancel RpcExecution: " + errMsg, e);
502 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
506 private void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
507 if (inputSchema != null && payload.getData() == null) {
508 // expected a non null payload
509 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
510 } else if (inputSchema == null && payload.getData() != null) {
511 // did not expect any input
512 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
516 // TODO: Validate "mandatory" and "config" values here??? Or should those be
518 // validate in a more central location inside MD-SAL core.
522 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
523 final ContainerNode value = (ContainerNode) payload.getData();
524 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
525 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
526 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
527 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
529 if (!(pathValue instanceof YangInstanceIdentifier)) {
530 final String errMsg = "Instance identifier was not normalized correctly ";
531 LOG.debug(errMsg + rpcQName);
532 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
535 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
536 String streamName = null;
537 if (!pathIdentifier.isEmpty()) {
538 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
540 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
541 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
543 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
544 scope = scope == null ? DEFAULT_SCOPE : scope;
546 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
547 + "/scope=" + scope);
550 if (Strings.isNullOrEmpty(streamName)) {
551 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
552 LOG.debug(errMsg + pathIdentifier);
553 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
556 final QName outputQname = QName.create(rpcQName, "output");
557 final QName streamNameQname = QName.create(rpcQName, "stream-name");
559 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
560 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
562 if (!Notificator.existListenerFor(streamName)) {
563 Notificator.createListener(pathIdentifier, streamName);
566 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
568 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
572 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
573 if (StringUtils.isNotBlank(noPayload)) {
574 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
577 String identifierEncoded = null;
578 DOMMountPoint mountPoint = null;
579 final SchemaContext schemaContext;
580 if (identifier.contains(ControllerContext.MOUNT)) {
581 // mounted RPC call - look up mount instance.
582 final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
583 mountPoint = mountPointId.getMountPoint();
584 schemaContext = mountPoint.getSchemaContext();
585 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
586 + ControllerContext.MOUNT.length() + 1;
587 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
588 identifierEncoded = remoteRpcName;
590 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
591 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
592 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
593 LOG.debug(slashErrorMsg);
594 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
596 identifierEncoded = identifier;
597 schemaContext = controllerContext.getGlobalSchema();
600 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
602 RpcDefinition rpc = null;
603 if (mountPoint == null) {
604 rpc = controllerContext.getRpcDefinition(identifierDecoded);
606 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
610 LOG.debug("RPC " + identifierDecoded + " does not exist.");
611 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
614 if (rpc.getInput() != null) {
615 LOG.debug("RPC " + rpc + " does not need input value.");
616 // FIXME : find a correct Error from specification
617 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
620 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
621 if (mountPoint != null) {
622 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
623 if ( ! mountRpcServices.isPresent()) {
624 throw new RestconfDocumentedException("Rpc service is missing.");
626 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
628 response = broker.invokeRpc(rpc.getPath(), null);
631 final DOMRpcResult result = checkRpcResponse(response);
633 DataSchemaNode resultNodeSchema = null;
634 NormalizedNode<?, ?> resultData = null;
635 if (result != null && result.getResult() != null) {
636 resultData = result.getResult();
637 final ContainerSchemaNode rpcDataSchemaNode =
638 SchemaContextUtil.getRpcDataSchema(schemaContext, rpc.getOutput().getPath());
639 resultNodeSchema = rpcDataSchemaNode.getDataChildByName(result.getResult().getNodeType());
642 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint,
643 schemaContext), resultData, QueryParametersParser.parseWriterParameters(uriInfo));
646 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
647 final String[] splittedIdentifier = identifierDecoded.split(":");
648 if (splittedIdentifier.length != 2) {
649 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
651 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
653 for (final Module module : schemaContext.getModules()) {
654 if (module.getName().equals(splittedIdentifier[0])) {
655 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
656 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
657 return rpcDefinition;
666 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
667 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
668 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
669 NormalizedNode<?, ?> data = null;
670 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
671 if (mountPoint != null) {
672 data = broker.readConfigurationData(mountPoint, normalizedII);
674 data = broker.readConfigurationData(normalizedII);
677 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
678 LOG.debug(errMsg + identifier);
679 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
681 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
685 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
686 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
687 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
688 NormalizedNode<?, ?> data = null;
689 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
690 if (mountPoint != null) {
691 data = broker.readOperationalData(mountPoint, normalizedII);
693 data = broker.readOperationalData(normalizedII);
696 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
697 LOG.debug(errMsg + identifier);
698 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
700 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
704 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
705 Preconditions.checkNotNull(identifier);
706 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
708 validateInput(iiWithData.getSchemaNode(), payload);
709 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
710 validateListKeysEqualityInPayloadAndUri(payload);
712 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
713 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
716 * There is a small window where another write transaction could be updating the same data
717 * simultaneously and we get an OptimisticLockFailedException. This error is likely
718 * transient and The WriteTransaction#submit API docs state that a retry will likely
719 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
720 * probably will never succeed so we'll fail in that case.
722 * By retrying we're attempting to hide the internal implementation of the data store and
723 * how it handles concurrent updates from the restconf client. The client has instructed us
724 * to put the data and we should make every effort to do so without pushing optimistic lock
725 * failures back to the client and forcing them to handle it via retry (and having to
726 * document the behavior).
731 if (mountPoint != null) {
732 broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
734 broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
738 } catch (final TransactionCommitFailedException e) {
739 if(e instanceof OptimisticLockFailedException) {
741 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
742 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
745 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
747 LOG.debug("Update ConfigDataStore fail " + identifier, e);
748 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
753 return Response.status(Status.OK).build();
756 private void validateTopLevelNodeName(final NormalizedNodeContext node,
757 final YangInstanceIdentifier identifier) {
759 final String payloadName = node.getData().getNodeType().getLocalName();
762 if (identifier.isEmpty()) {
764 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
765 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
766 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
770 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
771 if (!payloadName.equals(identifierName)) {
772 throw new RestconfDocumentedException("Payload name (" + payloadName
773 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
774 ErrorTag.MALFORMED_MESSAGE);
780 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
782 * @throws RestconfDocumentedException
783 * if key values or key count in payload and URI isn't equal
786 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
787 Preconditions.checkArgument(payload != null);
788 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
789 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
790 final SchemaNode schemaNode = iiWithData.getSchemaNode();
791 final NormalizedNode<?, ?> data = payload.getData();
792 if (schemaNode instanceof ListSchemaNode) {
793 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
794 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
795 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
796 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
801 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
802 final MapEntryNode payload, final List<QName> keyDefinitions) {
804 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
805 for (final QName keyDefinition : keyDefinitions) {
806 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
807 // should be caught during parsing URI to InstanceIdentifier
808 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
809 "Missing key " + keyDefinition + " in URI.");
811 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
813 if ( ! uriKeyValue.equals(dataKeyValue)) {
814 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
815 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
816 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
822 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
823 return createConfigurationData(payload, uriInfo);
826 // FIXME create RestconfIdetifierHelper and move this method there
827 private YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
828 Preconditions.checkArgument(payload != null);
829 Preconditions.checkArgument(payload.getData() != null);
830 Preconditions.checkArgument(payload.getData().getNodeType() != null);
831 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
832 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
834 final QName payloadNodeQname = payload.getData().getNodeType();
835 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
836 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
839 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
840 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
841 if(parentSchemaNode instanceof DataNodeContainer) {
842 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
843 for (final DataSchemaNode child : cast.getChildNodes()) {
844 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
845 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
849 if (parentSchemaNode instanceof RpcDefinition) {
852 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
853 LOG.info(errMsg + yangIdent);
854 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
858 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
859 if (payload == null) {
860 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
863 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
864 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
865 // if (payloadNS == null) {
866 // throw new RestconfDocumentedException(
867 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
868 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
871 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
872 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
873 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
875 if (mountPoint != null) {
876 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
878 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
880 } catch(final RestconfDocumentedException e) {
882 } catch (final Exception e) {
883 final String errMsg = "Error creating data ";
884 LOG.info(errMsg + uriInfo.getPath(), e);
885 throw new RestconfDocumentedException(errMsg, e);
888 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
889 // FIXME: Provide path to result.
890 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
891 if (location != null) {
892 responseBuilder.location(location);
894 return responseBuilder.build();
897 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
898 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
899 uriBuilder.path("config");
901 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
902 } catch (final Exception e) {
903 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
906 return uriBuilder.build();
910 public Response deleteConfigurationData(final String identifier) {
911 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
912 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
913 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
916 if (mountPoint != null) {
917 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
919 broker.commitConfigurationDataDelete(normalizedII).get();
921 } catch (final Exception e) {
922 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
923 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
924 if (searchedException.isPresent()) {
925 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
927 final String errMsg = "Error while deleting data";
929 throw new RestconfDocumentedException(errMsg, e);
931 return Response.status(Status.OK).build();
935 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
937 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
939 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
940 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
944 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
945 final String streamName = Notificator.createStreamNameFromUri(identifier);
946 if (Strings.isNullOrEmpty(streamName)) {
947 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
950 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
951 if (listener == null) {
952 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
955 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
956 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
957 paramToValues.get(DATASTORE_PARAM_NAME));
958 if (datastore == null) {
959 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
960 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
962 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
964 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
965 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
968 broker.registerToListenDataChanges(datastore, scope, listener);
970 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
971 int notificationPort = NOTIFICATION_PORT;
973 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
974 notificationPort = webSocketServerInstance.getPort();
975 } catch (final NullPointerException e) {
976 WebSocketServer.createInstance(NOTIFICATION_PORT);
978 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
979 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
981 return Response.status(Status.OK).location(uriToWebsocketServer).build();
985 * Load parameter for subscribing to stream from input composite node
989 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
991 private <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
992 final String paramName) {
993 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
994 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
997 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
998 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
999 if (!enumNode.isPresent()) {
1002 final Object rawValue = enumNode.get().getValue();
1003 if (!(rawValue instanceof String)) {
1007 return resolveAsEnum(classDescriptor, (String) rawValue);
1011 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1013 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1016 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1017 if (Strings.isNullOrEmpty(value)) {
1020 return resolveAsEnum(classDescriptor, value);
1023 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1024 final T[] enumConstants = classDescriptor.getEnumConstants();
1025 if (enumConstants != null) {
1026 for (final T enm : classDescriptor.getEnumConstants()) {
1027 if (((Enum<?>) enm).name().equals(value)) {
1035 private Map<String, String> resolveValuesFromUri(final String uri) {
1036 final Map<String, String> result = new HashMap<>();
1037 final String[] tokens = uri.split("/");
1038 for (int i = 1; i < tokens.length; i++) {
1039 final String[] parameterTokens = tokens[i].split("=");
1040 if (parameterTokens.length == 2) {
1041 result.put(parameterTokens[0], parameterTokens[1]);
1047 public BigInteger getOperationalReceived() {
1048 // TODO Auto-generated method stub
1052 private MapNode makeModuleMapNode(final Set<Module> modules) {
1053 Preconditions.checkNotNull(modules);
1054 final Module restconfModule = getRestconfModule();
1055 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1056 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1057 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1059 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1060 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1062 for (final Module module : modules) {
1063 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1065 return listModuleBuilder.build();
1068 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1069 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1070 "moduleSchemaNode has to be of type ListSchemaNode");
1071 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1072 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1073 .mapEntryBuilder(listModuleSchemaNode);
1075 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1076 (listModuleSchemaNode), "name");
1077 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1078 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1079 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1082 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1083 (listModuleSchemaNode), "revision");
1084 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1085 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1086 final String revision = REVISION_FORMAT.format(module.getRevision());
1087 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1090 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1091 (listModuleSchemaNode), "namespace");
1092 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1093 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1094 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1095 .withValue(module.getNamespace().toString()).build());
1097 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1098 (listModuleSchemaNode), "feature");
1099 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1100 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1101 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1102 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1103 for (final FeatureDefinition feature : module.getFeatures()) {
1104 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1105 .withValue(feature.getQName().getLocalName()).build());
1107 moduleNodeValues.withChild(featuresBuilder.build());
1109 return moduleNodeValues.build();
1112 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1113 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1114 "streamSchemaNode has to be of type ListSchemaNode");
1115 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1116 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1117 .mapEntryBuilder(listStreamSchemaNode);
1119 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1120 (listStreamSchemaNode), "name");
1121 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1122 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1123 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1126 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1127 (listStreamSchemaNode), "description");
1128 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1129 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1130 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1131 .withValue("DESCRIPTION_PLACEHOLDER").build());
1133 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1134 (listStreamSchemaNode), "replay-support");
1135 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1136 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1137 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1138 .withValue(Boolean.valueOf(true)).build());
1140 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1141 (listStreamSchemaNode), "replay-log-creation-time");
1142 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1143 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1144 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1145 .withValue("").build());
1147 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1148 (listStreamSchemaNode), "events");
1149 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1150 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1151 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1152 .withValue("").build());
1154 return streamNodeValues.build();