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.Collection;
18 import java.util.Collections;
19 import java.util.HashSet;
20 import java.util.List;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24 import javax.annotation.Nonnull;
25 import javax.annotation.Nullable;
26 import javax.annotation.RegEx;
27 import javax.xml.xpath.XPath;
28 import javax.xml.xpath.XPathExpressionException;
29 import javax.xml.xpath.XPathFactory;
30 import org.antlr.v4.runtime.tree.TerminalNode;
31 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.YangVersion;
34 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
35 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
36 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
37 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
38 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
39 import org.opendaylight.yangtools.yang.parser.spi.source.SourceException;
40 import org.opendaylight.yangtools.yang.parser.spi.source.StatementSourceReference;
41 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 public final class Utils {
46 private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
47 private static final CharMatcher LEFT_PARENTHESIS_MATCHER = CharMatcher.is('(');
48 private static final CharMatcher RIGHT_PARENTHESIS_MATCHER = CharMatcher.is(')');
49 private static final CharMatcher AMPERSAND_MATCHER = CharMatcher.is('&');
50 private static final CharMatcher QUESTION_MARK_MATCHER = CharMatcher.is('?');
51 private static final CharMatcher ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
52 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
53 private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
54 private static final Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
55 private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
57 private static final String YANG_XPATH_FUNCTIONS_STRING =
58 "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)([ \t\r\n]*)(\\()";
59 private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
60 private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
61 private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
62 private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
63 private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
65 private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
67 protected XPathFactory initialValue() {
68 return XPathFactory.newInstance();
73 throw new UnsupportedOperationException();
77 * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
78 * caches to them. Invoke this method if you want to detach those resources.
80 public static void detachFromCurrentThread() {
81 XPATH_FACTORY.remove();
84 public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(
85 final StmtContext<?, ?, ?> ctx, final String value) {
86 final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
88 // to detect if key contains duplicates
89 if (new HashSet<>(keyTokens).size() < keyTokens.size()) {
90 // FIXME: report all duplicate keys
91 throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
94 final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
95 for (final String keyToken : keyTokens) {
96 keyNodes.add(SchemaNodeIdentifier.SAME.createChild(StmtContextUtils.qnameFromArgument(ctx, keyToken)));
102 private static String trimSingleLastSlashFromXPath(final String path) {
103 return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
106 public static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
107 final XPath xPath = XPATH_FACTORY.get().newXPath();
108 xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
109 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
111 final String trimmed = trimSingleLastSlashFromXPath(path);
113 // XPath extension functions have to be prefixed
114 // yang-specific XPath functions are in fact extended functions, therefore we have to add
115 // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
116 // the "yang" prefix is bound to RFC6020 YANG namespace
117 final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
118 // TODO: we could capture the result and expose its 'evaluate' method
119 xPath.compile(prefixedXPath);
120 } catch (final XPathExpressionException e) {
121 LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
124 return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
127 private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
128 if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
129 // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
130 // Matcher.appendTail() will accept StringBuilder parameter in Java 9
131 final StringBuffer result = new StringBuffer();
132 final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
133 final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
134 while (matcher.find()) {
135 matcher.appendReplacement(result, prefix + matcher.group());
138 matcher.appendTail(result);
139 return result.toString();
145 public static QName trimPrefix(final QName identifier) {
146 final String prefixedLocalName = identifier.getLocalName();
147 final String[] namesParts = prefixedLocalName.split(":");
149 if (namesParts.length == 2) {
150 final String localName = namesParts[1];
151 return QName.create(identifier.getModule(), localName);
157 public static String trimPrefix(final String identifier) {
158 final List<String> namesParts = COLON_SPLITTER.splitToList(identifier);
159 if (namesParts.size() == 2) {
160 return namesParts.get(1);
165 @SuppressWarnings("checkstyle:illegalCatch")
166 public static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
167 // FIXME: is the path trimming really necessary??
168 final List<QName> qNames = new ArrayList<>();
169 for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
171 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
173 } catch (final RuntimeException e) {
174 throw new SourceException(ctx.getStatementSourceReference(), e,
175 "Failed to parse node '%s' in path '%s'", nodeName, path);
179 return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
182 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
183 final StatementSourceReference ref) {
184 return stringFromStringContext(context, YangVersion.VERSION_1, ref);
187 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
188 final YangVersion yangVersion, final StatementSourceReference ref) {
189 final StringBuilder sb = new StringBuilder();
190 List<TerminalNode> strings = context.STRING();
191 if (strings.isEmpty()) {
192 strings = Collections.singletonList(context.IDENTIFIER());
194 for (final TerminalNode stringNode : strings) {
195 final String str = stringNode.getText();
196 final char firstChar = str.charAt(0);
197 final char lastChar = str.charAt(str.length() - 1);
198 if (firstChar == '"' && lastChar == '"') {
199 final String innerStr = str.substring(1, str.length() - 1);
201 * Unescape escaped double quotes, tabs, new line and backslash
202 * in the inner string and trim the result.
204 checkDoubleQuotedString(innerStr, yangVersion, ref);
205 sb.append(ESCAPED_TAB.matcher(
207 ESCAPED_BACKSLASH.matcher(
208 ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
211 .replaceAll("\\\t"));
212 } else if (firstChar == '\'' && lastChar == '\'') {
214 * According to RFC6020 a single quote character cannot occur in
215 * a single-quoted string, even when preceded by a backslash.
217 sb.append(str.substring(1, str.length() - 1));
219 checkUnquotedString(str, yangVersion, ref);
223 return sb.toString();
226 private static void checkUnquotedString(final String str, final YangVersion yangVersion,
227 final StatementSourceReference ref) {
228 if (yangVersion == YangVersion.VERSION_1_1) {
229 SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
230 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
234 private static void checkDoubleQuotedString(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() - 1; i++) {
238 if (str.charAt(i) == '\\') {
239 switch (str.charAt(i + 1)) {
247 throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
248 + "quoted string the backslash must be followed by one of the following character "
249 + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
257 public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
258 final SchemaNodeIdentifier node) {
259 return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
263 public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
264 if ("true".equals(input)) {
266 } else if ("false".equals(input)) {
267 return Boolean.FALSE;
269 throw new SourceException(ctx.getStatementSourceReference(),
270 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
271 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
275 public static String internBoolean(final String input) {
276 if ("true".equals(input)) {
278 } else if ("false".equals(input)) {
286 * Replaces illegal characters of QName by the name of the character (e.g. '?' is replaced by "QuestionMark" etc.).
290 * @return result String
292 public static String replaceIllegalCharsForQName(String string) {
293 string = LEFT_PARENTHESIS_MATCHER.replaceFrom(string, "LeftParenthesis");
294 string = RIGHT_PARENTHESIS_MATCHER.replaceFrom(string, "RightParenthesis");
295 string = AMPERSAND_MATCHER.replaceFrom(string, "Ampersand");
296 string = QUESTION_MARK_MATCHER.replaceFrom(string, "QuestionMark");
301 public static boolean belongsToTheSameModule(final QName targetStmtQName, final QName sourceStmtQName) {
302 return targetStmtQName.getModule().equals(sourceStmtQName.getModule());