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.Preconditions.checkState;
11 import static com.google.common.base.Verify.verifyNotNull;
13 import com.google.common.annotations.VisibleForTesting;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Iterables;
16 import java.time.format.DateTimeParseException;
17 import java.util.AbstractMap.SimpleImmutableEntry;
18 import java.util.Date;
19 import java.util.Iterator;
20 import java.util.List;
21 import java.util.Locale;
22 import java.util.Map.Entry;
23 import java.util.Optional;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
26 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
27 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
28 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
29 import org.opendaylight.restconf.common.ErrorTags;
30 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
31 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
32 import org.opendaylight.restconf.common.schema.SchemaExportContext;
33 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
34 import org.opendaylight.yangtools.yang.common.ErrorTag;
35 import org.opendaylight.yangtools.yang.common.ErrorType;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.common.Revision;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
40 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
41 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
42 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
53 * Util class for parsing identifier.
55 public final class ParserIdentifier {
56 private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
57 private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
59 private ParserIdentifier() {
64 * Make {@link InstanceIdentifierContext} from {@link String} identifier
66 * For identifiers of data NOT behind mount points returned
67 * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
68 * controller's {@link SchemaContext}.
70 * For identifiers of data behind mount points returned
71 * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
72 * own {@link SchemaContext}.
76 * @param schemaContext
77 * - controller schema context
78 * @param mountPointService
79 * - mount point service
80 * @return {@link InstanceIdentifierContext}
82 // FIXME: NETCONF-631: this method should not be here, it should be a static factory in InstanceIdentifierContext:
84 // @NonNull InstanceIdentifierContext forUrl(identifier, schemaContexxt, mountPointService)
86 public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
87 final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
88 if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
89 return createIIdContext(schemaContext, identifier, null);
91 if (mountPointService.isEmpty()) {
92 throw new RestconfDocumentedException("Mount point service is not available");
95 final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
96 final String mountPointId = pathsIt.next();
97 final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
98 final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
99 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
100 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
102 final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
103 final String pathId = pathsIt.next().replaceFirst("/", "");
104 return createIIdContext(mountSchemaContext, pathId, mountPoint);
108 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
109 * and {@link SchemaContext}, {@link DOMMountPoint}.
111 * @param url Invocation URL
112 * @param schemaContext SchemaContext in which the path is to be interpreted in
113 * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
114 * @return {@link InstanceIdentifierContext}
115 * @throws RestconfDocumentedException if the path cannot be resolved
117 private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
118 final String url, final @Nullable DOMMountPoint mountPoint) {
119 final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
120 return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
124 private static SchemaNode getPathSchema(final EffectiveModelContext schemaContext,
125 final YangInstanceIdentifier urlPath) {
126 // First things first: an empty path means data invocation on SchemaContext
127 if (urlPath.isEmpty()) {
128 return schemaContext;
131 // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
132 final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
133 .findChild(verifyNotNull(urlPath.getParent()))
135 // Parent data node is not present, this is not a valid location.
136 () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
137 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
139 // Now try to resolve the last component as a data item...
140 final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
142 return data.getDataSchemaNode();
145 // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
146 // actions can reside everywhere else (and SchemaContext reports them empty)
147 final QName qname = urlPath.getLastPathArgument().getNodeType();
148 final DataSchemaNode parentSchema = parent.getDataSchemaNode();
149 if (parentSchema instanceof SchemaContext) {
150 for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
151 if (qname.equals(rpc.getQName())) {
156 if (parentSchema instanceof ActionNodeContainer) {
157 for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
158 if (qname.equals(action.getQName())) {
164 // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
166 throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
167 ErrorTag.INVALID_VALUE);
171 * Make a moduleName/Revision pair from identifier.
175 * @return {@link QName}
178 static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
179 // check if more than one slash is not used as path separator
180 if (identifier.contains("//")) {
181 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
182 throw new RestconfDocumentedException(
183 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
184 ErrorTag.INVALID_VALUE);
187 final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
188 final String moduleNameAndRevision;
189 if (mountIndex >= 0) {
190 moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
191 .replaceFirst("/", "");
193 moduleNameAndRevision = identifier;
196 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
197 if (pathArgs.size() != 2) {
198 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
199 throw new RestconfDocumentedException(
200 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
201 ErrorTag.INVALID_VALUE);
204 final Revision moduleRevision;
206 moduleRevision = Revision.of(pathArgs.get(1));
207 } catch (final DateTimeParseException e) {
208 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
209 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
210 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
213 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
217 * Parsing {@link Module} module by {@link String} module name and
218 * {@link Date} revision and from the parsed module create
219 * {@link SchemaExportContext}.
221 * @param schemaContext
222 * {@link EffectiveModelContext}
225 * @param domMountPointService
226 * {@link DOMMountPointService}
227 * @return {@link SchemaExportContext}
229 public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
230 final String identifier, final DOMMountPointService domMountPointService,
231 final DOMYangTextSourceProvider sourceProvider) {
232 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
233 final Iterator<String> componentIter = pathComponents.iterator();
234 if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
235 final String moduleName = validateAndGetModulName(componentIter);
236 final Revision revision = validateAndGetRevision(componentIter);
237 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
238 return new SchemaExportContext(schemaContext, module, sourceProvider);
240 final StringBuilder pathBuilder = new StringBuilder();
241 while (componentIter.hasNext()) {
242 final String current = componentIter.next();
244 if (RestconfConstants.MOUNT.equals(current)) {
245 pathBuilder.append('/').append(RestconfConstants.MOUNT);
249 if (pathBuilder.length() != 0) {
250 pathBuilder.append('/');
253 pathBuilder.append(current);
255 final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
256 Optional.of(domMountPointService));
257 final String moduleName = validateAndGetModulName(componentIter);
258 final Revision revision = validateAndGetRevision(componentIter);
259 final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
260 final Module module = context.findModule(moduleName, revision).orElse(null);
261 return new SchemaExportContext(context, module, sourceProvider);
265 public static YangInstanceIdentifier parserPatchTarget(final InstanceIdentifierContext<?> context,
266 final String target) {
267 final var schemaContext = context.getSchemaContext();
268 final var urlPath = context.getInstanceIdentifier();
269 final String targetUrl;
270 if (urlPath.isEmpty()) {
271 targetUrl = target.startsWith("/") ? target.substring(1) : target;
273 targetUrl = IdentifierCodec.serialize(urlPath, schemaContext) + target;
276 return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
280 * Validation and parsing of revision.
282 * @param revisionDate iterator
286 static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
287 RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
288 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
290 return Revision.of(revisionDate.next());
291 } catch (final DateTimeParseException e) {
292 throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
297 * Validation of name.
299 * @param moduleName iterator
300 * @return {@link String}
303 static String validateAndGetModulName(final Iterator<String> moduleName) {
304 RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
305 ErrorTag.INVALID_VALUE);
306 final String name = moduleName.next();
308 RestconfDocumentedException.throwIf(
309 name.isEmpty() || !ParserConstants.YANG_IDENTIFIER_START.matches(name.charAt(0)),
310 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
311 RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
312 "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
313 RestconfDocumentedException.throwIf(
314 !ParserConstants.YANG_IDENTIFIER_PART.matchesAllOf(name.substring(1)),
315 "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
320 private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
321 final EffectiveModelContext context = modelContext(mountPoint);
322 checkState(context != null, "Mount point %s does not have a model context", mountPoint);
326 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
327 return mountPoint.getService(DOMSchemaService.class)
328 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))