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