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 java.util.AbstractMap.SimpleEntry;
11 import java.util.ArrayList;
12 import java.util.HashSet;
13 import java.util.LinkedList;
14 import java.util.List;
16 import java.util.Objects;
17 import java.util.Optional;
19 import java.util.stream.Collectors;
20 import org.eclipse.jdt.annotation.NonNull;
21 import org.eclipse.jdt.annotation.Nullable;
22 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
23 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
24 import org.opendaylight.yangtools.yang.common.ErrorTag;
25 import org.opendaylight.yangtools.yang.common.ErrorType;
26 import org.opendaylight.yangtools.yang.common.QName;
27 import org.opendaylight.yangtools.yang.common.QNameModule;
28 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.model.api.DataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
37 * Utilities used for parsing of fields query parameter content.
39 * @param <T> type of identifier
41 public abstract class ParserFieldsParameter<T> {
42 private static final ParserFieldsParameter<QName> QNAME_PARSER = new QNameParser();
43 private static final ParserFieldsParameter<LinkedPathElement> PATH_PARSER = new PathParser();
45 private ParserFieldsParameter() {
49 * Parse fields parameter and return complete list of child nodes organized into levels.
51 * @param identifier identifier context created from request URI
52 * @param input input value of fields parameter
53 * @return {@link List} of levels; each level contains set of {@link QName}
55 public static @NonNull List<Set<QName>> parseFieldsParameter(final @NonNull InstanceIdentifierContext<?> identifier,
56 final @NonNull String input) {
57 return QNAME_PARSER.parseFields(identifier, input);
61 * Parse fields parameter and return list of child node paths saved in lists.
63 * @param identifier identifier context created from request URI
64 * @param input input value of fields parameter
65 * @return {@link List} of {@link YangInstanceIdentifier} that are relative to the last {@link PathArgument}
66 * of provided {@code identifier}
68 public static @NonNull List<YangInstanceIdentifier> parseFieldsPaths(
69 final @NonNull InstanceIdentifierContext<?> identifier, final @NonNull String input) {
70 final List<Set<LinkedPathElement>> levels = PATH_PARSER.parseFields(identifier, input);
71 final List<Map<PathArgument, LinkedPathElement>> mappedLevels = mapLevelsContentByIdentifiers(levels);
72 return buildPaths(mappedLevels);
75 private static List<Map<PathArgument, LinkedPathElement>> mapLevelsContentByIdentifiers(
76 final List<Set<LinkedPathElement>> levels) {
77 // this step is used for saving some processing power - we can directly find LinkedPathElement using
78 // representing PathArgument
79 return levels.stream()
80 .map(linkedPathElements -> linkedPathElements.stream()
81 .map(linkedPathElement -> new SimpleEntry<>(linkedPathElement.targetNodeIdentifier,
83 .collect(Collectors.toMap(SimpleEntry::getKey, SimpleEntry::getValue)))
84 .collect(Collectors.toList());
87 private static List<YangInstanceIdentifier> buildPaths(
88 final List<Map<PathArgument, LinkedPathElement>> mappedLevels) {
89 final List<YangInstanceIdentifier> completePaths = new ArrayList<>();
90 // we must traverse levels from the deepest level to the top level, because each LinkedPathElement is only
91 // linked to previous element
92 for (int levelIndex = mappedLevels.size() - 1; levelIndex >= 0; levelIndex--) {
93 // we go through unprocessed LinkedPathElements that represent leaves
94 for (final LinkedPathElement pathElement : mappedLevels.get(levelIndex).values()) {
95 if (pathElement.processed) {
96 // this element was already processed from the lower level - skip it
99 pathElement.processed = true;
101 // adding deepest path arguments, LinkedList is used for more effective insertion at the 0 index
102 final LinkedList<PathArgument> path = new LinkedList<>(pathElement.mixinNodesToTarget);
103 path.add(pathElement.targetNodeIdentifier);
105 PathArgument previousIdentifier = pathElement.previousNodeIdentifier;
106 // adding path arguments from the linked LinkedPathElements recursively
107 for (int buildingLevel = levelIndex - 1; buildingLevel >= 0; buildingLevel--) {
108 final LinkedPathElement previousElement = mappedLevels.get(buildingLevel).get(previousIdentifier);
109 path.addFirst(previousElement.targetNodeIdentifier);
110 path.addAll(0, previousElement.mixinNodesToTarget);
111 previousIdentifier = previousElement.previousNodeIdentifier;
112 previousElement.processed = true;
114 completePaths.add(YangInstanceIdentifier.create(path));
117 return completePaths;
121 * Parse fields parameter and return complete list of child nodes organized into levels.
123 * @param identifier identifier context created from request URI
124 * @param input input value of fields parameter
125 * @return {@link List} of levels; each level contains {@link Set} of identifiers of type {@link T}
127 private @NonNull List<Set<T>> parseFields(final @NonNull InstanceIdentifierContext<?> identifier,
128 final @NonNull String input) {
129 final List<Set<T>> parsed = new ArrayList<>();
130 final SchemaContext context = identifier.getSchemaContext();
131 final QNameModule startQNameModule = identifier.getSchemaNode().getQName().getModule();
132 final DataSchemaContextNode<?> startNode = DataSchemaContextNode.fromDataSchemaNode(
133 (DataSchemaNode) identifier.getSchemaNode());
135 if (startNode == null) {
136 throw new RestconfDocumentedException(
137 "Start node missing in " + input, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
140 parseInput(input, startQNameModule, startNode, parsed, context);
145 * Parse input value of fields parameter and create list of sets. Each set represents one level of child nodes.
147 * @param input input value of fields parameter
148 * @param startQNameModule starting qname module
149 * @param startNode starting node
150 * @param parsed list of results
151 * @param context schema context
153 private void parseInput(final @NonNull String input, final @NonNull QNameModule startQNameModule,
154 final @NonNull DataSchemaContextNode<?> startNode,
155 final @NonNull List<Set<T>> parsed, final SchemaContext context) {
156 final Set<T> startLevel = new HashSet<>();
157 parsed.add(startLevel);
159 int currentPosition = 0;
160 int startPosition = 0;
161 DataSchemaContextNode<?> currentNode = startNode;
162 QNameModule currentQNameModule = startQNameModule;
163 Set<T> currentLevel = startLevel;
165 while (currentPosition < input.length()) {
166 final char currentChar = input.charAt(currentPosition);
168 if (ParserConstants.YANG_IDENTIFIER_PART.matches(currentChar)) {
173 switch (currentChar) {
175 // add parsed identifier to results for current level
176 currentNode = addChildToResult(currentNode, input.substring(startPosition, currentPosition),
177 currentQNameModule, currentLevel);
179 currentLevel = prepareQNameLevel(parsed, currentLevel);
184 // new namespace and revision found
185 currentQNameModule = context.findModules(
186 input.substring(startPosition, currentPosition)).iterator().next().getQNameModule();
190 // add current child to parsed results for current level
191 final DataSchemaContextNode<?> child = addChildToResult(
193 input.substring(startPosition, currentPosition), currentQNameModule, currentLevel);
194 // call with child node as new start node for one level down
195 final int closingParenthesis = currentPosition
196 + findClosingParenthesis(input.substring(currentPosition + 1));
198 input.substring(currentPosition + 1, closingParenthesis),
204 // closing parenthesis must be at the end of input or separator and one more character is expected
205 currentPosition = closingParenthesis + 1;
206 if (currentPosition != input.length()) {
207 if (currentPosition + 1 < input.length()) {
208 if (input.charAt(currentPosition) == ';') {
211 throw new RestconfDocumentedException(
212 "Missing semicolon character after "
213 + child.getIdentifier().getNodeType().getLocalName()
215 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
218 throw new RestconfDocumentedException(
219 "Unexpected character '"
220 + input.charAt(currentPosition)
221 + "' found in fields parameter value",
222 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
228 // complete identifier found
231 input.substring(startPosition, currentPosition), currentQNameModule, currentLevel);
234 // next nodes can be placed on already utilized level-s
235 currentNode = startNode;
236 currentQNameModule = startQNameModule;
237 currentLevel = startLevel;
240 throw new RestconfDocumentedException(
241 "Unexpected character '" + currentChar + "' found in fields parameter value",
242 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
245 startPosition = currentPosition;
248 // parse input to end
249 if (startPosition < input.length()) {
250 addChildToResult(currentNode, input.substring(startPosition), currentQNameModule, currentLevel);
255 * Preparation of the identifiers level that is used as storage for parsed identifiers. If the current level exist
256 * at the index that doesn't equal to the last index of already parsed identifiers, a new level of identifiers
257 * is allocated and pushed to input parsed identifiers.
259 * @param parsedIdentifiers Already parsed list of identifiers grouped to multiple levels.
260 * @param currentLevel Current level of identifiers (set).
261 * @return Existing or new level of identifiers.
263 private Set<T> prepareQNameLevel(final List<Set<T>> parsedIdentifiers, final Set<T> currentLevel) {
264 final Optional<Set<T>> existingLevel = parsedIdentifiers.stream()
265 .filter(qNameSet -> qNameSet.equals(currentLevel))
267 if (existingLevel.isPresent()) {
268 final int index = parsedIdentifiers.indexOf(existingLevel.get());
269 if (index == parsedIdentifiers.size() - 1) {
270 final Set<T> nextLevel = new HashSet<>();
271 parsedIdentifiers.add(nextLevel);
275 return parsedIdentifiers.get(index + 1);
278 final Set<T> nextLevel = new HashSet<>();
279 parsedIdentifiers.add(nextLevel);
284 * Find position of matching parenthesis increased by one, but at most equals to input size.
286 * @param input input where to find for closing parenthesis
287 * @return int position of closing parenthesis increased by one
289 private static int findClosingParenthesis(final @NonNull String input) {
293 while (position < input.length()) {
294 final char currentChar = input.charAt(position);
296 if (currentChar == '(') {
300 if (currentChar == ')') {
311 // closing parenthesis was not found
312 if (position >= input.length()) {
313 throw new RestconfDocumentedException("Missing closing parenthesis in fields parameter",
314 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
321 * Add parsed child of current node to result for current level.
323 * @param currentNode current node
324 * @param childQName parsed identifier of child node
325 * @param level current nodes level
326 * @return {@link DataSchemaContextNode}
328 abstract @NonNull DataSchemaContextNode<?> addChildToResult(@NonNull DataSchemaContextNode<?> currentNode,
329 @NonNull QName childQName, @NonNull Set<T> level);
331 private @NonNull DataSchemaContextNode<?> addChildToResult(final @NonNull DataSchemaContextNode<?> currentNode,
332 final @NonNull String localName, final @NonNull QNameModule namespace, final @NonNull Set<T> level) {
333 return addChildToResult(currentNode, QName.create(namespace, localName), level);
337 * Fields parser that stores set of {@link QName}s in each level. Because of this fact, from the output
338 * it is is only possible to assume on what depth the selected element is placed. Identifiers of intermediary
339 * mixin nodes are also flatten to the same level as identifiers of data nodes.<br>
340 * Example: field 'a(/b/c);d/e' ('e' is place under choice node 'x') is parsed into following levels:<br>
342 * level 0: ['a', 'd']
343 * level 1: ['b', 'x', 'e']
347 private static final class QNameParser extends ParserFieldsParameter<QName> {
349 DataSchemaContextNode<?> addChildToResult(final DataSchemaContextNode<?> currentNode, final QName childQName,
350 final Set<QName> level) {
351 // resolve parent node
352 final DataSchemaContextNode<?> parentNode = resolveMixinNode(
353 currentNode, level, currentNode.getIdentifier().getNodeType());
354 if (parentNode == null) {
355 throw new RestconfDocumentedException(
356 "Not-mixin node missing in " + currentNode.getIdentifier().getNodeType().getLocalName(),
357 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
360 // resolve child node
361 final DataSchemaContextNode<?> childNode = resolveMixinNode(
362 parentNode.getChild(childQName), level, childQName);
363 if (childNode == null) {
364 throw new RestconfDocumentedException(
365 "Child " + childQName.getLocalName() + " node missing in "
366 + currentNode.getIdentifier().getNodeType().getLocalName(),
367 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
370 // add final childNode node to level nodes
371 level.add(childNode.getIdentifier().getNodeType());
376 * Resolve mixin node by searching for inner nodes until not mixin node or null is found.
377 * All nodes expect of not mixin node are added to current level nodes.
379 * @param node initial mixin or not-mixin node
380 * @param level current nodes level
381 * @param qualifiedName qname of initial node
382 * @return {@link DataSchemaContextNode}
384 private static @Nullable DataSchemaContextNode<?> resolveMixinNode(
385 final @Nullable DataSchemaContextNode<?> node, final @NonNull Set<QName> level,
386 final @NonNull QName qualifiedName) {
387 DataSchemaContextNode<?> currentNode = node;
388 while (currentNode != null && currentNode.isMixin()) {
389 level.add(qualifiedName);
390 currentNode = currentNode.getChild(qualifiedName);
398 * Fields parser that stores set of {@link LinkedPathElement}s in each level. Using {@link LinkedPathElement}
399 * it is possible to create a chain of path arguments and build complete paths since this element contains
400 * identifiers of intermediary mixin nodes and also linked previous element.<br>
401 * Example: field 'a(/b/c);d/e' ('e' is place under choice node 'x') is parsed into following levels:<br>
403 * level 0: ['./a', './d']
404 * level 1: ['a/b', '/d/x/e']
408 private static final class PathParser extends ParserFieldsParameter<LinkedPathElement> {
410 DataSchemaContextNode<?> addChildToResult(final DataSchemaContextNode<?> currentNode, final QName childQName,
411 final Set<LinkedPathElement> level) {
412 final List<PathArgument> collectedMixinNodes = new ArrayList<>();
414 DataSchemaContextNode<?> actualContextNode = currentNode.getChild(childQName);
415 while (actualContextNode != null && actualContextNode.isMixin()) {
416 if (actualContextNode.getDataSchemaNode() instanceof ListSchemaNode) {
417 // we need just a single node identifier from list in the path (key is not available)
418 actualContextNode = actualContextNode.getChild(childQName);
420 } else if (actualContextNode.getDataSchemaNode() instanceof LeafListSchemaNode) {
421 // NodeWithValue is unusable - stop parsing
424 collectedMixinNodes.add(actualContextNode.getIdentifier());
425 actualContextNode = actualContextNode.getChild(childQName);
429 if (actualContextNode == null) {
430 throw new RestconfDocumentedException("Child " + childQName.getLocalName() + " node missing in "
431 + currentNode.getIdentifier().getNodeType().getLocalName(),
432 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
434 final LinkedPathElement linkedPathElement = new LinkedPathElement(currentNode.getIdentifier(),
435 collectedMixinNodes, actualContextNode.getIdentifier());
436 level.add(linkedPathElement);
437 return actualContextNode;
442 * {@link PathArgument} of data element grouped with identifiers of leading mixin nodes and previous node.<br>
443 * - identifiers of mixin nodes on the path to the target node - required for construction of full valid
445 * - identifier of the previous non-mixin node - required to successfully create a chain of {@link PathArgument}s
447 private static final class LinkedPathElement {
448 private final PathArgument previousNodeIdentifier;
449 private final List<PathArgument> mixinNodesToTarget;
450 private final PathArgument targetNodeIdentifier;
451 private boolean processed = false;
454 * Creation of new {@link LinkedPathElement}.
456 * @param previousNodeIdentifier identifier of the previous non-mixin node
457 * @param mixinNodesToTarget identifiers of mixin nodes on the path to the target node
458 * @param targetNodeIdentifier identifier of target non-mixin node
460 private LinkedPathElement(final PathArgument previousNodeIdentifier,
461 final List<PathArgument> mixinNodesToTarget, final PathArgument targetNodeIdentifier) {
462 this.previousNodeIdentifier = previousNodeIdentifier;
463 this.mixinNodesToTarget = mixinNodesToTarget;
464 this.targetNodeIdentifier = targetNodeIdentifier;
468 public boolean equals(final Object obj) {
469 // this is need in order to make 'prepareQNameLevel(..)' working
473 if (obj == null || getClass() != obj.getClass()) {
476 final LinkedPathElement that = (LinkedPathElement) obj;
477 return targetNodeIdentifier.equals(that.targetNodeIdentifier);
481 public int hashCode() {
482 return Objects.hash(targetNodeIdentifier);