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