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 static com.google.common.base.Verify.verifyNotNull;
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Iterables;
15 import java.time.format.DateTimeParseException;
16 import java.util.AbstractMap.SimpleImmutableEntry;
17 import java.util.Date;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Locale;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
25 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
26 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
27 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
28 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
29 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
30 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
31 import org.opendaylight.restconf.common.schema.SchemaExportContext;
32 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.Revision;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.ActionNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * Util class for parsing identifier.
52 public final class ParserIdentifier {
54 private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
55 private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
57 private ParserIdentifier() {
58 throw new UnsupportedOperationException("Util class.");
62 * Make {@link InstanceIdentifierContext} from {@link String} identifier
64 * For identifiers of data NOT behind mount points returned
65 * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
66 * controller's {@link SchemaContext}.
68 * For identifiers of data behind mount points returned
69 * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
70 * own {@link SchemaContext}.
74 * @param schemaContext
75 * - controller schema context
76 * @param mountPointService
77 * - mount point service
78 * @return {@link InstanceIdentifierContext}
80 public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
81 final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
82 if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
83 return createIIdContext(schemaContext, identifier, 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 EffectiveModelContext mountSchemaContext = mountPoint.getEffectiveModelContext();
97 final String pathId = pathsIt.next().replaceFirst("/", "");
98 return createIIdContext(mountSchemaContext, pathId, mountPoint);
102 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
103 * and {@link SchemaContext}, {@link DOMMountPoint}.
105 * @param url Invocation URL
106 * @param schemaContext SchemaContext in which the path is to be interpreted in
107 * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
108 * @return {@link InstanceIdentifierContext}
109 * @throws RestconfDocumentedException if the path cannot be resolved
111 private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
112 final String url, final @Nullable DOMMountPoint mountPoint) {
113 final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
114 return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
118 private static SchemaNode getPathSchema(final SchemaContext schemaContext, final YangInstanceIdentifier urlPath) {
119 // First things first: an empty path means data invocation on SchemaContext
120 if (urlPath.isEmpty()) {
121 return schemaContext;
124 // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
125 final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
126 .findChild(verifyNotNull(urlPath.getParent()))
128 // Parent data node is not present, this is not a valid location.
129 () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
130 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
132 // Now try to resolve the last component as a data item...
133 final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
135 return data.getDataSchemaNode();
138 // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
139 // actions can reside everywhere else (and SchemaContext reports them empty)
140 final QName qname = urlPath.getLastPathArgument().getNodeType();
141 final DataSchemaNode parentSchema = parent.getDataSchemaNode();
142 if (parentSchema instanceof SchemaContext) {
143 for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
144 if (qname.equals(rpc.getQName())) {
149 if (parentSchema instanceof ActionNodeContainer) {
150 for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
151 if (qname.equals(action.getQName())) {
157 // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
159 throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
160 ErrorTag.INVALID_VALUE);
164 * Make {@link String} from {@link YangInstanceIdentifier}.
166 * @param instanceIdentifier Instance identifier
167 * @param schemaContext Schema context
168 * @return Yang instance identifier serialized to String
170 public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
171 final SchemaContext schemaContext) {
172 return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
176 * Make a moduleName/Revision pair from identifier.
180 * @return {@link QName}
182 public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
183 // check if more than one slash is not used as path separator
184 if (identifier.contains(
185 String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
186 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
187 throw new RestconfDocumentedException(
188 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
189 ErrorTag.INVALID_VALUE);
192 final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
193 final String moduleNameAndRevision;
194 if (mountIndex >= 0) {
195 moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
196 .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
198 moduleNameAndRevision = identifier;
201 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
202 if (pathArgs.size() != 2) {
203 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
204 throw new RestconfDocumentedException(
205 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
206 ErrorTag.INVALID_VALUE);
209 final Revision moduleRevision;
211 moduleRevision = Revision.of(pathArgs.get(1));
212 } catch (final DateTimeParseException e) {
213 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
214 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
215 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
218 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
222 * Parsing {@link Module} module by {@link String} module name and
223 * {@link Date} revision and from the parsed module create
224 * {@link SchemaExportContext}.
226 * @param schemaContext
227 * {@link EffectiveModelContext}
230 * @param domMountPointService
231 * {@link DOMMountPointService}
232 * @return {@link SchemaExportContext}
234 public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
235 final String identifier, final DOMMountPointService domMountPointService,
236 final DOMYangTextSourceProvider sourceProvider) {
237 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
238 final Iterator<String> componentIter = pathComponents.iterator();
239 if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
240 final String moduleName = validateAndGetModulName(componentIter);
241 final Revision revision = validateAndGetRevision(componentIter);
242 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
243 return new SchemaExportContext(schemaContext, module, sourceProvider);
245 final StringBuilder pathBuilder = new StringBuilder();
246 while (componentIter.hasNext()) {
247 final String current = componentIter.next();
249 if (RestconfConstants.MOUNT.equals(current)) {
250 pathBuilder.append("/");
251 pathBuilder.append(RestconfConstants.MOUNT);
255 if (pathBuilder.length() != 0) {
256 pathBuilder.append("/");
259 pathBuilder.append(current);
261 final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
262 Optional.of(domMountPointService));
263 final String moduleName = validateAndGetModulName(componentIter);
264 final Revision revision = validateAndGetRevision(componentIter);
265 final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
267 return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);
272 * Validation and parsing of revision.
274 * @param revisionDate iterator
278 static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
279 RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
280 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
282 return Revision.of(revisionDate.next());
283 } catch (final DateTimeParseException e) {
284 throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
289 * Validation of name.
291 * @param moduleName iterator
292 * @return {@link String}
295 static String validateAndGetModulName(final Iterator<String> moduleName) {
296 RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
297 ErrorTag.INVALID_VALUE);
298 final String name = moduleName.next();
300 RestconfDocumentedException.throwIf(
301 name.isEmpty() || !ParserConstants.YANG_IDENTIFIER_START.matches(name.charAt(0)),
302 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
303 RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
304 "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
305 RestconfDocumentedException.throwIf(
306 !ParserConstants.YANG_IDENTIFIER_PART.matchesAllOf(name.substring(1)),
307 "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);