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.base.Splitter;
13 import com.google.common.collect.Iterables;
14 import java.time.format.DateTimeParseException;
15 import java.util.AbstractMap.SimpleImmutableEntry;
16 import java.util.Date;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map.Entry;
20 import java.util.Optional;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
23 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
24 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
25 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
28 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
29 import org.opendaylight.restconf.common.schema.SchemaExportContext;
30 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
31 import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.Revision;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
36 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
37 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
38 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * Util class for parsing identifier.
51 public final class ParserIdentifier {
53 private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
54 private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
56 private ParserIdentifier() {
57 throw new UnsupportedOperationException("Util class.");
61 * Make {@link InstanceIdentifierContext} from {@link String} identifier
63 * For identifiers of data NOT behind mount points returned
64 * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
65 * controller's {@link SchemaContext}.
67 * For identifiers of data behind mount points returned
68 * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
69 * own {@link SchemaContext}.
73 * @param schemaContext
74 * - controller schema context
75 * @param mountPointService
76 * - mount point service
77 * @return {@link InstanceIdentifierContext}
79 public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
80 final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
81 if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
82 return createIIdContext(schemaContext, identifier, null);
84 if (!mountPointService.isPresent()) {
85 throw new RestconfDocumentedException("Mount point service is not available");
88 final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
89 final String mountPointId = pathsIt.next();
90 final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
91 final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
92 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
93 ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
95 final EffectiveModelContext mountSchemaContext = mountPoint.getEffectiveModelContext();
96 final String pathId = pathsIt.next().replaceFirst("/", "");
97 return createIIdContext(mountSchemaContext, pathId, mountPoint);
101 * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
102 * and {@link SchemaContext}, {@link DOMMountPoint}.
104 * @param url Invocation URL
105 * @param schemaContext SchemaContext in which the path is to be interpreted in
106 * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
107 * @return {@link InstanceIdentifierContext}
108 * @throws RestconfDocumentedException if the path cannot be resolved
110 private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
111 final String url, final @Nullable DOMMountPoint mountPoint) {
112 final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
113 return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
117 private static SchemaNode getPathSchema(final SchemaContext schemaContext, final YangInstanceIdentifier urlPath) {
118 // First things first: an empty path means data invocation on SchemaContext
119 if (urlPath.isEmpty()) {
120 return schemaContext;
123 // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
124 final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
125 .findChild(verifyNotNull(urlPath.getParent()))
127 // Parent data node is not present, this is not a valid location.
128 () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
129 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
131 // Now try to resolve the last component as a data item...
132 final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
134 return data.getDataSchemaNode();
137 // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
138 // actions can reside everywhere else (and SchemaContext reports them empty)
139 final QName qname = urlPath.getLastPathArgument().getNodeType();
140 final DataSchemaNode parentSchema = parent.getDataSchemaNode();
141 if (parentSchema instanceof SchemaContext) {
142 for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
143 if (qname.equals(rpc.getQName())) {
148 if (parentSchema instanceof ActionNodeContainer) {
149 for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
150 if (qname.equals(action.getQName())) {
156 // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
158 throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
159 ErrorTag.INVALID_VALUE);
163 * Make {@link String} from {@link YangInstanceIdentifier}.
165 * @param instanceIdentifier Instance identifier
166 * @param schemaContext Schema context
167 * @return Yang instance identifier serialized to String
169 public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
170 final SchemaContext schemaContext) {
171 return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
175 * Make a moduleName/Revision pair from identifier.
179 * @return {@link QName}
181 public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
182 // check if more than one slash is not used as path separator
183 if (identifier.contains(
184 String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
185 LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
186 throw new RestconfDocumentedException(
187 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
188 ErrorTag.INVALID_VALUE);
191 final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
192 final String moduleNameAndRevision;
193 if (mountIndex >= 0) {
194 moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
195 .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
197 moduleNameAndRevision = identifier;
200 final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
201 if (pathArgs.size() != 2) {
202 LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
203 throw new RestconfDocumentedException(
204 "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
205 ErrorTag.INVALID_VALUE);
208 final Revision moduleRevision;
210 moduleRevision = Revision.of(pathArgs.get(1));
211 } catch (final DateTimeParseException e) {
212 LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
213 throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
214 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
217 return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
221 * Parsing {@link Module} module by {@link String} module name and
222 * {@link Date} revision and from the parsed module create
223 * {@link SchemaExportContext}.
225 * @param schemaContext
226 * {@link EffectiveModelContext}
229 * @param domMountPointService
230 * {@link DOMMountPointService}
231 * @return {@link SchemaExportContext}
233 public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
234 final String identifier, final DOMMountPointService domMountPointService,
235 final DOMYangTextSourceProvider sourceProvider) {
236 final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
237 final Iterator<String> componentIter = pathComponents.iterator();
238 if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
239 final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
240 final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
241 final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
242 return new SchemaExportContext(schemaContext, module, sourceProvider);
244 final StringBuilder pathBuilder = new StringBuilder();
245 while (componentIter.hasNext()) {
246 final String current = componentIter.next();
248 if (RestconfConstants.MOUNT.equals(current)) {
249 pathBuilder.append("/");
250 pathBuilder.append(RestconfConstants.MOUNT);
254 if (pathBuilder.length() != 0) {
255 pathBuilder.append("/");
258 pathBuilder.append(current);
260 final InstanceIdentifierContext<?> point = ParserIdentifier
261 .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
262 final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
263 final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
264 final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
266 return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);