2 * Copyright (c) 2016 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
8 package org.opendaylight.restconf.nb.rfc8040.utils.parser;
10 import com.google.common.base.Splitter;
11 import com.google.common.collect.Iterables;
12 import java.time.format.DateTimeParseException;
13 import java.util.AbstractMap.SimpleImmutableEntry;
14 import java.util.Date;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.Optional;
19 import java.util.stream.Collectors;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
22 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
23 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
24 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
25 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
26 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
28 import org.opendaylight.restconf.common.schema.SchemaExportContext;
29 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
30 import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.Revision;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
37 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
38 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * Util class for parsing identifier.
50 public final class ParserIdentifier {
52 private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
53 private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
55 private ParserIdentifier() {
56 throw new UnsupportedOperationException("Util class.");
60 * Make {@link InstanceIdentifierContext} from {@link String} identifier
62 * For identifiers of data NOT behind mount points returned
63 * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
64 * controller's {@link SchemaContext}.
66 * For identifiers of data behind mount points returned
67 * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
68 * own {@link SchemaContext}.
72 * @param schemaContext
73 * - controller schema context
74 * @param mountPointService
75 * - mount point service
76 * @return {@link InstanceIdentifierContext}
78 public static InstanceIdentifierContext<?> toInstanceIdentifier(
79 final String identifier,
80 final SchemaContext schemaContext,
81 final Optional<DOMMountPointService> mountPointService) {
82 if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
83 return createIIdContext(IdentifierCodec.deserialize(identifier, schemaContext), schemaContext, null);
85 if (!mountPointService.isPresent()) {
86 throw new RestconfDocumentedException("Mount point service is not available");
89 final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
90 final String mountPointId = pathsIt.next();
91 final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
92 final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
93 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
94 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
96 final SchemaContext mountSchemaContext = mountPoint.getSchemaContext();
97 final String pathId = pathsIt.next().replaceFirst("/", "");
98 return createIIdContext(IdentifierCodec.deserialize(pathId, mountSchemaContext), mountSchemaContext,
103 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
104 * and {@link SchemaContext}, {@link DOMMountPoint}.
107 * - instance identifier
108 * @param schemaContext
110 * @param domMountPoint
111 * - optional mount point context
112 * @return {@link InstanceIdentifierContext}
114 private static InstanceIdentifierContext<?> createIIdContext(final YangInstanceIdentifier yangIId,
115 final SchemaContext schemaContext, final @Nullable DOMMountPoint domMountPoint) {
117 // Deal with data nodes first
118 final DataSchemaContextTree contextTree = DataSchemaContextTree.from(schemaContext);
119 final Optional<DataSchemaContextNode<?>> child = contextTree.findChild(yangIId);
120 if (child.isPresent()) {
121 return new InstanceIdentifierContext<SchemaNode>(yangIId, child.get().getDataSchemaNode(), domMountPoint,
125 // That failed, now try to recover by searching through the schema context
126 final List<QName> qnames = yangIId.getPathArguments().stream()
127 .filter(pathArgument -> pathArgument instanceof NodeIdentifier).map(PathArgument::getNodeType)
128 .collect(Collectors.toList());
129 final SchemaNode schemaNode = SchemaContextUtil.findNodeInSchemaContext(schemaContext, qnames);
130 if (schemaNode instanceof RpcDefinition) {
131 return new InstanceIdentifierContext<>(yangIId, (RpcDefinition) schemaNode, domMountPoint, schemaContext);
132 } else if (schemaNode instanceof ActionDefinition) {
133 return new InstanceIdentifierContext<>(yangIId, (ActionDefinition) schemaNode, domMountPoint,
135 } else if (schemaNode == null) {
136 throw new IllegalArgumentException("Failed to find schema for " + qnames);
138 throw new IllegalStateException("Unhandled schema " + schemaNode);
143 * Make {@link String} from {@link YangInstanceIdentifier}.
145 * @param instanceIdentifier Instance identifier
146 * @param schemaContext Schema context
147 * @return Yang instance identifier serialized to String
149 public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
150 final SchemaContext schemaContext) {
151 return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
155 * Make a moduleName/Revision pair from identifier.
159 * @return {@link QName}
161 public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
162 // check if more than one slash is not used as path separator
163 if (identifier.contains(
164 String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
165 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
166 throw new RestconfDocumentedException(
167 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
168 ErrorTag.INVALID_VALUE);
171 final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
172 final String moduleNameAndRevision;
173 if (mountIndex >= 0) {
174 moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
175 .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
177 moduleNameAndRevision = identifier;
180 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
181 if (pathArgs.size() != 2) {
182 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
183 throw new RestconfDocumentedException(
184 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
185 ErrorTag.INVALID_VALUE);
188 final Revision moduleRevision;
190 moduleRevision = Revision.of(pathArgs.get(1));
191 } catch (final DateTimeParseException e) {
192 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
193 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
194 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
197 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
201 * Parsing {@link Module} module by {@link String} module name and
202 * {@link Date} revision and from the parsed module create
203 * {@link SchemaExportContext}.
205 * @param schemaContext
206 * {@link SchemaContext}
209 * @param domMountPointService
210 * {@link DOMMountPointService}
211 * @return {@link SchemaExportContext}
213 public static SchemaExportContext toSchemaExportContextFromIdentifier(final SchemaContext schemaContext,
214 final String identifier, final DOMMountPointService domMountPointService,
215 final DOMYangTextSourceProvider sourceProvider) {
216 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
217 final Iterator<String> componentIter = pathComponents.iterator();
218 if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
219 final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
220 final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
221 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
222 return new SchemaExportContext(schemaContext, module, sourceProvider);
224 final StringBuilder pathBuilder = new StringBuilder();
225 while (componentIter.hasNext()) {
226 final String current = componentIter.next();
228 if (RestconfConstants.MOUNT.equals(current)) {
229 pathBuilder.append("/");
230 pathBuilder.append(RestconfConstants.MOUNT);
234 if (pathBuilder.length() != 0) {
235 pathBuilder.append("/");
238 pathBuilder.append(current);
240 final InstanceIdentifierContext<?> point = ParserIdentifier
241 .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
242 final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
243 final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
244 final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
246 return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);