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.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.Iterables;
17 import com.google.common.collect.Lists;
18 import com.google.common.collect.Maps;
19 import com.google.common.collect.Sets;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import com.google.common.util.concurrent.Futures;
23 import java.math.BigInteger;
25 import java.net.URISyntaxException;
26 import java.text.ParseException;
27 import java.text.SimpleDateFormat;
28 import java.util.ArrayList;
29 import java.util.Collection;
30 import java.util.Collections;
31 import java.util.Date;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
37 import java.util.concurrent.CancellationException;
38 import java.util.concurrent.CountDownLatch;
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.impl.schema.Builders;
80 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
81 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
82 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
83 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
84 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
85 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
87 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
89 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.Module;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.slf4j.Logger;
99 import org.slf4j.LoggerFactory;
101 public class RestconfImpl implements RestconfService {
103 private static final RestconfImpl INSTANCE = new RestconfImpl();
106 * Notifications are served on port 8181.
108 private static final int NOTIFICATION_PORT = 8181;
110 private static final int CHAR_NOT_FOUND = -1;
112 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
114 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
116 private BrokerFacade broker;
118 private ControllerContext controllerContext;
120 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
122 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
124 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
126 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
128 private static final String DATASTORE_PARAM_NAME = "datastore";
130 private static final String SCOPE_PARAM_NAME = "scope";
132 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
134 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
136 private static final QName NETCONF_BASE_QNAME;
138 private static final QNameModule SAL_REMOTE_AUGMENT;
140 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
142 public static final CharSequence DATA_SUBSCR = "data-change-event-subscription";
143 private static final CharSequence CREATE_DATA_SUBSCR = "create-" + DATA_SUBSCR;
145 public static final CharSequence NOTIFICATION_STREAM = "notification-stream";
146 private static final CharSequence CREATE_NOTIFICATION_STREAM = "create-" + NOTIFICATION_STREAM;
150 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
151 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
152 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
153 eventSubscriptionAugRevision);
154 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
155 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
156 } catch (final ParseException e) {
157 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
159 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
160 } catch (final URISyntaxException e) {
161 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
162 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
166 public void setBroker(final BrokerFacade broker) {
167 this.broker = broker;
170 public void setControllerContext(final ControllerContext controllerContext) {
171 this.controllerContext = controllerContext;
174 private RestconfImpl() {
177 public static RestconfImpl getInstance() {
182 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
183 final Set<Module> allModules = this.controllerContext.getAllModules();
184 final MapNode allModuleMap = makeModuleMapNode(allModules);
186 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
188 final Module restconfModule = getRestconfModule();
189 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
190 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
191 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
193 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
194 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
195 moduleContainerBuilder.withChild(allModuleMap);
197 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
198 null, schemaContext), moduleContainerBuilder.build(),
199 QueryParametersParser.parseWriterParameters(uriInfo));
203 * Valid only for mount point
206 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
207 Preconditions.checkNotNull(identifier);
208 if ( ! identifier.contains(ControllerContext.MOUNT)) {
209 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
210 + " URI has to end with " + ControllerContext.MOUNT;
211 LOG.debug(errMsg + " for " + identifier);
212 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
215 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
216 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
217 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
218 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
220 final Module restconfModule = getRestconfModule();
221 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
222 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
223 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
225 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
226 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
227 moduleContainerBuilder.withChild(mountPointModulesMap);
229 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
230 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
231 QueryParametersParser.parseWriterParameters(uriInfo));
235 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
236 Preconditions.checkNotNull(identifier);
237 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
238 Module module = null;
239 DOMMountPoint mountPoint = null;
240 final SchemaContext schemaContext;
241 if (identifier.contains(ControllerContext.MOUNT)) {
242 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
243 mountPoint = mountPointIdentifier.getMountPoint();
244 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
245 schemaContext = mountPoint.getSchemaContext();
247 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
248 schemaContext = this.controllerContext.getGlobalSchema();
251 if (module == null) {
252 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
253 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
255 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
258 final Module restconfModule = getRestconfModule();
259 final Set<Module> modules = Collections.singleton(module);
260 final MapNode moduleMap = makeModuleMapNode(modules);
262 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
263 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
264 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
266 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
267 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
271 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
272 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
273 final Set<String> availableStreams = Notificator.getStreamNames();
274 final Module restconfModule = getRestconfModule();
275 final DataSchemaNode streamSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
276 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
277 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
279 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
280 .mapBuilder((ListSchemaNode) streamSchemaNode);
282 for (final String streamName : availableStreams) {
283 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
286 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
287 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
288 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
290 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
291 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
292 streamsContainerBuilder.withChild(listStreamsBuilder.build());
295 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
296 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
300 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
301 final Set<Module> allModules = this.controllerContext.getAllModules();
302 return operationsFromModulesToNormalizedContext(allModules, null);
306 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
307 Set<Module> modules = null;
308 DOMMountPoint mountPoint = null;
309 if (identifier.contains(ControllerContext.MOUNT)) {
310 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
311 mountPoint = mountPointIdentifier.getMountPoint();
312 modules = this.controllerContext.getAllModules(mountPoint);
315 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
316 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
317 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
320 return operationsFromModulesToNormalizedContext(modules, mountPoint);
323 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
324 final DOMMountPoint mountPoint) {
325 throw new UnsupportedOperationException();
328 private Module getRestconfModule() {
329 final Module restconfModule = this.controllerContext.getRestconfModule();
330 if (restconfModule == null) {
331 LOG.debug("ietf-restconf module was not found.");
332 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
333 ErrorTag.OPERATION_NOT_SUPPORTED);
336 return restconfModule;
339 private static QName getModuleNameAndRevision(final String identifier) {
340 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
341 String moduleNameAndRevision = "";
342 if (mountIndex >= 0) {
343 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
345 moduleNameAndRevision = identifier;
348 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
349 final Iterable<String> split = splitter.split(moduleNameAndRevision);
350 final List<String> pathArgs = Lists.<String> newArrayList(split);
351 if (pathArgs.size() < 2) {
352 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
353 throw new RestconfDocumentedException(
354 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
355 ErrorTag.INVALID_VALUE);
359 final String moduleName = pathArgs.get(0);
360 final String revision = pathArgs.get(1);
361 final Date moduleRevision = REVISION_FORMAT.parse(revision);
362 return QName.create(null, moduleRevision, moduleName);
363 } catch (final ParseException e) {
364 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
365 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
366 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
371 public Object getRoot() {
376 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
377 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
378 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
379 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
380 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
381 final SchemaContext schemaContext;
382 if (mountPoint != null) {
383 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
384 if ( ! mountRpcServices.isPresent()) {
385 LOG.debug("Error: Rpc service is missing.");
386 throw new RestconfDocumentedException("Rpc service is missing.");
388 schemaContext = mountPoint.getSchemaContext();
389 response = mountRpcServices.get().invokeRpc(type, payload.getData());
391 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
392 if (identifier.contains(CREATE_DATA_SUBSCR)) {
393 response = invokeSalRemoteRpcSubscribeRPC(payload);
394 } else if (identifier.contains(CREATE_NOTIFICATION_STREAM)) {
395 response = invokeSalRemoteRpcNotifiStrRPC(payload);
397 final String msg = "Not supported operation";
399 throw new RestconfDocumentedException(msg, ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
402 response = this.broker.invokeRpc(type, payload.getData());
404 schemaContext = this.controllerContext.getGlobalSchema();
407 final DOMRpcResult result = checkRpcResponse(response);
409 RpcDefinition resultNodeSchema = null;
410 final NormalizedNode<?, ?> resultData = result.getResult();
411 if ((result != null) && (result.getResult() != null)) {
412 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
415 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
416 resultNodeSchema, mountPoint, schemaContext), resultData,
417 QueryParametersParser.parseWriterParameters(uriInfo));
420 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
421 if (response == null) {
425 final DOMRpcResult retValue = response.get();
426 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
429 LOG.debug("RpcError message", retValue.getErrors());
430 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
431 } catch (final InterruptedException e) {
432 final String errMsg = "The operation was interrupted while executing and did not complete.";
433 LOG.debug("Rpc Interrupt - " + errMsg, e);
434 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
435 } catch (final ExecutionException e) {
436 LOG.debug("Execution RpcError: ", e);
437 Throwable cause = e.getCause();
439 while (cause.getCause() != null) {
440 cause = cause.getCause();
443 if (cause instanceof IllegalArgumentException) {
444 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
445 ErrorTag.INVALID_VALUE);
446 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
447 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
449 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
451 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
453 } catch (final CancellationException e) {
454 final String errMsg = "The operation was cancelled while executing.";
455 LOG.debug("Cancel RpcExecution: " + errMsg, e);
456 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
460 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
461 if ((inputSchema != null) && (payload.getData() == null)) {
462 // expected a non null payload
463 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
464 } else if ((inputSchema == null) && (payload.getData() != null)) {
465 // did not expect any input
466 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
470 // TODO: Validate "mandatory" and "config" values here??? Or should those be
472 // validate in a more central location inside MD-SAL core.
476 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
477 final ContainerNode value = (ContainerNode) payload.getData();
478 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
479 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
480 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
481 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
483 if (!(pathValue instanceof YangInstanceIdentifier)) {
484 final String errMsg = "Instance identifier was not normalized correctly ";
485 LOG.debug(errMsg + rpcQName);
486 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
489 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
490 String streamName = (String) CREATE_DATA_SUBSCR;
491 if (!pathIdentifier.isEmpty()) {
492 final String fullRestconfIdentifier = DATA_SUBSCR
493 + this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
495 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
496 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
498 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
499 scope = scope == null ? DEFAULT_SCOPE : scope;
501 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
502 + "/scope=" + scope);
505 if (Strings.isNullOrEmpty(streamName)) {
506 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
507 LOG.debug(errMsg + pathIdentifier);
508 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
511 final QName outputQname = QName.create(rpcQName, "output");
512 final QName streamNameQname = QName.create(rpcQName, "stream-name");
514 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
515 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
517 if (!Notificator.existListenerFor(streamName)) {
518 Notificator.createListener(pathIdentifier, streamName);
521 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
523 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
527 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
528 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
529 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
532 String identifierEncoded = null;
533 DOMMountPoint mountPoint = null;
534 final SchemaContext schemaContext;
535 if (identifier.contains(ControllerContext.MOUNT)) {
536 // mounted RPC call - look up mount instance.
537 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
538 mountPoint = mountPointId.getMountPoint();
539 schemaContext = mountPoint.getSchemaContext();
540 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
541 + ControllerContext.MOUNT.length() + 1;
542 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
543 identifierEncoded = remoteRpcName;
545 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
546 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
547 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
548 LOG.debug(slashErrorMsg);
549 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
551 identifierEncoded = identifier;
552 schemaContext = this.controllerContext.getGlobalSchema();
555 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
557 RpcDefinition rpc = null;
558 if (mountPoint == null) {
559 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
561 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
565 LOG.debug("RPC " + identifierDecoded + " does not exist.");
566 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
569 if (rpc.getInput() != null) {
570 LOG.debug("RPC " + rpc + " does not need input value.");
571 // FIXME : find a correct Error from specification
572 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
575 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
576 if (mountPoint != null) {
577 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
578 if ( ! mountRpcServices.isPresent()) {
579 throw new RestconfDocumentedException("Rpc service is missing.");
581 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
583 response = this.broker.invokeRpc(rpc.getPath(), null);
586 final DOMRpcResult result = checkRpcResponse(response);
588 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
589 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
592 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
593 final String[] splittedIdentifier = identifierDecoded.split(":");
594 if (splittedIdentifier.length != 2) {
595 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
597 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
599 for (final Module module : schemaContext.getModules()) {
600 if (module.getName().equals(splittedIdentifier[0])) {
601 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
602 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
603 return rpcDefinition;
612 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
613 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
614 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
615 NormalizedNode<?, ?> data = null;
616 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
617 if (mountPoint != null) {
618 data = this.broker.readConfigurationData(mountPoint, normalizedII);
620 data = this.broker.readConfigurationData(normalizedII);
623 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
624 LOG.debug(errMsg + identifier);
625 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
627 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
631 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
632 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
633 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
634 NormalizedNode<?, ?> data = null;
635 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
636 if (mountPoint != null) {
637 data = this.broker.readOperationalData(mountPoint, normalizedII);
639 data = this.broker.readOperationalData(normalizedII);
642 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
643 LOG.debug(errMsg + identifier);
644 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
646 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
650 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
651 Preconditions.checkNotNull(identifier);
652 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
654 validateInput(iiWithData.getSchemaNode(), payload);
655 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
656 validateListKeysEqualityInPayloadAndUri(payload);
658 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
659 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
662 * There is a small window where another write transaction could be updating the same data
663 * simultaneously and we get an OptimisticLockFailedException. This error is likely
664 * transient and The WriteTransaction#submit API docs state that a retry will likely
665 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
666 * probably will never succeed so we'll fail in that case.
668 * By retrying we're attempting to hide the internal implementation of the data store and
669 * how it handles concurrent updates from the restconf client. The client has instructed us
670 * to put the data and we should make every effort to do so without pushing optimistic lock
671 * failures back to the client and forcing them to handle it via retry (and having to
672 * document the behavior).
674 PutResult result = null;
675 final TryOfPutData tryPutData = new TryOfPutData();
677 if (mountPoint != null) {
679 result = this.broker.commitMountPointDataPut(mountPoint, normalizedII, payload.getData());
681 result = this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII,
684 final CountDownLatch waiter = new CountDownLatch(1);
685 Futures.addCallback(result.getFutureOfPutData(), new FutureCallback<Void>() {
688 public void onSuccess(final Void result) {
689 handlingLoggerPut(null, tryPutData, identifier);
694 public void onFailure(final Throwable t) {
696 handlingLoggerPut(t, tryPutData, identifier);
702 } catch (final InterruptedException e) {
703 final String msg = "Problem while waiting for response";
705 throw new RestconfDocumentedException(msg, e);
708 if(tryPutData.isDone()){
711 throw new RestconfDocumentedException("Problem while PUT operations");
715 return Response.status(result.getStatus()).build();
718 protected void handlingLoggerPut(final Throwable t, final TryOfPutData tryPutData, final String identifier) {
720 if (t instanceof OptimisticLockFailedException) {
721 if (tryPutData.countGet() <= 0) {
722 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
723 throw new RestconfDocumentedException(t.getMessage(), t);
725 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
726 tryPutData.countDown();
728 LOG.debug("Update ConfigDataStore fail " + identifier, t);
729 throw new RestconfDocumentedException(t.getMessage(), t);
732 LOG.trace("PUT Successful " + identifier);
737 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
738 final YangInstanceIdentifier identifier) {
740 final String payloadName = node.getData().getNodeType().getLocalName();
743 if (identifier.isEmpty()) {
745 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
746 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
747 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
751 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
752 if (!payloadName.equals(identifierName)) {
753 throw new RestconfDocumentedException("Payload name (" + payloadName
754 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
755 ErrorTag.MALFORMED_MESSAGE);
761 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
763 * @throws RestconfDocumentedException
764 * if key values or key count in payload and URI isn't equal
767 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
768 Preconditions.checkArgument(payload != null);
769 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
770 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
771 final SchemaNode schemaNode = iiWithData.getSchemaNode();
772 final NormalizedNode<?, ?> data = payload.getData();
773 if (schemaNode instanceof ListSchemaNode) {
774 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
775 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
776 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
777 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
782 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
783 final MapEntryNode payload, final List<QName> keyDefinitions) {
785 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
786 for (final QName keyDefinition : keyDefinitions) {
787 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
788 // should be caught during parsing URI to InstanceIdentifier
789 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
790 "Missing key " + keyDefinition + " in URI.");
792 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
794 if ( ! uriKeyValue.equals(dataKeyValue)) {
795 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
796 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
797 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
803 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
804 return createConfigurationData(payload, uriInfo);
807 // FIXME create RestconfIdetifierHelper and move this method there
808 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
809 Preconditions.checkArgument(payload != null);
810 Preconditions.checkArgument(payload.getData() != null);
811 Preconditions.checkArgument(payload.getData().getNodeType() != null);
812 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
813 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
815 final QName payloadNodeQname = payload.getData().getNodeType();
816 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
817 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
820 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
821 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
822 if(parentSchemaNode instanceof DataNodeContainer) {
823 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
824 for (final DataSchemaNode child : cast.getChildNodes()) {
825 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
826 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
830 if (parentSchemaNode instanceof RpcDefinition) {
833 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
834 LOG.info(errMsg + yangIdent);
835 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
839 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
840 if (payload == null) {
841 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
844 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
845 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
846 // if (payloadNS == null) {
847 // throw new RestconfDocumentedException(
848 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
849 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
852 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
853 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
854 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
856 CheckedFuture<Void, TransactionCommitFailedException> future;
857 if (mountPoint != null) {
858 future = this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData());
860 future = this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII,
864 final CountDownLatch waiter = new CountDownLatch(1);
865 Futures.addCallback(future, new FutureCallback<Void>() {
868 public void onSuccess(final Void result) {
869 handlerLoggerPost(null, uriInfo);
874 public void onFailure(final Throwable t) {
876 handlerLoggerPost(t, uriInfo);
882 } catch (final InterruptedException e) {
883 final String msg = "Problem while waiting for response";
885 throw new RestconfDocumentedException(msg, e);
888 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
889 // FIXME: Provide path to result.
890 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
891 if (location != null) {
892 responseBuilder.location(location);
894 return responseBuilder.build();
897 protected void handlerLoggerPost(final Throwable t, final UriInfo uriInfo) {
899 final String errMsg = "Error creating data ";
900 LOG.warn(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), t);
901 throw new RestconfDocumentedException(errMsg, t);
903 LOG.trace("Successfuly create data.");
907 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
908 if(uriInfo == null) {
909 // This is null if invoked internally
913 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
914 uriBuilder.path("config");
916 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
917 } catch (final Exception e) {
918 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
921 return uriBuilder.build();
925 public Response deleteConfigurationData(final String identifier) {
926 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
927 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
928 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
930 final CheckedFuture<Void, TransactionCommitFailedException> future;
931 if (mountPoint != null) {
932 future = this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
934 future = this.broker.commitConfigurationDataDelete(normalizedII);
937 final CountDownLatch waiter = new CountDownLatch(1);
938 Futures.addCallback(future, new FutureCallback<Void>() {
941 public void onSuccess(final Void result) {
942 handlerLoggerDelete(null);
947 public void onFailure(final Throwable t) {
949 handlerLoggerDelete(t);
956 } catch (final InterruptedException e) {
957 final String msg = "Problem while waiting for response";
959 throw new RestconfDocumentedException(msg, e);
962 return Response.status(Status.OK).build();
965 protected void handlerLoggerDelete(final Throwable t) {
967 final String errMsg = "Error while deleting data";
969 throw new RestconfDocumentedException(errMsg, t);
971 LOG.trace("Successfuly delete data.");
976 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
978 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
980 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
981 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
985 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
986 if (identifier.contains(DATA_SUBSCR)) {
987 return dataSubs(identifier, uriInfo);
988 } else if (identifier.contains(NOTIFICATION_STREAM)) {
989 return notifStream(identifier, uriInfo);
991 final String msg = "Bad type of notification of sal-remote";
993 throw new RestconfDocumentedException(msg);
997 * Register notification listener by stream name
1003 * @return {@link Response}
1005 private Response notifStream(final String identifier, final UriInfo uriInfo) {
1006 final String streamName = Notificator.createStreamNameFromUri(identifier);
1007 if (Strings.isNullOrEmpty(streamName)) {
1008 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1010 final List<NotificationListenerAdapter> listeners = Notificator.getNotificationListenerFor(streamName);
1011 if ((listeners == null) || listeners.isEmpty()) {
1012 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL,
1013 ErrorTag.UNKNOWN_ELEMENT);
1016 for (final NotificationListenerAdapter listener : listeners) {
1017 this.broker.registerToListenNotification(listener);
1020 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1021 int notificationPort = NOTIFICATION_PORT;
1023 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1024 notificationPort = webSocketServerInstance.getPort();
1025 } catch (final NullPointerException e) {
1026 WebSocketServer.createInstance(NOTIFICATION_PORT);
1028 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1029 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1031 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1035 * Register data change listener by stream name
1041 * @return {@link Response}
1043 private Response dataSubs(final String identifier, final UriInfo uriInfo) {
1044 final String streamName = Notificator.createStreamNameFromUri(identifier);
1045 if (Strings.isNullOrEmpty(streamName)) {
1046 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
1049 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
1050 if (listener == null) {
1051 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
1054 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
1055 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
1056 paramToValues.get(DATASTORE_PARAM_NAME));
1057 if (datastore == null) {
1058 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
1059 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1061 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
1062 if (scope == null) {
1063 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
1064 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
1067 this.broker.registerToListenDataChanges(datastore, scope, listener);
1069 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
1070 int notificationPort = NOTIFICATION_PORT;
1072 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
1073 notificationPort = webSocketServerInstance.getPort();
1074 } catch (final NullPointerException e) {
1075 WebSocketServer.createInstance(NOTIFICATION_PORT);
1077 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
1078 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
1080 return Response.status(Status.OK).location(uriToWebsocketServer).build();
1084 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
1085 if (context == null) {
1086 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1090 return this.broker.patchConfigurationDataWithinTransaction(context,
1091 this.controllerContext.getGlobalSchema());
1092 } catch (final InterruptedException e) {
1093 LOG.debug("Patch transaction failed", e);
1094 throw new RestconfDocumentedException(e.getMessage());
1099 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
1100 if (context == null) {
1101 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
1105 return this.broker.patchConfigurationDataWithinTransaction(context,
1106 this.controllerContext.getGlobalSchema());
1107 } catch (final InterruptedException e) {
1108 LOG.debug("Patch transaction failed", e);
1109 throw new RestconfDocumentedException(e.getMessage());
1114 * Load parameter for subscribing to stream from input composite node
1118 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
1120 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
1121 final String paramName) {
1122 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
1123 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
1126 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
1127 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
1128 if (!enumNode.isPresent()) {
1131 final Object rawValue = enumNode.get().getValue();
1132 if (!(rawValue instanceof String)) {
1136 return resolveAsEnum(classDescriptor, (String) rawValue);
1140 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
1142 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
1145 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
1146 if (Strings.isNullOrEmpty(value)) {
1149 return resolveAsEnum(classDescriptor, value);
1152 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
1153 final T[] enumConstants = classDescriptor.getEnumConstants();
1154 if (enumConstants != null) {
1155 for (final T enm : classDescriptor.getEnumConstants()) {
1156 if (((Enum<?>) enm).name().equals(value)) {
1164 private static Map<String, String> resolveValuesFromUri(final String uri) {
1165 final Map<String, String> result = new HashMap<>();
1166 final String[] tokens = uri.split("/");
1167 for (int i = 1; i < tokens.length; i++) {
1168 final String[] parameterTokens = tokens[i].split("=");
1169 if (parameterTokens.length == 2) {
1170 result.put(parameterTokens[0], parameterTokens[1]);
1176 public BigInteger getOperationalReceived() {
1177 // TODO Auto-generated method stub
1181 private MapNode makeModuleMapNode(final Set<Module> modules) {
1182 Preconditions.checkNotNull(modules);
1183 final Module restconfModule = getRestconfModule();
1184 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1185 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1186 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1188 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1189 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1191 for (final Module module : modules) {
1192 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1194 return listModuleBuilder.build();
1197 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1198 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1199 "moduleSchemaNode has to be of type ListSchemaNode");
1200 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1201 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1202 .mapEntryBuilder(listModuleSchemaNode);
1204 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1205 (listModuleSchemaNode), "name");
1206 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1207 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1208 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1211 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1212 (listModuleSchemaNode), "revision");
1213 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1214 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1215 final String revision = REVISION_FORMAT.format(module.getRevision());
1216 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1219 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1220 (listModuleSchemaNode), "namespace");
1221 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1222 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1223 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1224 .withValue(module.getNamespace().toString()).build());
1226 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1227 (listModuleSchemaNode), "feature");
1228 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1229 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1230 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1231 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1232 for (final FeatureDefinition feature : module.getFeatures()) {
1233 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1234 .withValue(feature.getQName().getLocalName()).build());
1236 moduleNodeValues.withChild(featuresBuilder.build());
1238 return moduleNodeValues.build();
1241 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1242 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1243 "streamSchemaNode has to be of type ListSchemaNode");
1244 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1245 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1246 .mapEntryBuilder(listStreamSchemaNode);
1248 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1249 (listStreamSchemaNode), "name");
1250 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1251 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1252 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1255 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1256 (listStreamSchemaNode), "description");
1257 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1258 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1259 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1260 .withValue("DESCRIPTION_PLACEHOLDER").build());
1262 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1263 (listStreamSchemaNode), "replay-support");
1264 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1265 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1266 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1267 .withValue(Boolean.valueOf(true)).build());
1269 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1270 (listStreamSchemaNode), "replay-log-creation-time");
1271 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1272 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1273 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1274 .withValue("").build());
1276 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1277 (listStreamSchemaNode), "events");
1278 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1279 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1280 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1281 .withValue("").build());
1283 return streamNodeValues.build();
1287 * Prepare stream for notification
1290 * - contains list of qnames of notifications
1291 * @return - checked future object
1293 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcNotifiStrRPC(
1294 final NormalizedNodeContext payload) {
1295 final ContainerNode data = (ContainerNode) payload.getData();
1296 LeafSetNode leafSet = null;
1297 String outputType = "XML";
1298 for (final DataContainerChild<? extends PathArgument, ?> dataChild : data.getValue()) {
1299 if (dataChild instanceof LeafSetNode) {
1300 leafSet = (LeafSetNode) dataChild;
1301 } else if (dataChild instanceof AugmentationNode) {
1302 outputType = (String) (((AugmentationNode) dataChild).getValue()).iterator().next().getValue();
1306 final Collection<LeafSetEntryNode> entryNodes = leafSet.getValue();
1307 final List<SchemaPath> paths = new ArrayList<>();
1308 String streamName = CREATE_NOTIFICATION_STREAM + "/";
1310 final Iterator<LeafSetEntryNode> iterator = entryNodes.iterator();
1311 while (iterator.hasNext()) {
1312 final QName valueQName = QName.create((String) iterator.next().getValue());
1313 final Module module = ControllerContext.getInstance()
1314 .findModuleByNamespace(valueQName.getModule().getNamespace());
1315 Preconditions.checkNotNull(module, "Module for namespace " + valueQName.getModule().getNamespace()
1316 + " does not exist");
1317 NotificationDefinition notifiDef = null;
1318 for (final NotificationDefinition notification : module.getNotifications()) {
1319 if (notification.getQName().equals(valueQName)) {
1320 notifiDef = notification;
1324 final String moduleName = module.getName();
1325 Preconditions.checkNotNull(notifiDef,
1326 "Notification " + valueQName + "doesn't exist in module " + moduleName);
1327 paths.add(notifiDef.getPath());
1328 streamName = streamName + moduleName + ":" + valueQName.getLocalName();
1329 if (iterator.hasNext()) {
1330 streamName = streamName + ",";
1334 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
1335 final QName outputQname = QName.create(rpcQName, "output");
1336 final QName streamNameQname = QName.create(rpcQName, "notification-stream-identifier");
1338 final ContainerNode output = ImmutableContainerNodeBuilder.create()
1339 .withNodeIdentifier(new NodeIdentifier(outputQname))
1340 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
1342 if (!Notificator.existNotificationListenerFor(streamName)) {
1343 Notificator.createNotificationListener(paths, streamName, outputType);
1346 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
1348 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
1351 private class TryOfPutData {
1353 boolean done = false;