Add checkValidIdentifierStart()
[netconf.git] / restconf / restconf-nb-rfc8040 / src / main / java / org / opendaylight / restconf / nb / rfc8040 / utils / parser / YangInstanceIdentifierDeserializer.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.checkArgument;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.restconf.nb.rfc8040.utils.RestconfConstants.SLASH;
13 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.COLON;
14 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.COMMA;
15 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.EMPTY_STRING;
16 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.EQUAL;
17 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.FIRST_ENCODED_CHAR;
18 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.IDENTIFIER;
19 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.IDENTIFIER_FIRST_CHAR;
20 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.IDENTIFIER_PREDICATE;
21 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.LAST_ENCODED_CHAR;
22 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.PERCENT_ENCODED_RADIX;
23 import static org.opendaylight.restconf.nb.rfc8040.utils.parser.builder.ParserBuilderConstants.Deserializer.PERCENT_ENCODING;
24
25 import com.google.common.base.CharMatcher;
26 import com.google.common.collect.ImmutableList;
27 import com.google.common.collect.ImmutableMap;
28 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
29 import java.util.ArrayList;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Optional;
33 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
34 import org.opendaylight.restconf.common.errors.RestconfError;
35 import org.opendaylight.restconf.common.util.RestUtil;
36 import org.opendaylight.restconf.common.util.RestconfSchemaUtil;
37 import org.opendaylight.restconf.common.validation.RestconfValidationUtils;
38 import org.opendaylight.restconf.nb.rfc8040.codecs.RestCodec;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
41 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
43 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
44 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
45 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
46 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
62
63 /**
64  * Deserializer for {@link String} to {@link YangInstanceIdentifier} for
65  * restconf.
66  *
67  */
68 public final class YangInstanceIdentifierDeserializer {
69     private final SchemaContext schemaContext;
70     private final String data;
71
72     private DataSchemaContextNode<?> current;
73     private int offset;
74
75     private YangInstanceIdentifierDeserializer(final SchemaContext schemaContext, final String data) {
76         this.schemaContext = requireNonNull(schemaContext);
77         this.data = requireNonNull(data);
78         current = DataSchemaContextTree.from(schemaContext).getRoot();
79     }
80
81     /**
82      * Method to create {@link Iterable} from {@link PathArgument} which are parsing from data by {@link SchemaContext}.
83      *
84      * @param schemaContext for validate of parsing path arguments
85      * @param data path to data, in URL string form
86      * @return {@link Iterable} of {@link PathArgument}
87      */
88     public static Iterable<PathArgument> create(final SchemaContext schemaContext, final String data) {
89         return new YangInstanceIdentifierDeserializer(schemaContext, data).parse();
90     }
91
92     private List<PathArgument> parse() {
93         final List<PathArgument> path = new ArrayList<>();
94
95         while (!allCharsConsumed()) {
96             validArg();
97             final QName qname = prepareQName();
98
99             // this is the last identifier (input is consumed) or end of identifier (slash)
100             if (allCharsConsumed() || currentChar() == SLASH) {
101                 prepareIdentifier(qname, path);
102                 path.add(current == null ? NodeIdentifier.create(qname) : current.getIdentifier());
103             } else if (currentChar() == EQUAL) {
104                 if (nextContextNode(qname, path).getDataSchemaNode() instanceof ListSchemaNode) {
105                     prepareNodeWithPredicates(qname, path, (ListSchemaNode) current.getDataSchemaNode());
106                 } else {
107                     prepareNodeWithValue(qname, path);
108                 }
109             } else {
110                 throw new IllegalArgumentException("Bad char " + currentChar() + " on position " + offset + ".");
111             }
112         }
113
114         return ImmutableList.copyOf(path);
115     }
116
117     private void prepareNodeWithPredicates(final QName qname, final List<PathArgument> path,
118             final ListSchemaNode listSchemaNode) {
119         checkValid(listSchemaNode != null, "Data schema node is null");
120
121         final Iterator<QName> keys = listSchemaNode.getKeyDefinition().iterator();
122         final ImmutableMap.Builder<QName, Object> values = ImmutableMap.builder();
123
124         // skip already expected equal sign
125         skipCurrentChar();
126
127         // read key value separated by comma
128         while (keys.hasNext() && !allCharsConsumed() && currentChar() != SLASH) {
129
130             // empty key value
131             if (currentChar() == COMMA) {
132                 values.put(keys.next(), EMPTY_STRING);
133                 skipCurrentChar();
134                 continue;
135             }
136
137             // check if next value is parsable
138             RestconfValidationUtils.checkDocumentedError(IDENTIFIER_PREDICATE.matches(currentChar()),
139                     RestconfError.ErrorType.PROTOCOL,RestconfError.ErrorTag.MALFORMED_MESSAGE, "");
140
141             // parse value
142             final QName key = keys.next();
143             Optional<DataSchemaNode> leafSchemaNode = listSchemaNode.findDataChildByName(key);
144             if (!leafSchemaNode.isPresent()) {
145                 throw new RestconfDocumentedException("Schema not found for " + key,
146                         RestconfError.ErrorType.PROTOCOL, RestconfError.ErrorTag.BAD_ELEMENT);
147             }
148
149             final String value = findAndParsePercentEncoded(nextIdentifierFromNextSequence(IDENTIFIER_PREDICATE));
150             final Object valueByType = prepareValueByType(leafSchemaNode.get(), value);
151             values.put(key, valueByType);
152
153
154             // skip comma
155             if (keys.hasNext() && !allCharsConsumed() && currentChar() == COMMA) {
156                 skipCurrentChar();
157             }
158         }
159
160         // the last key is considered to be empty
161         if (keys.hasNext()) {
162             if (allCharsConsumed() || currentChar() == SLASH) {
163                 values.put(keys.next(), EMPTY_STRING);
164             }
165
166             // there should be no more missing keys
167             RestconfValidationUtils.checkDocumentedError(
168                     !keys.hasNext(),
169                     RestconfError.ErrorType.PROTOCOL,
170                     RestconfError.ErrorTag.MISSING_ATTRIBUTE,
171                     "Key value missing for: " + qname
172             );
173         }
174
175         path.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qname, values.build()));
176     }
177
178     private Object prepareValueByType(final DataSchemaNode schemaNode, final String value) {
179         Object decoded = null;
180
181         TypeDefinition<? extends TypeDefinition<?>> typedef = null;
182         if (schemaNode instanceof LeafListSchemaNode) {
183             typedef = ((LeafListSchemaNode) schemaNode).getType();
184         } else {
185             typedef = ((LeafSchemaNode) schemaNode).getType();
186         }
187         final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
188         if (baseType instanceof LeafrefTypeDefinition) {
189             typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext,
190                     schemaNode);
191         }
192         decoded = RestCodec.from(typedef, null, schemaContext).deserialize(value);
193         if (decoded == null) {
194             if (baseType instanceof IdentityrefTypeDefinition) {
195                 decoded = toQName(value, schemaNode, schemaContext);
196             }
197         }
198         return decoded;
199     }
200
201     private QName prepareQName() {
202         checkValidIdentifierStart();
203         final String preparedPrefix = nextIdentifierFromNextSequence(IDENTIFIER);
204         final String prefix;
205         final String localName;
206
207         if (allCharsConsumed()) {
208             return getQNameOfDataSchemaNode(preparedPrefix);
209         }
210
211         switch (currentChar()) {
212             case SLASH:
213             case EQUAL:
214                 prefix = preparedPrefix;
215                 return getQNameOfDataSchemaNode(prefix);
216             case COLON:
217                 prefix = preparedPrefix;
218                 skipCurrentChar();
219                 checkValidIdentifierStart();
220                 localName = nextIdentifierFromNextSequence(IDENTIFIER);
221
222                 if (!allCharsConsumed() && currentChar() == EQUAL) {
223                     return getQNameOfDataSchemaNode(localName);
224                 } else {
225                     final Module module = moduleForPrefix(prefix);
226                     checkArgument(module != null, "Failed to lookup prefix %s", prefix);
227                     return QName.create(module.getQNameModule(), localName);
228                 }
229             default:
230                 throw new IllegalArgumentException("Failed build path.");
231         }
232     }
233
234     private void prepareNodeWithValue(final QName qname, final List<PathArgument> path) {
235         skipCurrentChar();
236         final String value = nextIdentifierFromNextSequence(IDENTIFIER_PREDICATE);
237
238         // exception if value attribute is missing
239         RestconfValidationUtils.checkDocumentedError(
240                 !value.isEmpty(),
241                 RestconfError.ErrorType.PROTOCOL,
242                 RestconfError.ErrorTag.MISSING_ATTRIBUTE,
243                 "Value missing for: " + qname
244         );
245         final DataSchemaNode dataSchemaNode = current.getDataSchemaNode();
246         final Object valueByType = prepareValueByType(dataSchemaNode, findAndParsePercentEncoded(value));
247         path.add(new YangInstanceIdentifier.NodeWithValue<>(qname, valueByType));
248     }
249
250     private void prepareIdentifier(final QName qname, final List<PathArgument> path) {
251         final DataSchemaContextNode<?> currentNode = nextContextNode(qname, path);
252         if (currentNode == null) {
253             return;
254         }
255         checkValid(!currentNode.isKeyedEntry(), "Entry " + qname + " requires key or value predicate to be present");
256     }
257
258     @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH",
259             justification = "code does check for null 'current' but FB doesn't recognize it")
260     private DataSchemaContextNode<?> nextContextNode(final QName qname, final List<PathArgument> path) {
261         final DataSchemaContextNode<?> initialContext = current;
262         final DataSchemaNode initialDataSchema = initialContext.getDataSchemaNode();
263
264         current = initialContext.getChild(qname);
265
266         if (current == null) {
267             final Optional<Module> module = schemaContext.findModule(qname.getModule());
268             if (module.isPresent()) {
269                 for (final RpcDefinition rpcDefinition : module.get().getRpcs()) {
270                     if (rpcDefinition.getQName().getLocalName().equals(qname.getLocalName())) {
271                         return null;
272                     }
273                 }
274             }
275             if (findActionDefinition(initialDataSchema, qname.getLocalName()).isPresent()) {
276                 return null;
277             }
278         }
279         checkValid(current != null, qname + " is not correct schema node identifier.");
280         while (current.isMixin()) {
281             path.add(current.getIdentifier());
282             current = current.getChild(qname);
283         }
284         return current;
285     }
286
287     private Module moduleForPrefix(final String prefix) {
288         return schemaContext.findModules(prefix).stream().findFirst().orElse(null);
289     }
290
291     private boolean allCharsConsumed() {
292         return offset == data.length();
293     }
294
295     private void checkValid(final boolean condition, final String errorMsg) {
296         checkArgument(condition, "Could not parse Instance Identifier '%s'. Offset: %s : Reason: %s", data, offset,
297             errorMsg);
298     }
299
300     private void checkValidIdentifierStart() {
301         checkValid(IDENTIFIER_FIRST_CHAR.matches(currentChar()),
302             "Identifier must start with character from set 'a-zA-Z_'");
303     }
304
305     private char currentChar() {
306         return data.charAt(offset);
307     }
308
309     private void skipCurrentChar() {
310         offset++;
311     }
312
313     private String nextIdentifierFromNextSequence(final CharMatcher matcher) {
314         final int start = offset;
315         while (!allCharsConsumed() && matcher.matches(currentChar())) {
316             skipCurrentChar();
317         }
318         return data.substring(start, offset);
319     }
320
321     private void validArg() {
322         // every identifier except of the first MUST start with slash
323         if (offset != 0) {
324             checkValid(SLASH == currentChar(), "Identifier must start with '/'.");
325
326             // skip consecutive slashes, users often assume restconf URLs behave just as HTTP does by squashing
327             // multiple slashes into a single one
328             while (!allCharsConsumed() && SLASH == currentChar()) {
329                 skipCurrentChar();
330             }
331
332             // check if slash is not also the last char in identifier
333             checkValid(!allCharsConsumed(), "Identifier cannot end with '/'.");
334         }
335     }
336
337     private QName getQNameOfDataSchemaNode(final String nodeName) {
338         final DataSchemaNode dataSchemaNode = current.getDataSchemaNode();
339         if (dataSchemaNode instanceof ContainerSchemaNode) {
340             return getQNameOfDataSchemaNode((ContainerSchemaNode) dataSchemaNode, nodeName);
341         } else if (dataSchemaNode instanceof ListSchemaNode) {
342             return getQNameOfDataSchemaNode((ListSchemaNode) dataSchemaNode, nodeName);
343         }
344
345         throw new UnsupportedOperationException("Unsupported schema node " + dataSchemaNode);
346     }
347
348     private static <T extends DataNodeContainer & SchemaNode & ActionNodeContainer> QName getQNameOfDataSchemaNode(
349             final T parent, String nodeName) {
350         final Optional<ActionDefinition> actionDef = findActionDefinition(parent, nodeName);
351         final SchemaNode node;
352         if (actionDef.isPresent()) {
353             node = actionDef.get();
354         } else {
355             node = RestconfSchemaUtil.findSchemaNodeInCollection(parent.getChildNodes(), nodeName);
356         }
357         return node.getQName();
358     }
359
360     private static Optional<ActionDefinition> findActionDefinition(final SchemaNode dataSchemaNode,
361             final String nodeName) {
362         requireNonNull(dataSchemaNode, "DataSchema Node must not be null.");
363         if (dataSchemaNode instanceof ActionNodeContainer) {
364             return ((ActionNodeContainer) dataSchemaNode).getActions().stream()
365                     .filter(actionDef -> actionDef.getQName().getLocalName().equals(nodeName)).findFirst();
366         }
367         return Optional.empty();
368     }
369
370     private static String findAndParsePercentEncoded(final String preparedPrefix) {
371         if (preparedPrefix.indexOf(PERCENT_ENCODING) == -1) {
372             return preparedPrefix;
373         }
374
375         final StringBuilder parsedPrefix = new StringBuilder(preparedPrefix);
376         final CharMatcher matcher = CharMatcher.is(PERCENT_ENCODING);
377
378         while (matcher.matchesAnyOf(parsedPrefix)) {
379             final int percentCharPosition = matcher.indexIn(parsedPrefix);
380             parsedPrefix.replace(percentCharPosition, percentCharPosition + LAST_ENCODED_CHAR,
381                     String.valueOf((char) Integer.parseInt(parsedPrefix.substring(
382                             percentCharPosition + FIRST_ENCODED_CHAR, percentCharPosition + LAST_ENCODED_CHAR),
383                             PERCENT_ENCODED_RADIX)));
384         }
385
386         return parsedPrefix.toString();
387     }
388
389     private static Object toQName(final String value, final DataSchemaNode schemaNode,
390             final SchemaContext schemaContext) {
391         final String moduleName = toModuleName(value);
392         final String nodeName = toNodeName(value);
393         final Module module = schemaContext.findModules(moduleName).iterator().next();
394         for (final IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
395             final QName qName = identitySchemaNode.getQName();
396             if (qName.getLocalName().equals(nodeName)) {
397                 return qName;
398             }
399         }
400         return QName.create(schemaNode.getQName().getNamespace(), schemaNode.getQName().getRevision(), nodeName);
401     }
402
403     private static String toNodeName(final String str) {
404         final int idx = str.indexOf(':');
405         if (idx == -1) {
406             return str;
407         }
408
409         if (str.indexOf(':', idx + 1) != -1) {
410             return str;
411         }
412
413         return str.substring(idx + 1);
414     }
415
416     private static String toModuleName(final String str) {
417         final int idx = str.indexOf(':');
418         if (idx == -1) {
419             return null;
420         }
421
422         if (str.indexOf(':', idx + 1) != -1) {
423             return null;
424         }
425
426         return str.substring(0, idx);
427     }
428 }