ae8e1995a2e235c7c1339db00a5b315e6bd3ac91
[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.context.InstanceIdentifierContext;
30 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
31 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
32 import org.opendaylight.restconf.common.schema.SchemaExportContext;
33 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
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.data.api.YangInstanceIdentifier;
38 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
39 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
40 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
41 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
44 import org.opendaylight.yangtools.yang.model.api.Module;
45 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
46 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * Util class for parsing identifier.
53  */
54 public final class ParserIdentifier {
55     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
56     private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
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     public static InstanceIdentifierContext<?> toInstanceIdentifier(final String identifier,
82             final EffectiveModelContext schemaContext, final Optional<DOMMountPointService> mountPointService) {
83         if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
84             return createIIdContext(schemaContext, identifier, null);
85         }
86         if (mountPointService.isEmpty()) {
87             throw new RestconfDocumentedException("Mount point service is not available");
88         }
89
90         final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
91         final String mountPointId = pathsIt.next();
92         final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
93         final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
94                 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
95                     ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED_TRANSPORT));
96
97         final EffectiveModelContext mountSchemaContext = coerceModelContext(mountPoint);
98         final String pathId = pathsIt.next().replaceFirst("/", "");
99         return createIIdContext(mountSchemaContext, pathId, mountPoint);
100     }
101
102     /**
103      * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
104      * and {@link SchemaContext}, {@link DOMMountPoint}.
105      *
106      * @param url Invocation URL
107      * @param schemaContext SchemaContext in which the path is to be interpreted in
108      * @param mountPoint A mount point handle, if the URL is being interpreted relative to a mount point
109      * @return {@link InstanceIdentifierContext}
110      * @throws RestconfDocumentedException if the path cannot be resolved
111      */
112     private static InstanceIdentifierContext<?> createIIdContext(final EffectiveModelContext schemaContext,
113             final String url, final @Nullable DOMMountPoint mountPoint) {
114         final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
115         return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
116                 schemaContext);
117     }
118
119     private static SchemaNode getPathSchema(final EffectiveModelContext schemaContext,
120             final YangInstanceIdentifier urlPath) {
121         // First things first: an empty path means data invocation on SchemaContext
122         if (urlPath.isEmpty()) {
123             return schemaContext;
124         }
125
126         // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
127         final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
128                 .findChild(verifyNotNull(urlPath.getParent()))
129                 .orElseThrow(
130                     // Parent data node is not present, this is not a valid location.
131                     () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
132                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
133
134         // Now try to resolve the last component as a data item...
135         final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
136         if (data != null) {
137             return data.getDataSchemaNode();
138         }
139
140         // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
141         // actions can reside everywhere else (and SchemaContext reports them empty)
142         final QName qname = urlPath.getLastPathArgument().getNodeType();
143         final DataSchemaNode parentSchema = parent.getDataSchemaNode();
144         if (parentSchema instanceof SchemaContext) {
145             for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
146                 if (qname.equals(rpc.getQName())) {
147                     return rpc;
148                 }
149             }
150         }
151         if (parentSchema instanceof ActionNodeContainer) {
152             for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
153                 if (qname.equals(action.getQName())) {
154                     return action;
155                 }
156             }
157         }
158
159         // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
160         //          is deemed invalid
161         throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
162             ErrorTag.INVALID_VALUE);
163     }
164
165     /**
166      * Make {@link String} from {@link YangInstanceIdentifier}.
167      *
168      * @param instanceIdentifier    Instance identifier
169      * @param schemaContext         Schema context
170      * @return                      Yang instance identifier serialized to String
171      */
172     public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
173             final EffectiveModelContext schemaContext) {
174         return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
175     }
176
177     /**
178      * Make a moduleName/Revision pair from identifier.
179      *
180      * @param identifier
181      *             path parameter
182      * @return {@link QName}
183      */
184     public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
185         // check if more than one slash is not used as path separator
186         if (identifier.contains("//")) {
187             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
188             throw new RestconfDocumentedException(
189                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
190                     ErrorTag.INVALID_VALUE);
191         }
192
193         final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
194         final String moduleNameAndRevision;
195         if (mountIndex >= 0) {
196             moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
197                     .replaceFirst("/", "");
198         } else {
199             moduleNameAndRevision = identifier;
200         }
201
202         final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
203         if (pathArgs.size() != 2) {
204             LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
205             throw new RestconfDocumentedException(
206                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
207                     ErrorTag.INVALID_VALUE);
208         }
209
210         final Revision moduleRevision;
211         try {
212             moduleRevision = Revision.of(pathArgs.get(1));
213         } catch (final DateTimeParseException e) {
214             LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
215             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
216                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
217         }
218
219         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
220     }
221
222     /**
223      * Parsing {@link Module} module by {@link String} module name and
224      * {@link Date} revision and from the parsed module create
225      * {@link SchemaExportContext}.
226      *
227      * @param schemaContext
228      *             {@link EffectiveModelContext}
229      * @param identifier
230      *             path parameter
231      * @param domMountPointService
232      *             {@link DOMMountPointService}
233      * @return {@link SchemaExportContext}
234      */
235     public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
236             final String identifier, final DOMMountPointService domMountPointService,
237             final DOMYangTextSourceProvider sourceProvider) {
238         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
239         final Iterator<String> componentIter = pathComponents.iterator();
240         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
241             final String moduleName = validateAndGetModulName(componentIter);
242             final Revision revision = validateAndGetRevision(componentIter);
243             final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
244             return new SchemaExportContext(schemaContext, module, sourceProvider);
245         } else {
246             final StringBuilder pathBuilder = new StringBuilder();
247             while (componentIter.hasNext()) {
248                 final String current = componentIter.next();
249
250                 if (RestconfConstants.MOUNT.equals(current)) {
251                     pathBuilder.append('/').append(RestconfConstants.MOUNT);
252                     break;
253                 }
254
255                 if (pathBuilder.length() != 0) {
256                     pathBuilder.append('/');
257                 }
258
259                 pathBuilder.append(current);
260             }
261             final InstanceIdentifierContext<?> point = toInstanceIdentifier(pathBuilder.toString(), schemaContext,
262                 Optional.of(domMountPointService));
263             final String moduleName = validateAndGetModulName(componentIter);
264             final Revision revision = validateAndGetRevision(componentIter);
265             final EffectiveModelContext context = coerceModelContext(point.getMountPoint());
266             final Module module = context.findModule(moduleName, revision).orElse(null);
267             return new SchemaExportContext(context, module, sourceProvider);
268         }
269     }
270
271     public static YangInstanceIdentifier parserPatchTarget(final InstanceIdentifierContext<?> context,
272             final String target) {
273         final var schemaContext = context.getSchemaContext();
274         final var urlPath = context.getInstanceIdentifier();
275         final String targetUrl;
276         if (urlPath.isEmpty()) {
277             targetUrl = target.startsWith("/") ? target.substring(1) : target;
278         } else {
279             targetUrl = stringFromYangInstanceIdentifier(urlPath, schemaContext) + target;
280         }
281
282         return toInstanceIdentifier(targetUrl, schemaContext, Optional.empty()).getInstanceIdentifier();
283     }
284
285     /**
286      * Validation and parsing of revision.
287      *
288      * @param revisionDate iterator
289      * @return A Revision
290      */
291     @VisibleForTesting
292     static Revision validateAndGetRevision(final Iterator<String> revisionDate) {
293         RestconfDocumentedException.throwIf(!revisionDate.hasNext(), "Revision date must be supplied.",
294             ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
295         try {
296             return Revision.of(revisionDate.next());
297         } catch (final DateTimeParseException e) {
298             throw new RestconfDocumentedException("Supplied revision is not in expected date format YYYY-mm-dd", e);
299         }
300     }
301
302     /**
303      * Validation of name.
304      *
305      * @param moduleName iterator
306      * @return {@link String}
307      */
308     @VisibleForTesting
309     static String validateAndGetModulName(final Iterator<String> moduleName) {
310         RestconfDocumentedException.throwIf(!moduleName.hasNext(), "Module name must be supplied.", ErrorType.PROTOCOL,
311             ErrorTag.INVALID_VALUE);
312         final String name = moduleName.next();
313
314         RestconfDocumentedException.throwIf(
315             name.isEmpty() || !ParserConstants.YANG_IDENTIFIER_START.matches(name.charAt(0)),
316             "Identifier must start with character from set 'a-zA-Z_", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
317         RestconfDocumentedException.throwIf(name.toUpperCase(Locale.ROOT).startsWith("XML"),
318             "Identifier must NOT start with XML ignore case.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
319         RestconfDocumentedException.throwIf(
320             !ParserConstants.YANG_IDENTIFIER_PART.matchesAllOf(name.substring(1)),
321             "Supplied name has not expected identifier format.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
322
323         return name;
324     }
325
326     private static EffectiveModelContext coerceModelContext(final DOMMountPoint mountPoint) {
327         final EffectiveModelContext context = modelContext(mountPoint);
328         checkState(context != null, "Mount point %s does not have a model context", mountPoint);
329         return context;
330     }
331
332     private static EffectiveModelContext modelContext(final DOMMountPoint mountPoint) {
333         return mountPoint.getService(DOMSchemaService.class)
334             .flatMap(svc -> Optional.ofNullable(svc.getGlobalContext()))
335             .orElse(null);
336     }
337 }