de75763e0c7af8dfd4ce6216e03cebf16f6859ce
[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 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("/[^/].*");
56     @RegEx
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);
64
65     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
66         @Override
67         protected XPathFactory initialValue() {
68             return XPathFactory.newInstance();
69         }
70     };
71
72     private Utils() {
73         throw new UnsupportedOperationException();
74     }
75
76     /**
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.
79      */
80     public static void detachFromCurrentThread() {
81         XPATH_FACTORY.remove();
82     }
83
84     public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(
85             final StmtContext<?, ?, ?> ctx, final String value) {
86         final List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
87
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);
92         }
93
94         final Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
95         for (final String keyToken : keyTokens) {
96             keyNodes.add(SchemaNodeIdentifier.SAME.createChild(StmtContextUtils.qnameFromArgument(ctx, keyToken)));
97         }
98
99         return keyNodes;
100     }
101
102     private static String trimSingleLastSlashFromXPath(final String path) {
103         return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
104     }
105
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)));
110
111         final String trimmed = trimSingleLastSlashFromXPath(path);
112         try {
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);
122         }
123
124         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
125     }
126
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());
136             }
137
138             matcher.appendTail(result);
139             return result.toString();
140         }
141
142         return path;
143     }
144
145     public static QName trimPrefix(final QName identifier) {
146         final String prefixedLocalName = identifier.getLocalName();
147         final String[] namesParts = prefixedLocalName.split(":");
148
149         if (namesParts.length == 2) {
150             final String localName = namesParts[1];
151             return QName.create(identifier.getModule(), localName);
152         }
153
154         return identifier;
155     }
156
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);
161         }
162         return identifier;
163     }
164
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))) {
170             try {
171                 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
172                 qNames.add(qName);
173             } catch (final RuntimeException e) {
174                 throw new SourceException(ctx.getStatementSourceReference(), e,
175                         "Failed to parse node '%s' in path '%s'", nodeName, path);
176             }
177         }
178
179         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
180     }
181
182     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
183             final StatementSourceReference ref) {
184         return stringFromStringContext(context, YangVersion.VERSION_1, ref);
185     }
186
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());
193         }
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);
200                 /*
201                  * Unescape escaped double quotes, tabs, new line and backslash
202                  * in the inner string and trim the result.
203                  */
204                 checkDoubleQuotedString(innerStr, yangVersion, ref);
205                 sb.append(ESCAPED_TAB.matcher(
206                     ESCAPED_LF.matcher(
207                         ESCAPED_BACKSLASH.matcher(
208                             ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
209                         .replaceAll("\\\\"))
210                     .replaceAll("\\\n"))
211                     .replaceAll("\\\t"));
212             } else if (firstChar == '\'' && lastChar == '\'') {
213                 /*
214                  * According to RFC6020 a single quote character cannot occur in
215                  * a single-quoted string, even when preceded by a backslash.
216                  */
217                 sb.append(str.substring(1, str.length() - 1));
218             } else {
219                 checkUnquotedString(str, yangVersion, ref);
220                 sb.append(str);
221             }
222         }
223         return sb.toString();
224     }
225
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);
231         }
232     }
233
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)) {
240                         case 'n':
241                         case 't':
242                         case '\\':
243                         case '\"':
244                             i++;
245                             break;
246                         default:
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));
250                     }
251                 }
252             }
253         }
254     }
255
256     @Nullable
257     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
258             final SchemaNodeIdentifier node) {
259         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
260             node);
261     }
262
263     public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
264         if ("true".equals(input)) {
265             return Boolean.TRUE;
266         } else if ("false".equals(input)) {
267             return Boolean.FALSE;
268         } else {
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);
272         }
273     }
274
275     public static String internBoolean(final String input) {
276         if ("true".equals(input)) {
277             return "true";
278         } else if ("false".equals(input)) {
279             return "false";
280         } else {
281             return input;
282         }
283     }
284
285     /**
286      * Replaces illegal characters of QName by the name of the character (e.g. '?' is replaced by "QuestionMark" etc.).
287      *
288      * @param string
289      *            input String
290      * @return result String
291      */
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");
297
298         return string;
299     }
300
301     public static boolean belongsToTheSameModule(final QName targetStmtQName, final QName sourceStmtQName) {
302         return targetStmtQName.getModule().equals(sourceStmtQName.getModule());
303     }
304 }