80f695680c20acec1f959ddb09478b6843f7a805
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / stmt / rfc6020 / Utils.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.parser.stmt.rfc6020;
9
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;
12
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;
21 import java.util.Set;
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;
44
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("/[^/].*");
52     @RegEx
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);
60
61     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
62         @Override
63         protected XPathFactory initialValue() {
64             return XPathFactory.newInstance();
65         }
66     };
67
68     private Utils() {
69         throw new UnsupportedOperationException();
70     }
71
72     /**
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.
75      */
76     public static void detachFromCurrentThread() {
77         XPATH_FACTORY.remove();
78     }
79
80     public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(
81             final StmtContext<?, ?, ?> ctx, final String value) {
82         final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
83
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);
88         }
89
90         final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
91         for (final String keyToken : keyTokens) {
92             keyNodes.add(SchemaNodeIdentifier.SAME.createChild(StmtContextUtils.qnameFromArgument(ctx, keyToken)));
93         }
94
95         return keyNodes;
96     }
97
98     private static String trimSingleLastSlashFromXPath(final String path) {
99         return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
100     }
101
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)));
106
107         final String trimmed = trimSingleLastSlashFromXPath(path);
108         try {
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);
118         }
119
120         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
121     }
122
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());
132             }
133
134             matcher.appendTail(result);
135             return result.toString();
136         }
137
138         return path;
139     }
140
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);
145         }
146         return identifier;
147     }
148
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))) {
154             try {
155                 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
156                 qNames.add(qName);
157             } catch (final RuntimeException e) {
158                 throw new SourceException(ctx.getStatementSourceReference(), e,
159                         "Failed to parse node '%s' in path '%s'", nodeName, path);
160             }
161         }
162
163         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
164     }
165
166     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
167             final StatementSourceReference ref) {
168         return stringFromStringContext(context, YangVersion.VERSION_1, ref);
169     }
170
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());
177         }
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);
184                 /*
185                  * Unescape escaped double quotes, tabs, new line and backslash
186                  * in the inner string and trim the result.
187                  */
188                 checkDoubleQuotedString(innerStr, yangVersion, ref);
189                 sb.append(ESCAPED_TAB.matcher(
190                     ESCAPED_LF.matcher(
191                         ESCAPED_BACKSLASH.matcher(
192                             ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
193                         .replaceAll("\\\\"))
194                     .replaceAll("\\\n"))
195                     .replaceAll("\\\t"));
196             } else if (firstChar == '\'' && lastChar == '\'') {
197                 /*
198                  * According to RFC6020 a single quote character cannot occur in
199                  * a single-quoted string, even when preceded by a backslash.
200                  */
201                 sb.append(str.substring(1, str.length() - 1));
202             } else {
203                 checkUnquotedString(str, yangVersion, ref);
204                 sb.append(str);
205             }
206         }
207         return sb.toString();
208     }
209
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);
215         }
216     }
217
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)) {
224                         case 'n':
225                         case 't':
226                         case '\\':
227                         case '\"':
228                             i++;
229                             break;
230                         default:
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));
234                     }
235                 }
236             }
237         }
238     }
239
240     @Nullable
241     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
242             final SchemaNodeIdentifier node) {
243         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
244             node);
245     }
246
247     public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
248         if ("true".equals(input)) {
249             return Boolean.TRUE;
250         } else if ("false".equals(input)) {
251             return Boolean.FALSE;
252         } else {
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);
256         }
257     }
258
259     public static String internBoolean(final String input) {
260         if ("true".equals(input)) {
261             return "true";
262         } else if ("false".equals(input)) {
263             return "false";
264         } else {
265             return input;
266         }
267     }
268 }