Teach RFC8040 URL parser about actions
[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 com.google.common.base.Splitter;
11 import com.google.common.collect.Iterables;
12 import java.time.format.DateTimeParseException;
13 import java.util.AbstractMap.SimpleImmutableEntry;
14 import java.util.Date;
15 import java.util.Iterator;
16 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.Optional;
19 import java.util.stream.Collectors;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.opendaylight.mdsal.dom.api.DOMMountPoint;
22 import org.opendaylight.mdsal.dom.api.DOMMountPointService;
23 import org.opendaylight.mdsal.dom.api.DOMYangTextSourceProvider;
24 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
25 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
26 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
27 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
28 import org.opendaylight.restconf.common.schema.SchemaExportContext;
29 import org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants;
30 import org.opendaylight.restconf.nb.rfc8040.utils.validations.RestconfValidation;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.Revision;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
34 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
37 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
38 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * Util class for parsing identifier.
49  */
50 public final class ParserIdentifier {
51
52     private static final Logger LOG = LoggerFactory.getLogger(ParserIdentifier.class);
53     private static final Splitter MP_SPLITTER = Splitter.on("/" + RestconfConstants.MOUNT);
54
55     private ParserIdentifier() {
56         throw new UnsupportedOperationException("Util class.");
57     }
58
59     /**
60      * Make {@link InstanceIdentifierContext} from {@link String} identifier
61      * <br>
62      * For identifiers of data NOT behind mount points returned
63      * {@link InstanceIdentifierContext} is prepared with {@code null} reference of {@link DOMMountPoint} and with
64      * controller's {@link SchemaContext}.
65      * <br>
66      * For identifiers of data behind mount points returned
67      * {@link InstanceIdentifierContext} is prepared with reference of {@link DOMMountPoint} and its
68      * own {@link SchemaContext}.
69      *
70      * @param identifier
71      *           - path identifier
72      * @param schemaContext
73      *           - controller schema context
74      * @param mountPointService
75      *           - mount point service
76      * @return {@link InstanceIdentifierContext}
77      */
78     public static InstanceIdentifierContext<?> toInstanceIdentifier(
79             final String identifier,
80             final SchemaContext schemaContext,
81             final Optional<DOMMountPointService> mountPointService) {
82         if (identifier == null || !identifier.contains(RestconfConstants.MOUNT)) {
83             return createIIdContext(IdentifierCodec.deserialize(identifier, schemaContext), schemaContext, null);
84         }
85         if (!mountPointService.isPresent()) {
86             throw new RestconfDocumentedException("Mount point service is not available");
87         }
88
89         final Iterator<String> pathsIt = MP_SPLITTER.split(identifier).iterator();
90         final String mountPointId = pathsIt.next();
91         final YangInstanceIdentifier mountPath = IdentifierCodec.deserialize(mountPointId, schemaContext);
92         final DOMMountPoint mountPoint = mountPointService.get().getMountPoint(mountPath)
93                 .orElseThrow(() -> new RestconfDocumentedException("Mount point does not exist.",
94                     ErrorType.PROTOCOL, ErrorTag.DATA_MISSING));
95
96         final SchemaContext mountSchemaContext = mountPoint.getSchemaContext();
97         final String pathId = pathsIt.next().replaceFirst("/", "");
98         return createIIdContext(IdentifierCodec.deserialize(pathId, mountSchemaContext), mountSchemaContext,
99             mountPoint);
100     }
101
102     /**
103      * Method to create {@link InstanceIdentifierContext} from {@link YangInstanceIdentifier}
104      * and {@link SchemaContext}, {@link DOMMountPoint}.
105      *
106      * @param yangIId
107      *               - instance identifier
108      * @param schemaContext
109      *               - schema context
110      * @param domMountPoint
111      *               - optional mount point context
112      * @return {@link InstanceIdentifierContext}
113      */
114     private static InstanceIdentifierContext<?> createIIdContext(final YangInstanceIdentifier yangIId,
115             final SchemaContext schemaContext, final @Nullable DOMMountPoint domMountPoint) {
116
117         // Deal with data nodes first
118         final DataSchemaContextTree contextTree = DataSchemaContextTree.from(schemaContext);
119         final Optional<DataSchemaContextNode<?>> child = contextTree.findChild(yangIId);
120         if (child.isPresent()) {
121             return new InstanceIdentifierContext<SchemaNode>(yangIId, child.get().getDataSchemaNode(), domMountPoint,
122                 schemaContext);
123         }
124
125         // That failed, now try to recover by searching through the schema context
126         final List<QName> qnames = yangIId.getPathArguments().stream()
127             .filter(pathArgument -> pathArgument instanceof NodeIdentifier).map(PathArgument::getNodeType)
128             .collect(Collectors.toList());
129         final SchemaNode schemaNode = SchemaContextUtil.findNodeInSchemaContext(schemaContext, qnames);
130         if (schemaNode instanceof RpcDefinition) {
131             return new InstanceIdentifierContext<>(yangIId, (RpcDefinition) schemaNode, domMountPoint, schemaContext);
132         } else if (schemaNode instanceof ActionDefinition) {
133             return new InstanceIdentifierContext<>(yangIId, (ActionDefinition) schemaNode, domMountPoint,
134                     schemaContext);
135         } else if (schemaNode == null) {
136             throw new IllegalArgumentException("Failed to find schema for " + qnames);
137         } else {
138             throw new IllegalStateException("Unhandled schema " + schemaNode);
139         }
140     }
141
142     /**
143      * Make {@link String} from {@link YangInstanceIdentifier}.
144      *
145      * @param instanceIdentifier    Instance identifier
146      * @param schemaContext         Schema context
147      * @return                      Yang instance identifier serialized to String
148      */
149     public static String stringFromYangInstanceIdentifier(final YangInstanceIdentifier instanceIdentifier,
150             final SchemaContext schemaContext) {
151         return IdentifierCodec.serialize(instanceIdentifier, schemaContext);
152     }
153
154     /**
155      * Make a moduleName/Revision pair from identifier.
156      *
157      * @param identifier
158      *             path parameter
159      * @return {@link QName}
160      */
161     public static Entry<String, Revision> makeQNameFromIdentifier(final String identifier) {
162         // check if more than one slash is not used as path separator
163         if (identifier.contains(
164                 String.valueOf(RestconfConstants.SLASH).concat(String.valueOf(RestconfConstants.SLASH)))) {
165             LOG.debug("URI has bad format. It should be \'moduleName/yyyy-MM-dd\' {}", identifier);
166             throw new RestconfDocumentedException(
167                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
168                     ErrorTag.INVALID_VALUE);
169         }
170
171         final int mountIndex = identifier.indexOf(RestconfConstants.MOUNT);
172         final String moduleNameAndRevision;
173         if (mountIndex >= 0) {
174             moduleNameAndRevision = identifier.substring(mountIndex + RestconfConstants.MOUNT.length())
175                     .replaceFirst(String.valueOf(RestconfConstants.SLASH), "");
176         } else {
177             moduleNameAndRevision = identifier;
178         }
179
180         final List<String> pathArgs = RestconfConstants.SLASH_SPLITTER.splitToList(moduleNameAndRevision);
181         if (pathArgs.size() != 2) {
182             LOG.debug("URI has bad format '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
183             throw new RestconfDocumentedException(
184                     "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
185                     ErrorTag.INVALID_VALUE);
186         }
187
188         final Revision moduleRevision;
189         try {
190             moduleRevision = Revision.of(pathArgs.get(1));
191         } catch (final DateTimeParseException e) {
192             LOG.debug("URI has bad format: '{}'. It should be 'moduleName/yyyy-MM-dd'", identifier);
193             throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
194                     ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, e);
195         }
196
197         return new SimpleImmutableEntry<>(pathArgs.get(0), moduleRevision);
198     }
199
200     /**
201      * Parsing {@link Module} module by {@link String} module name and
202      * {@link Date} revision and from the parsed module create
203      * {@link SchemaExportContext}.
204      *
205      * @param schemaContext
206      *             {@link SchemaContext}
207      * @param identifier
208      *             path parameter
209      * @param domMountPointService
210      *             {@link DOMMountPointService}
211      * @return {@link SchemaExportContext}
212      */
213     public static SchemaExportContext toSchemaExportContextFromIdentifier(final SchemaContext schemaContext,
214             final String identifier, final DOMMountPointService domMountPointService,
215             final DOMYangTextSourceProvider sourceProvider) {
216         final Iterable<String> pathComponents = RestconfConstants.SLASH_SPLITTER.split(identifier);
217         final Iterator<String> componentIter = pathComponents.iterator();
218         if (!Iterables.contains(pathComponents, RestconfConstants.MOUNT)) {
219             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
220             final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
221             final Module module = schemaContext.findModule(moduleName, revision).orElse(null);
222             return new SchemaExportContext(schemaContext, module, sourceProvider);
223         } else {
224             final StringBuilder pathBuilder = new StringBuilder();
225             while (componentIter.hasNext()) {
226                 final String current = componentIter.next();
227
228                 if (RestconfConstants.MOUNT.equals(current)) {
229                     pathBuilder.append("/");
230                     pathBuilder.append(RestconfConstants.MOUNT);
231                     break;
232                 }
233
234                 if (pathBuilder.length() != 0) {
235                     pathBuilder.append("/");
236                 }
237
238                 pathBuilder.append(current);
239             }
240             final InstanceIdentifierContext<?> point = ParserIdentifier
241                     .toInstanceIdentifier(pathBuilder.toString(), schemaContext, Optional.of(domMountPointService));
242             final String moduleName = RestconfValidation.validateAndGetModulName(componentIter);
243             final Revision revision = RestconfValidation.validateAndGetRevision(componentIter);
244             final Module module = point.getMountPoint().getSchemaContext().findModule(moduleName, revision)
245                     .orElse(null);
246             return new SchemaExportContext(point.getMountPoint().getSchemaContext(), module, sourceProvider);
247         }
248     }
249 }