2 * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.restconf.nb.rfc8040.utils.parser;
10 import static java.util.Objects.requireNonNull;
12 import com.google.common.base.CharMatcher;
13 import com.google.common.collect.ImmutableList;
14 import com.google.common.collect.ImmutableMap;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.util.ArrayList;
17 import java.util.Iterator;
18 import java.util.List;
19 import java.util.Optional;
20 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
21 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
22 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
23 import org.opendaylight.restconf.common.util.RestUtil;
24 import org.opendaylight.restconf.common.util.RestconfSchemaUtil;
25 import org.opendaylight.restconf.nb.rfc8040.codecs.RestCodec;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
31 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
32 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
33 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
34 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
35 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
38 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.Module;
43 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
44 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
45 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
52 * Deserializer for {@link String} to {@link YangInstanceIdentifier} for restconf.
54 public final class YangInstanceIdentifierDeserializer {
55 private static final CharMatcher IDENTIFIER_PREDICATE =
56 CharMatcher.noneOf(ParserConstants.RFC3986_RESERVED_CHARACTERS).precomputed();
57 private static final String PARSING_FAILED_MESSAGE = "Could not parse Instance Identifier '%s'. "
58 + "Offset: '%d' : Reason: ";
59 private static final CharMatcher PERCENT_ENCODING = CharMatcher.is('%');
60 // position of the first encoded char after percent sign in percent encoded string
61 private static final int FIRST_ENCODED_CHAR = 1;
62 // position of the last encoded char after percent sign in percent encoded string
63 private static final int LAST_ENCODED_CHAR = 3;
64 // percent encoded radix for parsing integers
65 private static final int PERCENT_ENCODED_RADIX = 16;
67 private final EffectiveModelContext schemaContext;
68 private final String data;
70 private DataSchemaContextNode<?> current;
73 private YangInstanceIdentifierDeserializer(final EffectiveModelContext schemaContext, final String data) {
74 this.schemaContext = requireNonNull(schemaContext);
75 this.data = requireNonNull(data);
76 current = DataSchemaContextTree.from(schemaContext).getRoot();
80 * Method to create {@link Iterable} from {@link PathArgument} which are parsing from data by {@link SchemaContext}.
82 * @param schemaContext for validate of parsing path arguments
83 * @param data path to data, in URL string form
84 * @return {@link Iterable} of {@link PathArgument}
86 public static Iterable<PathArgument> create(final EffectiveModelContext schemaContext, final String data) {
87 return new YangInstanceIdentifierDeserializer(schemaContext, data).parse();
90 private List<PathArgument> parse() {
91 final List<PathArgument> path = new ArrayList<>();
93 while (!allCharsConsumed()) {
95 final QName qname = prepareQName();
97 // this is the last identifier (input is consumed) or end of identifier (slash)
98 if (allCharsConsumed() || currentChar() == '/') {
99 prepareIdentifier(qname, path);
100 path.add(current == null ? NodeIdentifier.create(qname) : current.getIdentifier());
101 } else if (currentChar() == '=') {
102 if (nextContextNode(qname, path).getDataSchemaNode() instanceof ListSchemaNode) {
103 prepareNodeWithPredicates(qname, path, (ListSchemaNode) current.getDataSchemaNode());
105 prepareNodeWithValue(qname, path);
108 throw getParsingCharFailedException();
112 return ImmutableList.copyOf(path);
115 private void prepareNodeWithPredicates(final QName qname, final List<PathArgument> path,
116 final ListSchemaNode listSchemaNode) {
117 checkValid(listSchemaNode != null, ErrorTag.MALFORMED_MESSAGE, "Data schema node is null");
119 final Iterator<QName> keys = listSchemaNode.getKeyDefinition().iterator();
120 final ImmutableMap.Builder<QName, Object> values = ImmutableMap.builder();
122 // skip already expected equal sign
125 // read key value separated by comma
126 while (keys.hasNext() && !allCharsConsumed() && currentChar() != '/') {
129 if (currentChar() == ',') {
130 values.put(keys.next(), "");
135 // check if next value is parsable
136 checkValid(IDENTIFIER_PREDICATE.matches(currentChar()), ErrorTag.MALFORMED_MESSAGE,
137 "Value that starts with character %c is not parsable.", currentChar());
140 final QName key = keys.next();
141 Optional<DataSchemaNode> leafSchemaNode = listSchemaNode.findDataChildByName(key);
142 RestconfDocumentedException.throwIf(!leafSchemaNode.isPresent(), ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT,
143 "Schema not found for %s", key);
145 final String value = findAndParsePercentEncoded(nextIdentifierFromNextSequence(IDENTIFIER_PREDICATE));
146 final Object valueByType = prepareValueByType(leafSchemaNode.get(), value);
147 values.put(key, valueByType);
150 if (keys.hasNext() && !allCharsConsumed() && currentChar() == ',') {
155 // the last key is considered to be empty
156 if (keys.hasNext()) {
157 // at this point, it must be true that current char is '/' or all chars have already been consumed
158 values.put(keys.next(), "");
160 // there should be no more missing keys
161 RestconfDocumentedException.throwIf(keys.hasNext(), ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE,
162 "Cannot parse input identifier '%s'. Key value is missing for QName: %s", data, qname);
165 path.add(YangInstanceIdentifier.NodeIdentifierWithPredicates.of(qname, values.build()));
168 private Object prepareValueByType(final DataSchemaNode schemaNode, final String value) {
171 TypeDefinition<? extends TypeDefinition<?>> typedef;
172 if (schemaNode instanceof LeafListSchemaNode) {
173 typedef = ((LeafListSchemaNode) schemaNode).getType();
175 typedef = ((LeafSchemaNode) schemaNode).getType();
177 final TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(typedef);
178 if (baseType instanceof LeafrefTypeDefinition) {
179 typedef = SchemaContextUtil.getBaseTypeForLeafRef((LeafrefTypeDefinition) baseType, schemaContext,
182 decoded = RestCodec.from(typedef, null, schemaContext).deserialize(value);
183 if (decoded == null) {
184 if (baseType instanceof IdentityrefTypeDefinition) {
185 decoded = toQName(value, schemaNode, schemaContext);
191 private QName prepareQName() {
192 checkValidIdentifierStart();
193 final String preparedPrefix = nextIdentifierFromNextSequence(ParserConstants.YANG_IDENTIFIER_PART);
195 final String localName;
197 if (allCharsConsumed()) {
198 return getQNameOfDataSchemaNode(preparedPrefix);
201 switch (currentChar()) {
204 prefix = preparedPrefix;
205 return getQNameOfDataSchemaNode(prefix);
207 prefix = preparedPrefix;
209 checkValidIdentifierStart();
210 localName = nextIdentifierFromNextSequence(ParserConstants.YANG_IDENTIFIER_PART);
212 if (!allCharsConsumed() && currentChar() == '=') {
213 return getQNameOfDataSchemaNode(localName);
215 final Module module = moduleForPrefix(prefix);
216 RestconfDocumentedException.throwIf(module == null, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT,
217 "Failed to lookup for module with name '%s'.", prefix);
218 return QName.create(module.getQNameModule(), localName);
221 throw getParsingCharFailedException();
225 private void prepareNodeWithValue(final QName qname, final List<PathArgument> path) {
227 final String value = nextIdentifierFromNextSequence(IDENTIFIER_PREDICATE);
229 // exception if value attribute is missing
230 RestconfDocumentedException.throwIf(value.isEmpty(), ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE,
231 "Cannot parse input identifier '%s' - value is missing for QName: %s.", data, qname);
232 final DataSchemaNode dataSchemaNode = current.getDataSchemaNode();
233 final Object valueByType = prepareValueByType(dataSchemaNode, findAndParsePercentEncoded(value));
234 path.add(new YangInstanceIdentifier.NodeWithValue<>(qname, valueByType));
237 private void prepareIdentifier(final QName qname, final List<PathArgument> path) {
238 final DataSchemaContextNode<?> currentNode = nextContextNode(qname, path);
239 if (currentNode != null) {
240 checkValid(!currentNode.isKeyedEntry(), ErrorTag.MISSING_ATTRIBUTE,
241 "Entry '%s' requires key or value predicate to be present.", qname);
245 @SuppressFBWarnings(value = "NP_NULL_ON_SOME_PATH",
246 justification = "code does check for null 'current' but FB doesn't recognize it")
247 private DataSchemaContextNode<?> nextContextNode(final QName qname, final List<PathArgument> path) {
248 final DataSchemaContextNode<?> initialContext = current;
249 final DataSchemaNode initialDataSchema = initialContext.getDataSchemaNode();
251 current = initialContext.getChild(qname);
253 if (current == null) {
254 final Optional<Module> module = schemaContext.findModule(qname.getModule());
255 if (module.isPresent()) {
256 for (final RpcDefinition rpcDefinition : module.get().getRpcs()) {
257 if (rpcDefinition.getQName().getLocalName().equals(qname.getLocalName())) {
262 if (findActionDefinition(initialDataSchema, qname.getLocalName()).isPresent()) {
266 checkValid(current != null, ErrorTag.MALFORMED_MESSAGE, "'%s' is not correct schema node identifier.", qname);
267 while (current.isMixin()) {
268 path.add(current.getIdentifier());
269 current = current.getChild(qname);
274 private Module moduleForPrefix(final String prefix) {
275 return schemaContext.findModules(prefix).stream().findFirst().orElse(null);
278 private boolean allCharsConsumed() {
279 return offset == data.length();
282 private void checkValid(final boolean condition, final ErrorTag errorTag, final String errorMsg,
283 final Object... messageArgs) {
284 final Object[] allMessageArguments = new Object[messageArgs.length + 2];
285 allMessageArguments[0] = data;
286 allMessageArguments[1] = offset;
287 System.arraycopy(messageArgs, 0, allMessageArguments, 2, messageArgs.length);
288 RestconfDocumentedException.throwIf(!condition, ErrorType.PROTOCOL, errorTag,
289 PARSING_FAILED_MESSAGE + errorMsg, allMessageArguments);
292 private void checkValidIdentifierStart() {
293 checkValid(ParserConstants.YANG_IDENTIFIER_START.matches(currentChar()), ErrorTag.MALFORMED_MESSAGE,
294 "Identifier must start with character from set 'a-zA-Z_'");
297 private RestconfDocumentedException getParsingCharFailedException() {
298 return new RestconfDocumentedException(String.format(PARSING_FAILED_MESSAGE, data, offset)
299 + String.format("Bad char '%c' on the current position.", currentChar()),
300 ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
303 private char currentChar() {
304 return data.charAt(offset);
307 private void skipCurrentChar() {
311 private String nextIdentifierFromNextSequence(final CharMatcher matcher) {
312 final int start = offset;
313 while (!allCharsConsumed() && matcher.matches(currentChar())) {
316 return data.substring(start, offset);
319 private void validArg() {
320 // every identifier except of the first MUST start with slash
322 checkValid('/' == currentChar(), ErrorTag.MALFORMED_MESSAGE, "Identifier must start with '/'.");
324 // skip consecutive slashes, users often assume restconf URLs behave just as HTTP does by squashing
325 // multiple slashes into a single one
326 while (!allCharsConsumed() && '/' == currentChar()) {
330 // check if slash is not also the last char in identifier
331 checkValid(!allCharsConsumed(), ErrorTag.MALFORMED_MESSAGE, "Identifier cannot end with '/'.");
335 private QName getQNameOfDataSchemaNode(final String nodeName) {
336 final DataSchemaNode dataSchemaNode = current.getDataSchemaNode();
337 if (dataSchemaNode instanceof ContainerLike) {
338 return getQNameOfDataSchemaNode((ContainerLike) dataSchemaNode, nodeName);
339 } else if (dataSchemaNode instanceof ListSchemaNode) {
340 return getQNameOfDataSchemaNode((ListSchemaNode) dataSchemaNode, nodeName);
343 throw new UnsupportedOperationException("Unsupported schema node " + dataSchemaNode);
346 private static <T extends DataNodeContainer & SchemaNode & ActionNodeContainer> QName getQNameOfDataSchemaNode(
347 final T parent, final String nodeName) {
348 final Optional<? extends ActionDefinition> actionDef = findActionDefinition(parent, nodeName);
349 final SchemaNode node;
350 if (actionDef.isPresent()) {
351 node = actionDef.get();
353 node = RestconfSchemaUtil.findSchemaNodeInCollection(parent.getChildNodes(), nodeName);
355 return node.getQName();
358 private static Optional<? extends ActionDefinition> findActionDefinition(final SchemaNode dataSchemaNode,
359 final String nodeName) {
360 requireNonNull(dataSchemaNode, "DataSchema Node must not be null.");
361 if (dataSchemaNode instanceof ActionNodeContainer) {
362 return ((ActionNodeContainer) dataSchemaNode).getActions().stream()
363 .filter(actionDef -> actionDef.getQName().getLocalName().equals(nodeName)).findFirst();
365 return Optional.empty();
368 private static String findAndParsePercentEncoded(final String preparedPrefix) {
369 if (preparedPrefix.indexOf('%') == -1) {
370 return preparedPrefix;
373 // FIXME: this is extremely inefficient: we should be converting ranges of characters, not driven by
374 // CharMatcher, but by String.indexOf()
375 final StringBuilder parsedPrefix = new StringBuilder(preparedPrefix);
376 while (PERCENT_ENCODING.matchesAnyOf(parsedPrefix)) {
377 final int percentCharPosition = PERCENT_ENCODING.indexIn(parsedPrefix);
378 parsedPrefix.replace(percentCharPosition, percentCharPosition + LAST_ENCODED_CHAR,
379 String.valueOf((char) Integer.parseInt(parsedPrefix.substring(
380 percentCharPosition + FIRST_ENCODED_CHAR, percentCharPosition + LAST_ENCODED_CHAR),
381 PERCENT_ENCODED_RADIX)));
384 return parsedPrefix.toString();
387 private static Object toQName(final String value, final DataSchemaNode schemaNode,
388 final SchemaContext schemaContext) {
389 final String moduleName = toModuleName(value);
390 final String nodeName = toNodeName(value);
391 final Module module = schemaContext.findModules(moduleName).iterator().next();
392 for (final IdentitySchemaNode identitySchemaNode : module.getIdentities()) {
393 final QName qName = identitySchemaNode.getQName();
394 if (qName.getLocalName().equals(nodeName)) {
398 return QName.create(schemaNode.getQName().getNamespace(), schemaNode.getQName().getRevision(), nodeName);
401 private static String toNodeName(final String str) {
402 final int idx = str.indexOf(':');
407 if (str.indexOf(':', idx + 1) != -1) {
411 return str.substring(idx + 1);
414 private static String toModuleName(final String str) {
415 final int idx = str.indexOf(':');
420 if (str.indexOf(':', idx + 1) != -1) {
424 return str.substring(0, idx);