Update MRI projects for Aluminium
[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.Verify.verifyNotNull;
11
12 import com.google.common.base.Splitter;
13 import com.google.common.collect.Iterables;
14 import java.time.format.DateTimeParseException;
15 import java.util.AbstractMap.SimpleImmutableEntry;
16 import java.util.Date;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Map.Entry;
20 import java.util.Optional;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
23 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
24 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
25 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
26 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
28 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
29 import org.opendaylight.restconf.common.schema.SchemaExportContext;
30 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
31 import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.Revision;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
35 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
36 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
37 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
38 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
41 import org.opendaylight.yangtools.yang.model.api.Module;
42 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
44 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * Util class for parsing identifier.
50  */
51 public final class ParserIdentifier {
52
53     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
54     private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
55
56     private ParserIdentifier() {
57         throw new UnsupportedOperationException("Util class.");
58     }
59
60     /**
61      * Make {@link InstanceIdentifierContext} from {@link String} identifier
62      * <br>
63      * For identifiers of data NOT behind mount points returned
64      * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
65      * controller's {@link SchemaContext}.
66      * <br>
67      * For identifiers of data behind mount points returned
68      * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
69      * own {@link SchemaContext}.
70      *
71      * @param identifier
72      *           - path identifier
73      * @param schemaContext
74      *           - controller schema context
75      * @param mountPointService
76      *           - mount point service
77      * @return {@link InstanceIdentifierContext}
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.isPresent()) {
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, ErrorTag.DATA_MISSING));
94
95         final EffectiveModelContext mountSchemaContext = mountPoint.getEffectiveModelContext();
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         final YangInstanceIdentifier urlPath = IdentifierCodec.deserialize(url, schemaContext);
113         return new InstanceIdentifierContext<>(urlPath, getPathSchema(schemaContext, urlPath), mountPoint,
114                 schemaContext);
115     }
116
117     private static SchemaNode getPathSchema(final SchemaContext schemaContext, final YangInstanceIdentifier urlPath) {
118         // First things first: an empty path means data invocation on SchemaContext
119         if (urlPath.isEmpty()) {
120             return schemaContext;
121         }
122
123         // Peel the last component and locate the parent data node, empty path resolves to SchemaContext
124         final DataSchemaContextNode<?> parent = DataSchemaContextTree.from(schemaContext)
125                 .findChild(verifyNotNull(urlPath.getParent()))
126                 .orElseThrow(
127                     // Parent data node is not present, this is not a valid location.
128                     () -> new RestconfDocumentedException("Parent of " + urlPath + " not found",
129                         ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE));
130
131         // Now try to resolve the last component as a data item...
132         final DataSchemaContextNode<?> data = parent.getChild(urlPath.getLastPathArgument());
133         if (data != null) {
134             return data.getDataSchemaNode();
135         }
136
137         // ... otherwise this has to be an operation invocation. RPCs cannot be defined anywhere but schema root,
138         // actions can reside everywhere else (and SchemaContext reports them empty)
139         final QName qname = urlPath.getLastPathArgument().getNodeType();
140         final DataSchemaNode parentSchema = parent.getDataSchemaNode();
141         if (parentSchema instanceof SchemaContext) {
142             for (final RpcDefinition rpc : ((SchemaContext) parentSchema).getOperations()) {
143                 if (qname.equals(rpc.getQName())) {
144                     return rpc;
145                 }
146             }
147         }
148         if (parentSchema instanceof ActionNodeContainer) {
149             for (final ActionDefinition action : ((ActionNodeContainer) parentSchema).getActions()) {
150                 if (qname.equals(action.getQName())) {
151                     return action;
152                 }
153             }
154         }
155
156         // No luck: even if we found the parent, we did not locate a data, nor RPC, nor action node, hence the URL
157         //          is deemed invalid
158         throw new RestconfDocumentedException("Context for " + urlPath + " not found", ErrorType.PROTOCOL,
159             ErrorTag.INVALID_VALUE);
160     }
161
162     /**
163      * Make {@link String} from {@link YangInstanceIdentifier}.
164      *
165      * @param instanceIdentifier    Instance identifier
166      * @param schemaContext         Schema context
167      * @return                      Yang instance identifier serialized to String
168      */
169     public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
170             final SchemaContext schemaContext) {
171         return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
172     }
173
174     /**
175      * Make a moduleName/Revision pair from identifier.
176      *
177      * @param identifier
178      *             path parameter
179      * @return {@link QName}
180      */
181     public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
182         // check if more than one slash is not used as path separator
183         if (identifier.contains(
184                 String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
185             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
186             throw new RestconfDocumentedException(
187                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
188                     ErrorTag.INVALID_VALUE);
189         }
190
191         final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
192         final String moduleNameAndRevision;
193         if (mountIndex >= 0) {
194             moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
195                     .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
196         } else {
197             moduleNameAndRevision = identifier;
198         }
199
200         final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
201         if (pathArgs.size() != 2) {
202             LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
203             throw new RestconfDocumentedException(
204                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
205                     ErrorTag.INVALID_VALUE);
206         }
207
208         final Revision moduleRevision;
209         try {
210             moduleRevision = Revision.of(pathArgs.get(1));
211         } catch (final DateTimeParseException e) {
212             LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
213             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
214                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
215         }
216
217         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
218     }
219
220     /**
221      * Parsing {@link Module} module by {@link String} module name and
222      * {@link Date} revision and from the parsed module create
223      * {@link SchemaExportContext}.
224      *
225      * @param schemaContext
226      *             {@link EffectiveModelContext}
227      * @param identifier
228      *             path parameter
229      * @param domMountPointService
230      *             {@link DOMMountPointService}
231      * @return {@link SchemaExportContext}
232      */
233     public static SchemaExportContext toSchemaExportContextFromIdentifier(final EffectiveModelContext schemaContext,
234             final String identifier, final DOMMountPointService domMountPointService,
235             final DOMYangTextSourceProvider sourceProvider) {
236         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
237         final Iterator<String> componentIter = pathComponents.iterator();
238         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
239             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
240             final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
241             final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
242             return new SchemaExportContext(schemaContext, module, sourceProvider);
243         } else {
244             final StringBuilder pathBuilder = new StringBuilder();
245             while (componentIter.hasNext()) {
246                 final String current = componentIter.next();
247
248                 if (RestconfConstants.MOUNT.equals(current)) {
249                     pathBuilder.append("/");
250                     pathBuilder.append(RestconfConstants.MOUNT);
251                     break;
252                 }
253
254                 if (pathBuilder.length() != 0) {
255                     pathBuilder.append("/");
256                 }
257
258                 pathBuilder.append(current);
259             }
260             final InstanceIdentifierContext<?> point = ParserIdentifier
261                     .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
262             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
263             final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
264             final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
265                     .orElse(null);
266             return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);
267         }
268     }
269 }