5b550dd711e568991e540026ac064f039e3ff13b
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / utils / parser / ParserIdentifier.java
1 /*
2  * Copyright (c) 2016 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.restconf.nb.rfc8040.utils.parser;
9
10 import static com.google.common.base.Preconditions.checkState;
11 import static com.google.common.base.Verify.verifyNotNull;
12
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;
51
52 /**
53  * Util class for parsing identifier.
54  */
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);
58
59     private ParserIdentifier() {
60         // Hidden on purpose
61     }
62
63     /**
64      * Make {@link InstanceIdentifierContext} from {@link String} identifier
65      * <br>
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}.
69      * <br>
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}.
73      *
74      * @param identifier
75      *           - path identifier
76      * @param schemaContext
77      *           - controller schema context
78      * @param mountPointService
79      *           - mount point service
80      * @return {@link InstanceIdentifierContext}
81      */
82     // FIXME: NETCONF-631: this method should not be here, it should be a static factory in InstanceIdentifierContext:
83     //
84     //        @NonNull InstanceIdentifierContext forUrl(identifier, schemaContexxt, mountPointService)
85     //
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);
90         }
91         if (mountPointService.isEmpty()) {
92             throw new RestconfDocumentedException("Mount point service is not available");
93         }
94
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));
101
102         final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
103         final String pathId = pathsIt.next().replaceFirst("/", "");
104         return createIIdContext(mountSchemaContext, pathId, mountPoint);
105     }
106
107     /**
108      * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
109      * and {@link SchemaContext}, {@link DOMMountPoint}.
110      *
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
116      */
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,
121                 schemaContext);
122     }
123
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;
129         }
130
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()))
134                 .orElseThrow(
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));
138
139         // Now try to resolve the last component as a data item...
140         final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
141         if (data != null) {
142             return data.getDataSchemaNode();
143         }
144
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())) {
152                     return rpc;
153                 }
154             }
155         }
156         if (parentSchema instanceof ActionNodeContainer) {
157             for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
158                 if (qname.equals(action.getQName())) {
159                     return action;
160                 }
161             }
162         }
163
164         // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
165         //          is deemed invalid
166         throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
167             ErrorTag.INVALID_VALUE);
168     }
169
170     /**
171      * Make a moduleName/Revision pair from identifier.
172      *
173      * @param identifier
174      *             path parameter
175      * @return {@link QName}
176      */
177     @VisibleForTesting
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);
185         }
186
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("/", "");
192         } else {
193             moduleNameAndRevision = identifier;
194         }
195
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);
202         }
203
204         final Revision moduleRevision;
205         try {
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);
211         }
212
213         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
214     }
215
216     /**
217      * Parsing {@link Module} module by {@link String} module name and
218      * {@link Date} revision and from the parsed module create
219      * {@link SchemaExportContext}.
220      *
221      * @param schemaContext
222      *             {@link EffectiveModelContext}
223      * @param identifier
224      *             path parameter
225      * @param domMountPointService
226      *             {@link DOMMountPointService}
227      * @return {@link SchemaExportContext}
228      */
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);
239         } else {
240             final StringBuilder pathBuilder = new StringBuilder();
241             while (componentIter.hasNext()) {
242                 final String current = componentIter.next();
243
244                 if (RestconfConstants.MOUNT.equals(current)) {
245                     pathBuilder.append('/').append(RestconfConstants.MOUNT);
246                     break;
247                 }
248
249                 if (pathBuilder.length() != 0) {
250                     pathBuilder.append('/');
251                 }
252
253                 pathBuilder.append(current);
254             }
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);
262         }
263     }
264
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;
272         } else {
273             targetUrl = IdentifierCodec.serialize(urlPath, schemaContext) + target;
274         }
275
276         return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
277     }
278
279     /**
280      * Validation and parsing of revision.
281      *
282      * @param revisionDate iterator
283      * @return A Revision
284      */
285     @VisibleForTesting
286     static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
287         RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
288             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
289         try {
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);
293         }
294     }
295
296     /**
297      * Validation of name.
298      *
299      * @param moduleName iterator
300      * @return {@link String}
301      */
302     @VisibleForTesting
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();
307
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);
316
317         return name;
318     }
319
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);
323         return context;
324     }
325
326     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
327         return mountPoint.getService(DOMSchemaService.class)
328             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
329             .orElse(null);
330     }
331 }