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.netconf.sal.restconf.impl;
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Predicate;
15 import com.google.common.base.Predicates;
16 import com.google.common.base.Splitter;
17 import com.google.common.base.Strings;
18 import com.google.common.base.Throwables;
19 import com.google.common.collect.Iterables;
20 import com.google.common.collect.Lists;
21 import com.google.common.collect.Maps;
22 import com.google.common.collect.Sets;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
25 import java.math.BigInteger;
27 import java.net.URISyntaxException;
28 import java.text.ParseException;
29 import java.text.SimpleDateFormat;
30 import java.util.ArrayList;
31 import java.util.Collections;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.List;
37 import java.util.concurrent.CancellationException;
38 import java.util.concurrent.ExecutionException;
39 import javax.ws.rs.core.Context;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.Response.ResponseBuilder;
42 import javax.ws.rs.core.Response.Status;
43 import javax.ws.rs.core.UriBuilder;
44 import javax.ws.rs.core.UriInfo;
45 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
46 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
47 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
48 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
49 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
54 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
55 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
56 import org.opendaylight.netconf.sal.rest.api.Draft02;
57 import org.opendaylight.netconf.sal.rest.api.RestconfService;
58 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
60 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
61 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
62 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
63 import org.opendaylight.yangtools.yang.common.QName;
64 import org.opendaylight.yangtools.yang.common.QNameModule;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
69 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
72 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
78 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
79 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
84 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
86 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
93 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
94 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
95 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
96 import org.opendaylight.yangtools.yang.model.util.EmptyType;
97 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
98 import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBuilder;
99 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
100 import org.opendaylight.yangtools.yang.parser.builder.impl.ModuleBuilder;
101 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
105 public class RestconfImpl implements RestconfService {
107 private static final RestconfImpl INSTANCE = new RestconfImpl();
109 private static final int NOTIFICATION_PORT = 8181;
111 private static final int CHAR_NOT_FOUND = -1;
113 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
115 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
117 private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
119 private BrokerFacade broker;
121 private ControllerContext controllerContext;
123 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
125 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
127 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
129 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
131 private static final String DATASTORE_PARAM_NAME = "datastore";
133 private static final String SCOPE_PARAM_NAME = "scope";
135 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
137 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
139 private static final QName NETCONF_BASE_QNAME;
141 private static final QNameModule SAL_REMOTE_AUGMENT;
143 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
147 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
148 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
149 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
150 eventSubscriptionAugRevision);
151 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
152 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
153 } catch (final ParseException e) {
154 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
156 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
157 } catch (final URISyntaxException e) {
158 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
159 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
163 public void setBroker(final BrokerFacade broker) {
164 this.broker = broker;
167 public void setControllerContext(final ControllerContext controllerContext) {
168 this.controllerContext = controllerContext;
171 private RestconfImpl() {
174 public static RestconfImpl getInstance() {
179 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
180 final Set<Module> allModules = controllerContext.getAllModules();
181 final MapNode allModuleMap = makeModuleMapNode(allModules);
183 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
185 final Module restconfModule = getRestconfModule();
186 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
187 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
188 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
190 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
191 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
192 moduleContainerBuilder.withChild(allModuleMap);
194 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
195 null, schemaContext), moduleContainerBuilder.build(),
196 QueryParametersParser.parseWriterParameters(uriInfo));
200 * Valid only for mount point
203 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
204 Preconditions.checkNotNull(identifier);
205 if ( ! identifier.contains(ControllerContext.MOUNT)) {
206 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
207 + " URI has to end with " + ControllerContext.MOUNT;
208 LOG.debug(errMsg + " for " + identifier);
209 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
212 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
213 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
214 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
215 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
217 final Module restconfModule = getRestconfModule();
218 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
219 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
220 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
222 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
223 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
224 moduleContainerBuilder.withChild(mountPointModulesMap);
226 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
227 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
228 QueryParametersParser.parseWriterParameters(uriInfo));
232 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
233 Preconditions.checkNotNull(identifier);
234 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
235 Module module = null;
236 DOMMountPoint mountPoint = null;
237 final SchemaContext schemaContext;
238 if (identifier.contains(ControllerContext.MOUNT)) {
239 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
240 mountPoint = mountPointIdentifier.getMountPoint();
241 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
242 schemaContext = mountPoint.getSchemaContext();
244 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
245 schemaContext = controllerContext.getGlobalSchema();
248 if (module == null) {
249 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
250 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
252 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
255 final Module restconfModule = getRestconfModule();
256 final Set<Module> modules = Collections.singleton(module);
257 final MapNode moduleMap = makeModuleMapNode(modules);
259 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
260 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
261 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
263 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
264 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
268 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
269 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
270 final Set<String> availableStreams = Notificator.getStreamNames();
271 final Module restconfModule = getRestconfModule();
272 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
273 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
274 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
276 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
277 .mapBuilder((ListSchemaNode) streamSchemaNode);
279 for (final String streamName : availableStreams) {
280 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
283 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
284 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
285 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
287 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
288 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
289 streamsContainerBuilder.withChild(listStreamsBuilder.build());
292 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
293 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
297 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
298 final Set<Module> allModules = controllerContext.getAllModules();
299 return operationsFromModulesToNormalizedContext(allModules, null);
303 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
304 Set<Module> modules = null;
305 DOMMountPoint mountPoint = null;
306 if (identifier.contains(ControllerContext.MOUNT)) {
307 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
308 mountPoint = mountPointIdentifier.getMountPoint();
309 modules = controllerContext.getAllModules(mountPoint);
312 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
313 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
314 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
317 return operationsFromModulesToNormalizedContext(modules, mountPoint);
320 private static final Predicate<GroupingBuilder> GROUPING_FILTER = new Predicate<GroupingBuilder>() {
322 public boolean apply(final GroupingBuilder g) {
323 return Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE.equals(g.getQName().getLocalName());
327 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
328 final DOMMountPoint mountPoint) {
330 final Module restconfModule = getRestconfModule();
331 final ModuleBuilder restConfModuleBuilder = new ModuleBuilder(restconfModule);
332 final Set<GroupingBuilder> gropingBuilders = restConfModuleBuilder.getGroupingBuilders();
333 final Iterable<GroupingBuilder> filteredGroups = Iterables.filter(gropingBuilders, GROUPING_FILTER);
334 final GroupingBuilder restconfGroupingBuilder = Iterables.getFirst(filteredGroups, null);
335 final ContainerSchemaNodeBuilder restContainerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restconfGroupingBuilder
336 .getDataChildByName(Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
337 final ContainerSchemaNodeBuilder containerSchemaNodeBuilder = (ContainerSchemaNodeBuilder) restContainerSchemaNodeBuilder
338 .getDataChildByName(Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
340 final ContainerSchemaNodeBuilder fakeOperationsSchemaNodeBuilder = containerSchemaNodeBuilder;
341 final SchemaPath fakeSchemaPath = fakeOperationsSchemaNodeBuilder.getPath().createChild(QName.create("dummy"));
343 final List<LeafNode<Object>> operationsAsData = new ArrayList<>();
345 for (final Module module : modules) {
346 final Set<RpcDefinition> rpcs = module.getRpcs();
347 for (final RpcDefinition rpc : rpcs) {
348 final QName rpcQName = rpc.getQName();
349 final String name = module.getName();
351 final QName qName = QName.create(restconfModule.getQNameModule(), rpcQName.getLocalName());
352 final LeafSchemaNodeBuilder leafSchemaNodeBuilder = new LeafSchemaNodeBuilder(name, 0, qName, fakeSchemaPath);
353 final LeafSchemaNodeBuilder fakeRpcSchemaNodeBuilder = leafSchemaNodeBuilder;
354 fakeRpcSchemaNodeBuilder.setAugmenting(true);
356 final EmptyType instance = EmptyType.getInstance();
357 fakeRpcSchemaNodeBuilder.setType(instance);
358 final LeafSchemaNode fakeRpcSchemaNode = fakeRpcSchemaNodeBuilder.build();
359 fakeOperationsSchemaNodeBuilder.addChildNode(fakeRpcSchemaNode);
361 final LeafNode<Object> leaf = Builders.leafBuilder(fakeRpcSchemaNode).build();
362 operationsAsData.add(leaf);
366 final ContainerSchemaNode operContainerSchemaNode = fakeOperationsSchemaNodeBuilder.build();
367 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> operContainerNode = Builders.containerBuilder(operContainerSchemaNode);
369 for (final LeafNode<Object> oper : operationsAsData) {
370 operContainerNode.withChild(oper);
373 final Set<Module> fakeRpcModules = Collections.singleton(restConfModuleBuilder.build());
375 final YangParserImpl yangParser = new YangParserImpl();
376 final SchemaContext fakeSchemaCx = yangParser.resolveSchemaContext(fakeRpcModules);
378 final InstanceIdentifierContext<?> fakeIICx = new InstanceIdentifierContext<>(null, operContainerSchemaNode, mountPoint, fakeSchemaCx);
380 return new NormalizedNodeContext(fakeIICx, operContainerNode.build());
383 private Module getRestconfModule() {
384 final Module restconfModule = controllerContext.getRestconfModule();
385 if (restconfModule == null) {
386 LOG.debug("ietf-restconf module was not found.");
387 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
388 ErrorTag.OPERATION_NOT_SUPPORTED);
391 return restconfModule;
394 private static QName getModuleNameAndRevision(final String identifier) {
395 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
396 String moduleNameAndRevision = "";
397 if (mountIndex >= 0) {
398 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
400 moduleNameAndRevision = identifier;
403 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
404 final Iterable<String> split = splitter.split(moduleNameAndRevision);
405 final List<String> pathArgs = Lists.<String> newArrayList(split);
406 if (pathArgs.size() < 2) {
407 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
408 throw new RestconfDocumentedException(
409 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
410 ErrorTag.INVALID_VALUE);
414 final String moduleName = pathArgs.get(0);
415 final String revision = pathArgs.get(1);
416 final Date moduleRevision = REVISION_FORMAT.parse(revision);
417 return QName.create(null, moduleRevision, moduleName);
418 } catch (final ParseException e) {
419 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
420 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
421 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
426 public Object getRoot() {
431 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
432 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
433 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
434 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
435 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
436 final SchemaContext schemaContext;
437 if (mountPoint != null) {
438 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
439 if ( ! mountRpcServices.isPresent()) {
440 LOG.debug("Error: Rpc service is missing.");
441 throw new RestconfDocumentedException("Rpc service is missing.");
443 schemaContext = mountPoint.getSchemaContext();
444 response = mountRpcServices.get().invokeRpc(type, payload.getData());
446 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
447 response = invokeSalRemoteRpcSubscribeRPC(payload);
449 response = broker.invokeRpc(type, payload.getData());
451 schemaContext = controllerContext.getGlobalSchema();
454 final DOMRpcResult result = checkRpcResponse(response);
456 RpcDefinition resultNodeSchema = null;
457 final NormalizedNode<?, ?> resultData = result.getResult();
458 if (result != null && result.getResult() != null) {
459 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
462 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
463 resultNodeSchema, mountPoint, schemaContext), resultData,
464 QueryParametersParser.parseWriterParameters(uriInfo));
467 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
468 if (response == null) {
472 final DOMRpcResult retValue = response.get();
473 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
476 LOG.debug("RpcError message", retValue.getErrors());
477 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
478 } catch (final InterruptedException e) {
479 final String errMsg = "The operation was interrupted while executing and did not complete.";
480 LOG.debug("Rpc Interrupt - " + errMsg, e);
481 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
482 } catch (final ExecutionException e) {
483 LOG.debug("Execution RpcError: ", e);
484 Throwable cause = e.getCause();
486 while (cause.getCause() != null) {
487 cause = cause.getCause();
490 if (cause instanceof IllegalArgumentException) {
491 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
492 ErrorTag.INVALID_VALUE);
493 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
494 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
496 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
498 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
500 } catch (final CancellationException e) {
501 final String errMsg = "The operation was cancelled while executing.";
502 LOG.debug("Cancel RpcExecution: " + errMsg, e);
503 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
507 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
508 if (inputSchema != null && payload.getData() == null) {
509 // expected a non null payload
510 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
511 } else if (inputSchema == null && payload.getData() != null) {
512 // did not expect any input
513 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
517 // TODO: Validate "mandatory" and "config" values here??? Or should those be
519 // validate in a more central location inside MD-SAL core.
523 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
524 final ContainerNode value = (ContainerNode) payload.getData();
525 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
526 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
527 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
528 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
530 if (!(pathValue instanceof YangInstanceIdentifier)) {
531 final String errMsg = "Instance identifier was not normalized correctly ";
532 LOG.debug(errMsg + rpcQName);
533 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
536 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
537 String streamName = null;
538 if (!pathIdentifier.isEmpty()) {
539 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
541 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
542 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
544 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
545 scope = scope == null ? DEFAULT_SCOPE : scope;
547 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
548 + "/scope=" + scope);
551 if (Strings.isNullOrEmpty(streamName)) {
552 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
553 LOG.debug(errMsg + pathIdentifier);
554 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
557 final QName outputQname = QName.create(rpcQName, "output");
558 final QName streamNameQname = QName.create(rpcQName, "stream-name");
560 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
561 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
563 if (!Notificator.existListenerFor(streamName)) {
564 Notificator.createListener(pathIdentifier, streamName);
567 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
569 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
573 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
574 if (noPayload != null && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
575 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
578 String identifierEncoded = null;
579 DOMMountPoint mountPoint = null;
580 final SchemaContext schemaContext;
581 if (identifier.contains(ControllerContext.MOUNT)) {
582 // mounted RPC call - look up mount instance.
583 final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
584 mountPoint = mountPointId.getMountPoint();
585 schemaContext = mountPoint.getSchemaContext();
586 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
587 + ControllerContext.MOUNT.length() + 1;
588 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
589 identifierEncoded = remoteRpcName;
591 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
592 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
593 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
594 LOG.debug(slashErrorMsg);
595 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
597 identifierEncoded = identifier;
598 schemaContext = controllerContext.getGlobalSchema();
601 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
603 RpcDefinition rpc = null;
604 if (mountPoint == null) {
605 rpc = controllerContext.getRpcDefinition(identifierDecoded, null);
607 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
611 LOG.debug("RPC " + identifierDecoded + " does not exist.");
612 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
615 if (rpc.getInput() != null) {
616 LOG.debug("RPC " + rpc + " does not need input value.");
617 // FIXME : find a correct Error from specification
618 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
621 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
622 if (mountPoint != null) {
623 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
624 if ( ! mountRpcServices.isPresent()) {
625 throw new RestconfDocumentedException("Rpc service is missing.");
627 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
629 response = broker.invokeRpc(rpc.getPath(), null);
632 final DOMRpcResult result = checkRpcResponse(response);
634 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
635 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
638 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
639 final String[] splittedIdentifier = identifierDecoded.split(":");
640 if (splittedIdentifier.length != 2) {
641 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
643 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
645 for (final Module module : schemaContext.getModules()) {
646 if (module.getName().equals(splittedIdentifier[0])) {
647 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
648 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
649 return rpcDefinition;
658 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
659 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
660 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
661 NormalizedNode<?, ?> data = null;
662 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
663 if (mountPoint != null) {
664 data = broker.readConfigurationData(mountPoint, normalizedII);
666 data = broker.readConfigurationData(normalizedII);
669 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
670 LOG.debug(errMsg + identifier);
671 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
673 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
677 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
678 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
679 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
680 NormalizedNode<?, ?> data = null;
681 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
682 if (mountPoint != null) {
683 data = broker.readOperationalData(mountPoint, normalizedII);
685 data = broker.readOperationalData(normalizedII);
688 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
689 LOG.debug(errMsg + identifier);
690 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
692 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
696 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
697 Preconditions.checkNotNull(identifier);
698 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
700 validateInput(iiWithData.getSchemaNode(), payload);
701 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
702 validateListKeysEqualityInPayloadAndUri(payload);
704 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
705 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
708 * There is a small window where another write transaction could be updating the same data
709 * simultaneously and we get an OptimisticLockFailedException. This error is likely
710 * transient and The WriteTransaction#submit API docs state that a retry will likely
711 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
712 * probably will never succeed so we'll fail in that case.
714 * By retrying we're attempting to hide the internal implementation of the data store and
715 * how it handles concurrent updates from the restconf client. The client has instructed us
716 * to put the data and we should make every effort to do so without pushing optimistic lock
717 * failures back to the client and forcing them to handle it via retry (and having to
718 * document the behavior).
723 if (mountPoint != null) {
724 broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
726 broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
730 } catch (final TransactionCommitFailedException e) {
731 if(e instanceof OptimisticLockFailedException) {
733 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
734 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
737 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
739 LOG.debug("Update ConfigDataStore fail " + identifier, e);
740 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
742 } catch (Exception e) {
743 final String errMsg = "Error updating data ";
744 LOG.debug(errMsg + identifier, e);
745 throw new RestconfDocumentedException(errMsg, e);
749 return Response.status(Status.OK).build();
752 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
753 final YangInstanceIdentifier identifier) {
755 final String payloadName = node.getData().getNodeType().getLocalName();
758 if (identifier.isEmpty()) {
760 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
761 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
762 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
766 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
767 if (!payloadName.equals(identifierName)) {
768 throw new RestconfDocumentedException("Payload name (" + payloadName
769 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
770 ErrorTag.MALFORMED_MESSAGE);
776 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
778 * @throws RestconfDocumentedException
779 * if key values or key count in payload and URI isn't equal
782 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
783 Preconditions.checkArgument(payload != null);
784 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
785 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
786 final SchemaNode schemaNode = iiWithData.getSchemaNode();
787 final NormalizedNode<?, ?> data = payload.getData();
788 if (schemaNode instanceof ListSchemaNode) {
789 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
790 if (lastPathArgument instanceof NodeIdentifierWithPredicates && data instanceof MapEntryNode) {
791 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
792 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
797 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
798 final MapEntryNode payload, final List<QName> keyDefinitions) {
800 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
801 for (final QName keyDefinition : keyDefinitions) {
802 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
803 // should be caught during parsing URI to InstanceIdentifier
804 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
805 "Missing key " + keyDefinition + " in URI.");
807 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
809 if ( ! uriKeyValue.equals(dataKeyValue)) {
810 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
811 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
812 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
818 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
819 return createConfigurationData(payload, uriInfo);
822 // FIXME create RestconfIdetifierHelper and move this method there
823 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
824 Preconditions.checkArgument(payload != null);
825 Preconditions.checkArgument(payload.getData() != null);
826 Preconditions.checkArgument(payload.getData().getNodeType() != null);
827 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
828 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
830 final QName payloadNodeQname = payload.getData().getNodeType();
831 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
832 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
835 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
836 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
837 if(parentSchemaNode instanceof DataNodeContainer) {
838 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
839 for (final DataSchemaNode child : cast.getChildNodes()) {
840 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
841 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
845 if (parentSchemaNode instanceof RpcDefinition) {
848 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
849 LOG.info(errMsg + yangIdent);
850 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
854 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
855 if (payload == null) {
856 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
859 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
860 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
861 // if (payloadNS == null) {
862 // throw new RestconfDocumentedException(
863 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
864 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
867 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
868 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
869 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
871 if (mountPoint != null) {
872 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
874 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
876 } catch(final RestconfDocumentedException e) {
878 } catch (final Exception e) {
879 final String errMsg = "Error creating data ";
880 LOG.info(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), e);
881 throw new RestconfDocumentedException(errMsg, e);
884 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
885 // FIXME: Provide path to result.
886 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
887 if (location != null) {
888 responseBuilder.location(location);
890 return responseBuilder.build();
893 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
894 if(uriInfo == null) {
895 // This is null if invoked internally
899 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
900 uriBuilder.path("config");
902 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
903 } catch (final Exception e) {
904 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
907 return uriBuilder.build();
911 public Response deleteConfigurationData(final String identifier) {
912 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
913 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
914 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
917 if (mountPoint != null) {
918 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
920 broker.commitConfigurationDataDelete(normalizedII).get();
922 } catch (final Exception e) {
923 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
924 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
925 if (searchedException.isPresent()) {
926 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
928 final String errMsg = "Error while deleting data";
930 throw new RestconfDocumentedException(errMsg, e);
932 return Response.status(Status.OK).build();
936 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
938 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
940 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
941 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
945 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
946 final String streamName = Notificator.createStreamNameFromUri(identifier);
947 if (Strings.isNullOrEmpty(streamName)) {
948 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
951 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
952 if (listener == null) {
953 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
956 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
957 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
958 paramToValues.get(DATASTORE_PARAM_NAME));
959 if (datastore == null) {
960 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
961 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
963 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
965 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
966 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
969 broker.registerToListenDataChanges(datastore, scope, listener);
971 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
972 int notificationPort = NOTIFICATION_PORT;
974 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
975 notificationPort = webSocketServerInstance.getPort();
976 } catch (final NullPointerException e) {
977 WebSocketServer.createInstance(NOTIFICATION_PORT);
979 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
980 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
982 return Response.status(Status.OK).location(uriToWebsocketServer).build();
986 public PATCHStatusContext patchConfigurationData(String identifier, PATCHContext context, UriInfo uriInfo) {
987 if (context == null) {
988 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
990 return broker.patchConfigurationDataWithinTransaction(context, controllerContext.getGlobalSchema());
994 public PATCHStatusContext patchConfigurationData(PATCHContext context, @Context UriInfo uriInfo) {
995 if (context == null) {
996 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
998 return broker.patchConfigurationDataWithinTransaction(context, controllerContext.getGlobalSchema());
1002 * Load parameter for subscribing to stream from input composite node
1006 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1008 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1009 final String paramName) {
1010 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1011 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1014 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1015 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1016 if (!enumNode.isPresent()) {
1019 final Object rawValue = enumNode.get().getValue();
1020 if (!(rawValue instanceof String)) {
1024 return resolveAsEnum(classDescriptor, (String) rawValue);
1028 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1030 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1033 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1034 if (Strings.isNullOrEmpty(value)) {
1037 return resolveAsEnum(classDescriptor, value);
1040 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1041 final T[] enumConstants = classDescriptor.getEnumConstants();
1042 if (enumConstants != null) {
1043 for (final T enm : classDescriptor.getEnumConstants()) {
1044 if (((Enum<?>) enm).name().equals(value)) {
1052 private static Map<String, String> resolveValuesFromUri(final String uri) {
1053 final Map<String, String> result = new HashMap<>();
1054 final String[] tokens = uri.split("/");
1055 for (int i = 1; i < tokens.length; i++) {
1056 final String[] parameterTokens = tokens[i].split("=");
1057 if (parameterTokens.length == 2) {
1058 result.put(parameterTokens[0], parameterTokens[1]);
1064 public BigInteger getOperationalReceived() {
1065 // TODO Auto-generated method stub
1069 private MapNode makeModuleMapNode(final Set<Module> modules) {
1070 Preconditions.checkNotNull(modules);
1071 final Module restconfModule = getRestconfModule();
1072 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1073 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1074 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1076 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1077 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1079 for (final Module module : modules) {
1080 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1082 return listModuleBuilder.build();
1085 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1086 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1087 "moduleSchemaNode has to be of type ListSchemaNode");
1088 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1089 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1090 .mapEntryBuilder(listModuleSchemaNode);
1092 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1093 (listModuleSchemaNode), "name");
1094 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1095 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1096 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1099 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1100 (listModuleSchemaNode), "revision");
1101 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1102 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1103 final String revision = REVISION_FORMAT.format(module.getRevision());
1104 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1107 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1108 (listModuleSchemaNode), "namespace");
1109 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1110 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1111 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1112 .withValue(module.getNamespace().toString()).build());
1114 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1115 (listModuleSchemaNode), "feature");
1116 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1117 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1118 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1119 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1120 for (final FeatureDefinition feature : module.getFeatures()) {
1121 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1122 .withValue(feature.getQName().getLocalName()).build());
1124 moduleNodeValues.withChild(featuresBuilder.build());
1126 return moduleNodeValues.build();
1129 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1130 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1131 "streamSchemaNode has to be of type ListSchemaNode");
1132 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1133 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1134 .mapEntryBuilder(listStreamSchemaNode);
1136 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1137 (listStreamSchemaNode), "name");
1138 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1139 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1140 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1143 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1144 (listStreamSchemaNode), "description");
1145 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1146 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1147 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1148 .withValue("DESCRIPTION_PLACEHOLDER").build());
1150 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1151 (listStreamSchemaNode), "replay-support");
1152 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1153 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1154 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1155 .withValue(Boolean.valueOf(true)).build());
1157 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1158 (listStreamSchemaNode), "replay-log-creation-time");
1159 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1160 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1161 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1162 .withValue("").build());
1164 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1165 (listStreamSchemaNode), "events");
1166 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1167 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1168 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1169 .withValue("").build());
1171 return streamNodeValues.build();