2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2014 Brocade Communication Systems, Inc.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.restconf.impl;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Predicates;
14 import com.google.common.base.Splitter;
15 import com.google.common.base.Strings;
16 import com.google.common.base.Throwables;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
19 import com.google.common.collect.Sets;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.Futures;
22 import java.math.BigInteger;
24 import java.net.URISyntaxException;
25 import java.text.ParseException;
26 import java.text.SimpleDateFormat;
27 import java.util.Collections;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
34 import java.util.concurrent.CancellationException;
35 import java.util.concurrent.ExecutionException;
36 import javax.ws.rs.core.Response;
37 import javax.ws.rs.core.Response.ResponseBuilder;
38 import javax.ws.rs.core.Response.Status;
39 import javax.ws.rs.core.UriBuilder;
40 import javax.ws.rs.core.UriInfo;
41 import org.apache.commons.lang3.StringUtils;
42 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
43 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
44 import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
45 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
46 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
47 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
50 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
51 import org.opendaylight.controller.sal.rest.api.Draft02;
52 import org.opendaylight.controller.sal.rest.api.RestconfService;
53 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
54 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
55 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
56 import org.opendaylight.controller.sal.streams.listeners.Notificator;
57 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.common.QNameModule;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
63 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
64 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
65 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
66 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
67 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
68 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
70 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
71 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModifiedNodeDoesNotExistException;
72 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
73 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
74 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
75 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
76 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
77 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
78 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
80 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
82 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.Module;
86 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
87 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
88 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
90 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
94 public class RestconfImpl implements RestconfService {
96 private enum UriParameters {
97 PRETTY_PRINT("prettyPrint"),
100 private String uriParameterName;
102 UriParameters(final String uriParameterName) {
103 this.uriParameterName = uriParameterName;
107 public String toString() {
108 return uriParameterName;
112 private static final RestconfImpl INSTANCE = new RestconfImpl();
114 private static final int NOTIFICATION_PORT = 8181;
116 private static final int CHAR_NOT_FOUND = -1;
118 private static final String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
120 private static final SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
122 private static final String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
124 private static final String SAL_REMOTE_RPC_SUBSRCIBE = "create-data-change-event-subscription";
126 private BrokerFacade broker;
128 private ControllerContext controllerContext;
130 private static final Logger LOG = LoggerFactory.getLogger(RestconfImpl.class);
132 private static final DataChangeScope DEFAULT_SCOPE = DataChangeScope.BASE;
134 private static final LogicalDatastoreType DEFAULT_DATASTORE = LogicalDatastoreType.CONFIGURATION;
136 private static final URI NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT = URI.create("urn:sal:restconf:event:subscription");
138 private static final String DATASTORE_PARAM_NAME = "datastore";
140 private static final String SCOPE_PARAM_NAME = "scope";
142 private static final String NETCONF_BASE = "urn:ietf:params:xml:ns:netconf:base:1.0";
144 private static final String NETCONF_BASE_PAYLOAD_NAME = "data";
146 private static final QName NETCONF_BASE_QNAME;
148 private static final QNameModule SAL_REMOTE_AUGMENT;
150 private static final YangInstanceIdentifier.AugmentationIdentifier SAL_REMOTE_AUG_IDENTIFIER;
154 final Date eventSubscriptionAugRevision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-07-08");
155 NETCONF_BASE_QNAME = QName.create(QNameModule.create(new URI(NETCONF_BASE), null), NETCONF_BASE_PAYLOAD_NAME );
156 SAL_REMOTE_AUGMENT = QNameModule.create(NAMESPACE_EVENT_SUBSCRIPTION_AUGMENT,
157 eventSubscriptionAugRevision);
158 SAL_REMOTE_AUG_IDENTIFIER = new YangInstanceIdentifier.AugmentationIdentifier(Sets.newHashSet(QName.create(SAL_REMOTE_AUGMENT, "scope"),
159 QName.create(SAL_REMOTE_AUGMENT, "datastore")));
160 } catch (final ParseException e) {
161 throw new RestconfDocumentedException(
162 "It wasn't possible to convert revision date of sal-remote-augment to date", ErrorType.APPLICATION,
163 ErrorTag.OPERATION_FAILED);
164 } catch (final URISyntaxException e) {
165 throw new RestconfDocumentedException(
166 "It wasn't possible to create instance of URI class with "+NETCONF_BASE+" URI", ErrorType.APPLICATION,
167 ErrorTag.OPERATION_FAILED);
171 public void setBroker(final BrokerFacade broker) {
172 this.broker = broker;
175 public void setControllerContext(final ControllerContext controllerContext) {
176 this.controllerContext = controllerContext;
179 private RestconfImpl() {
182 public static RestconfImpl getInstance() {
187 public NormalizedNodeContext getModules(final UriInfo uriInfo) {
188 final Set<Module> allModules = controllerContext.getAllModules();
189 final MapNode allModuleMap = makeModuleMapNode(allModules);
191 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
193 final Module restconfModule = getRestconfModule();
194 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
195 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
196 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
198 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
199 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
200 moduleContainerBuilder.withChild(allModuleMap);
202 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
203 null, schemaContext), moduleContainerBuilder.build());
207 * Valid only for mount point
210 public NormalizedNodeContext getModules(final String identifier, final UriInfo uriInfo) {
211 Preconditions.checkNotNull(identifier);
212 if ( ! identifier.contains(ControllerContext.MOUNT)) {
213 final String errMsg = "URI has bad format. If modules behind mount point should be showed,"
214 + " URI has to end with " + ControllerContext.MOUNT;
215 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
218 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
219 final DOMMountPoint mountPoint = mountPointIdentifier.getMountPoint();
220 final Set<Module> modules = controllerContext.getAllModules(mountPoint);
221 final MapNode mountPointModulesMap = makeModuleMapNode(modules);
223 final Module restconfModule = getRestconfModule();
224 final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
225 restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
226 Preconditions.checkState(modulesSchemaNode instanceof ContainerSchemaNode);
228 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> moduleContainerBuilder =
229 Builders.containerBuilder((ContainerSchemaNode) modulesSchemaNode);
230 moduleContainerBuilder.withChild(mountPointModulesMap);
232 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, modulesSchemaNode,
233 mountPoint, controllerContext.getGlobalSchema()), moduleContainerBuilder.build());
237 public NormalizedNodeContext getModule(final String identifier, final UriInfo uriInfo) {
238 Preconditions.checkNotNull(identifier);
239 final QName moduleNameAndRevision = getModuleNameAndRevision(identifier);
240 Module module = null;
241 DOMMountPoint mountPoint = null;
242 final SchemaContext schemaContext;
243 if (identifier.contains(ControllerContext.MOUNT)) {
244 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
245 mountPoint = mountPointIdentifier.getMountPoint();
246 module = controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
247 schemaContext = mountPoint.getSchemaContext();
249 module = controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
250 schemaContext = controllerContext.getGlobalSchema();
253 if (module == null) {
254 final String errMsg = "Module with name '" + moduleNameAndRevision.getLocalName()
255 + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.";
256 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
259 final Module restconfModule = getRestconfModule();
260 final Set<Module> modules = Collections.singleton(module);
261 final MapNode moduleMap = makeModuleMapNode(modules);
263 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
264 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
265 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
267 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, moduleSchemaNode, mountPoint,
268 schemaContext), moduleMap);
272 public NormalizedNodeContext getAvailableStreams(final UriInfo uriInfo) {
273 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
274 final Set<String> availableStreams = Notificator.getStreamNames();
275 final Module restconfModule = getRestconfModule();
276 final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
277 Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
278 Preconditions.checkState(streamSchemaNode instanceof ListSchemaNode);
280 final CollectionNodeBuilder<MapEntryNode, MapNode> listStreamsBuilder = Builders
281 .mapBuilder((ListSchemaNode) streamSchemaNode);
283 for (final String streamName : availableStreams) {
284 listStreamsBuilder.withChild(toStreamEntryNode(streamName, streamSchemaNode));
287 final DataSchemaNode streamsContainerSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
288 restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
289 Preconditions.checkState(streamsContainerSchemaNode instanceof ContainerSchemaNode);
291 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> streamsContainerBuilder =
292 Builders.containerBuilder((ContainerSchemaNode) streamsContainerSchemaNode);
293 streamsContainerBuilder.withChild(listStreamsBuilder.build());
296 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, streamsContainerSchemaNode, null,
297 schemaContext), streamsContainerBuilder.build());
301 public NormalizedNodeContext getOperations(final UriInfo uriInfo) {
302 final Set<Module> allModules = controllerContext.getAllModules();
303 return operationsFromModulesToNormalizedContext(allModules, null);
307 public NormalizedNodeContext getOperations(final String identifier, final UriInfo uriInfo) {
308 Set<Module> modules = null;
309 DOMMountPoint mountPoint = null;
310 if (identifier.contains(ControllerContext.MOUNT)) {
311 final InstanceIdentifierContext<?> mountPointIdentifier = controllerContext.toMountPointIdentifier(identifier);
312 mountPoint = mountPointIdentifier.getMountPoint();
313 modules = controllerContext.getAllModules(mountPoint);
316 final String errMsg = "URI has bad format. If operations behind mount point should be showed, URI has to end with ";
317 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) {
326 // FIXME find best way to change restconf-netconf yang schema for provide this functionality
327 final String errMsg = "We are not able support view operations functionality yet.";
328 throw new RestconfDocumentedException(errMsg, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
331 private Module getRestconfModule() {
332 final Module restconfModule = controllerContext.getRestconfModule();
333 if (restconfModule == null) {
334 throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
335 ErrorTag.OPERATION_NOT_SUPPORTED);
338 return restconfModule;
341 private QName getModuleNameAndRevision(final String identifier) {
342 final int mountIndex = identifier.indexOf(ControllerContext.MOUNT);
343 String moduleNameAndRevision = "";
344 if (mountIndex >= 0) {
345 moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
347 moduleNameAndRevision = identifier;
350 final Splitter splitter = Splitter.on("/").omitEmptyStrings();
351 final Iterable<String> split = splitter.split(moduleNameAndRevision);
352 final List<String> pathArgs = Lists.<String> newArrayList(split);
353 if (pathArgs.size() < 2) {
354 throw new RestconfDocumentedException(
355 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
356 ErrorTag.INVALID_VALUE);
360 final String moduleName = pathArgs.get(0);
361 final String revision = pathArgs.get(1);
362 final Date moduleRevision = REVISION_FORMAT.parse(revision);
363 return QName.create(null, moduleRevision, moduleName);
364 } catch (final ParseException e) {
365 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 (identifier.contains(MOUNT_POINT_MODULE_NAME) && mountPoint != null) {
383 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
384 if ( ! mountRpcServices.isPresent()) {
385 throw new RestconfDocumentedException("Rpc service is missing.");
387 schemaContext = mountPoint.getSchemaContext();
388 response = mountRpcServices.get().invokeRpc(type, payload.getData());
390 if (namespace.toString().equals(SAL_REMOTE_NAMESPACE)) {
391 response = invokeSalRemoteRpcSubscribeRPC(payload);
393 response = broker.invokeRpc(type, payload.getData());
395 schemaContext = controllerContext.getGlobalSchema();
398 final DOMRpcResult result = checkRpcResponse(response);
400 RpcDefinition resultNodeSchema = null;
401 final NormalizedNode<?, ?> resultData = result.getResult();
402 if (result != null && result.getResult() != null) {
403 resultNodeSchema = (RpcDefinition) payload.getInstanceIdentifierContext().getSchemaNode();
406 return new NormalizedNodeContext(new InstanceIdentifierContext<RpcDefinition>(null,
407 resultNodeSchema, mountPoint, schemaContext), resultData);
410 private DOMRpcResult checkRpcResponse(final CheckedFuture<DOMRpcResult, DOMRpcException> response) {
411 if (response == null) {
415 final DOMRpcResult retValue = response.get();
416 if (retValue.getErrors() == null || retValue.getErrors().isEmpty()) {
419 throw new RestconfDocumentedException("RpcError message", null, retValue.getErrors());
420 } catch (final InterruptedException e) {
421 throw new RestconfDocumentedException(
422 "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
423 ErrorTag.PARTIAL_OPERATION);
424 } catch (final ExecutionException e) {
425 Throwable cause = e.getCause();
427 while (cause.getCause() != null) {
428 cause = cause.getCause();
431 if (cause instanceof IllegalArgumentException) {
432 throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
433 ErrorTag.INVALID_VALUE);
436 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
439 throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
442 } catch (final CancellationException e) {
443 throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
444 ErrorTag.PARTIAL_OPERATION);
448 private void validateInput(final SchemaNode inputSchema, final NormalizedNodeContext payload) {
449 if (inputSchema != null && payload.getData() == null) {
450 // expected a non null payload
451 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
452 } else if (inputSchema == null && payload.getData() != null) {
453 // did not expect any input
454 throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
458 // TODO: Validate "mandatory" and "config" values here??? Or should those be
460 // validate in a more central location inside MD-SAL core.
464 private CheckedFuture<DOMRpcResult, DOMRpcException> invokeSalRemoteRpcSubscribeRPC(final NormalizedNodeContext payload) {
465 final ContainerNode value = (ContainerNode) payload.getData();
466 final QName rpcQName = payload.getInstanceIdentifierContext().getSchemaNode().getQName();
467 final Optional<DataContainerChild<? extends PathArgument, ?>> path = value.getChild(new NodeIdentifier(
468 QName.create(payload.getInstanceIdentifierContext().getSchemaNode().getQName(), "path")));
469 final Object pathValue = path.isPresent() ? path.get().getValue() : null;
471 if (!(pathValue instanceof YangInstanceIdentifier)) {
472 throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
473 ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
476 final YangInstanceIdentifier pathIdentifier = ((YangInstanceIdentifier) pathValue);
477 String streamName = null;
478 if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
479 final String fullRestconfIdentifier = controllerContext.toFullRestconfIdentifier(pathIdentifier, null);
481 LogicalDatastoreType datastore = parseEnumTypeParameter(value, LogicalDatastoreType.class,
482 DATASTORE_PARAM_NAME);
483 datastore = datastore == null ? DEFAULT_DATASTORE : datastore;
485 DataChangeScope scope = parseEnumTypeParameter(value, DataChangeScope.class, SCOPE_PARAM_NAME);
486 scope = scope == null ? DEFAULT_SCOPE : scope;
488 streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier + "/datastore=" + datastore
489 + "/scope=" + scope);
492 if (Strings.isNullOrEmpty(streamName)) {
493 throw new RestconfDocumentedException(
494 "Path is empty or contains value node which is not Container or List build-in type.",
495 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
498 final QName outputQname = QName.create(rpcQName, "output");
499 final QName streamNameQname = QName.create(rpcQName, "stream-name");
501 final ContainerNode output = ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(outputQname))
502 .withChild(ImmutableNodes.leafNode(streamNameQname, streamName)).build();
504 if (!Notificator.existListenerFor(streamName)) {
505 final YangInstanceIdentifier normalizedPathIdentifier = controllerContext.toNormalized(pathIdentifier);
506 Notificator.createListener(normalizedPathIdentifier, streamName);
509 final DOMRpcResult defaultDOMRpcResult = new DefaultDOMRpcResult(output);
511 return Futures.immediateCheckedFuture(defaultDOMRpcResult);
515 public NormalizedNodeContext invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
516 if (StringUtils.isNotBlank(noPayload)) {
517 throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
520 String identifierEncoded = null;
521 DOMMountPoint mountPoint = null;
522 final SchemaContext schemaContext;
523 if (identifier.contains(ControllerContext.MOUNT)) {
524 // mounted RPC call - look up mount instance.
525 final InstanceIdentifierContext<?> mountPointId = controllerContext.toMountPointIdentifier(identifier);
526 mountPoint = mountPointId.getMountPoint();
527 schemaContext = mountPoint.getSchemaContext();
528 final int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
529 + ControllerContext.MOUNT.length() + 1;
530 final String remoteRpcName = identifier.substring(startOfRemoteRpcName);
531 identifierEncoded = remoteRpcName;
533 } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
534 final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
535 + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
536 throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
538 identifierEncoded = identifier;
539 schemaContext = controllerContext.getGlobalSchema();
542 final String identifierDecoded = controllerContext.urlPathArgDecode(identifierEncoded);
544 RpcDefinition rpc = null;
545 if (mountPoint == null) {
546 rpc = controllerContext.getRpcDefinition(identifierDecoded);
548 rpc = findRpc(mountPoint.getSchemaContext(), identifierDecoded);
552 throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
555 if (rpc.getInput() != null) {
556 // FIXME : find a correct Error from specification
557 throw new IllegalStateException("RPC " + rpc + " does'n need input value!");
560 final CheckedFuture<DOMRpcResult, DOMRpcException> response;
561 if (mountPoint != null) {
562 final Optional<DOMRpcService> mountRpcServices = mountPoint.getService(DOMRpcService.class);
563 if ( ! mountRpcServices.isPresent()) {
564 throw new RestconfDocumentedException("Rpc service is missing.");
566 response = mountRpcServices.get().invokeRpc(rpc.getPath(), null);
568 response = broker.invokeRpc(rpc.getPath(), null);
571 final DOMRpcResult result = checkRpcResponse(response);
573 DataSchemaNode resultNodeSchema = null;
574 NormalizedNode<?, ?> resultData = null;
575 if (result != null && result.getResult() != null) {
576 resultData = result.getResult();
577 final ContainerSchemaNode rpcDataSchemaNode =
578 SchemaContextUtil.getRpcDataSchema(schemaContext, rpc.getOutput().getPath());
579 resultNodeSchema = rpcDataSchemaNode.getDataChildByName(result.getResult().getNodeType());
582 return new NormalizedNodeContext(new InstanceIdentifierContext<>(null, resultNodeSchema, mountPoint,
583 schemaContext), resultData);
586 private RpcDefinition findRpc(final SchemaContext schemaContext, final String identifierDecoded) {
587 final String[] splittedIdentifier = identifierDecoded.split(":");
588 if (splittedIdentifier.length != 2) {
589 throw new RestconfDocumentedException(identifierDecoded
590 + " couldn't be splitted to 2 parts (module:rpc name)", ErrorType.APPLICATION,
591 ErrorTag.INVALID_VALUE);
593 for (final Module module : schemaContext.getModules()) {
594 if (module.getName().equals(splittedIdentifier[0])) {
595 for (final RpcDefinition rpcDefinition : module.getRpcs()) {
596 if (rpcDefinition.getQName().getLocalName().equals(splittedIdentifier[1])) {
597 return rpcDefinition;
606 public NormalizedNodeContext readConfigurationData(final String identifier, final UriInfo uriInfo) {
607 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
608 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
609 NormalizedNode<?, ?> data = null;
610 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
611 if (mountPoint != null) {
612 data = broker.readConfigurationData(mountPoint, normalizedII);
614 data = broker.readConfigurationData(normalizedII);
617 throw new RestconfDocumentedException(
618 "Request could not be completed because the relevant data model content does not exist.",
619 ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
621 return new NormalizedNodeContext(iiWithData, data);
624 // FIXME: Move this to proper place
625 @SuppressWarnings("unused")
626 private Integer parseDepthParameter(final UriInfo info) {
627 final String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
628 if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
633 final Integer depth = Integer.valueOf(param);
635 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
636 "Invalid depth parameter: " + depth, null,
637 "The depth parameter must be an integer > 1 or \"unbounded\""));
641 } catch (final NumberFormatException e) {
642 throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
643 "Invalid depth parameter: " + e.getMessage(), null,
644 "The depth parameter must be an integer > 1 or \"unbounded\""));
649 public NormalizedNodeContext readOperationalData(final String identifier, final UriInfo info) {
650 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
651 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
652 NormalizedNode<?, ?> data = null;
653 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
654 if (mountPoint != null) {
655 data = broker.readOperationalData(mountPoint, normalizedII);
657 data = broker.readOperationalData(normalizedII);
660 throw new RestconfDocumentedException(
661 "Request could not be completed because the relevant data model content does not exist.",
662 ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
664 return new NormalizedNodeContext(iiWithData, data);
668 public Response updateConfigurationData(final String identifier, final NormalizedNodeContext payload) {
669 Preconditions.checkNotNull(identifier);
670 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
672 validateInput(iiWithData.getSchemaNode(), payload);
673 validateTopLevelNodeName(payload, iiWithData.getInstanceIdentifier());
674 validateListKeysEqualityInPayloadAndUri(iiWithData, payload.getData());
676 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
677 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
680 * There is a small window where another write transaction could be updating the same data
681 * simultaneously and we get an OptimisticLockFailedException. This error is likely
682 * transient and The WriteTransaction#submit API docs state that a retry will likely
683 * succeed. So we'll try again if that scenario occurs. If it fails a third time then it
684 * probably will never succeed so we'll fail in that case.
686 * By retrying we're attempting to hide the internal implementation of the data store and
687 * how it handles concurrent updates from the restconf client. The client has instructed us
688 * to put the data and we should make every effort to do so without pushing optimistic lock
689 * failures back to the client and forcing them to handle it via retry (and having to
690 * document the behavior).
695 if (mountPoint != null) {
696 broker.commitConfigurationDataPut(mountPoint, normalizedII, payload.getData()).checkedGet();
698 broker.commitConfigurationDataPut(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
702 } catch (final TransactionCommitFailedException e) {
703 if(e instanceof OptimisticLockFailedException) {
705 LOG.debug("Got OptimisticLockFailedException on last try - failing");
706 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
709 LOG.debug("Got OptimisticLockFailedException - trying again");
711 throw new RestconfDocumentedException(e.getMessage(), e, e.getErrorList());
716 return Response.status(Status.OK).build();
719 private void validateTopLevelNodeName(final NormalizedNodeContext node,
720 final YangInstanceIdentifier identifier) {
722 final String payloadName = node.getData().getNodeType().getLocalName();
723 final Iterator<PathArgument> pathArguments = identifier.getReversePathArguments().iterator();
726 if ( ! pathArguments.hasNext()) {
728 if ( ! node.getData().getNodeType().equals(NETCONF_BASE_QNAME)) {
729 throw new RestconfDocumentedException("Instance identifier has to contain at least one path argument",
730 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
734 final String identifierName = pathArguments.next().getNodeType().getLocalName();
735 if ( ! payloadName.equals(identifierName)) {
736 throw new RestconfDocumentedException("Payload name (" + payloadName
737 + ") is different from identifier name (" + identifierName + ")", ErrorType.PROTOCOL,
738 ErrorTag.MALFORMED_MESSAGE);
744 * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
746 * @throws RestconfDocumentedException
747 * if key values or key count in payload and URI isn't equal
750 private void validateListKeysEqualityInPayloadAndUri(final InstanceIdentifierContext<?> iiWithData,
751 final NormalizedNode<?, ?> payload) {
752 if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
753 final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
754 final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
755 if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
756 final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
758 isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
763 private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final NormalizedNode<?, ?> payload,
764 final List<QName> keyDefinitions) {
765 for (final QName keyDefinition : keyDefinitions) {
766 final Object uriKeyValue = uriKeyValues.get(keyDefinition);
767 // should be caught during parsing URI to InstanceIdentifier
768 if (uriKeyValue == null) {
769 final String errMsg = "Missing key " + keyDefinition + " in URI.";
770 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
772 // TODO thing about the possibility to fix
773 // final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
774 // if (payloadKeyValues.isEmpty()) {
775 // final String errMsg = "Missing key " + keyDefinition.getLocalName() + " in the message body.";
776 // throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
779 // final Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
780 // if (!uriKeyValue.equals(payloadKeyValue)) {
781 // final String errMsg = "The value '" + uriKeyValue + "' for key '" + keyDefinition.getLocalName() +
782 // "' specified in the URI doesn't match the value '" + payloadKeyValue + "' specified in the message body. ";
783 // throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
789 public Response createConfigurationData(final String identifier, final NormalizedNodeContext payload, final UriInfo uriInfo) {
790 return createConfigurationData(payload, uriInfo);
793 // FIXME create RestconfIdetifierHelper and move this method there
794 private YangInstanceIdentifier checkConsistencyOfNormalizedNodeContext(final NormalizedNodeContext payload) {
795 Preconditions.checkArgument(payload != null);
796 Preconditions.checkArgument(payload.getData() != null);
797 Preconditions.checkArgument(payload.getData().getNodeType() != null);
798 Preconditions.checkArgument(payload.getInstanceIdentifierContext() != null);
799 Preconditions.checkArgument(payload.getInstanceIdentifierContext().getInstanceIdentifier() != null);
801 final QName payloadNodeQname = payload.getData().getNodeType();
802 final YangInstanceIdentifier yangIdent = payload.getInstanceIdentifierContext().getInstanceIdentifier();
803 if (payloadNodeQname.compareTo(yangIdent.getLastPathArgument().getNodeType()) > 0) {
806 final InstanceIdentifierContext<?> parentContext = payload.getInstanceIdentifierContext();
807 final SchemaNode parentSchemaNode = parentContext.getSchemaNode();
808 if(parentSchemaNode instanceof DataNodeContainer) {
809 final DataNodeContainer cast = (DataNodeContainer) parentSchemaNode;
810 for (final DataSchemaNode child : cast.getChildNodes()) {
811 if (payloadNodeQname.compareTo(child.getQName()) == 0) {
812 return YangInstanceIdentifier.builder(yangIdent).node(child.getQName()).build();
816 if (parentSchemaNode instanceof RpcDefinition) {
819 final String errMsg = "Error parsing input: DataSchemaNode has not children";
820 throw new RestconfDocumentedException(errMsg, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
824 public Response createConfigurationData(final NormalizedNodeContext payload, final UriInfo uriInfo) {
825 if (payload == null) {
826 throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
829 // FIXME: move this to parsing stage (we can have augmentation nodes here which do not have namespace)
830 // final URI payloadNS = payload.getData().getNodeType().getNamespace();
831 // if (payloadNS == null) {
832 // throw new RestconfDocumentedException(
833 // "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
834 // ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
837 final DOMMountPoint mountPoint = payload.getInstanceIdentifierContext().getMountPoint();
838 final InstanceIdentifierContext<?> iiWithData = payload.getInstanceIdentifierContext();
839 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
841 if (mountPoint != null) {
842 broker.commitConfigurationDataPost(mountPoint, normalizedII, payload.getData()).checkedGet();
844 broker.commitConfigurationDataPost(controllerContext.getGlobalSchema(), normalizedII, payload.getData()).checkedGet();
846 } catch(final RestconfDocumentedException e) {
848 } catch (final Exception e) {
849 throw new RestconfDocumentedException("Error creating data", e);
852 final ResponseBuilder responseBuilder = Response.status(Status.NO_CONTENT);
853 // FIXME: Provide path to result.
854 final URI location = resolveLocation(uriInfo, "", mountPoint, normalizedII);
855 if (location != null) {
856 responseBuilder.location(location);
858 return responseBuilder.build();
861 private URI resolveLocation(final UriInfo uriInfo, final String uriBehindBase, final DOMMountPoint mountPoint, final YangInstanceIdentifier normalizedII) {
862 final UriBuilder uriBuilder = uriInfo.getBaseUriBuilder();
863 uriBuilder.path("config");
865 uriBuilder.path(controllerContext.toFullRestconfIdentifier(normalizedII, mountPoint));
866 } catch (final Exception e) {
867 LOG.debug("Location for instance identifier"+normalizedII+"wasn't created", e);
870 return uriBuilder.build();
874 public Response deleteConfigurationData(final String identifier) {
875 final InstanceIdentifierContext<?> iiWithData = controllerContext.toInstanceIdentifier(identifier);
876 final DOMMountPoint mountPoint = iiWithData.getMountPoint();
877 final YangInstanceIdentifier normalizedII = iiWithData.getInstanceIdentifier();
880 if (mountPoint != null) {
881 broker.commitConfigurationDataDelete(mountPoint, normalizedII);
883 broker.commitConfigurationDataDelete(normalizedII).get();
885 } catch (final Exception e) {
886 final Optional<Throwable> searchedException = Iterables.tryFind(Throwables.getCausalChain(e),
887 Predicates.instanceOf(ModifiedNodeDoesNotExistException.class));
888 if (searchedException.isPresent()) {
889 throw new RestconfDocumentedException("Data specified for deleting doesn't exist.", ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
891 throw new RestconfDocumentedException("Error while deleting data", e);
893 return Response.status(Status.OK).build();
897 * Subscribes to some path in schema context (stream) to listen on changes on this stream.
899 * Additional parameters for subscribing to stream are loaded via rpc input parameters:
901 * <li>datastore</li> - default CONFIGURATION (other values of {@link LogicalDatastoreType} enum type)
902 * <li>scope</li> - default BASE (other values of {@link DataChangeScope})
906 public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
907 final String streamName = Notificator.createStreamNameFromUri(identifier);
908 if (Strings.isNullOrEmpty(streamName)) {
909 throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
912 final ListenerAdapter listener = Notificator.getListenerFor(streamName);
913 if (listener == null) {
914 throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
917 final Map<String, String> paramToValues = resolveValuesFromUri(identifier);
918 final LogicalDatastoreType datastore = parserURIEnumParameter(LogicalDatastoreType.class,
919 paramToValues.get(DATASTORE_PARAM_NAME));
920 if (datastore == null) {
921 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /datastore=)",
922 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
924 final DataChangeScope scope = parserURIEnumParameter(DataChangeScope.class, paramToValues.get(SCOPE_PARAM_NAME));
926 throw new RestconfDocumentedException("Stream name doesn't contains datastore value (pattern /scope=)",
927 ErrorType.APPLICATION, ErrorTag.MISSING_ATTRIBUTE);
930 broker.registerToListenDataChanges(datastore, scope, listener);
932 final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
933 int notificationPort = NOTIFICATION_PORT;
935 final WebSocketServer webSocketServerInstance = WebSocketServer.getInstance();
936 notificationPort = webSocketServerInstance.getPort();
937 } catch (final NullPointerException e) {
938 WebSocketServer.createInstance(NOTIFICATION_PORT);
940 final UriBuilder uriToWebsocketServerBuilder = uriBuilder.port(notificationPort).scheme("ws");
941 final URI uriToWebsocketServer = uriToWebsocketServerBuilder.replacePath(streamName).build();
943 return Response.status(Status.OK).location(uriToWebsocketServer).build();
947 * Load parameter for subscribing to stream from input composite node
951 * @return enum object if its string value is equal to {@code paramName}. In other cases null.
953 private <T> T parseEnumTypeParameter(final ContainerNode value, final Class<T> classDescriptor,
954 final String paramName) {
955 final Optional<DataContainerChild<? extends PathArgument, ?>> augNode = value.getChild(SAL_REMOTE_AUG_IDENTIFIER);
956 if (!augNode.isPresent() && !(augNode instanceof AugmentationNode)) {
959 final Optional<DataContainerChild<? extends PathArgument, ?>> enumNode =
960 ((AugmentationNode) augNode.get()).getChild(new NodeIdentifier(QName.create(SAL_REMOTE_AUGMENT, paramName)));
961 if (!enumNode.isPresent()) {
964 final Object rawValue = enumNode.get().getValue();
965 if (!(rawValue instanceof String)) {
969 return resolveAsEnum(classDescriptor, (String) rawValue);
973 * Checks whether {@code value} is one of the string representation of enumeration {@code classDescriptor}
975 * @return enum object if string value of {@code classDescriptor} enumeration is equal to {@code value}. Other cases
978 private <T> T parserURIEnumParameter(final Class<T> classDescriptor, final String value) {
979 if (Strings.isNullOrEmpty(value)) {
982 return resolveAsEnum(classDescriptor, value);
985 private <T> T resolveAsEnum(final Class<T> classDescriptor, final String value) {
986 final T[] enumConstants = classDescriptor.getEnumConstants();
987 if (enumConstants != null) {
988 for (final T enm : classDescriptor.getEnumConstants()) {
989 if (((Enum<?>) enm).name().equals(value)) {
997 private Map<String, String> resolveValuesFromUri(final String uri) {
998 final Map<String, String> result = new HashMap<>();
999 final String[] tokens = uri.split("/");
1000 for (int i = 1; i < tokens.length; i++) {
1001 final String[] parameterTokens = tokens[i].split("=");
1002 if (parameterTokens.length == 2) {
1003 result.put(parameterTokens[0], parameterTokens[1]);
1009 public BigInteger getOperationalReceived() {
1010 // TODO Auto-generated method stub
1014 private MapNode makeModuleMapNode(final Set<Module> modules) {
1015 Preconditions.checkNotNull(modules);
1016 final Module restconfModule = getRestconfModule();
1017 final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
1018 restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
1019 Preconditions.checkState(moduleSchemaNode instanceof ListSchemaNode);
1021 final CollectionNodeBuilder<MapEntryNode, MapNode> listModuleBuilder = Builders
1022 .mapBuilder((ListSchemaNode) moduleSchemaNode);
1024 for (final Module module : modules) {
1025 listModuleBuilder.withChild(toModuleEntryNode(module, moduleSchemaNode));
1027 return listModuleBuilder.build();
1030 protected MapEntryNode toModuleEntryNode(final Module module, final DataSchemaNode moduleSchemaNode) {
1031 Preconditions.checkArgument(moduleSchemaNode instanceof ListSchemaNode,
1032 "moduleSchemaNode has to be of type ListSchemaNode");
1033 final ListSchemaNode listModuleSchemaNode = (ListSchemaNode) moduleSchemaNode;
1034 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> moduleNodeValues = Builders
1035 .mapEntryBuilder(listModuleSchemaNode);
1037 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1038 (listModuleSchemaNode), "name");
1039 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1040 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1041 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(module.getName())
1044 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1045 (listModuleSchemaNode), "revision");
1046 final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1047 Preconditions.checkState(revisionSchemaNode instanceof LeafSchemaNode);
1048 final String revision = REVISION_FORMAT.format(module.getRevision());
1049 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) revisionSchemaNode).withValue(revision)
1052 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1053 (listModuleSchemaNode), "namespace");
1054 final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1055 Preconditions.checkState(namespaceSchemaNode instanceof LeafSchemaNode);
1056 moduleNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) namespaceSchemaNode)
1057 .withValue(module.getNamespace().toString()).build());
1059 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1060 (listModuleSchemaNode), "feature");
1061 final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1062 Preconditions.checkState(featureSchemaNode instanceof LeafListSchemaNode);
1063 final ListNodeBuilder<Object, LeafSetEntryNode<Object>> featuresBuilder = Builders
1064 .leafSetBuilder((LeafListSchemaNode) featureSchemaNode);
1065 for (final FeatureDefinition feature : module.getFeatures()) {
1066 featuresBuilder.withChild(Builders.leafSetEntryBuilder(((LeafListSchemaNode) featureSchemaNode))
1067 .withValue(feature.getQName().getLocalName()).build());
1069 moduleNodeValues.withChild(featuresBuilder.build());
1071 return moduleNodeValues.build();
1074 protected MapEntryNode toStreamEntryNode(final String streamName, final DataSchemaNode streamSchemaNode) {
1075 Preconditions.checkArgument(streamSchemaNode instanceof ListSchemaNode,
1076 "streamSchemaNode has to be of type ListSchemaNode");
1077 final ListSchemaNode listStreamSchemaNode = (ListSchemaNode) streamSchemaNode;
1078 final DataContainerNodeAttrBuilder<NodeIdentifierWithPredicates, MapEntryNode> streamNodeValues = Builders
1079 .mapEntryBuilder(listStreamSchemaNode);
1081 List<DataSchemaNode> instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1082 (listStreamSchemaNode), "name");
1083 final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1084 Preconditions.checkState(nameSchemaNode instanceof LeafSchemaNode);
1085 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode).withValue(streamName)
1088 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1089 (listStreamSchemaNode), "description");
1090 final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1091 Preconditions.checkState(descriptionSchemaNode instanceof LeafSchemaNode);
1092 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) nameSchemaNode)
1093 .withValue("DESCRIPTION_PLACEHOLDER").build());
1095 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1096 (listStreamSchemaNode), "replay-support");
1097 final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1098 Preconditions.checkState(replaySupportSchemaNode instanceof LeafSchemaNode);
1099 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replaySupportSchemaNode)
1100 .withValue(Boolean.valueOf(true)).build());
1102 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1103 (listStreamSchemaNode), "replay-log-creation-time");
1104 final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1105 Preconditions.checkState(replayLogCreationTimeSchemaNode instanceof LeafSchemaNode);
1106 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) replayLogCreationTimeSchemaNode)
1107 .withValue("").build());
1109 instanceDataChildrenByName = ControllerContext.findInstanceDataChildrenByName(
1110 (listStreamSchemaNode), "events");
1111 final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
1112 Preconditions.checkState(eventsSchemaNode instanceof LeafSchemaNode);
1113 streamNodeValues.withChild(Builders.leafBuilder((LeafSchemaNode) eventsSchemaNode)
1114 .withValue("").build());
1116 return streamNodeValues.build();