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 ANYQUOTE_MATCHER = CharMatcher.anyOf("'\"");
48 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
49 private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
50 private static final Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
51 private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
53 private static final String YANG_XPATH_FUNCTIONS_STRING =
54 "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)([ \t\r\n]*)(\\()";
55 private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
56 private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
57 private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
58 private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
59 private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
61 private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
63 protected XPathFactory initialValue() {
64 return XPathFactory.newInstance();
69 throw new UnsupportedOperationException();
73 * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
74 * caches to them. Invoke this method if you want to detach those resources.
76 public static void detachFromCurrentThread() {
77 XPATH_FACTORY.remove();
80 public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(
81 final StmtContext<?, ?, ?> ctx, final String value) {
82 final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
84 // to detect if key contains duplicates
85 if (new HashSet<>(keyTokens).size() < keyTokens.size()) {
86 // FIXME: report all duplicate keys
87 throw new SourceException(ctx.getStatementSourceReference(), "Duplicate value in list key: %s", value);
90 final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
91 for (final String keyToken : keyTokens) {
92 keyNodes.add(SchemaNodeIdentifier.SAME.createChild(StmtContextUtils.qnameFromArgument(ctx, keyToken)));
98 private static String trimSingleLastSlashFromXPath(final String path) {
99 return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
102 public static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
103 final XPath xPath = XPATH_FACTORY.get().newXPath();
104 xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
105 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
107 final String trimmed = trimSingleLastSlashFromXPath(path);
109 // XPath extension functions have to be prefixed
110 // yang-specific XPath functions are in fact extended functions, therefore we have to add
111 // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
112 // the "yang" prefix is bound to RFC6020 YANG namespace
113 final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
114 // TODO: we could capture the result and expose its 'evaluate' method
115 xPath.compile(prefixedXPath);
116 } catch (final XPathExpressionException e) {
117 LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
120 return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
123 private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
124 if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
125 // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
126 // Matcher.appendTail() will accept StringBuilder parameter in Java 9
127 final StringBuffer result = new StringBuffer();
128 final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
129 final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
130 while (matcher.find()) {
131 matcher.appendReplacement(result, prefix + matcher.group());
134 matcher.appendTail(result);
135 return result.toString();
141 public static String trimPrefix(final String identifier) {
142 final List<String> namesParts = COLON_SPLITTER.splitToList(identifier);
143 if (namesParts.size() == 2) {
144 return namesParts.get(1);
149 @SuppressWarnings("checkstyle:illegalCatch")
150 public static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
151 // FIXME: is the path trimming really necessary??
152 final List<QName> qNames = new ArrayList<>();
153 for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
155 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
157 } catch (final RuntimeException e) {
158 throw new SourceException(ctx.getStatementSourceReference(), e,
159 "Failed to parse node '%s' in path '%s'", nodeName, path);
163 return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
166 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
167 final StatementSourceReference ref) {
168 return stringFromStringContext(context, YangVersion.VERSION_1, ref);
171 public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
172 final YangVersion yangVersion, final StatementSourceReference ref) {
173 final StringBuilder sb = new StringBuilder();
174 List<TerminalNode> strings = context.STRING();
175 if (strings.isEmpty()) {
176 strings = Collections.singletonList(context.IDENTIFIER());
178 for (final TerminalNode stringNode : strings) {
179 final String str = stringNode.getText();
180 final char firstChar = str.charAt(0);
181 final char lastChar = str.charAt(str.length() - 1);
182 if (firstChar == '"' && lastChar == '"') {
183 final String innerStr = str.substring(1, str.length() - 1);
185 * Unescape escaped double quotes, tabs, new line and backslash
186 * in the inner string and trim the result.
188 checkDoubleQuotedString(innerStr, yangVersion, ref);
189 sb.append(ESCAPED_TAB.matcher(
191 ESCAPED_BACKSLASH.matcher(
192 ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
195 .replaceAll("\\\t"));
196 } else if (firstChar == '\'' && lastChar == '\'') {
198 * According to RFC6020 a single quote character cannot occur in
199 * a single-quoted string, even when preceded by a backslash.
201 sb.append(str.substring(1, str.length() - 1));
203 checkUnquotedString(str, yangVersion, ref);
207 return sb.toString();
210 private static void checkUnquotedString(final String str, final YangVersion yangVersion,
211 final StatementSourceReference ref) {
212 if (yangVersion == YangVersion.VERSION_1_1) {
213 SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
214 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
218 private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
219 final StatementSourceReference ref) {
220 if (yangVersion == YangVersion.VERSION_1_1) {
221 for (int i = 0; i < str.length() - 1; i++) {
222 if (str.charAt(i) == '\\') {
223 switch (str.charAt(i + 1)) {
231 throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
232 + "quoted string the backslash must be followed by one of the following character "
233 + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
241 public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
242 final SchemaNodeIdentifier node) {
243 return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
247 public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
248 if ("true".equals(input)) {
250 } else if ("false".equals(input)) {
251 return Boolean.FALSE;
253 throw new SourceException(ctx.getStatementSourceReference(),
254 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
255 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
259 public static String internBoolean(final String input) {
260 if ("true".equals(input)) {
262 } else if ("false".equals(input)) {