Remove RestconfError.ErrorTag
[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     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);
86         }
87         if (mountPointService.isEmpty()) {
88             throw new RestconfDocumentedException("Mount point service is not available");
89         }
90
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, ErrorTags.RESOURCE_DENIED_TRANSPORT));
97
98         final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
99         final String pathId = pathsIt.next().replaceFirst("/", "");
100         return createIIdContext(mountSchemaContext, pathId, mountPoint);
101     }
102
103     /**
104      * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
105      * and {@link SchemaContext}, {@link DOMMountPoint}.
106      *
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
112      */
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,
117                 schemaContext);
118     }
119
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;
125         }
126
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()))
130                 .orElseThrow(
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));
134
135         // Now try to resolve the last component as a data item...
136         final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
137         if (data != null) {
138             return data.getDataSchemaNode();
139         }
140
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())) {
148                     return rpc;
149                 }
150             }
151         }
152         if (parentSchema instanceof ActionNodeContainer) {
153             for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
154                 if (qname.equals(action.getQName())) {
155                     return action;
156                 }
157             }
158         }
159
160         // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
161         //          is deemed invalid
162         throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
163             ErrorTag.INVALID_VALUE);
164     }
165
166     /**
167      * Make {@link String} from {@link YangInstanceIdentifier}.
168      *
169      * @param instanceIdentifier    Instance identifier
170      * @param schemaContext         Schema context
171      * @return                      Yang instance identifier serialized to String
172      */
173     public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
174             final EffectiveModelContext schemaContext) {
175         return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
176     }
177
178     /**
179      * Make a moduleName/Revision pair from identifier.
180      *
181      * @param identifier
182      *             path parameter
183      * @return {@link QName}
184      */
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);
192         }
193
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("/", "");
199         } else {
200             moduleNameAndRevision = identifier;
201         }
202
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);
209         }
210
211         final Revision moduleRevision;
212         try {
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);
218         }
219
220         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
221     }
222
223     /**
224      * Parsing {@link Module} module by {@link String} module name and
225      * {@link Date} revision and from the parsed module create
226      * {@link SchemaExportContext}.
227      *
228      * @param schemaContext
229      *             {@link EffectiveModelContext}
230      * @param identifier
231      *             path parameter
232      * @param domMountPointService
233      *             {@link DOMMountPointService}
234      * @return {@link SchemaExportContext}
235      */
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);
246         } else {
247             final StringBuilder pathBuilder = new StringBuilder();
248             while (componentIter.hasNext()) {
249                 final String current = componentIter.next();
250
251                 if (RestconfConstants.MOUNT.equals(current)) {
252                     pathBuilder.append('/').append(RestconfConstants.MOUNT);
253                     break;
254                 }
255
256                 if (pathBuilder.length() != 0) {
257                     pathBuilder.append('/');
258                 }
259
260                 pathBuilder.append(current);
261             }
262             final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
263                 Optional.of(domMountPointService));
264             final String moduleName = validateAndGetModulName(componentIter);
265             final Revision revision = validateAndGetRevision(componentIter);
266             final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
267             final Module module = context.findModule(moduleName, revision).orElse(null);
268             return new SchemaExportContext(context, module, sourceProvider);
269         }
270     }
271
272     public static YangInstanceIdentifier parserPatchTarget(final InstanceIdentifierContext<?> context,
273             final String target) {
274         final var schemaContext = context.getSchemaContext();
275         final var urlPath = context.getInstanceIdentifier();
276         final String targetUrl;
277         if (urlPath.isEmpty()) {
278             targetUrl = target.startsWith("/") ? target.substring(1) : target;
279         } else {
280             targetUrl = stringFromYangInstanceIdentifier(urlPath, schemaContext) + target;
281         }
282
283         return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
284     }
285
286     /**
287      * Validation and parsing of revision.
288      *
289      * @param revisionDate iterator
290      * @return A Revision
291      */
292     @VisibleForTesting
293     static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
294         RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
295             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
296         try {
297             return Revision.of(revisionDate.next());
298         } catch (final DateTimeParseException e) {
299             throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
300         }
301     }
302
303     /**
304      * Validation of name.
305      *
306      * @param moduleName iterator
307      * @return {@link String}
308      */
309     @VisibleForTesting
310     static String validateAndGetModulName(final Iterator<String> moduleName) {
311         RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
312             ErrorTag.INVALID_VALUE);
313         final String name = moduleName.next();
314
315         RestconfDocumentedException.throwIf(
316             name.isEmpty() || !ParserConstants.YANG_IDENTIFIER_START.matches(name.charAt(0)),
317             "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
318         RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
319             "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
320         RestconfDocumentedException.throwIf(
321             !ParserConstants.YANG_IDENTIFIER_PART.matchesAllOf(name.substring(1)),
322             "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
323
324         return name;
325     }
326
327     private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
328         final EffectiveModelContext context = modelContext(mountPoint);
329         checkState(context != null, "Mount point %s does not have a model context", mountPoint);
330         return context;
331     }
332
333     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
334         return mountPoint.getService(DOMSchemaService.class)
335             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
336             .orElse(null);
337     }
338 }