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.parser.builder;
10 import com.google.common.base.CharMatcher;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableList;
13 import com.google.common.collect.ImmutableMap;
14 import java.util.Iterator;
15 import java.util.LinkedList;
16 import java.util.List;
17 import org.opendaylight.netconf.md.sal.rest.common.RestconfValidationUtils;
18 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
19 import org.opendaylight.restconf.utils.RestconfConstants;
20 import org.opendaylight.restconf.utils.parser.builder.ParserBuilderConstants;
21 import org.opendaylight.restconf.utils.schema.context.RestconfSchemaUtil;
22 import org.opendaylight.yangtools.yang.common.QName;
23 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
24 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
25 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
26 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
34 * Deserializer for {@link String} to {@link YangInstanceIdentifier} for
38 public final class YangInstanceIdentifierDeserializer {
40 private YangInstanceIdentifierDeserializer() {
41 throw new UnsupportedOperationException("Util class.");
45 * Method to create {@link Iterable} from {@link PathArgument} which are
46 * parsing from data by {@link SchemaContext}.
48 * @param schemaContext
49 * - for validate of parsing path arguments
52 * @return {@link Iterable} of {@link PathArgument}
54 public static Iterable<PathArgument> create(final SchemaContext schemaContext, final String data) {
55 final List<PathArgument> path = new LinkedList<>();
56 final MainVarsWrapper variables = new YangInstanceIdentifierDeserializer.MainVarsWrapper(
57 data, DataSchemaContextTree.from(schemaContext).getRoot(),
58 YangInstanceIdentifierDeserializer.MainVarsWrapper.STARTING_OFFSET, schemaContext);
60 checkValid(!data.isEmpty(), "Empty path is not valid", variables.getData(), variables.getOffset());
62 if (!data.equals(String.valueOf(RestconfConstants.SLASH))) {
63 while (!allCharsConsumed(variables)) {
65 final QName qname = prepareQName(variables);
67 // this is the last identifier (input is consumed) or end of identifier (slash)
68 if (allCharsConsumed(variables)
69 || currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH) {
70 prepareIdentifier(qname, path, variables);
71 path.add(variables.getCurrent().getIdentifier());
72 } else if (currentChar(variables.getOffset(),
73 variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL) {
74 if (nextContextNode(qname, path, variables).getDataSchemaNode() instanceof ListSchemaNode) {
75 prepareNodeWithPredicates(qname, path, variables);
77 prepareNodeWithValue(qname, path, variables);
80 throw new IllegalArgumentException(
81 "Bad char " + currentChar(variables.getOffset(), variables.getData()) + " on position "
82 + variables.getOffset() + ".");
87 return ImmutableList.copyOf(path);
90 private static void prepareNodeWithPredicates(final QName qname, final List<PathArgument> path,
91 final MainVarsWrapper variables) {
93 final DataSchemaNode dataSchemaNode = variables.getCurrent().getDataSchemaNode();
94 checkValid((dataSchemaNode != null), "Data schema node is null", variables.getData(), variables.getOffset());
96 final Iterator<QName> keys = ((ListSchemaNode) dataSchemaNode).getKeyDefinition().iterator();
97 final ImmutableMap.Builder<QName, Object> values = ImmutableMap.builder();
99 // skip already expected equal sign
100 skipCurrentChar(variables);
102 // read key value separated by comma
103 while (keys.hasNext() && !allCharsConsumed(variables) && currentChar(variables.getOffset(),
104 variables.getData()) != RestconfConstants.SLASH) {
107 if (currentChar(variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA) {
108 values.put(keys.next(), ParserBuilderConstants.Deserializer.EMPTY_STRING);
109 skipCurrentChar(variables);
113 // check if next value is parsable
114 RestconfValidationUtils.checkDocumentedError(
115 ParserBuilderConstants.Deserializer.IDENTIFIER_PREDICATE
116 .matches(currentChar(variables.getOffset(), variables.getData())),
117 RestconfError.ErrorType.PROTOCOL,
118 RestconfError.ErrorTag.MALFORMED_MESSAGE,
123 values.put(keys.next(), findAndParsePercentEncoded(nextIdentifierFromNextSequence(
124 ParserBuilderConstants.Deserializer.IDENTIFIER_PREDICATE, variables)));
127 if (keys.hasNext() && !allCharsConsumed(variables) && currentChar(
128 variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.COMMA) {
129 skipCurrentChar(variables);
133 // the last key is considered to be empty
134 if (keys.hasNext()) {
135 if (allCharsConsumed(variables)
136 || currentChar(variables.getOffset(), variables.getData()) == RestconfConstants.SLASH) {
137 values.put(keys.next(), ParserBuilderConstants.Deserializer.EMPTY_STRING);
140 // there should be no more missing keys
141 RestconfValidationUtils.checkDocumentedError(
143 RestconfError.ErrorType.PROTOCOL,
144 RestconfError.ErrorTag.MISSING_ATTRIBUTE,
145 "Key value missing for: " + qname
149 path.add(new YangInstanceIdentifier.NodeIdentifierWithPredicates(qname, values.build()));
153 private static QName prepareQName(final MainVarsWrapper variables) {
155 ParserBuilderConstants.Deserializer.IDENTIFIER_FIRST_CHAR
156 .matches(currentChar(variables.getOffset(), variables.getData())),
157 "Identifier must start with character from set 'a-zA-Z_'", variables.getData(), variables.getOffset());
158 final String preparedPrefix = nextIdentifierFromNextSequence(
159 ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
160 final String prefix, localName;
162 if (allCharsConsumed(variables)) {
163 return getQNameOfDataSchemaNode(preparedPrefix, variables);
166 switch (currentChar(variables.getOffset(), variables.getData())) {
167 case RestconfConstants.SLASH:
168 prefix = preparedPrefix;
169 return getQNameOfDataSchemaNode(prefix, variables);
170 case ParserBuilderConstants.Deserializer.COLON:
171 prefix = preparedPrefix;
172 skipCurrentChar(variables);
174 ParserBuilderConstants.Deserializer.IDENTIFIER_FIRST_CHAR
175 .matches(currentChar(variables.getOffset(), variables.getData())),
176 "Identifier must start with character from set 'a-zA-Z_'", variables.getData(),
177 variables.getOffset());
178 localName = nextIdentifierFromNextSequence(ParserBuilderConstants.Deserializer.IDENTIFIER, variables);
180 if (!allCharsConsumed(variables) && currentChar
181 (variables.getOffset(), variables.getData()) == ParserBuilderConstants.Deserializer.EQUAL) {
182 return getQNameOfDataSchemaNode(localName, variables);
184 final Module module = moduleForPrefix(prefix, variables.getSchemaContext());
185 Preconditions.checkArgument(module != null, "Failed to lookup prefix %s", prefix);
186 return QName.create(module.getQNameModule(), localName);
188 case ParserBuilderConstants.Deserializer.EQUAL:
189 prefix = preparedPrefix;
190 return getQNameOfDataSchemaNode(prefix, variables);
192 throw new IllegalArgumentException("Failed build path.");
196 private static String nextIdentifierFromNextSequence(final CharMatcher matcher, final MainVarsWrapper variables) {
197 final int start = variables.getOffset();
198 nextSequenceEnd(matcher, variables);
199 return variables.getData().substring(start, variables.getOffset());
202 private static void nextSequenceEnd(final CharMatcher matcher, final MainVarsWrapper variables) {
203 while (!allCharsConsumed(variables)
204 && matcher.matches(variables.getData().charAt(variables.getOffset()))) {
205 variables.setOffset(variables.getOffset() + 1);
209 private static void prepareNodeWithValue(final QName qname, final List<PathArgument> path,
210 final MainVarsWrapper variables) {
211 skipCurrentChar(variables);
212 final String value = nextIdentifierFromNextSequence(
213 ParserBuilderConstants.Deserializer.IDENTIFIER_PREDICATE, variables);
215 // exception if value attribute is missing
216 RestconfValidationUtils.checkDocumentedError(
218 RestconfError.ErrorType.PROTOCOL,
219 RestconfError.ErrorTag.MISSING_ATTRIBUTE,
220 "Value missing for: " + qname
223 path.add(new YangInstanceIdentifier.NodeWithValue<>(qname, findAndParsePercentEncoded(value)));
226 private static void prepareIdentifier(final QName qname, final List<PathArgument> path,
227 final MainVarsWrapper variables) {
228 final DataSchemaContextNode<?> currentNode = nextContextNode(qname, path, variables);
229 checkValid(!currentNode.isKeyedEntry(), "Entry " + qname + " requires key or value predicate to be present",
230 variables.getData(), variables.getOffset());
233 private static DataSchemaContextNode<?> nextContextNode(final QName qname, final List<PathArgument> path,
234 final MainVarsWrapper variables) {
235 variables.setCurrent(variables.getCurrent().getChild(qname));
236 DataSchemaContextNode<?> current = variables.getCurrent();
237 checkValid(current != null, qname + " is not correct schema node identifier.", variables.getData(),
238 variables.getOffset());
239 while (current.isMixin()) {
240 path.add(current.getIdentifier());
241 current = current.getChild(qname);
242 variables.setCurrent(current);
247 private static String findAndParsePercentEncoded(final String preparedPrefix) {
248 if (!preparedPrefix.contains(String.valueOf(ParserBuilderConstants.Deserializer.PERCENT_ENCODING))) {
249 return preparedPrefix;
252 final StringBuilder parsedPrefix = new StringBuilder(preparedPrefix);
253 final CharMatcher matcher = CharMatcher.is(ParserBuilderConstants.Deserializer.PERCENT_ENCODING);
255 while (matcher.matchesAnyOf(parsedPrefix)) {
256 final int percentCharPosition = matcher.indexIn(parsedPrefix);
257 parsedPrefix.replace(
259 percentCharPosition + ParserBuilderConstants.Deserializer.LAST_ENCODED_CHAR,
260 String.valueOf((char) Integer.parseInt(parsedPrefix.substring(
261 percentCharPosition + ParserBuilderConstants.Deserializer.FIRST_ENCODED_CHAR,
262 percentCharPosition + ParserBuilderConstants.Deserializer.LAST_ENCODED_CHAR),
263 ParserBuilderConstants.Deserializer.PERCENT_ENCODED_RADIX)));
266 return parsedPrefix.toString();
269 private static QName getQNameOfDataSchemaNode(final String nodeName, final MainVarsWrapper variables) {
270 final DataSchemaNode dataSchemaNode = variables.getCurrent().getDataSchemaNode();
271 if (dataSchemaNode instanceof ContainerSchemaNode) {
272 final ContainerSchemaNode contSchemaNode = (ContainerSchemaNode) dataSchemaNode;
273 final DataSchemaNode node = RestconfSchemaUtil.findSchemaNodeInCollection(contSchemaNode.getChildNodes(),
275 return node.getQName();
276 } else if (dataSchemaNode instanceof ListSchemaNode) {
277 final ListSchemaNode listSchemaNode = (ListSchemaNode) dataSchemaNode;
278 final DataSchemaNode node = RestconfSchemaUtil.findSchemaNodeInCollection(listSchemaNode.getChildNodes(),
280 return node.getQName();
282 throw new UnsupportedOperationException();
285 private static Module moduleForPrefix(final String prefix, final SchemaContext schemaContext) {
286 return schemaContext.findModuleByName(prefix, null);
289 private static void validArg(final MainVarsWrapper variables) {
290 checkValid(RestconfConstants.SLASH == currentChar(variables.getOffset(), variables.getData()),
291 "Identifier must start with '/'.", variables.getData(), variables.getOffset());
292 skipCurrentChar(variables);
293 checkValid(!allCharsConsumed(variables), "Identifier cannot end with '/'.",
294 variables.getData(), variables.getOffset());
297 private static void skipCurrentChar(final MainVarsWrapper variables) {
298 variables.setOffset(variables.getOffset() + 1);
301 private static char currentChar(final int offset, final String data) {
302 return data.charAt(offset);
305 private static void checkValid(final boolean condition, final String errorMsg, final String data,
307 Preconditions.checkArgument(condition, "Could not parse Instance Identifier '%s'. Offset: %s : Reason: %s",
308 data, offset, errorMsg);
311 private static boolean allCharsConsumed(final MainVarsWrapper variables) {
312 return variables.getOffset() == variables.getData().length();
315 private final static class MainVarsWrapper {
316 private static final int STARTING_OFFSET = 0;
318 private final SchemaContext schemaContext;
319 private final String data;
320 private DataSchemaContextNode<?> current;
323 public MainVarsWrapper(final String data, final DataSchemaContextNode<?> current, final int offset,
324 final SchemaContext schemaContext) {
326 this.setCurrent(current);
327 this.setOffset(offset);
328 this.schemaContext = schemaContext;
331 public String getData() {
335 public DataSchemaContextNode<?> getCurrent() {
339 public void setCurrent(final DataSchemaContextNode<?> current) {
340 this.current = current;
343 public int getOffset() {
347 public void setOffset(final int offset) {
348 this.offset = offset;
351 public SchemaContext getSchemaContext() {
352 return this.schemaContext;