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;
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.DOMSchemaService;
27 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
28 import org.opendaylight.restconf.common.ErrorTags;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.SchemaExportContext;
32 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
33 import org.opendaylight.yangtools.yang.common.ErrorTag;
34 import org.opendaylight.yangtools.yang.common.ErrorType;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.Revision;
37 import org.opendaylight.yangtools.yang.common.YangNames;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Util class for parsing identifier.
48 public final class ParserIdentifier {
49 private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
51 // FIXME: Remove this constant. All logic relying on this constant should instead rely on YangInstanceIdentifier
52 // equivalent coming out of argument parsing. This may require keeping List<YangInstanceIdentifier> as the
53 // nested path split on yang-ext:mount. This splitting needs to be based on consulting the
54 // EffectiveModelContext and allowing it only where yang-ext:mount is actually used in models.
55 private static final String MOUNT = "yang-ext:mount";
56 private static final Splitter MP_SPLITTER = Splitter.on("/" + MOUNT);
58 private ParserIdentifier() {
63 * Make {@link InstanceIdentifierContext} from {@link String} identifier
65 * For identifiers of data NOT behind mount points returned
66 * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
67 * controller's {@link SchemaContext}.
69 * For identifiers of data behind mount points returned
70 * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
71 * own {@link SchemaContext}.
75 * @param schemaContext
76 * - controller schema context
77 * @param mountPointService
78 * - mount point service
79 * @return {@link InstanceIdentifierContext}
81 // FIXME: NETCONF-631: this method should not be here, it should be a static factory in InstanceIdentifierContext:
83 // @NonNull InstanceIdentifierContext forUrl(identifier, schemaContexxt, mountPointService)
85 public static InstanceIdentifierContext toInstanceIdentifier(final String identifier,
86 final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
87 if (identifier == null || !identifier.contains(MOUNT)) {
88 return createIIdContext(schemaContext, identifier, null);
90 if (mountPointService.isEmpty()) {
91 throw new RestconfDocumentedException("Mount point service is not available");
94 final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
95 final String mountPointId = pathsIt.next();
96 final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
97 final DOMMountPoint mountPoint = mountPointService.orElseThrow().getMountPoint(mountPath)
98 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
99 ErrorType.PROTOCOL, ErrorTags.RESOURCE_DENIED_TRANSPORT));
101 final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
102 final String pathId = pathsIt.next().replaceFirst("/", "");
103 return createIIdContext(mountSchemaContext, pathId, mountPoint);
107 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
108 * and {@link SchemaContext}, {@link DOMMountPoint}.
110 * @param url Invocation URL
111 * @param schemaContext SchemaContext in which the path is to be interpreted in
112 * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
113 * @return {@link InstanceIdentifierContext}
114 * @throws RestconfDocumentedException if the path cannot be resolved
116 private static InstanceIdentifierContext createIIdContext(final EffectiveModelContext schemaContext,
117 final String url, final @Nullable DOMMountPoint mountPoint) {
118 // First things first: an empty path means data invocation on SchemaContext
120 return mountPoint != null ? InstanceIdentifierContext.ofMountPointRoot(mountPoint, schemaContext)
121 : InstanceIdentifierContext.ofLocalRoot(schemaContext);
124 final var result = YangInstanceIdentifierDeserializer.create(schemaContext, url);
125 return InstanceIdentifierContext.ofPath(result.stack, result.node, result.path, mountPoint);
129 * Make a moduleName/Revision pair from identifier.
133 * @return {@link QName}
136 static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
137 // check if more than one slash is not used as path separator
138 if (identifier.contains("//")) {
139 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
140 throw new RestconfDocumentedException(
141 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
142 ErrorTag.INVALID_VALUE);
145 final int mountIndex = identifier.indexOf(MOUNT);
146 final String moduleNameAndRevision;
147 if (mountIndex >= 0) {
148 moduleNameAndRevision = identifier.substring(mountIndex + MOUNT.length()).replaceFirst("/", "");
150 moduleNameAndRevision = identifier;
153 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
154 if (pathArgs.size() != 2) {
155 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
156 throw new RestconfDocumentedException(
157 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
158 ErrorTag.INVALID_VALUE);
161 final Revision moduleRevision;
163 moduleRevision = Revision.of(pathArgs.get(1));
164 } catch (final DateTimeParseException e) {
165 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
166 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
167 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
170 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
174 * Parsing {@link Module} module by {@link String} module name and
175 * {@link Date} revision and from the parsed module create
176 * {@link SchemaExportContext}.
178 * @param schemaContext
179 * {@link EffectiveModelContext}
182 * @param domMountPointService
183 * {@link DOMMountPointService}
184 * @return {@link SchemaExportContext}
186 public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
187 final String identifier, final DOMMountPointService domMountPointService,
188 final DOMYangTextSourceProvider sourceProvider) {
189 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
190 final Iterator<String> componentIter = pathComponents.iterator();
191 if (!Iterables.contains(pathComponents, MOUNT)) {
192 final String moduleName = validateAndGetModulName(componentIter);
193 final Revision revision = validateAndGetRevision(componentIter);
194 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
195 return new SchemaExportContext(schemaContext, module, sourceProvider);
197 final StringBuilder pathBuilder = new StringBuilder();
198 while (componentIter.hasNext()) {
199 final String current = componentIter.next();
201 if (MOUNT.equals(current)) {
202 pathBuilder.append('/').append(MOUNT);
206 if (pathBuilder.length() != 0) {
207 pathBuilder.append('/');
210 pathBuilder.append(current);
212 final InstanceIdentifierContext point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
213 Optional.of(domMountPointService));
214 final String moduleName = validateAndGetModulName(componentIter);
215 final Revision revision = validateAndGetRevision(componentIter);
216 final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
217 final Module module = context.findModule(moduleName, revision).orElse(null);
218 return new SchemaExportContext(context, module, sourceProvider);
222 public static YangInstanceIdentifier parserPatchTarget(final InstanceIdentifierContext context,
223 final String target) {
224 final var schemaContext = context.getSchemaContext();
225 final var urlPath = context.getInstanceIdentifier();
226 final String targetUrl;
227 if (urlPath.isEmpty()) {
228 targetUrl = target.startsWith("/") ? target.substring(1) : target;
230 targetUrl = IdentifierCodec.serialize(urlPath, schemaContext) + target;
233 return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
237 * Validation and parsing of revision.
239 * @param revisionDate iterator
243 static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
244 RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
245 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
247 return Revision.of(revisionDate.next());
248 } catch (final DateTimeParseException e) {
249 throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
254 * Validation of name.
256 * @param moduleName iterator
257 * @return {@link String}
260 static String validateAndGetModulName(final Iterator<String> moduleName) {
261 RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
262 ErrorTag.INVALID_VALUE);
263 final String name = moduleName.next();
265 RestconfDocumentedException.throwIf(
266 name.isEmpty() || !YangNames.IDENTIFIER_START.matches(name.charAt(0)),
267 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
268 RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
269 "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
270 RestconfDocumentedException.throwIf(
271 YangNames.NOT_IDENTIFIER_PART.matchesAnyOf(name.substring(1)),
272 "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
277 private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
278 final EffectiveModelContext context = modelContext(mountPoint);
279 checkState(context != null, "Mount point %s does not have a model context", mountPoint);
283 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
284 return mountPoint.getService(DOMSchemaService.class)
285 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))