Use YangNames CharMatchers in parser
[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.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;
52
53 /**
54  * Util class for parsing identifier.
55  */
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);
59
60     private ParserIdentifier() {
61         // Hidden on purpose
62     }
63
64     /**
65      * Make {@link InstanceIdentifierContext} from {@link String} identifier
66      * <br>
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}.
70      * <br>
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}.
74      *
75      * @param identifier
76      *           - path identifier
77      * @param schemaContext
78      *           - controller schema context
79      * @param mountPointService
80      *           - mount point service
81      * @return {@link InstanceIdentifierContext}
82      */
83     // FIXME: NETCONF-631: this method should not be here, it should be a static factory in InstanceIdentifierContext:
84     //
85     //        @NonNull InstanceIdentifierContext forUrl(identifier, schemaContexxt, mountPointService)
86     //
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);
91         }
92         if (mountPointService.isEmpty()) {
93             throw new RestconfDocumentedException("Mount point service is not available");
94         }
95
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));
102
103         final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
104         final String pathId = pathsIt.next().replaceFirst("/", "");
105         return createIIdContext(mountSchemaContext, pathId, mountPoint);
106     }
107
108     /**
109      * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
110      * and {@link SchemaContext}, {@link DOMMountPoint}.
111      *
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
117      */
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,
122                 schemaContext);
123     }
124
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;
130         }
131
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()))
135                 .orElseThrow(
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));
139
140         // Now try to resolve the last component as a data item...
141         final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
142         if (data != null) {
143             return data.getDataSchemaNode();
144         }
145
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())) {
153                     return rpc;
154                 }
155             }
156         }
157         if (parentSchema instanceof ActionNodeContainer) {
158             for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
159                 if (qname.equals(action.getQName())) {
160                     return action;
161                 }
162             }
163         }
164
165         // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
166         //          is deemed invalid
167         throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
168             ErrorTag.INVALID_VALUE);
169     }
170
171     /**
172      * Make a moduleName/Revision pair from identifier.
173      *
174      * @param identifier
175      *             path parameter
176      * @return {@link QName}
177      */
178     @VisibleForTesting
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);
186         }
187
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("/", "");
193         } else {
194             moduleNameAndRevision = identifier;
195         }
196
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);
203         }
204
205         final Revision moduleRevision;
206         try {
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);
212         }
213
214         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
215     }
216
217     /**
218      * Parsing {@link Module} module by {@link String} module name and
219      * {@link Date} revision and from the parsed module create
220      * {@link SchemaExportContext}.
221      *
222      * @param schemaContext
223      *             {@link EffectiveModelContext}
224      * @param identifier
225      *             path parameter
226      * @param domMountPointService
227      *             {@link DOMMountPointService}
228      * @return {@link SchemaExportContext}
229      */
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);
240         } else {
241             final StringBuilder pathBuilder = new StringBuilder();
242             while (componentIter.hasNext()) {
243                 final String current = componentIter.next();
244
245                 if (RestconfConstants.MOUNT.equals(current)) {
246                     pathBuilder.append('/').append(RestconfConstants.MOUNT);
247                     break;
248                 }
249
250                 if (pathBuilder.length() != 0) {
251                     pathBuilder.append('/');
252                 }
253
254                 pathBuilder.append(current);
255             }
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);
263         }
264     }
265
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;
273         } else {
274             targetUrl = IdentifierCodec.serialize(urlPath, schemaContext) + target;
275         }
276
277         return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
278     }
279
280     /**
281      * Validation and parsing of revision.
282      *
283      * @param revisionDate iterator
284      * @return A Revision
285      */
286     @VisibleForTesting
287     static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
288         RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
289             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
290         try {
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);
294         }
295     }
296
297     /**
298      * Validation of name.
299      *
300      * @param moduleName iterator
301      * @return {@link String}
302      */
303     @VisibleForTesting
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();
308
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);
317
318         return name;
319     }
320
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);
324         return context;
325     }
326
327     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
328         return mountPoint.getService(DOMSchemaService.class)
329             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
330             .orElse(null);
331     }
332 }