Throws RDE exception in case model was not found
[netconf.git] / restconf / restconf-nb / 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
12 import com.google.common.annotations.VisibleForTesting;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Iterables;
15 import java.time.format.DateTimeParseException;
16 import java.util.AbstractMap.SimpleImmutableEntry;
17 import java.util.Date;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Locale;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
25 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
26 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
27 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
28 import org.opendaylight.restconf.common.ErrorTags;
29 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.nb.rfc8040.rests.services.api.SchemaExportContext;
32 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
33 import org.opendaylight.yangtools.yang.common.ErrorTag;
34 import org.opendaylight.yangtools.yang.common.ErrorType;
35 import org.opendaylight.yangtools.yang.common.QName;
36 import org.opendaylight.yangtools.yang.common.Revision;
37 import org.opendaylight.yangtools.yang.common.YangNames;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
39 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * Util class for parsing identifier.
47  */
48 public final class ParserIdentifier {
49     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
50     private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
51
52     private ParserIdentifier() {
53         // Hidden on purpose
54     }
55
56     /**
57      * Make {@link InstanceIdentifierContext} from {@link String} identifier
58      * <br>
59      * For identifiers of data NOT behind mount points returned
60      * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
61      * controller's {@link SchemaContext}.
62      * <br>
63      * For identifiers of data behind mount points returned
64      * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
65      * own {@link SchemaContext}.
66      *
67      * @param identifier
68      *           - path identifier
69      * @param schemaContext
70      *           - controller schema context
71      * @param mountPointService
72      *           - mount point service
73      * @return {@link InstanceIdentifierContext}
74      */
75     // FIXME: NETCONF-631: this method should not be here, it should be a static factory in InstanceIdentifierContext:
76     //
77     //        @NonNull InstanceIdentifierContext forUrl(identifier, schemaContexxt, mountPointService)
78     //
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);
83         }
84         if (mountPointService.isEmpty()) {
85             throw new RestconfDocumentedException("Mount point service is not available");
86         }
87
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, ErrorTags.RESOURCE_DENIED_TRANSPORT));
94
95         final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
96         final String pathId = pathsIt.next().replaceFirst("/", "");
97         return createIIdContext(mountSchemaContext, pathId, mountPoint);
98     }
99
100     /**
101      * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
102      * and {@link SchemaContext}, {@link DOMMountPoint}.
103      *
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
109      */
110     private static InstanceIdentifierContext createIIdContext(final EffectiveModelContext schemaContext,
111             final String url, final @Nullable DOMMountPoint mountPoint) {
112         // First things first: an empty path means data invocation on SchemaContext
113         if (url == null) {
114             return mountPoint != null ? InstanceIdentifierContext.ofMountPointRoot(mountPoint, schemaContext)
115                 : InstanceIdentifierContext.ofLocalRoot(schemaContext);
116         }
117
118         final var result = YangInstanceIdentifierDeserializer.create(schemaContext, url);
119         return InstanceIdentifierContext.ofPath(result.stack, result.node, result.path, mountPoint);
120     }
121
122     /**
123      * Make a moduleName/Revision pair from identifier.
124      *
125      * @param identifier
126      *             path parameter
127      * @return {@link QName}
128      */
129     @VisibleForTesting
130     static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
131         // check if more than one slash is not used as path separator
132         if (identifier.contains("//")) {
133             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
134             throw new RestconfDocumentedException(
135                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
136                     ErrorTag.INVALID_VALUE);
137         }
138
139         final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
140         final String moduleNameAndRevision;
141         if (mountIndex >= 0) {
142             moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
143                     .replaceFirst("/", "");
144         } else {
145             moduleNameAndRevision = identifier;
146         }
147
148         final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
149         if (pathArgs.size() != 2) {
150             LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
151             throw new RestconfDocumentedException(
152                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
153                     ErrorTag.INVALID_VALUE);
154         }
155
156         final Revision moduleRevision;
157         try {
158             moduleRevision = Revision.of(pathArgs.get(1));
159         } catch (final DateTimeParseException e) {
160             LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
161             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
162                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
163         }
164
165         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
166     }
167
168     /**
169      * Parsing {@link Module} module by {@link String} module name and
170      * {@link Date} revision and from the parsed module create
171      * {@link SchemaExportContext}.
172      *
173      * @param schemaContext
174      *             {@link EffectiveModelContext}
175      * @param identifier
176      *             path parameter
177      * @param domMountPointService
178      *             {@link DOMMountPointService}
179      * @return {@link SchemaExportContext}
180      */
181     public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
182             final String identifier, final DOMMountPointService domMountPointService,
183             final DOMYangTextSourceProvider sourceProvider) {
184         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
185         final Iterator<String> componentIter = pathComponents.iterator();
186         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
187             final String moduleName = validateAndGetModulName(componentIter);
188             final Revision revision = validateAndGetRevision(componentIter);
189             final Module module = coerceModule(schemaContext, moduleName, revision, null);
190             return new SchemaExportContext(schemaContext, module, sourceProvider);
191         } else {
192             final StringBuilder pathBuilder = new StringBuilder();
193             while (componentIter.hasNext()) {
194                 final String current = componentIter.next();
195
196                 if (RestconfConstants.MOUNT.equals(current)) {
197                     pathBuilder.append('/').append(RestconfConstants.MOUNT);
198                     break;
199                 }
200
201                 if (pathBuilder.length() != 0) {
202                     pathBuilder.append('/');
203                 }
204
205                 pathBuilder.append(current);
206             }
207             final InstanceIdentifierContext point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
208                 Optional.of(domMountPointService));
209             final String moduleName = validateAndGetModulName(componentIter);
210             final Revision revision = validateAndGetRevision(componentIter);
211             final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
212             final Module module = coerceModule(context, moduleName, revision, point.getMountPoint());
213             return new SchemaExportContext(context, module, sourceProvider);
214         }
215     }
216
217     /**
218      * Validation and parsing of revision.
219      *
220      * @param revisionDate iterator
221      * @return A Revision
222      */
223     @VisibleForTesting
224     static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
225         RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
226             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
227         try {
228             return Revision.of(revisionDate.next());
229         } catch (final DateTimeParseException e) {
230             throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
231         }
232     }
233
234     /**
235      * Validation of name.
236      *
237      * @param moduleName iterator
238      * @return {@link String}
239      */
240     @VisibleForTesting
241     static String validateAndGetModulName(final Iterator<String> moduleName) {
242         RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
243             ErrorTag.INVALID_VALUE);
244         final String name = moduleName.next();
245
246         RestconfDocumentedException.throwIf(
247             name.isEmpty() || !YangNames.IDENTIFIER_START.matches(name.charAt(0)),
248             "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
249         RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
250             "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
251         RestconfDocumentedException.throwIf(
252             YangNames.NOT_IDENTIFIER_PART.matchesAnyOf(name.substring(1)),
253             "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
254
255         return name;
256     }
257
258     private static Module coerceModule(final EffectiveModelContext context, final String moduleName,
259             final Revision revision, final DOMMountPoint mountPoint) {
260         final var module = context.findModule(moduleName, revision);
261         if (module.isEmpty()) {
262             final var msg = "Module %s %s cannot be found on %s.".formatted(moduleName, revision,
263                 mountPoint == null ? "controller" : mountPoint.getIdentifier());
264             throw new RestconfDocumentedException(msg, ErrorType.APPLICATION, ErrorTag.DATA_MISSING);
265         }
266         return module.orElseThrow();
267     }
268
269     private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
270         final EffectiveModelContext context = modelContext(mountPoint);
271         checkState(context != null, "Mount point %s does not have a model context", mountPoint);
272         return context;
273     }
274
275     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
276         return mountPoint.getService(DOMSchemaService.class)
277             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
278             .orElse(null);
279     }
280 }