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.common.YangNames;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
40 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
41 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
42 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
43 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * Util class for parsing identifier.
56 public final class ParserIdentifier {
57 private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
58 private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
60 private ParserIdentifier() {
65 * Make {@link InstanceIdentifierContext} from {@link String} identifier
67 * For identifiers of data NOT behind mount points returned
68 * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
69 * controller's {@link SchemaContext}.
71 * For identifiers of data behind mount points returned
72 * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
73 * own {@link SchemaContext}.
77 * @param schemaContext
78 * - controller schema context
79 * @param mountPointService
80 * - mount point service
81 * @return {@link InstanceIdentifierContext}
83 // FIXME: NETCONF-631: this method should not be here, it should be a static factory in InstanceIdentifierContext:
85 // @NonNull InstanceIdentifierContext forUrl(identifier, schemaContexxt, mountPointService)
87 public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
88 final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
89 if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
90 return createIIdContext(schemaContext, identifier, null);
92 if (mountPointService.isEmpty()) {
93 throw new RestconfDocumentedException("Mount point service is not available");
96 final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
97 final String mountPointId = pathsIt.next();
98 final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
99 final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
100 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
101 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
103 final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
104 final String pathId = pathsIt.next().replaceFirst("/", "");
105 return createIIdContext(mountSchemaContext, pathId, mountPoint);
109 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
110 * and {@link SchemaContext}, {@link DOMMountPoint}.
112 * @param url Invocation URL
113 * @param schemaContext SchemaContext in which the path is to be interpreted in
114 * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
115 * @return {@link InstanceIdentifierContext}
116 * @throws RestconfDocumentedException if the path cannot be resolved
118 private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
119 final String url, final @Nullable DOMMountPoint mountPoint) {
120 final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
121 return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
125 private static SchemaNode getPathSchema(final EffectiveModelContext schemaContext,
126 final YangInstanceIdentifier urlPath) {
127 // First things first: an empty path means data invocation on SchemaContext
128 if (urlPath.isEmpty()) {
129 return schemaContext;
132 // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
133 final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
134 .findChild(verifyNotNull(urlPath.getParent()))
136 // Parent data node is not present, this is not a valid location.
137 () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
138 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
140 // Now try to resolve the last component as a data item...
141 final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
143 return data.getDataSchemaNode();
146 // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
147 // actions can reside everywhere else (and SchemaContext reports them empty)
148 final QName qname = urlPath.getLastPathArgument().getNodeType();
149 final DataSchemaNode parentSchema = parent.getDataSchemaNode();
150 if (parentSchema instanceof SchemaContext) {
151 for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
152 if (qname.equals(rpc.getQName())) {
157 if (parentSchema instanceof ActionNodeContainer) {
158 for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
159 if (qname.equals(action.getQName())) {
165 // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
167 throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
168 ErrorTag.INVALID_VALUE);
172 * Make a moduleName/Revision pair from identifier.
176 * @return {@link QName}
179 static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
180 // check if more than one slash is not used as path separator
181 if (identifier.contains("//")) {
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 int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
189 final String moduleNameAndRevision;
190 if (mountIndex >= 0) {
191 moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
192 .replaceFirst("/", "");
194 moduleNameAndRevision = identifier;
197 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
198 if (pathArgs.size() != 2) {
199 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
200 throw new RestconfDocumentedException(
201 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
202 ErrorTag.INVALID_VALUE);
205 final Revision moduleRevision;
207 moduleRevision = Revision.of(pathArgs.get(1));
208 } catch (final DateTimeParseException e) {
209 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
210 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
211 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
214 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
218 * Parsing {@link Module} module by {@link String} module name and
219 * {@link Date} revision and from the parsed module create
220 * {@link SchemaExportContext}.
222 * @param schemaContext
223 * {@link EffectiveModelContext}
226 * @param domMountPointService
227 * {@link DOMMountPointService}
228 * @return {@link SchemaExportContext}
230 public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
231 final String identifier, final DOMMountPointService domMountPointService,
232 final DOMYangTextSourceProvider sourceProvider) {
233 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
234 final Iterator<String> componentIter = pathComponents.iterator();
235 if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
236 final String moduleName = validateAndGetModulName(componentIter);
237 final Revision revision = validateAndGetRevision(componentIter);
238 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
239 return new SchemaExportContext(schemaContext, module, sourceProvider);
241 final StringBuilder pathBuilder = new StringBuilder();
242 while (componentIter.hasNext()) {
243 final String current = componentIter.next();
245 if (RestconfConstants.MOUNT.equals(current)) {
246 pathBuilder.append('/').append(RestconfConstants.MOUNT);
250 if (pathBuilder.length() != 0) {
251 pathBuilder.append('/');
254 pathBuilder.append(current);
256 final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
257 Optional.of(domMountPointService));
258 final String moduleName = validateAndGetModulName(componentIter);
259 final Revision revision = validateAndGetRevision(componentIter);
260 final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
261 final Module module = context.findModule(moduleName, revision).orElse(null);
262 return new SchemaExportContext(context, module, sourceProvider);
266 public static YangInstanceIdentifier parserPatchTarget(final InstanceIdentifierContext<?> context,
267 final String target) {
268 final var schemaContext = context.getSchemaContext();
269 final var urlPath = context.getInstanceIdentifier();
270 final String targetUrl;
271 if (urlPath.isEmpty()) {
272 targetUrl = target.startsWith("/") ? target.substring(1) : target;
274 targetUrl = IdentifierCodec.serialize(urlPath, schemaContext) + target;
277 return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
281 * Validation and parsing of revision.
283 * @param revisionDate iterator
287 static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
288 RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
289 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
291 return Revision.of(revisionDate.next());
292 } catch (final DateTimeParseException e) {
293 throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
298 * Validation of name.
300 * @param moduleName iterator
301 * @return {@link String}
304 static String validateAndGetModulName(final Iterator<String> moduleName) {
305 RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
306 ErrorTag.INVALID_VALUE);
307 final String name = moduleName.next();
309 RestconfDocumentedException.throwIf(
310 name.isEmpty() || !YangNames.IDENTIFIER_START.matches(name.charAt(0)),
311 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
312 RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
313 "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
314 RestconfDocumentedException.throwIf(
315 YangNames.NOT_IDENTIFIER_PART.matchesAnyOf(name.substring(1)),
316 "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
321 private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
322 final EffectiveModelContext context = modelContext(mountPoint);
323 checkState(context != null, "Mount point %s does not have a model context", mountPoint);
327 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
328 return mountPoint.getService(DOMSchemaService.class)
329 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))