2 * Copyright (c) 2015 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.yangtools.yang.parser.stmt.rfc6020;
10 import static org.opendaylight.yangtools.yang.common.YangConstants.RFC6020_YANG_NAMESPACE;
11 import static org.opendaylight.yangtools.yang.common.YangConstants.YANG_XPATH_FUNCTIONS_PREFIX;
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.ImmutableBiMap;
16 import com.google.common.collect.ImmutableSet;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.Collections;
20 import java.util.HashSet;
21 import java.util.List;
23 import java.util.regex.Matcher;
24 import java.util.regex.Pattern;
25 import javax.annotation.Nonnull;
26 import javax.annotation.Nullable;
27 import javax.annotation.RegEx;
28 import javax.xml.xpath.XPath;
29 import javax.xml.xpath.XPathExpressionException;
30 import javax.xml.xpath.XPathFactory;
31 import org.antlr.v4.runtime.tree.TerminalNode;
32 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.YangVersion;
35 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
36 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Relative;
38 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
39 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
40 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
41 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
42 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
43 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 public final class Utils {
48 private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
49 private static final CharMatcher LEFT_PARENTHESIS_MATCHER = CharMatcher.is('(');
50 private static final CharMatcher RIGHT_PARENTHESIS_MATCHER = CharMatcher.is(')');
51 private static final CharMatcher AMPERSAND_MATCHER = CharMatcher.is('&');
52 private static final CharMatcher QUESTION_MARK_MATCHER = CharMatcher.is('?');
53 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
54 private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
55 private static final Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
56 private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
58 private static final String YANG_XPATH_FUNCTIONS_STRING =
59 "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)(\\()";
60 private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
62 private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
64 protected XPathFactory initialValue() {
65 return XPathFactory.newInstance();
70 throw new UnsupportedOperationException();
74 * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
75 * caches to them. Invoke this method if you want to detach those resources.
77 public static void detachFromCurrentThread() {
78 XPATH_FACTORY.remove();
81 public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(final StmtContext<?, ?, ?> ctx,
83 final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
85 // to detect if key contains duplicates
86 if (new HashSet<>(keyTokens).size() < keyTokens.size()) {
87 // FIXME: report all duplicate keys
88 throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
91 final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
93 for (final String keyToken : keyTokens) {
95 final SchemaNodeIdentifier.Relative keyNode = (Relative) SchemaNodeIdentifier.Relative.create(false,
96 StmtContextUtils.qnameFromArgument(ctx, keyToken));
97 keyNodes.add(keyNode);
103 static Collection<SchemaNodeIdentifier.Relative> parseUniqueConstraintArgument(final StmtContext<?, ?, ?> ctx,
104 final String argumentValue) {
105 final Set<SchemaNodeIdentifier.Relative> uniqueConstraintNodes = new HashSet<>();
106 for (final String uniqueArgToken : SPACE_SPLITTER.split(argumentValue)) {
107 final SchemaNodeIdentifier nodeIdentifier = Utils.nodeIdentifierFromPath(ctx, uniqueArgToken);
108 SourceException.throwIf(nodeIdentifier.isAbsolute(), ctx.getStatementSourceReference(),
109 "Unique statement argument '%s' contains schema node identifier '%s' "
110 + "which is not in the descendant node identifier form.", argumentValue, uniqueArgToken);
111 uniqueConstraintNodes.add((SchemaNodeIdentifier.Relative) nodeIdentifier);
113 return ImmutableSet.copyOf(uniqueConstraintNodes);
116 private static String trimSingleLastSlashFromXPath(final String path) {
117 return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
120 static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
121 final XPath xPath = XPATH_FACTORY.get().newXPath();
122 xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
123 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
125 final String trimmed = trimSingleLastSlashFromXPath(path);
127 // XPath extension functions have to be prefixed
128 // yang-specific XPath functions are in fact extended functions, therefore we have to add
129 // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
130 // the "yang" prefix is bound to RFC6020 YANG namespace
131 final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
132 // TODO: we could capture the result and expose its 'evaluate' method
133 xPath.compile(prefixedXPath);
134 } catch (final XPathExpressionException e) {
135 LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
138 return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
141 private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
142 if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
143 // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
144 // Matcher.appendTail() will accept StringBuilder parameter in Java 9
145 final StringBuffer result = new StringBuffer();
146 final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
147 final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
148 while (matcher.find()) {
149 matcher.appendReplacement(result, prefix + matcher.group());
152 matcher.appendTail(result);
153 return result.toString();
159 public static QName trimPrefix(final QName identifier) {
160 final String prefixedLocalName = identifier.getLocalName();
161 final String[] namesParts = prefixedLocalName.split(":");
163 if (namesParts.length == 2) {
164 final String localName = namesParts[1];
165 return QName.create(identifier.getModule(), localName);
171 public static String trimPrefix(final String identifier) {
172 final List<String> namesParts = COLON_SPLITTER.splitToList(identifier);
173 if (namesParts.size() == 2) {
174 return namesParts.get(1);
179 static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
180 // FIXME: is the path trimming really necessary??
181 final List<QName> qNames = new ArrayList<>();
182 for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
184 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
186 } catch (final RuntimeException e) {
187 throw new SourceException(ctx.getStatementSourceReference(), e,
188 "Failed to parse node '%s' in path '%s'", nodeName, path);
192 return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
195 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
196 final StatementSourceReference ref) {
197 return stringFromStringContext(context, YangVersion.VERSION_1, ref);
200 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
201 final YangVersion yangVersion, final StatementSourceReference ref) {
202 final StringBuilder sb = new StringBuilder();
203 List<TerminalNode> strings = context.STRING();
204 if (strings.isEmpty()) {
205 strings = Collections.singletonList(context.IDENTIFIER());
207 for (final TerminalNode stringNode : strings) {
208 final String str = stringNode.getText();
209 final char firstChar = str.charAt(0);
210 final char lastChar = str.charAt(str.length() - 1);
211 if (firstChar == '"' && lastChar == '"') {
212 final String innerStr = str.substring(1, str.length() - 1);
214 * Unescape escaped double quotes, tabs, new line and backslash
215 * in the inner string and trim the result.
217 checkDoubleQuotedString(innerStr, yangVersion, ref);
218 sb.append(innerStr.replace("\\\"", "\"").replace("\\\\", "\\").replace("\\n", "\n")
219 .replace("\\t", "\t"));
220 } else if (firstChar == '\'' && lastChar == '\'') {
222 * According to RFC6020 a single quote character cannot occur in
223 * a single-quoted string, even when preceded by a backslash.
225 sb.append(str.substring(1, str.length() - 1));
227 checkUnquotedString(str, yangVersion, ref);
231 return sb.toString();
234 private static void checkUnquotedString(final String str, final YangVersion yangVersion,
235 final StatementSourceReference ref) {
236 if (yangVersion == YangVersion.VERSION_1_1) {
237 for (int i = 0; i < str.length(); i++) {
238 switch (str.charAt(i)) {
241 throw new SourceException(ref, "Yang 1.1: unquoted string (%s) contains illegal characters", str);
247 private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
248 final StatementSourceReference ref) {
249 if (yangVersion == YangVersion.VERSION_1_1) {
250 for (int i = 0; i < str.length() - 1; i++) {
251 if (str.charAt(i) == '\\') {
252 switch (str.charAt(i + 1)) {
260 throw new SourceException(ref,
261 "Yang 1.1: illegal double quoted string (%s). In double quoted string the backslash must be followed "
262 + "by one of the following character [n,t,\",\\], but was '%s'.", str,
271 public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
272 final SchemaNodeIdentifier node) {
273 return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class, node);
276 static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
277 if ("true".equals(input)) {
279 } else if ("false".equals(input)) {
280 return Boolean.FALSE;
282 throw new SourceException(ctx.getStatementSourceReference(),
283 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
284 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
288 static String internBoolean(final String input) {
289 if ("true".equals(input)) {
291 } else if ("false".equals(input)) {
299 * Replaces illegal characters of QName by the name of the character (e.g.
300 * '?' is replaced by "QuestionMark" etc.).
304 * @return result String
306 public static String replaceIllegalCharsForQName(String string) {
307 string = LEFT_PARENTHESIS_MATCHER.replaceFrom(string, "LeftParenthesis");
308 string = RIGHT_PARENTHESIS_MATCHER.replaceFrom(string, "RightParenthesis");
309 string = AMPERSAND_MATCHER.replaceFrom(string, "Ampersand");
310 string = QUESTION_MARK_MATCHER.replaceFrom(string, "QuestionMark");
315 public static boolean belongsToTheSameModule(final QName targetStmtQName, final QName sourceStmtQName) {
316 return targetStmtQName.getModule().equals(sourceStmtQName.getModule());