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.Collections;
30 import java.util.Date;
31 import java.util.HashMap;
32 import java.util.List;
35 import java.util.concurrent.CancellationException;
36 import java.util.concurrent.ExecutionException;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.Response;
39 import javax.ws.rs.core.Response.ResponseBuilder;
40 import javax.ws.rs.core.Response.Status;
41 import javax.ws.rs.core.UriBuilder;
42 import javax.ws.rs.core.UriInfo;
43 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
44 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
45 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
46 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
47 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
54 import org.opendaylight.netconf.sal.rest.api.Draft02;
55 import org.opendaylight.netconf.sal.rest.api.RestconfService;
56 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
57 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
58 import org.opendaylight.netconf.sal.streams.listeners.ListenerAdapter;
59 import org.opendaylight.netconf.sal.streams.listeners.Notificator;
60 import org.opendaylight.netconf.sal.streams.websockets.WebSocketServer;
61 import org.opendaylight.yangtools.yang.common.QName;
62 import org.opendaylight.yangtools.yang.common.QNameModule;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
64 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
65 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
66 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
67 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
70 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
72 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
73 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
74 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
75 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
76 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
77 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
78 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
79 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
80 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
85 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.Module;
89 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
90 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
91 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
96 public class RestconfImpl implements RestconfService {
98 private static final RestconfImpl INSTANCE = new RestconfImpl();
101 * Notifications are served on port 8181.
103 private static final int NOTIFICATION_PORT = 8181;
105 private static final int CHAR_NOT_FOUND = -1;
107 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
109 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
111 private BrokerFacade broker;
113 private ControllerContext controllerContext;
115 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
117 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
119 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
121 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
123 private static final String DATASTORE_PARAM_NAME = "datastore";
125 private static final String SCOPE_PARAM_NAME = "scope";
127 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
129 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
131 private static final QName NETCONF_BASE_QNAME;
133 private static final QNameModule SAL_REMOTE_AUGMENT;
135 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
139 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
140 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
141 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
142 eventSubscriptionAugRevision);
143 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
144 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
145 } catch (final ParseException e) {
146 final String errMsg = "It wasn't possible to convert revision date of sal-remote-augment to date";
148 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
149 } catch (final URISyntaxException e) {
150 final String errMsg = "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI";
151 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
155 public void setBroker(final BrokerFacade broker) {
156 this.broker = broker;
159 public void setControllerContext(final ControllerContext controllerContext) {
160 this.controllerContext = controllerContext;
163 private RestconfImpl() {
166 public static RestconfImpl getInstance() {
171 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
172 final Set<Module> allModules = this.controllerContext.getAllModules();
173 final MapNode allModuleMap = makeModuleMapNode(allModules);
175 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
177 final Module restconfModule = getRestconfModule();
178 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
179 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
180 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
182 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
183 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
184 moduleContainerBuilder.withChild(allModuleMap);
186 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
187 null, schemaContext), moduleContainerBuilder.build(),
188 QueryParametersParser.parseWriterParameters(uriInfo));
192 * Valid only for mount point
195 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
196 Preconditions.checkNotNull(identifier);
197 if ( ! identifier.contains(ControllerContext.MOUNT)) {
198 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
199 + " URI has to end with " + ControllerContext.MOUNT;
200 LOG.debug(errMsg + " for " + identifier);
201 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
204 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
205 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
206 final Set<Module> modules = this.controllerContext.getAllModules(mountPoint);
207 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
209 final Module restconfModule = getRestconfModule();
210 final DataSchemaNode modulesSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
211 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
212 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
214 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
215 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
216 moduleContainerBuilder.withChild(mountPointModulesMap);
218 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
219 mountPoint, this.controllerContext.getGlobalSchema()), moduleContainerBuilder.build(),
220 QueryParametersParser.parseWriterParameters(uriInfo));
224 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
225 Preconditions.checkNotNull(identifier);
226 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
227 Module module = null;
228 DOMMountPoint mountPoint = null;
229 final SchemaContext schemaContext;
230 if (identifier.contains(ControllerContext.MOUNT)) {
231 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
232 mountPoint = mountPointIdentifier.getMountPoint();
233 module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
234 schemaContext = mountPoint.getSchemaContext();
236 module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
237 schemaContext = this.controllerContext.getGlobalSchema();
240 if (module == null) {
241 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
242 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
244 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
247 final Module restconfModule = getRestconfModule();
248 final Set<Module> modules = Collections.singleton(module);
249 final MapNode moduleMap = makeModuleMapNode(modules);
251 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
252 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
253 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
255 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
256 schemaContext), moduleMap, QueryParametersParser.parseWriterParameters(uriInfo));
260 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
261 final SchemaContext schemaContext = this.controllerContext.getGlobalSchema();
262 final Set<String> availableStreams = Notificator.getStreamNames();
263 final Module restconfModule = getRestconfModule();
264 final DataSchemaNode streamSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
265 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
266 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
268 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
269 .mapBuilder((ListSchemaNode) streamSchemaNode);
271 for (final String streamName : availableStreams) {
272 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
275 final DataSchemaNode streamsContainerSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
276 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
277 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
279 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
280 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
281 streamsContainerBuilder.withChild(listStreamsBuilder.build());
284 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
285 schemaContext), streamsContainerBuilder.build(), QueryParametersParser.parseWriterParameters(uriInfo));
289 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
290 final Set<Module> allModules = this.controllerContext.getAllModules();
291 return operationsFromModulesToNormalizedContext(allModules, null);
295 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
296 Set<Module> modules = null;
297 DOMMountPoint mountPoint = null;
298 if (identifier.contains(ControllerContext.MOUNT)) {
299 final InstanceIdentifierContext<?> mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
300 mountPoint = mountPointIdentifier.getMountPoint();
301 modules = this.controllerContext.getAllModules(mountPoint);
304 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
305 LOG.debug(errMsg + ControllerContext.MOUNT + " for " + identifier);
306 throw new RestconfDocumentedException(errMsg + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
309 return operationsFromModulesToNormalizedContext(modules, mountPoint);
312 private NormalizedNodeContext operationsFromModulesToNormalizedContext(final Set<Module> modules,
313 final DOMMountPoint mountPoint) {
314 throw new UnsupportedOperationException();
317 private Module getRestconfModule() {
318 final Module restconfModule = this.controllerContext.getRestconfModule();
319 if (restconfModule == null) {
320 LOG.debug("ietf-restconf module was not found.");
321 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
322 ErrorTag.OPERATION_NOT_SUPPORTED);
325 return restconfModule;
328 private static QName getModuleNameAndRevision(final String identifier) {
329 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
330 String moduleNameAndRevision = "";
331 if (mountIndex >= 0) {
332 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
334 moduleNameAndRevision = identifier;
337 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
338 final Iterable<String> split = splitter.split(moduleNameAndRevision);
339 final List<String> pathArgs = Lists.<String> newArrayList(split);
340 if (pathArgs.size() < 2) {
341 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
342 throw new RestconfDocumentedException(
343 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
344 ErrorTag.INVALID_VALUE);
348 final String moduleName = pathArgs.get(0);
349 final String revision = pathArgs.get(1);
350 final Date moduleRevision = REVISION_FORMAT.parse(revision);
351 return QName.create(null, moduleRevision, moduleName);
352 } catch (final ParseException e) {
353 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' " + identifier);
354 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
355 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
360 public Object getRoot() {
365 public NormalizedNodeContext invokeRpc(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
366 final SchemaPath type = payload.getInstanceIdentifierContext().getSchemaNode().getPath();
367 final URI namespace = payload.getInstanceIdentifierContext().getSchemaNode().getQName().getNamespace();
368 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
369 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
370 final SchemaContext schemaContext;
371 if (mountPoint != null) {
372 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
373 if ( ! mountRpcServices.isPresent()) {
374 LOG.debug("Error: Rpc service is missing.");
375 throw new RestconfDocumentedException("Rpc service is missing.");
377 schemaContext = mountPoint.getSchemaContext();
378 response = mountRpcServices.get().invokeRpc(type, payload.getData());
380 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
381 response = invokeSalRemoteRpcSubscribeRPC(payload);
383 response = this.broker.invokeRpc(type, payload.getData());
385 schemaContext = this.controllerContext.getGlobalSchema();
388 final DOMRpcResult result = checkRpcResponse(response);
390 RpcDefinition resultNodeSchema = null;
391 final NormalizedNode<?, ?> resultData = result.getResult();
392 if ((result != null) && (result.getResult() != null)) {
393 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
396 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
397 resultNodeSchema, mountPoint, schemaContext), resultData,
398 QueryParametersParser.parseWriterParameters(uriInfo));
401 private static DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
402 if (response == null) {
406 final DOMRpcResult retValue = response.get();
407 if ((retValue.getErrors() == null) || retValue.getErrors().isEmpty()) {
410 LOG.debug("RpcError message", retValue.getErrors());
411 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
412 } catch (final InterruptedException e) {
413 final String errMsg = "The operation was interrupted while executing and did not complete.";
414 LOG.debug("Rpc Interrupt - " + errMsg, e);
415 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
416 } catch (final ExecutionException e) {
417 LOG.debug("Execution RpcError: ", e);
418 Throwable cause = e.getCause();
420 while (cause.getCause() != null) {
421 cause = cause.getCause();
424 if (cause instanceof IllegalArgumentException) {
425 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
426 ErrorTag.INVALID_VALUE);
427 } else if (cause instanceof DOMRpcImplementationNotAvailableException) {
428 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
430 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",cause);
432 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",e);
434 } catch (final CancellationException e) {
435 final String errMsg = "The operation was cancelled while executing.";
436 LOG.debug("Cancel RpcExecution: " + errMsg, e);
437 throw new RestconfDocumentedException(errMsg, ErrorType.RPC, ErrorTag.PARTIAL_OPERATION);
441 private static void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
442 if ((inputSchema != null) && (payload.getData() == null)) {
443 // expected a non null payload
444 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
445 } else if ((inputSchema == null) && (payload.getData() != null)) {
446 // did not expect any input
447 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
451 // TODO: Validate "mandatory" and "config" values here??? Or should those be
453 // validate in a more central location inside MD-SAL core.
457 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
458 final ContainerNode value = (ContainerNode) payload.getData();
459 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
460 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
461 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
462 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
464 if (!(pathValue instanceof YangInstanceIdentifier)) {
465 final String errMsg = "Instance identifier was not normalized correctly ";
466 LOG.debug(errMsg + rpcQName);
467 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
470 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
471 String streamName = null;
472 if (!pathIdentifier.isEmpty()) {
473 final String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
475 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class, DATASTORE_PARAM_NAME);
476 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
478 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
479 scope = scope == null ? DEFAULT_SCOPE : scope;
481 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
482 + "/scope=" + scope);
485 if (Strings.isNullOrEmpty(streamName)) {
486 final String errMsg = "Path is empty or contains value node which is not Container or List build-in type.";
487 LOG.debug(errMsg + pathIdentifier);
488 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
491 final QName outputQname = QName.create(rpcQName, "output");
492 final QName streamNameQname = QName.create(rpcQName, "stream-name");
494 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
495 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
497 if (!Notificator.existListenerFor(streamName)) {
498 Notificator.createListener(pathIdentifier, streamName);
501 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
503 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
507 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
508 if ((noPayload != null) && !CharMatcher.WHITESPACE.matchesAllOf(noPayload)) {
509 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
512 String identifierEncoded = null;
513 DOMMountPoint mountPoint = null;
514 final SchemaContext schemaContext;
515 if (identifier.contains(ControllerContext.MOUNT)) {
516 // mounted RPC call - look up mount instance.
517 final InstanceIdentifierContext<?> mountPointId = this.controllerContext.toMountPointIdentifier(identifier);
518 mountPoint = mountPointId.getMountPoint();
519 schemaContext = mountPoint.getSchemaContext();
520 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
521 + ControllerContext.MOUNT.length() + 1;
522 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
523 identifierEncoded = remoteRpcName;
525 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
526 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
527 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
528 LOG.debug(slashErrorMsg);
529 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
531 identifierEncoded = identifier;
532 schemaContext = this.controllerContext.getGlobalSchema();
535 final String identifierDecoded = this.controllerContext.urlPathArgDecode(identifierEncoded);
537 RpcDefinition rpc = null;
538 if (mountPoint == null) {
539 rpc = this.controllerContext.getRpcDefinition(identifierDecoded, null);
541 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
545 LOG.debug("RPC " + identifierDecoded + " does not exist.");
546 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
549 if (rpc.getInput() != null) {
550 LOG.debug("RPC " + rpc + " does not need input value.");
551 // FIXME : find a correct Error from specification
552 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
555 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
556 if (mountPoint != null) {
557 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
558 if ( ! mountRpcServices.isPresent()) {
559 throw new RestconfDocumentedException("Rpc service is missing.");
561 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
563 response = this.broker.invokeRpc(rpc.getPath(), null);
566 final DOMRpcResult result = checkRpcResponse(response);
568 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpc, mountPoint, schemaContext),
569 result.getResult(), QueryParametersParser.parseWriterParameters(uriInfo));
572 private static RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
573 final String[] splittedIdentifier = identifierDecoded.split(":");
574 if (splittedIdentifier.length != 2) {
575 final String errMsg = identifierDecoded + " couldn't be splitted to 2 parts (module:rpc name)";
577 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.INVALID_VALUE);
579 for (final Module module : schemaContext.getModules()) {
580 if (module.getName().equals(splittedIdentifier[0])) {
581 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
582 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
583 return rpcDefinition;
592 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
593 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
594 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
595 NormalizedNode<?, ?> data = null;
596 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
597 if (mountPoint != null) {
598 data = this.broker.readConfigurationData(mountPoint, normalizedII);
600 data = this.broker.readConfigurationData(normalizedII);
603 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
604 LOG.debug(errMsg + identifier);
605 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
607 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
611 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo uriInfo) {
612 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
613 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
614 NormalizedNode<?, ?> data = null;
615 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
616 if (mountPoint != null) {
617 data = this.broker.readOperationalData(mountPoint, normalizedII);
619 data = this.broker.readOperationalData(normalizedII);
622 final String errMsg = "Request could not be completed because the relevant data model content does not exist ";
623 LOG.debug(errMsg + identifier);
624 throw new RestconfDocumentedException(errMsg , ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
626 return new NormalizedNodeContext(iiWithData, data, QueryParametersParser.parseWriterParameters(uriInfo));
630 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
631 Preconditions.checkNotNull(identifier);
632 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
634 validateInput(iiWithData.getSchemaNode(), payload);
635 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
636 validateListKeysEqualityInPayloadAndUri(payload);
638 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
639 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
642 * There is a small window where another write transaction could be updating the same data
643 * simultaneously and we get an OptimisticLockFailedException. This error is likely
644 * transient and The WriteTransaction#submit API docs state that a retry will likely
645 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
646 * probably will never succeed so we'll fail in that case.
648 * By retrying we're attempting to hide the internal implementation of the data store and
649 * how it handles concurrent updates from the restconf client. The client has instructed us
650 * to put the data and we should make every effort to do so without pushing optimistic lock
651 * failures back to the client and forcing them to handle it via retry (and having to
652 * document the behavior).
657 if (mountPoint != null) {
658 this.broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
660 this.broker.commitConfigurationDataPut(this.controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
664 } catch (final TransactionCommitFailedException e) {
665 if(e instanceof OptimisticLockFailedException) {
667 LOG.debug("Got OptimisticLockFailedException on last try - failing " + identifier);
668 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
671 LOG.debug("Got OptimisticLockFailedException - trying again " + identifier);
673 LOG.debug("Update ConfigDataStore fail " + identifier, e);
674 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
676 } catch (final Exception e) {
677 final String errMsg = "Error updating data ";
678 LOG.debug(errMsg + identifier, e);
679 throw new RestconfDocumentedException(errMsg, e);
683 return Response.status(Status.OK).build();
686 private static void validateTopLevelNodeName(final NormalizedNodeContext node,
687 final YangInstanceIdentifier identifier) {
689 final String payloadName = node.getData().getNodeType().getLocalName();
692 if (identifier.isEmpty()) {
694 if (!node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
695 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
696 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
700 final String identifierName = identifier.getLastPathArgument().getNodeType().getLocalName();
701 if (!payloadName.equals(identifierName)) {
702 throw new RestconfDocumentedException("Payload name (" + payloadName
703 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
704 ErrorTag.MALFORMED_MESSAGE);
710 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
712 * @throws RestconfDocumentedException
713 * if key values or key count in payload and URI isn't equal
716 private static void validateListKeysEqualityInPayloadAndUri(final NormalizedNodeContext payload) {
717 Preconditions.checkArgument(payload != null);
718 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
719 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
720 final SchemaNode schemaNode = iiWithData.getSchemaNode();
721 final NormalizedNode<?, ?> data = payload.getData();
722 if (schemaNode instanceof ListSchemaNode) {
723 final List<QName> keyDefinitions = ((ListSchemaNode) schemaNode).getKeyDefinition();
724 if ((lastPathArgument instanceof NodeIdentifierWithPredicates) && (data instanceof MapEntryNode)) {
725 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument).getKeyValues();
726 isEqualUriAndPayloadKeyValues(uriKeyValues, (MapEntryNode) data, keyDefinitions);
731 private static void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues,
732 final MapEntryNode payload, final List<QName> keyDefinitions) {
734 final Map<QName, Object> mutableCopyUriKeyValues = Maps.newHashMap(uriKeyValues);
735 for (final QName keyDefinition : keyDefinitions) {
736 final Object uriKeyValue = mutableCopyUriKeyValues.remove(keyDefinition);
737 // should be caught during parsing URI to InstanceIdentifier
738 RestconfValidationUtils.checkDocumentedError(uriKeyValue != null, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING,
739 "Missing key " + keyDefinition + " in URI.");
741 final Object dataKeyValue = payload.getIdentifier().getKeyValues().get(keyDefinition);
743 if ( ! uriKeyValue.equals(dataKeyValue)) {
744 final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
745 "' specified in the URI doesn't match the value '" + dataKeyValue + "' specified in the message body. ";
746 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
752 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
753 return createConfigurationData(payload, uriInfo);
756 // FIXME create RestconfIdetifierHelper and move this method there
757 private static YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
758 Preconditions.checkArgument(payload != null);
759 Preconditions.checkArgument(payload.getData() != null);
760 Preconditions.checkArgument(payload.getData().getNodeType() != null);
761 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
762 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
764 final QName payloadNodeQname = payload.getData().getNodeType();
765 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
766 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
769 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
770 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
771 if(parentSchemaNode instanceof DataNodeContainer) {
772 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
773 for (final DataSchemaNode child : cast.getChildNodes()) {
774 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
775 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
779 if (parentSchemaNode instanceof RpcDefinition) {
782 final String errMsg = "Error parsing input: DataSchemaNode has not children ";
783 LOG.info(errMsg + yangIdent);
784 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
788 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
789 if (payload == null) {
790 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
793 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
794 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
795 // if (payloadNS == null) {
796 // throw new RestconfDocumentedException(
797 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
798 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
801 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
802 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
803 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
805 if (mountPoint != null) {
806 this.broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
808 this.broker.commitConfigurationDataPost(this.controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
810 } catch(final RestconfDocumentedException e) {
812 } catch (final Exception e) {
813 final String errMsg = "Error creating data ";
814 LOG.info(errMsg + (uriInfo != null ? uriInfo.getPath() : ""), e);
815 throw new RestconfDocumentedException(errMsg, e);
818 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
819 // FIXME: Provide path to result.
820 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
821 if (location != null) {
822 responseBuilder.location(location);
824 return responseBuilder.build();
827 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
828 if(uriInfo == null) {
829 // This is null if invoked internally
833 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
834 uriBuilder.path("config");
836 uriBuilder.path(this.controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
837 } catch (final Exception e) {
838 LOG.info("Location for instance identifier" + normalizedII + "wasn't created", e);
841 return uriBuilder.build();
845 public Response deleteConfigurationData(final String identifier) {
846 final InstanceIdentifierContext<?> iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
847 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
848 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
851 if (mountPoint != null) {
852 this.broker.commitConfigurationDataDelete(mountPoint, normalizedII);
854 this.broker.commitConfigurationDataDelete(normalizedII).get();
856 } catch (final Exception e) {
857 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
858 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
859 if (searchedException.isPresent()) {
860 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
862 final String errMsg = "Error while deleting data";
864 throw new RestconfDocumentedException(errMsg, e);
866 return Response.status(Status.OK).build();
870 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
872 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
874 * <li>datastore - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)</li>
875 * <li>scope - default BASE (other values of {@link DataChangeScope})</li>
879 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
880 final String streamName = Notificator.createStreamNameFromUri(identifier);
881 if (Strings.isNullOrEmpty(streamName)) {
882 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
885 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
886 if (listener == null) {
887 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
890 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
891 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
892 paramToValues.get(DATASTORE_PARAM_NAME));
893 if (datastore == null) {
894 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
895 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
897 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
899 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
900 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
903 this.broker.registerToListenDataChanges(datastore, scope, listener);
905 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
906 int notificationPort = NOTIFICATION_PORT;
908 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
909 notificationPort = webSocketServerInstance.getPort();
910 } catch (final NullPointerException e) {
911 WebSocketServer.createInstance(NOTIFICATION_PORT);
913 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
914 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
916 return Response.status(Status.OK).location(uriToWebsocketServer).build();
920 public PATCHStatusContext patchConfigurationData(final String identifier, final PATCHContext context, final UriInfo uriInfo) {
921 if (context == null) {
922 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
924 return this.broker.patchConfigurationDataWithinTransaction(context, this.controllerContext.getGlobalSchema());
928 public PATCHStatusContext patchConfigurationData(final PATCHContext context, @Context final UriInfo uriInfo) {
929 if (context == null) {
930 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
932 return this.broker.patchConfigurationDataWithinTransaction(context, this.controllerContext.getGlobalSchema());
936 * Load parameter for subscribing to stream from input composite node
940 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
942 private static <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
943 final String paramName) {
944 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
945 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
948 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
949 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
950 if (!enumNode.isPresent()) {
953 final Object rawValue = enumNode.get().getValue();
954 if (!(rawValue instanceof String)) {
958 return resolveAsEnum(classDescriptor, (String) rawValue);
962 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
964 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
967 private static <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
968 if (Strings.isNullOrEmpty(value)) {
971 return resolveAsEnum(classDescriptor, value);
974 private static <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
975 final T[] enumConstants = classDescriptor.getEnumConstants();
976 if (enumConstants != null) {
977 for (final T enm : classDescriptor.getEnumConstants()) {
978 if (((Enum<?>) enm).name().equals(value)) {
986 private static Map<String, String> resolveValuesFromUri(final String uri) {
987 final Map<String, String> result = new HashMap<>();
988 final String[] tokens = uri.split("/");
989 for (int i = 1; i < tokens.length; i++) {
990 final String[] parameterTokens = tokens[i].split("=");
991 if (parameterTokens.length == 2) {
992 result.put(parameterTokens[0], parameterTokens[1]);
998 public BigInteger getOperationalReceived() {
999 // TODO Auto-generated method stub
1003 private MapNode makeModuleMapNode(final Set<Module> modules) {
1004 Preconditions.checkNotNull(modules);
1005 final Module restconfModule = getRestconfModule();
1006 final DataSchemaNode moduleSchemaNode = this.controllerContext.getRestconfModuleRestConfSchemaNode(
1007 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1008 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1010 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1011 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1013 for (final Module module : modules) {
1014 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1016 return listModuleBuilder.build();
1019 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1020 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1021 "moduleSchemaNode has to be of type ListSchemaNode");
1022 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1023 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1024 .mapEntryBuilder(listModuleSchemaNode);
1026 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1027 (listModuleSchemaNode), "name");
1028 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1029 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1030 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1033 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1034 (listModuleSchemaNode), "revision");
1035 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1036 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1037 final String revision = REVISION_FORMAT.format(module.getRevision());
1038 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1041 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1042 (listModuleSchemaNode), "namespace");
1043 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1044 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1045 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1046 .withValue(module.getNamespace().toString()).build());
1048 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1049 (listModuleSchemaNode), "feature");
1050 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1051 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1052 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1053 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1054 for (final FeatureDefinition feature : module.getFeatures()) {
1055 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1056 .withValue(feature.getQName().getLocalName()).build());
1058 moduleNodeValues.withChild(featuresBuilder.build());
1060 return moduleNodeValues.build();
1063 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1064 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1065 "streamSchemaNode has to be of type ListSchemaNode");
1066 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1067 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1068 .mapEntryBuilder(listStreamSchemaNode);
1070 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1071 (listStreamSchemaNode), "name");
1072 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1073 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1074 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1077 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1078 (listStreamSchemaNode), "description");
1079 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1080 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1081 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1082 .withValue("DESCRIPTION_PLACEHOLDER").build());
1084 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1085 (listStreamSchemaNode), "replay-support");
1086 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1087 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1088 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1089 .withValue(Boolean.valueOf(true)).build());
1091 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1092 (listStreamSchemaNode), "replay-log-creation-time");
1093 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1094 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1095 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1096 .withValue("").build());
1098 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1099 (listStreamSchemaNode), "events");
1100 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1101 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1102 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1103 .withValue("").build());
1105 return streamNodeValues.build();