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.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 enum UriParameters {
107 PRETTY_PRINT("prettyPrint"),
110 private String uriParameterName;
112 UriParameters(final String uriParameterName) {
113 this.uriParameterName = uriParameterName;
117 public String toString() {
118 return uriParameterName;
122 private static final RestconfImpl INSTANCE = new RestconfImpl();
124 private static final int NOTIFICATION_PORT = 8181;
126 private static final int CHAR_NOT_FOUND = -1;
128 private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
130 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
132 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
134 private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
136 private BrokerFacade broker;
138 private ControllerContext controllerContext;
140 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
142 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
144 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
146 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
148 private static final String DATASTORE_PARAM_NAME = "datastore";
150 private static final String SCOPE_PARAM_NAME = "scope";
152 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
154 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
156 private static final QName NETCONF_BASE_QNAME;
158 private static final QNameModule SAL_REMOTE_AUGMENT;
160 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
164 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
165 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
166 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
167 eventSubscriptionAugRevision);
168 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
169 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
170 } catch (final ParseException e) {
171 throw new RestconfDocumentedException(
172 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
173 ErrorTag.OPERATION_FAILED);
174 } catch (final URISyntaxException e) {
175 throw new RestconfDocumentedException(
176 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
177 ErrorTag.OPERATION_FAILED);
181 public void setBroker(final BrokerFacade broker) {
182 this.broker = broker;
185 public void setControllerContext(final ControllerContext controllerContext) {
186 this.controllerContext = controllerContext;
189 private RestconfImpl() {
192 public static RestconfImpl getInstance() {
197 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
198 final Set<Module> allModules = controllerContext.getAllModules();
199 final MapNode allModuleMap = makeModuleMapNode(allModules);
201 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
203 final Module restconfModule = getRestconfModule();
204 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
205 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
206 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
208 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
209 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
210 moduleContainerBuilder.withChild(allModuleMap);
212 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
213 null, schemaContext), moduleContainerBuilder.build());
217 * Valid only for mount point
220 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
221 Preconditions.checkNotNull(identifier);
222 if ( ! identifier.contains(ControllerContext.MOUNT)) {
223 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
224 + " URI has to end with " + ControllerContext.MOUNT;
225 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
228 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
229 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
230 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
231 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
233 final Module restconfModule = getRestconfModule();
234 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
235 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
236 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
238 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
239 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
240 moduleContainerBuilder.withChild(mountPointModulesMap);
242 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
243 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build());
247 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
248 Preconditions.checkNotNull(identifier);
249 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
250 Module module = null;
251 DOMMountPoint mountPoint = null;
252 final SchemaContext schemaContext;
253 if (identifier.contains(ControllerContext.MOUNT)) {
254 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
255 mountPoint = mountPointIdentifier.getMountPoint();
256 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
257 schemaContext = mountPoint.getSchemaContext();
259 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
260 schemaContext = controllerContext.getGlobalSchema();
263 if (module == null) {
264 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
265 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
266 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
269 final Module restconfModule = getRestconfModule();
270 final Set<Module> modules = Collections.singleton(module);
271 final MapNode moduleMap = makeModuleMapNode(modules);
273 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
274 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
275 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
277 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
278 schemaContext), moduleMap);
282 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
283 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
284 final Set<String> availableStreams = Notificator.getStreamNames();
285 final Module restconfModule = getRestconfModule();
286 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
287 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
288 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
290 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
291 .mapBuilder((ListSchemaNode) streamSchemaNode);
293 for (final String streamName : availableStreams) {
294 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
297 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
298 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
299 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
301 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
302 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
303 streamsContainerBuilder.withChild(listStreamsBuilder.build());
306 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
307 schemaContext), streamsContainerBuilder.build());
311 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
312 final Set<Module> allModules = controllerContext.getAllModules();
313 return operationsFromModulesToNormalizedContext(allModules, null);
317 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
318 Set<Module> modules = null;
319 DOMMountPoint mountPoint = null;
320 if (identifier.contains(ControllerContext.MOUNT)) {
321 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
322 mountPoint = mountPointIdentifier.getMountPoint();
323 modules = controllerContext.getAllModules(mountPoint);
326 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
327 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
330 return operationsFromModulesToNormalizedContext(modules, mountPoint);
333 private static final Predicate<GroupingBuilder> GROUPING_FILTER = new Predicate<GroupingBuilder>() {
335 public boolean apply(final GroupingBuilder g) {
336 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
340 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
341 final DOMMountPoint mountPoint) {
343 final Module restconfModule = getRestconfModule();
344 final ModuleBuilder restConfModuleBuilder = new ModuleBuilder(restconfModule);
345 final Set<GroupingBuilder> gropingBuilders = restConfModuleBuilder.getGroupingBuilders();
346 final Iterable<GroupingBuilder> filteredGroups = Iterables.filter(gropingBuilders, GROUPING_FILTER);
347 final GroupingBuilder restconfGroupingBuilder = Iterables.getFirst(filteredGroups, null);
348 final ContainerSchemaNodeBuilder restContainerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restconfGroupingBuilder
349 .getDataChildByName(Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
350 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restContainerSchemaNodeBuilder
351 .getDataChildByName(Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
353 final ContainerSchemaNodeBuilder fakeOperationsSchemaNodeBuilder = containerSchemaNodeBuilder;
354 final SchemaPath fakeSchemaPath = fakeOperationsSchemaNodeBuilder.getPath().createChild(QName.create("dummy"));
356 final List<LeafNode<Object>> operationsAsData = new ArrayList<>();
358 for (final Module module : modules) {
359 final Set<RpcDefinition> rpcs = module.getRpcs();
360 for (final RpcDefinition rpc : rpcs) {
361 final QName rpcQName = rpc.getQName();
362 final String name = module.getName();
364 final QName qName = QName.create(restconfModule.getQNameModule(), rpcQName.getLocalName());
365 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, qName, fakeSchemaPath);
366 final LeafSchemaNodeBuilder fakeRpcSchemaNodeBuilder = leafSchemaNodeBuilder;
367 fakeRpcSchemaNodeBuilder.setAugmenting(true);
369 final EmptyType instance = EmptyType.getInstance();
370 fakeRpcSchemaNodeBuilder.setType(instance);
371 final LeafSchemaNode fakeRpcSchemaNode = fakeRpcSchemaNodeBuilder.build();
372 fakeOperationsSchemaNodeBuilder.addChildNode(fakeRpcSchemaNode);
374 final LeafNode<Object> leaf = Builders.leafBuilder(fakeRpcSchemaNode).build();
375 operationsAsData.add(leaf);
379 final ContainerSchemaNode operContainerSchemaNode = fakeOperationsSchemaNodeBuilder.build();
380 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> operContainerNode = Builders.containerBuilder(operContainerSchemaNode);
382 for (final LeafNode<Object> oper : operationsAsData) {
383 operContainerNode.withChild(oper);
386 final Set<Module> fakeRpcModules = Collections.singleton(restConfModuleBuilder.build());
388 final YangParserImpl yangParser = new YangParserImpl();
389 final SchemaContext fakeSchemaCx = yangParser.resolveSchemaContext(fakeRpcModules);
391 final InstanceIdentifierContext<?> fakeIICx = new InstanceIdentifierContext<>(null, operContainerSchemaNode, mountPoint, fakeSchemaCx);
393 return new NormalizedNodeContext(fakeIICx, operContainerNode.build());
396 private Module getRestconfModule() {
397 final Module restconfModule = controllerContext.getRestconfModule();
398 if (restconfModule == null) {
399 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
400 ErrorTag.OPERATION_NOT_SUPPORTED);
403 return restconfModule;
406 private QName getModuleNameAndRevision(final String identifier) {
407 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
408 String moduleNameAndRevision = "";
409 if (mountIndex >= 0) {
410 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
412 moduleNameAndRevision = identifier;
415 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
416 final Iterable<String> split = splitter.split(moduleNameAndRevision);
417 final List<String> pathArgs = Lists.<String> newArrayList(split);
418 if (pathArgs.size() < 2) {
419 throw new RestconfDocumentedException(
420 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
421 ErrorTag.INVALID_VALUE);
425 final String moduleName = pathArgs.get(0);
426 final String revision = pathArgs.get(1);
427 final Date moduleRevision = REVISION_FORMAT.parse(revision);
428 return QName.create(null, moduleRevision, moduleName);
429 } catch (final ParseException e) {
430 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
431 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
436 public Object getRoot() {
441 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
442 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
443 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
444 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
445 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
446 final SchemaContext schemaContext;
447 if (identifier.contains(MOUNT_POINT_MODULE_NAME) && mountPoint != null) {
448 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
449 if ( ! mountRpcServices.isPresent()) {
450 throw new RestconfDocumentedException("Rpc service is missing.");
452 schemaContext = mountPoint.getSchemaContext();
453 response = mountRpcServices.get().invokeRpc(type, payload.getData());
455 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
456 response = invokeSalRemoteRpcSubscribeRPC(payload);
458 response = broker.invokeRpc(type, payload.getData());
460 schemaContext = controllerContext.getGlobalSchema();
463 final DOMRpcResult result = checkRpcResponse(response);
465 RpcDefinition resultNodeSchema = null;
466 final NormalizedNode<?, ?> resultData = result.getResult();
467 if (result != null && result.getResult() != null) {
468 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
471 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
472 resultNodeSchema, mountPoint, schemaContext), resultData);
475 private DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
476 if (response == null) {
480 final DOMRpcResult retValue = response.get();
481 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
484 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
485 } catch (final InterruptedException e) {
486 throw new RestconfDocumentedException(
487 "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
488 ErrorTag.PARTIAL_OPERATION);
489 } catch (final ExecutionException e) {
490 Throwable cause = e.getCause();
492 while (cause.getCause() != null) {
493 cause = cause.getCause();
496 if (cause instanceof IllegalArgumentException) {
497 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
498 ErrorTag.INVALID_VALUE);
501 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
504 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
507 } catch (final CancellationException e) {
508 throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
509 ErrorTag.PARTIAL_OPERATION);
513 private void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
514 if (inputSchema != null && payload.getData() == null) {
515 // expected a non null payload
516 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
517 } else if (inputSchema == null && payload.getData() != null) {
518 // did not expect any input
519 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
523 // TODO: Validate "mandatory" and "config" values here??? Or should those be
525 // validate in a more central location inside MD-SAL core.
529 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
530 final ContainerNode value = (ContainerNode) payload.getData();
531 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
532 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
533 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
534 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
536 if (!(pathValue instanceof YangInstanceIdentifier)) {
537 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
538 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
541 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
542 String streamName = null;
543 if (!pathIdentifier.isEmpty()) {
544 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
546 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
547 DATASTORE_PARAM_NAME);
548 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
550 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
551 scope = scope == null ? DEFAULT_SCOPE : scope;
553 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
554 + "/scope=" + scope);
557 if (Strings.isNullOrEmpty(streamName)) {
558 throw new RestconfDocumentedException(
559 "Path is empty or contains value node which is not Container or List build-in type.",
560 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
563 final QName outputQname = QName.create(rpcQName, "output");
564 final QName streamNameQname = QName.create(rpcQName, "stream-name");
566 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
567 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
569 if (!Notificator.existListenerFor(streamName)) {
570 Notificator.createListener(pathIdentifier, streamName);
573 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
575 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
579 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
580 if (StringUtils.isNotBlank(noPayload)) {
581 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
584 String identifierEncoded = null;
585 DOMMountPoint mountPoint = null;
586 final SchemaContext schemaContext;
587 if (identifier.contains(ControllerContext.MOUNT)) {
588 // mounted RPC call - look up mount instance.
589 final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
590 mountPoint = mountPointId.getMountPoint();
591 schemaContext = mountPoint.getSchemaContext();
592 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
593 + ControllerContext.MOUNT.length() + 1;
594 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
595 identifierEncoded = remoteRpcName;
597 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
598 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
599 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
600 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
602 identifierEncoded = identifier;
603 schemaContext = controllerContext.getGlobalSchema();
606 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
608 RpcDefinition rpc = null;
609 if (mountPoint == null) {
610 rpc = controllerContext.getRpcDefinition(identifierDecoded);
612 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
616 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
619 if (rpc.getInput() != null) {
620 // FIXME : find a correct Error from specification
621 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
624 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
625 if (mountPoint != null) {
626 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
627 if ( ! mountRpcServices.isPresent()) {
628 throw new RestconfDocumentedException("Rpc service is missing.");
630 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
632 response = broker.invokeRpc(rpc.getPath(), null);
635 final DOMRpcResult result = checkRpcResponse(response);
637 DataSchemaNode resultNodeSchema = null;
638 NormalizedNode<?, ?> resultData = null;
639 if (result != null && result.getResult() != null) {
640 resultData = result.getResult();
641 final ContainerSchemaNode rpcDataSchemaNode =
642 SchemaContextUtil.getRpcDataSchema(schemaContext, rpc.getOutput().getPath());
643 resultNodeSchema = rpcDataSchemaNode.getDataChildByName(result.getResult().getNodeType());
646 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint,
647 schemaContext), resultData);
650 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
651 final String[] splittedIdentifier = identifierDecoded.split(":");
652 if (splittedIdentifier.length != 2) {
653 throw new RestconfDocumentedException(identifierDecoded
654 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
655 ErrorTag.INVALID_VALUE);
657 for (final Module module : schemaContext.getModules()) {
658 if (module.getName().equals(splittedIdentifier[0])) {
659 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
660 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
661 return rpcDefinition;
670 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
671 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
672 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
673 NormalizedNode<?, ?> data = null;
674 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
675 if (mountPoint != null) {
676 data = broker.readConfigurationData(mountPoint, normalizedII);
678 data = broker.readConfigurationData(normalizedII);
681 throw new RestconfDocumentedException(
682 "Request could not be completed because the relevant data model content does not exist.",
683 ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
685 return new NormalizedNodeContext(iiWithData, data);
688 // FIXME: Move this to proper place
689 @SuppressWarnings("unused")
690 private Integer parseDepthParameter(final UriInfo info) {
691 final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
692 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
697 final Integer depth = Integer.valueOf(param);
699 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
700 "Invalid depth parameter: " + depth, null,
701 "The depth parameter must be an integer > 1 or \"unbounded\""));
705 } catch (final NumberFormatException e) {
706 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
707 "Invalid depth parameter: " + e.getMessage(), null,
708 "The depth parameter must be an integer > 1 or \"unbounded\""));
713 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
714 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
715 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
716 NormalizedNode<?, ?> data = null;
717 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
718 if (mountPoint != null) {
719 data = broker.readOperationalData(mountPoint, normalizedII);
721 data = broker.readOperationalData(normalizedII);
724 throw new RestconfDocumentedException(
725 "Request could not be completed because the relevant data model content does not exist.",
726 ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
728 return new NormalizedNodeContext(iiWithData, data);
732 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
733 Preconditions.checkNotNull(identifier);
734 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
736 validateInput(iiWithData.getSchemaNode(), payload);
737 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
738 validateListKeysEqualityInPayloadAndUri(payload);
740 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
741 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
744 * There is a small window where another write transaction could be updating the same data
745 * simultaneously and we get an OptimisticLockFailedException. This error is likely
746 * transient and The WriteTransaction#submit API docs state that a retry will likely
747 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
748 * probably will never succeed so we'll fail in that case.
750 * By retrying we're attempting to hide the internal implementation of the data store and
751 * how it handles concurrent updates from the restconf client. The client has instructed us
752 * to put the data and we should make every effort to do so without pushing optimistic lock
753 * failures back to the client and forcing them to handle it via retry (and having to
754 * document the behavior).
759 if (mountPoint != null) {
760 broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
762 broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
766 } catch (final TransactionCommitFailedException e) {
767 if(e instanceof OptimisticLockFailedException) {
769 LOG.debug("Got OptimisticLockFailedException on last try - failing");
770 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
773 LOG.debug("Got OptimisticLockFailedException - trying again");
775 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
780 return Response.status(Status.OK).build();
783 private void validateTopLevelNodeName(final NormalizedNodeContext node,
784 final YangInstanceIdentifier identifier) {
786 final String payloadName = node.getData().getNodeType().getLocalName();
789 if (identifier.isEmpty()) {
791 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
792 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
793 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
797 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
798 if (!payloadName.equals(identifierName)) {
799 throw new RestconfDocumentedException("Payload name (" + payloadName
800 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
801 ErrorTag.MALFORMED_MESSAGE);
807 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
809 * @throws RestconfDocumentedException
810 * if key values or key count in payload and URI isn't equal
813 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
814 Preconditions.checkArgument(payload != null);
815 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
816 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
817 final SchemaNode schemaNode = iiWithData.getSchemaNode();
818 final NormalizedNode<?, ?> data = payload.getData();
819 if (schemaNode instanceof ListSchemaNode) {
820 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
821 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
822 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
823 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
828 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
829 final MapEntryNode payload, final List<QName> keyDefinitions) {
831 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
832 for (final QName keyDefinition : keyDefinitions) {
833 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
834 // should be caught during parsing URI to InstanceIdentifier
835 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
836 "Missing key " + keyDefinition + " in URI.");
838 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
840 if ( ! uriKeyValue.equals(dataKeyValue)) {
841 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
842 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
843 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
849 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
850 return createConfigurationData(payload, uriInfo);
853 // FIXME create RestconfIdetifierHelper and move this method there
854 private YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
855 Preconditions.checkArgument(payload != null);
856 Preconditions.checkArgument(payload.getData() != null);
857 Preconditions.checkArgument(payload.getData().getNodeType() != null);
858 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
859 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
861 final QName payloadNodeQname = payload.getData().getNodeType();
862 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
863 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
866 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
867 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
868 if(parentSchemaNode instanceof DataNodeContainer) {
869 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
870 for (final DataSchemaNode child : cast.getChildNodes()) {
871 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
872 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
876 if (parentSchemaNode instanceof RpcDefinition) {
879 final String errMsg = "Error parsing input: DataSchemaNode has not children";
880 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
884 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
885 if (payload == null) {
886 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
889 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
890 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
891 // if (payloadNS == null) {
892 // throw new RestconfDocumentedException(
893 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
894 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
897 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
898 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
899 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
901 if (mountPoint != null) {
902 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
904 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
906 } catch(final RestconfDocumentedException e) {
908 } catch (final Exception e) {
909 throw new RestconfDocumentedException("Error creating data", e);
912 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
913 // FIXME: Provide path to result.
914 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
915 if (location != null) {
916 responseBuilder.location(location);
918 return responseBuilder.build();
921 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
922 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
923 uriBuilder.path("config");
925 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
926 } catch (final Exception e) {
927 LOG.debug("Location for instance identifier"+normalizedII+"wasn't created", e);
930 return uriBuilder.build();
934 public Response deleteConfigurationData(final String identifier) {
935 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
936 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
937 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
940 if (mountPoint != null) {
941 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
943 broker.commitConfigurationDataDelete(normalizedII).get();
945 } catch (final Exception e) {
946 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
947 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
948 if (searchedException.isPresent()) {
949 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
951 throw new RestconfDocumentedException("Error while deleting data", e);
953 return Response.status(Status.OK).build();
957 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
959 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
961 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
962 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
966 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
967 final String streamName = Notificator.createStreamNameFromUri(identifier);
968 if (Strings.isNullOrEmpty(streamName)) {
969 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
972 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
973 if (listener == null) {
974 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
977 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
978 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
979 paramToValues.get(DATASTORE_PARAM_NAME));
980 if (datastore == null) {
981 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
982 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
984 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
986 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
987 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
990 broker.registerToListenDataChanges(datastore, scope, listener);
992 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
993 int notificationPort = NOTIFICATION_PORT;
995 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
996 notificationPort = webSocketServerInstance.getPort();
997 } catch (final NullPointerException e) {
998 WebSocketServer.createInstance(NOTIFICATION_PORT);
1000 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1001 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1003 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1007 * Load parameter for subscribing to stream from input composite node
1011 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1013 private <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1014 final String paramName) {
1015 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1016 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1019 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1020 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1021 if (!enumNode.isPresent()) {
1024 final Object rawValue = enumNode.get().getValue();
1025 if (!(rawValue instanceof String)) {
1029 return resolveAsEnum(classDescriptor, (String) rawValue);
1033 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1035 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1038 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1039 if (Strings.isNullOrEmpty(value)) {
1042 return resolveAsEnum(classDescriptor, value);
1045 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1046 final T[] enumConstants = classDescriptor.getEnumConstants();
1047 if (enumConstants != null) {
1048 for (final T enm : classDescriptor.getEnumConstants()) {
1049 if (((Enum<?>) enm).name().equals(value)) {
1057 private Map<String, String> resolveValuesFromUri(final String uri) {
1058 final Map<String, String> result = new HashMap<>();
1059 final String[] tokens = uri.split("/");
1060 for (int i = 1; i < tokens.length; i++) {
1061 final String[] parameterTokens = tokens[i].split("=");
1062 if (parameterTokens.length == 2) {
1063 result.put(parameterTokens[0], parameterTokens[1]);
1069 public BigInteger getOperationalReceived() {
1070 // TODO Auto-generated method stub
1074 private MapNode makeModuleMapNode(final Set<Module> modules) {
1075 Preconditions.checkNotNull(modules);
1076 final Module restconfModule = getRestconfModule();
1077 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1078 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1079 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1081 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1082 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1084 for (final Module module : modules) {
1085 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1087 return listModuleBuilder.build();
1090 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1091 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1092 "moduleSchemaNode has to be of type ListSchemaNode");
1093 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1094 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1095 .mapEntryBuilder(listModuleSchemaNode);
1097 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1098 (listModuleSchemaNode), "name");
1099 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1100 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1101 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1104 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1105 (listModuleSchemaNode), "revision");
1106 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1107 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1108 final String revision = REVISION_FORMAT.format(module.getRevision());
1109 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1112 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1113 (listModuleSchemaNode), "namespace");
1114 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1115 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1116 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1117 .withValue(module.getNamespace().toString()).build());
1119 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1120 (listModuleSchemaNode), "feature");
1121 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1122 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1123 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1124 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1125 for (final FeatureDefinition feature : module.getFeatures()) {
1126 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1127 .withValue(feature.getQName().getLocalName()).build());
1129 moduleNodeValues.withChild(featuresBuilder.build());
1131 return moduleNodeValues.build();
1134 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1135 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1136 "streamSchemaNode has to be of type ListSchemaNode");
1137 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1138 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1139 .mapEntryBuilder(listStreamSchemaNode);
1141 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1142 (listStreamSchemaNode), "name");
1143 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1144 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1145 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1148 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1149 (listStreamSchemaNode), "description");
1150 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1151 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1152 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1153 .withValue("DESCRIPTION_PLACEHOLDER").build());
1155 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1156 (listStreamSchemaNode), "replay-support");
1157 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1158 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1159 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1160 .withValue(Boolean.valueOf(true)).build());
1162 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1163 (listStreamSchemaNode), "replay-log-creation-time");
1164 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1165 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1166 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1167 .withValue("").build());
1169 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1170 (listStreamSchemaNode), "events");
1171 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1172 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1173 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1174 .withValue("").build());
1176 return streamNodeValues.build();