20c2b3ec310064e4e22504e603295dde7e3dacc0
[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(nextIdentifierFromNextSequence(
146                     ParserBuilderConstants.Deserializer.IDENTIFIER_PREDICATE, variables));
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 = nextIdentifierFromNextSequence(
245                 ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
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 = nextIdentifierFromNextSequence(ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
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 String nextIdentifierFromNextSequence(final CharMatcher matcher, final MainVarsWrapper variables) {
280         final int start = variables.getOffset();
281         nextSequenceEnd(matcher, variables);
282         return variables.getData().substring(start, variables.getOffset());
283     }
284
285     private static void nextSequenceEnd(final CharMatcher matcher, final MainVarsWrapper variables) {
286         while (!variables.allCharsConsumed() && matcher.matches(variables.currentChar())) {
287             variables.skipCurrentChar();
288         }
289     }
290
291     private static void prepareNodeWithValue(final QName qname, final List<PathArgument> path,
292             final MainVarsWrapper variables) {
293         variables.skipCurrentChar();
294         final String value = nextIdentifierFromNextSequence(
295                 ParserBuilderConstants.Deserializer.IDENTIFIER_PREDICATE, variables);
296
297         // exception if value attribute is missing
298         RestconfValidationUtils.checkDocumentedError(
299                 !value.isEmpty(),
300                 RestconfError.ErrorType.PROTOCOL,
301                 RestconfError.ErrorTag.MISSING_ATTRIBUTE,
302                 "Value missing for: " + qname
303         );
304         final DataSchemaNode dataSchemaNode = variables.getCurrent().getDataSchemaNode();
305         final Object valueByType = prepareValueByType(dataSchemaNode, findAndParsePercentEncoded(value), variables);
306         path.add(new YangInstanceIdentifier.NodeWithValue<>(qname, valueByType));
307     }
308
309     private static void prepareIdentifier(final QName qname, final List<PathArgument> path,
310             final MainVarsWrapper variables) {
311         final DataSchemaContextNode<?> currentNode = nextContextNode(qname, path, variables);
312         if (currentNode == null) {
313             return;
314         }
315         variables.checkValid(!currentNode.isKeyedEntry(),
316             "Entry " + qname + " requires key or value predicate to be present");
317     }
318
319     @SuppressFBWarnings("NP_NULL_ON_SOME_PATH") // code does check for null 'current' but FB doesn't recognize it
320     private static DataSchemaContextNode<?> nextContextNode(final QName qname, final List<PathArgument> path,
321             final MainVarsWrapper variables) {
322         final DataSchemaContextNode<?> initialContext = variables.getCurrent();
323         final DataSchemaNode initialDataSchema = initialContext.getDataSchemaNode();
324
325         DataSchemaContextNode<?> current = initialContext.getChild(qname);
326         variables.setCurrent(current);
327
328         if (current == null) {
329             final Optional<Module> module = variables.getSchemaContext().findModule(qname.getModule());
330             if (module.isPresent()) {
331                 for (final RpcDefinition rpcDefinition : module.get().getRpcs()) {
332                     if (rpcDefinition.getQName().getLocalName().equals(qname.getLocalName())) {
333                         return null;
334                     }
335                 }
336             }
337             if (findActionDefinition(initialDataSchema, qname.getLocalName()).isPresent()) {
338                 return null;
339             }
340         }
341         variables.checkValid(current != null, qname + " is not correct schema node identifier.");
342         while (current.isMixin()) {
343             path.add(current.getIdentifier());
344             current = current.getChild(qname);
345             variables.setCurrent(current);
346         }
347         return current;
348     }
349
350     private static String findAndParsePercentEncoded(final String preparedPrefix) {
351         if (!preparedPrefix.contains(String.valueOf(ParserBuilderConstants.Deserializer.PERCENT_ENCODING))) {
352             return preparedPrefix;
353         }
354
355         final StringBuilder parsedPrefix = new StringBuilder(preparedPrefix);
356         final CharMatcher matcher = CharMatcher.is(ParserBuilderConstants.Deserializer.PERCENT_ENCODING);
357
358         while (matcher.matchesAnyOf(parsedPrefix)) {
359             final int percentCharPosition = matcher.indexIn(parsedPrefix);
360             parsedPrefix.replace(
361                     percentCharPosition,
362                     percentCharPosition + ParserBuilderConstants.Deserializer.LAST_ENCODED_CHAR,
363                     String.valueOf((char) Integer.parseInt(parsedPrefix.substring(
364                             percentCharPosition + ParserBuilderConstants.Deserializer.FIRST_ENCODED_CHAR,
365                             percentCharPosition + ParserBuilderConstants.Deserializer.LAST_ENCODED_CHAR),
366                             ParserBuilderConstants.Deserializer.PERCENT_ENCODED_RADIX)));
367         }
368
369         return parsedPrefix.toString();
370     }
371
372     private static QName getQNameOfDataSchemaNode(final String nodeName, final MainVarsWrapper variables) {
373         final DataSchemaNode dataSchemaNode = variables.getCurrent().getDataSchemaNode();
374         if (dataSchemaNode instanceof ContainerSchemaNode) {
375             return getQNameOfDataSchemaNode((ContainerSchemaNode) dataSchemaNode, nodeName);
376         } else if (dataSchemaNode instanceof ListSchemaNode) {
377             return getQNameOfDataSchemaNode((ListSchemaNode) dataSchemaNode, nodeName);
378         }
379
380         throw new UnsupportedOperationException("Unsupported schema node " + dataSchemaNode);
381     }
382
383     private static <T extends DataNodeContainer & SchemaNode & ActionNodeContainer> QName getQNameOfDataSchemaNode(
384             final T parent, String nodeName) {
385         final Optional<ActionDefinition> actionDef = findActionDefinition(parent, nodeName);
386         final SchemaNode node;
387         if (actionDef.isPresent()) {
388             node = actionDef.get();
389         } else {
390             node = RestconfSchemaUtil.findSchemaNodeInCollection(parent.getChildNodes(), nodeName);
391         }
392         return node.getQName();
393     }
394
395     private static Module moduleForPrefix(final String prefix, final SchemaContext schemaContext) {
396         return schemaContext.findModules(prefix).stream().findFirst().orElse(null);
397     }
398
399     private static void validArg(final MainVarsWrapper variables) {
400         // every identifier except of the first MUST start with slash
401         if (variables.getOffset() != MainVarsWrapper.STARTING_OFFSET) {
402             variables.checkValid(RestconfConstants.SLASH == variables.currentChar(), "Identifier must start with '/'.");
403
404             // skip consecutive slashes, users often assume restconf URLs behave just as HTTP does by squashing
405             // multiple slashes into a single one
406             while (!variables.allCharsConsumed() && RestconfConstants.SLASH == variables.currentChar()) {
407                 variables.skipCurrentChar();
408             }
409
410             // check if slash is not also the last char in identifier
411             variables.checkValid(!variables.allCharsConsumed(), "Identifier cannot end with '/'.");
412         }
413     }
414
415     private static Optional<ActionDefinition> findActionDefinition(final SchemaNode dataSchemaNode,
416             final String nodeName) {
417         requireNonNull(dataSchemaNode, "DataSchema Node must not be null.");
418         if (dataSchemaNode instanceof ActionNodeContainer) {
419             return ((ActionNodeContainer) dataSchemaNode).getActions().stream()
420                     .filter(actionDef -> actionDef.getQName().getLocalName().equals(nodeName)).findFirst();
421         }
422         return Optional.empty();
423     }
424
425     private static final class MainVarsWrapper {
426         private static final int STARTING_OFFSET = 0;
427
428         private final SchemaContext schemaContext;
429         private final String data;
430
431         private DataSchemaContextNode<?> current;
432         private int offset;
433
434         MainVarsWrapper(final String data, final DataSchemaContextNode<?> current, final int offset,
435                 final SchemaContext schemaContext) {
436             this.data = data;
437             this.current = current;
438             this.offset = offset;
439             this.schemaContext = schemaContext;
440         }
441
442         boolean allCharsConsumed() {
443             return offset == data.length();
444         }
445
446         void checkValid(final boolean condition, final String errorMsg) {
447             checkArgument(condition, "Could not parse Instance Identifier '%s'. Offset: %s : Reason: %s", data, offset,
448                 errorMsg);
449         }
450
451         char currentChar() {
452             return data.charAt(offset);
453         }
454
455         void skipCurrentChar() {
456             offset++;
457         }
458
459         public String getData() {
460             return data;
461         }
462
463         public DataSchemaContextNode<?> getCurrent() {
464             return current;
465         }
466
467         public void setCurrent(final DataSchemaContextNode<?> current) {
468             this.current = current;
469         }
470
471         public int getOffset() {
472             return offset;
473         }
474
475         public SchemaContext getSchemaContext() {
476             return schemaContext;
477         }
478     }
479 }