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.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.Collection;
31 import java.util.Collections;
32 import java.util.Date;
33 import java.util.HashMap;
34 import java.util.Iterator;
35 import java.util.List;
38 import java.util.concurrent.CancellationException;
39 import java.util.concurrent.ExecutionException;
40 import javax.ws.rs.core.Context;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.Response.ResponseBuilder;
43 import javax.ws.rs.core.Response.Status;
44 import javax.ws.rs.core.UriBuilder;
45 import javax.ws.rs.core.UriInfo;
46 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
47 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
48 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
49 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
52 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
53 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
54 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
55 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
56 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
57 import org.opendaylight.netconf.sal.rest.api.Draft02;
58 import org.opendaylight.netconf.sal.rest.api.RestconfService;
59 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
60 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
61 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
62 import org.opendaylight.netconf.sal.streams.listeners.NotificationListenerAdapter;
63 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
64 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
65 import org.opendaylight.yangtools.yang.common.QName;
66 import org.opendaylight.yangtools.yang.common.QNameModule;
67 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
68 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
69 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
70 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
71 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
74 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
75 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
76 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
77 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
78 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
79 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
80 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
81 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
85 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
86 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
88 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
90 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
93 import org.opendaylight.yangtools.yang.model.api.Module;
94 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
95 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
99 import org.slf4j.Logger;
100 import org.slf4j.LoggerFactory;
102 public class RestconfImpl implements RestconfService {
104 private static final RestconfImpl INSTANCE = new RestconfImpl();
107 * Notifications are served on port 8181.
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 BrokerFacade broker;
119 private ControllerContext controllerContext;
121 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
123 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
125 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
127 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
129 private static final String DATASTORE_PARAM_NAME = "datastore";
131 private static final String SCOPE_PARAM_NAME = "scope";
133 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
135 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
137 private static final QName NETCONF_BASE_QNAME;
139 private static final QNameModule SAL_REMOTE_AUGMENT;
141 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
143 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
144 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
146 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
147 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
151 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
152 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
153 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
154 eventSubscriptionAugRevision);
155 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
156 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
157 } catch (final ParseException e) {
158 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
160 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
161 } catch (final URISyntaxException e) {
162 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
163 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
167 public void setBroker(final BrokerFacade broker) {
168 this.broker = broker;
171 public void setControllerContext(final ControllerContext controllerContext) {
172 this.controllerContext = controllerContext;
175 private RestconfImpl() {
178 public static RestconfImpl getInstance() {
183 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
184 final Set<Module> allModules = this.controllerContext.getAllModules();
185 final MapNode allModuleMap = makeModuleMapNode(allModules);
187 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
189 final Module restconfModule = getRestconfModule();
190 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
191 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
192 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
194 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
195 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
196 moduleContainerBuilder.withChild(allModuleMap);
198 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
199 null, schemaContext), moduleContainerBuilder.build(),
200 QueryParametersParser.parseWriterParameters(uriInfo));
204 * Valid only for mount point
207 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
208 Preconditions.checkNotNull(identifier);
209 if ( ! identifier.contains(ControllerContext.MOUNT)) {
210 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
211 + " URI has to end with " + ControllerContext.MOUNT;
212 LOG.debug(errMsg + " for " + identifier);
213 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
216 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
217 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
218 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
219 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
221 final Module restconfModule = getRestconfModule();
222 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
223 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
224 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
226 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
227 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
228 moduleContainerBuilder.withChild(mountPointModulesMap);
230 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
231 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
232 QueryParametersParser.parseWriterParameters(uriInfo));
236 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
237 Preconditions.checkNotNull(identifier);
238 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
239 Module module = null;
240 DOMMountPoint mountPoint = null;
241 final SchemaContext schemaContext;
242 if (identifier.contains(ControllerContext.MOUNT)) {
243 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
244 mountPoint = mountPointIdentifier.getMountPoint();
245 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
246 schemaContext = mountPoint.getSchemaContext();
248 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
249 schemaContext = this.controllerContext.getGlobalSchema();
252 if (module == null) {
253 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
254 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
256 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
259 final Module restconfModule = getRestconfModule();
260 final Set<Module> modules = Collections.singleton(module);
261 final MapNode moduleMap = makeModuleMapNode(modules);
263 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
264 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
265 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
267 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
268 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
272 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
273 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
274 final Set<String> availableStreams = Notificator.getStreamNames();
275 final Module restconfModule = getRestconfModule();
276 final DataSchemaNode streamSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
277 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
278 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
280 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
281 .mapBuilder((ListSchemaNode) streamSchemaNode);
283 for (final String streamName : availableStreams) {
284 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
287 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
288 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
289 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
291 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
292 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
293 streamsContainerBuilder.withChild(listStreamsBuilder.build());
296 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
297 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
301 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
302 final Set<Module> allModules = this.controllerContext.getAllModules();
303 return operationsFromModulesToNormalizedContext(allModules, null);
307 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
308 Set<Module> modules = null;
309 DOMMountPoint mountPoint = null;
310 if (identifier.contains(ControllerContext.MOUNT)) {
311 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
312 mountPoint = mountPointIdentifier.getMountPoint();
313 modules = this.controllerContext.getAllModules(mountPoint);
316 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
317 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
318 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
321 return operationsFromModulesToNormalizedContext(modules, mountPoint);
324 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
325 final DOMMountPoint mountPoint) {
326 throw new UnsupportedOperationException();
329 private Module getRestconfModule() {
330 final Module restconfModule = this.controllerContext.getRestconfModule();
331 if (restconfModule == null) {
332 LOG.debug("ietf-restconf module was not found.");
333 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
334 ErrorTag.OPERATION_NOT_SUPPORTED);
337 return restconfModule;
340 private static QName getModuleNameAndRevision(final String identifier) {
341 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
342 String moduleNameAndRevision = "";
343 if (mountIndex >= 0) {
344 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
346 moduleNameAndRevision = identifier;
349 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
350 final Iterable<String> split = splitter.split(moduleNameAndRevision);
351 final List<String> pathArgs = Lists.<String> newArrayList(split);
352 if (pathArgs.size() < 2) {
353 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
354 throw new RestconfDocumentedException(
355 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
356 ErrorTag.INVALID_VALUE);
360 final String moduleName = pathArgs.get(0);
361 final String revision = pathArgs.get(1);
362 final Date moduleRevision = REVISION_FORMAT.parse(revision);
363 return QName.create(null, moduleRevision, moduleName);
364 } catch (final ParseException e) {
365 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
366 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
367 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
372 public Object getRoot() {
377 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
378 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
379 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
380 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
381 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
382 final SchemaContext schemaContext;
383 if (mountPoint != null) {
384 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
385 if ( ! mountRpcServices.isPresent()) {
386 LOG.debug("Error: Rpc service is missing.");
387 throw new RestconfDocumentedException("Rpc service is missing.");
389 schemaContext = mountPoint.getSchemaContext();
390 response = mountRpcServices.get().invokeRpc(type, payload.getData());
392 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
393 if (identifier.contains(CREATE_DATA_SUBSCR)) {
394 response = invokeSalRemoteRpcSubscribeRPC(payload);
395 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
396 response = invokeSalRemoteRpcNotifiStrRPC(payload);
398 final String msg = "Not supported operation";
400 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
403 response = this.broker.invokeRpc(type, payload.getData());
405 schemaContext = this.controllerContext.getGlobalSchema();
408 final DOMRpcResult result = checkRpcResponse(response);
410 RpcDefinition resultNodeSchema = null;
411 final NormalizedNode<?, ?> resultData = result.getResult();
412 if ((result != null) && (result.getResult() != null)) {
413 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
416 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
417 resultNodeSchema, mountPoint, schemaContext), resultData,
418 QueryParametersParser.parseWriterParameters(uriInfo));
421 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
422 if (response == null) {
426 final DOMRpcResult retValue = response.get();
427 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
430 LOG.debug("RpcError message", retValue.getErrors());
431 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
432 } catch (final InterruptedException e) {
433 final String errMsg = "The operation was interrupted while executing and did not complete.";
434 LOG.debug("Rpc Interrupt - " + errMsg, e);
435 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
436 } catch (final ExecutionException e) {
437 LOG.debug("Execution RpcError: ", e);
438 Throwable cause = e.getCause();
440 while (cause.getCause() != null) {
441 cause = cause.getCause();
444 if (cause instanceof IllegalArgumentException) {
445 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
446 ErrorTag.INVALID_VALUE);
447 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
448 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
450 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
452 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
454 } catch (final CancellationException e) {
455 final String errMsg = "The operation was cancelled while executing.";
456 LOG.debug("Cancel RpcExecution: " + errMsg, e);
457 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
461 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
462 if ((inputSchema != null) && (payload.getData() == null)) {
463 // expected a non null payload
464 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
465 } else if ((inputSchema == null) && (payload.getData() != null)) {
466 // did not expect any input
467 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
471 // TODO: Validate "mandatory" and "config" values here??? Or should those be
473 // validate in a more central location inside MD-SAL core.
477 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
478 final ContainerNode value = (ContainerNode) payload.getData();
479 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
480 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
481 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
482 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
484 if (!(pathValue instanceof YangInstanceIdentifier)) {
485 final String errMsg = "Instance identifier was not normalized correctly ";
486 LOG.debug(errMsg + rpcQName);
487 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
490 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
491 String streamName = (String) CREATE_DATA_SUBSCR;
492 if (!pathIdentifier.isEmpty()) {
493 final String fullRestconfIdentifier = DATA_SUBSCR
494 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
496 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
497 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
499 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
500 scope = scope == null ? DEFAULT_SCOPE : scope;
502 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
503 + "/scope=" + scope);
506 if (Strings.isNullOrEmpty(streamName)) {
507 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
508 LOG.debug(errMsg + pathIdentifier);
509 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
512 final QName outputQname = QName.create(rpcQName, "output");
513 final QName streamNameQname = QName.create(rpcQName, "stream-name");
515 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
516 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
518 if (!Notificator.existListenerFor(streamName)) {
519 Notificator.createListener(pathIdentifier, streamName);
522 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
524 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
528 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
529 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
530 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
533 String identifierEncoded = null;
534 DOMMountPoint mountPoint = null;
535 final SchemaContext schemaContext;
536 if (identifier.contains(ControllerContext.MOUNT)) {
537 // mounted RPC call - look up mount instance.
538 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
539 mountPoint = mountPointId.getMountPoint();
540 schemaContext = mountPoint.getSchemaContext();
541 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
542 + ControllerContext.MOUNT.length() + 1;
543 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
544 identifierEncoded = remoteRpcName;
546 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
547 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
548 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
549 LOG.debug(slashErrorMsg);
550 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
552 identifierEncoded = identifier;
553 schemaContext = this.controllerContext.getGlobalSchema();
556 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
558 RpcDefinition rpc = null;
559 if (mountPoint == null) {
560 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
562 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
566 LOG.debug("RPC " + identifierDecoded + " does not exist.");
567 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
570 if (rpc.getInput() != null) {
571 LOG.debug("RPC " + rpc + " does not need input value.");
572 // FIXME : find a correct Error from specification
573 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
576 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
577 if (mountPoint != null) {
578 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
579 if ( ! mountRpcServices.isPresent()) {
580 throw new RestconfDocumentedException("Rpc service is missing.");
582 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
584 response = this.broker.invokeRpc(rpc.getPath(), null);
587 final DOMRpcResult result = checkRpcResponse(response);
589 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
590 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
593 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
594 final String[] splittedIdentifier = identifierDecoded.split(":");
595 if (splittedIdentifier.length != 2) {
596 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
598 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
600 for (final Module module : schemaContext.getModules()) {
601 if (module.getName().equals(splittedIdentifier[0])) {
602 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
603 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
604 return rpcDefinition;
613 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
614 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
615 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
616 NormalizedNode<?, ?> data = null;
617 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
618 if (mountPoint != null) {
619 data = this.broker.readConfigurationData(mountPoint, normalizedII);
621 data = this.broker.readConfigurationData(normalizedII);
624 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
625 LOG.debug(errMsg + identifier);
626 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
628 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
632 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
633 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
634 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
635 NormalizedNode<?, ?> data = null;
636 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
637 if (mountPoint != null) {
638 data = this.broker.readOperationalData(mountPoint, normalizedII);
640 data = this.broker.readOperationalData(normalizedII);
643 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
644 LOG.debug(errMsg + identifier);
645 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
647 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
651 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
652 Preconditions.checkNotNull(identifier);
653 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
655 validateInput(iiWithData.getSchemaNode(), payload);
656 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
657 validateListKeysEqualityInPayloadAndUri(payload);
659 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
660 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
663 * There is a small window where another write transaction could be updating the same data
664 * simultaneously and we get an OptimisticLockFailedException. This error is likely
665 * transient and The WriteTransaction#submit API docs state that a retry will likely
666 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
667 * probably will never succeed so we'll fail in that case.
669 * By retrying we're attempting to hide the internal implementation of the data store and
670 * how it handles concurrent updates from the restconf client. The client has instructed us
671 * to put the data and we should make every effort to do so without pushing optimistic lock
672 * failures back to the client and forcing them to handle it via retry (and having to
673 * document the behavior).
678 if (mountPoint != null) {
679 this.broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
681 this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
685 } catch (final TransactionCommitFailedException e) {
686 if(e instanceof OptimisticLockFailedException) {
688 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
689 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
692 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
694 LOG.debug("Update ConfigDataStore fail " + identifier, e);
695 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
697 } catch (final Exception e) {
698 final String errMsg = "Error updating data ";
699 LOG.debug(errMsg + identifier, e);
700 throw new RestconfDocumentedException(errMsg, e);
704 return Response.status(Status.OK).build();
707 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
708 final YangInstanceIdentifier identifier) {
710 final String payloadName = node.getData().getNodeType().getLocalName();
713 if (identifier.isEmpty()) {
715 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
716 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
717 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
721 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
722 if (!payloadName.equals(identifierName)) {
723 throw new RestconfDocumentedException("Payload name (" + payloadName
724 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
725 ErrorTag.MALFORMED_MESSAGE);
731 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
733 * @throws RestconfDocumentedException
734 * if key values or key count in payload and URI isn't equal
737 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
738 Preconditions.checkArgument(payload != null);
739 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
740 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
741 final SchemaNode schemaNode = iiWithData.getSchemaNode();
742 final NormalizedNode<?, ?> data = payload.getData();
743 if (schemaNode instanceof ListSchemaNode) {
744 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
745 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
746 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
747 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
752 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
753 final MapEntryNode payload, final List<QName> keyDefinitions) {
755 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
756 for (final QName keyDefinition : keyDefinitions) {
757 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
758 // should be caught during parsing URI to InstanceIdentifier
759 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
760 "Missing key " + keyDefinition + " in URI.");
762 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
764 if ( ! uriKeyValue.equals(dataKeyValue)) {
765 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
766 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
767 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
773 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
774 return createConfigurationData(payload, uriInfo);
777 // FIXME create RestconfIdetifierHelper and move this method there
778 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
779 Preconditions.checkArgument(payload != null);
780 Preconditions.checkArgument(payload.getData() != null);
781 Preconditions.checkArgument(payload.getData().getNodeType() != null);
782 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
783 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
785 final QName payloadNodeQname = payload.getData().getNodeType();
786 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
787 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
790 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
791 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
792 if(parentSchemaNode instanceof DataNodeContainer) {
793 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
794 for (final DataSchemaNode child : cast.getChildNodes()) {
795 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
796 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
800 if (parentSchemaNode instanceof RpcDefinition) {
803 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
804 LOG.info(errMsg + yangIdent);
805 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
809 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
810 if (payload == null) {
811 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
814 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
815 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
816 // if (payloadNS == null) {
817 // throw new RestconfDocumentedException(
818 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
819 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
822 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
823 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
824 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
826 if (mountPoint != null) {
827 this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
829 this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
831 } catch(final RestconfDocumentedException e) {
833 } catch (final Exception e) {
834 final String errMsg = "Error creating data ";
835 LOG.info(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), e);
836 throw new RestconfDocumentedException(errMsg, e);
839 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
840 // FIXME: Provide path to result.
841 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
842 if (location != null) {
843 responseBuilder.location(location);
845 return responseBuilder.build();
848 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
849 if(uriInfo == null) {
850 // This is null if invoked internally
854 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
855 uriBuilder.path("config");
857 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
858 } catch (final Exception e) {
859 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
862 return uriBuilder.build();
866 public Response deleteConfigurationData(final String identifier) {
867 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
868 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
869 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
872 if (mountPoint != null) {
873 this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
875 this.broker.commitConfigurationDataDelete(normalizedII).get();
877 } catch (final Exception e) {
878 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
879 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
880 if (searchedException.isPresent()) {
881 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
883 final String errMsg = "Error while deleting data";
885 throw new RestconfDocumentedException(errMsg, e);
887 return Response.status(Status.OK).build();
891 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
893 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
895 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
896 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
900 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
901 if (identifier.contains(DATA_SUBSCR)) {
902 return dataSubs(identifier, uriInfo);
903 } else if (identifier.contains(NOTIFICATION_STREAM)) {
904 return notifStream(identifier, uriInfo);
906 final String msg = "Bad type of notification of sal-remote";
908 throw new RestconfDocumentedException(msg);
912 * Register notification listener by stream name
918 * @return {@link Response}
920 private Response notifStream(final String identifier, final UriInfo uriInfo) {
921 final String streamName = Notificator.createStreamNameFromUri(identifier);
922 if (Strings.isNullOrEmpty(streamName)) {
923 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
925 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
926 if ((listeners == null) || listeners.isEmpty()) {
927 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
928 ErrorTag.UNKNOWN_ELEMENT);
931 for (final NotificationListenerAdapter listener : listeners) {
932 this.broker.registerToListenNotification(listener);
935 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
936 int notificationPort = NOTIFICATION_PORT;
938 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
939 notificationPort = webSocketServerInstance.getPort();
940 } catch (final NullPointerException e) {
941 WebSocketServer.createInstance(NOTIFICATION_PORT);
943 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
944 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
946 return Response.status(Status.OK).location(uriToWebsocketServer).build();
950 * Register data change listener by stream name
956 * @return {@link Response}
958 private Response dataSubs(final String identifier, final UriInfo uriInfo) {
959 final String streamName = Notificator.createStreamNameFromUri(identifier);
960 if (Strings.isNullOrEmpty(streamName)) {
961 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
964 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
965 if (listener == null) {
966 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
969 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
970 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
971 paramToValues.get(DATASTORE_PARAM_NAME));
972 if (datastore == null) {
973 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
974 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
976 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
978 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
979 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
982 this.broker.registerToListenDataChanges(datastore, scope, listener);
984 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
985 int notificationPort = NOTIFICATION_PORT;
987 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
988 notificationPort = webSocketServerInstance.getPort();
989 } catch (final NullPointerException e) {
990 WebSocketServer.createInstance(NOTIFICATION_PORT);
992 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
993 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
995 return Response.status(Status.OK).location(uriToWebsocketServer).build();
999 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
1000 if (context == null) {
1001 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1003 return this.broker.patchConfigurationDataWithinTransaction(context, this.controllerContext.getGlobalSchema());
1007 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1008 if (context == null) {
1009 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1011 return this.broker.patchConfigurationDataWithinTransaction(context, this.controllerContext.getGlobalSchema());
1015 * Load parameter for subscribing to stream from input composite node
1019 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1021 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1022 final String paramName) {
1023 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1024 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1027 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1028 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1029 if (!enumNode.isPresent()) {
1032 final Object rawValue = enumNode.get().getValue();
1033 if (!(rawValue instanceof String)) {
1037 return resolveAsEnum(classDescriptor, (String) rawValue);
1041 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1043 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1046 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1047 if (Strings.isNullOrEmpty(value)) {
1050 return resolveAsEnum(classDescriptor, value);
1053 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1054 final T[] enumConstants = classDescriptor.getEnumConstants();
1055 if (enumConstants != null) {
1056 for (final T enm : classDescriptor.getEnumConstants()) {
1057 if (((Enum<?>) enm).name().equals(value)) {
1065 private static Map<String, String> resolveValuesFromUri(final String uri) {
1066 final Map<String, String> result = new HashMap<>();
1067 final String[] tokens = uri.split("/");
1068 for (int i = 1; i < tokens.length; i++) {
1069 final String[] parameterTokens = tokens[i].split("=");
1070 if (parameterTokens.length == 2) {
1071 result.put(parameterTokens[0], parameterTokens[1]);
1077 public BigInteger getOperationalReceived() {
1078 // TODO Auto-generated method stub
1082 private MapNode makeModuleMapNode(final Set<Module> modules) {
1083 Preconditions.checkNotNull(modules);
1084 final Module restconfModule = getRestconfModule();
1085 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1086 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1087 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1089 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1090 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1092 for (final Module module : modules) {
1093 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1095 return listModuleBuilder.build();
1098 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1099 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1100 "moduleSchemaNode has to be of type ListSchemaNode");
1101 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1102 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1103 .mapEntryBuilder(listModuleSchemaNode);
1105 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1106 (listModuleSchemaNode), "name");
1107 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1108 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1109 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1112 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1113 (listModuleSchemaNode), "revision");
1114 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1115 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1116 final String revision = REVISION_FORMAT.format(module.getRevision());
1117 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1120 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1121 (listModuleSchemaNode), "namespace");
1122 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1123 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1124 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1125 .withValue(module.getNamespace().toString()).build());
1127 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1128 (listModuleSchemaNode), "feature");
1129 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1130 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1131 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1132 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1133 for (final FeatureDefinition feature : module.getFeatures()) {
1134 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1135 .withValue(feature.getQName().getLocalName()).build());
1137 moduleNodeValues.withChild(featuresBuilder.build());
1139 return moduleNodeValues.build();
1142 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1143 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1144 "streamSchemaNode has to be of type ListSchemaNode");
1145 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1146 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1147 .mapEntryBuilder(listStreamSchemaNode);
1149 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1150 (listStreamSchemaNode), "name");
1151 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1152 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1153 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1156 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1157 (listStreamSchemaNode), "description");
1158 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1159 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1160 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1161 .withValue("DESCRIPTION_PLACEHOLDER").build());
1163 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1164 (listStreamSchemaNode), "replay-support");
1165 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1166 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1167 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1168 .withValue(Boolean.valueOf(true)).build());
1170 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1171 (listStreamSchemaNode), "replay-log-creation-time");
1172 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1173 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1174 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1175 .withValue("").build());
1177 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1178 (listStreamSchemaNode), "events");
1179 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1180 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1181 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1182 .withValue("").build());
1184 return streamNodeValues.build();
1188 * Prepare stream for notification
1191 * - contains list of qnames of notifications
1192 * @return - checked future object
1194 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1195 final NormalizedNodeContext payload) {
1196 final ContainerNode data = (ContainerNode) payload.getData();
1197 LeafSetNode leafSet = null;
1198 String outputType = "XML";
1199 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1200 if (dataChild instanceof LeafSetNode) {
1201 leafSet = (LeafSetNode) dataChild;
1202 } else if (dataChild instanceof AugmentationNode) {
1203 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1207 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1208 final List<SchemaPath> paths = new ArrayList<>();
1209 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1211 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1212 while (iterator.hasNext()) {
1213 final QName valueQName = QName.create((String) iterator.next().getValue());
1214 final Module module = ControllerContext.getInstance()
1215 .findModuleByNamespace(valueQName.getModule().getNamespace());
1216 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1217 + " does not exist");
1218 NotificationDefinition notifiDef = null;
1219 for (final NotificationDefinition notification : module.getNotifications()) {
1220 if (notification.getQName().equals(valueQName)) {
1221 notifiDef = notification;
1225 final String moduleName = module.getName();
1226 Preconditions.checkNotNull(notifiDef,
1227 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1228 paths.add(notifiDef.getPath());
1229 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1230 if (iterator.hasNext()) {
1231 streamName = streamName + ",";
1235 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1236 final QName outputQname = QName.create(rpcQName, "output");
1237 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1239 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1240 .withNodeIdentifier(new NodeIdentifier(outputQname))
1241 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1243 if (!Notificator.existNotificationListenerFor(streamName)) {
1244 Notificator.createNotificationListener(paths, streamName, outputType);
1247 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1249 return Futures.immediateCheckedFuture(defaultDOMRpcResult);