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 java.util.ArrayList;
17 import java.util.Collections;
18 import java.util.List;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import javax.annotation.RegEx;
24 import javax.xml.xpath.XPath;
25 import javax.xml.xpath.XPathExpressionException;
26 import javax.xml.xpath.XPathFactory;
27 import org.antlr.v4.runtime.tree.TerminalNode;
28 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.YangVersion;
31 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
32 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
33 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
34 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
35 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
36 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
37 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
38 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 public final class Utils {
43 private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
44 private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
45 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
46 private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
48 private static final String YANG_XPATH_FUNCTIONS_STRING =
49 "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)([ \t\r\n]*)(\\()";
50 private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
51 private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
52 private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
53 private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
54 private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
56 private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
58 protected XPathFactory initialValue() {
59 return XPathFactory.newInstance();
64 throw new UnsupportedOperationException();
68 * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
69 * caches to them. Invoke this method if you want to detach those resources.
71 public static void detachFromCurrentThread() {
72 XPATH_FACTORY.remove();
75 private static String trimSingleLastSlashFromXPath(final String path) {
76 return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
79 public static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
80 final XPath xPath = XPATH_FACTORY.get().newXPath();
81 xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
82 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
84 final String trimmed = trimSingleLastSlashFromXPath(path);
86 // XPath extension functions have to be prefixed
87 // yang-specific XPath functions are in fact extended functions, therefore we have to add
88 // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
89 // the "yang" prefix is bound to RFC6020 YANG namespace
90 final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
91 // TODO: we could capture the result and expose its 'evaluate' method
92 xPath.compile(prefixedXPath);
93 } catch (final XPathExpressionException e) {
94 LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
97 return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
100 private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
101 if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
102 // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
103 // Matcher.appendTail() will accept StringBuilder parameter in Java 9
104 final StringBuffer result = new StringBuffer();
105 final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
106 final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
107 while (matcher.find()) {
108 matcher.appendReplacement(result, prefix + matcher.group());
111 matcher.appendTail(result);
112 return result.toString();
118 @SuppressWarnings("checkstyle:illegalCatch")
119 public static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
120 // FIXME: is the path trimming really necessary??
121 final List<QName> qNames = new ArrayList<>();
122 for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
124 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
126 } catch (final RuntimeException e) {
127 throw new SourceException(ctx.getStatementSourceReference(), e,
128 "Failed to parse node '%s' in path '%s'", nodeName, path);
132 return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
135 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
136 final StatementSourceReference ref) {
137 return stringFromStringContext(context, YangVersion.VERSION_1, ref);
140 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
141 final YangVersion yangVersion, final StatementSourceReference ref) {
142 final StringBuilder sb = new StringBuilder();
143 List<TerminalNode> strings = context.STRING();
144 if (strings.isEmpty()) {
145 strings = Collections.singletonList(context.IDENTIFIER());
147 for (final TerminalNode stringNode : strings) {
148 final String str = stringNode.getText();
149 final char firstChar = str.charAt(0);
150 final char lastChar = str.charAt(str.length() - 1);
151 if (firstChar == '"' && lastChar == '"') {
152 final String innerStr = str.substring(1, str.length() - 1);
154 * Unescape escaped double quotes, tabs, new line and backslash
155 * in the inner string and trim the result.
157 checkDoubleQuotedString(innerStr, yangVersion, ref);
158 sb.append(ESCAPED_TAB.matcher(
160 ESCAPED_BACKSLASH.matcher(
161 ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
164 .replaceAll("\\\t"));
165 } else if (firstChar == '\'' && lastChar == '\'') {
167 * According to RFC6020 a single quote character cannot occur in
168 * a single-quoted string, even when preceded by a backslash.
170 sb.append(str.substring(1, str.length() - 1));
172 checkUnquotedString(str, yangVersion, ref);
176 return sb.toString();
179 private static void checkUnquotedString(final String str, final YangVersion yangVersion,
180 final StatementSourceReference ref) {
181 if (yangVersion == YangVersion.VERSION_1_1) {
182 SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
183 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
187 private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
188 final StatementSourceReference ref) {
189 if (yangVersion == YangVersion.VERSION_1_1) {
190 for (int i = 0; i < str.length() - 1; i++) {
191 if (str.charAt(i) == '\\') {
192 switch (str.charAt(i + 1)) {
200 throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
201 + "quoted string the backslash must be followed by one of the following character "
202 + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
210 public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
211 final SchemaNodeIdentifier node) {
212 return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
216 public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
217 if ("true".equals(input)) {
219 } else if ("false".equals(input)) {
220 return Boolean.FALSE;
222 throw new SourceException(ctx.getStatementSourceReference(),
223 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
224 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
228 public static String internBoolean(final String input) {
229 if ("true".equals(input)) {
231 } else if ("false".equals(input)) {