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.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
33 import org.opendaylight.restconf.common.schema.SchemaExportContext;
34 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.Revision;
37 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
39 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
40 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
41 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Util class for parsing identifier.
54 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() {
60 throw new UnsupportedOperationException("Util class.");
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 public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
83 final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
84 if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
85 return createIIdContext(schemaContext, identifier, null);
87 if (!mountPointService.isPresent()) {
88 throw new RestconfDocumentedException("Mount point service is not available");
91 final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
92 final String mountPointId = pathsIt.next();
93 final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
94 final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
95 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
96 ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED_TRANSPORT));
98 final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
99 final String pathId = pathsIt.next().replaceFirst("/", "");
100 return createIIdContext(mountSchemaContext, pathId, mountPoint);
104 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
105 * and {@link SchemaContext}, {@link DOMMountPoint}.
107 * @param url Invocation URL
108 * @param schemaContext SchemaContext in which the path is to be interpreted in
109 * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
110 * @return {@link InstanceIdentifierContext}
111 * @throws RestconfDocumentedException if the path cannot be resolved
113 private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
114 final String url, final @Nullable DOMMountPoint mountPoint) {
115 final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
116 return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
120 private static SchemaNode getPathSchema(final EffectiveModelContext schemaContext,
121 final YangInstanceIdentifier urlPath) {
122 // First things first: an empty path means data invocation on SchemaContext
123 if (urlPath.isEmpty()) {
124 return schemaContext;
127 // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
128 final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
129 .findChild(verifyNotNull(urlPath.getParent()))
131 // Parent data node is not present, this is not a valid location.
132 () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
133 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
135 // Now try to resolve the last component as a data item...
136 final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
138 return data.getDataSchemaNode();
141 // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
142 // actions can reside everywhere else (and SchemaContext reports them empty)
143 final QName qname = urlPath.getLastPathArgument().getNodeType();
144 final DataSchemaNode parentSchema = parent.getDataSchemaNode();
145 if (parentSchema instanceof SchemaContext) {
146 for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
147 if (qname.equals(rpc.getQName())) {
152 if (parentSchema instanceof ActionNodeContainer) {
153 for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
154 if (qname.equals(action.getQName())) {
160 // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
162 throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
163 ErrorTag.INVALID_VALUE);
167 * Make {@link String} from {@link YangInstanceIdentifier}.
169 * @param instanceIdentifier Instance identifier
170 * @param schemaContext Schema context
171 * @return Yang instance identifier serialized to String
173 public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
174 final EffectiveModelContext schemaContext) {
175 return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
179 * Make a moduleName/Revision pair from identifier.
183 * @return {@link QName}
185 public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
186 // check if more than one slash is not used as path separator
187 if (identifier.contains("//")) {
188 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
189 throw new RestconfDocumentedException(
190 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
191 ErrorTag.INVALID_VALUE);
194 final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
195 final String moduleNameAndRevision;
196 if (mountIndex >= 0) {
197 moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
198 .replaceFirst("/", "");
200 moduleNameAndRevision = identifier;
203 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
204 if (pathArgs.size() != 2) {
205 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
206 throw new RestconfDocumentedException(
207 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
208 ErrorTag.INVALID_VALUE);
211 final Revision moduleRevision;
213 moduleRevision = Revision.of(pathArgs.get(1));
214 } catch (final DateTimeParseException e) {
215 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
216 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
217 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
220 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
224 * Parsing {@link Module} module by {@link String} module name and
225 * {@link Date} revision and from the parsed module create
226 * {@link SchemaExportContext}.
228 * @param schemaContext
229 * {@link EffectiveModelContext}
232 * @param domMountPointService
233 * {@link DOMMountPointService}
234 * @return {@link SchemaExportContext}
236 public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
237 final String identifier, final DOMMountPointService domMountPointService,
238 final DOMYangTextSourceProvider sourceProvider) {
239 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
240 final Iterator<String> componentIter = pathComponents.iterator();
241 if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
242 final String moduleName = validateAndGetModulName(componentIter);
243 final Revision revision = validateAndGetRevision(componentIter);
244 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
245 return new SchemaExportContext(schemaContext, module, sourceProvider);
247 final StringBuilder pathBuilder = new StringBuilder();
248 while (componentIter.hasNext()) {
249 final String current = componentIter.next();
251 if (RestconfConstants.MOUNT.equals(current)) {
252 pathBuilder.append("/");
253 pathBuilder.append(RestconfConstants.MOUNT);
257 if (pathBuilder.length() != 0) {
258 pathBuilder.append("/");
261 pathBuilder.append(current);
263 final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
264 Optional.of(domMountPointService));
265 final String moduleName = validateAndGetModulName(componentIter);
266 final Revision revision = validateAndGetRevision(componentIter);
267 final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
268 final Module module = context.findModule(moduleName, revision).orElse(null);
269 return new SchemaExportContext(context, module, sourceProvider);
274 * Validation and parsing of revision.
276 * @param revisionDate iterator
280 static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
281 RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
282 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
284 return Revision.of(revisionDate.next());
285 } catch (final DateTimeParseException e) {
286 throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
291 * Validation of name.
293 * @param moduleName iterator
294 * @return {@link String}
297 static String validateAndGetModulName(final Iterator<String> moduleName) {
298 RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
299 ErrorTag.INVALID_VALUE);
300 final String name = moduleName.next();
302 RestconfDocumentedException.throwIf(
303 name.isEmpty() || !ParserConstants.YANG_IDENTIFIER_START.matches(name.charAt(0)),
304 "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
305 RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
306 "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
307 RestconfDocumentedException.throwIf(
308 !ParserConstants.YANG_IDENTIFIER_PART.matchesAllOf(name.substring(1)),
309 "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
314 private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
315 final EffectiveModelContext context = modelContext(mountPoint);
316 checkState(context != null, "Mount point %s does not have a model context", mountPoint);
320 private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
321 return mountPoint.getService(DOMSchemaService.class)
322 .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))