Remove Utils.transformKeysStringToKeyNodes()
[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.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;
41
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 Splitter COLON_SPLITTER = Splitter.on(":").omitEmptyStrings().trimResults();
47     private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
48     @RegEx
49     private static final String YANG_XPATH_FUNCTIONS_STRING =
50             "(re-match|deref|derived-from(-or-self)?|enum-value|bit-is-set)([ \t\r\n]*)(\\()";
51     private static final Pattern YANG_XPATH_FUNCTIONS_PATTERN = Pattern.compile(YANG_XPATH_FUNCTIONS_STRING);
52     private static final Pattern ESCAPED_DQUOT = Pattern.compile("\\\"", Pattern.LITERAL);
53     private static final Pattern ESCAPED_BACKSLASH = Pattern.compile("\\\\", Pattern.LITERAL);
54     private static final Pattern ESCAPED_LF = Pattern.compile("\\n", Pattern.LITERAL);
55     private static final Pattern ESCAPED_TAB = Pattern.compile("\\t", Pattern.LITERAL);
56
57     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
58         @Override
59         protected XPathFactory initialValue() {
60             return XPathFactory.newInstance();
61         }
62     };
63
64     private Utils() {
65         throw new UnsupportedOperationException();
66     }
67
68     /**
69      * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
70      * caches to them. Invoke this method if you want to detach those resources.
71      */
72     public static void detachFromCurrentThread() {
73         XPATH_FACTORY.remove();
74     }
75
76     private static String trimSingleLastSlashFromXPath(final String path) {
77         return path.endsWith("/") ? path.substring(0, path.length() - 1) : path;
78     }
79
80     public static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
81         final XPath xPath = XPATH_FACTORY.get().newXPath();
82         xPath.setNamespaceContext(StmtNamespaceContext.create(ctx,
83                 ImmutableBiMap.of(RFC6020_YANG_NAMESPACE.toString(), YANG_XPATH_FUNCTIONS_PREFIX)));
84
85         final String trimmed = trimSingleLastSlashFromXPath(path);
86         try {
87             // XPath extension functions have to be prefixed
88             // yang-specific XPath functions are in fact extended functions, therefore we have to add
89             // "yang" prefix to them so that they can be properly validated with the XPath.compile() method
90             // the "yang" prefix is bound to RFC6020 YANG namespace
91             final String prefixedXPath = addPrefixToYangXPathFunctions(trimmed, ctx);
92             // TODO: we could capture the result and expose its 'evaluate' method
93             xPath.compile(prefixedXPath);
94         } catch (final XPathExpressionException e) {
95             LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
96         }
97
98         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
99     }
100
101     private static String addPrefixToYangXPathFunctions(final String path, final StmtContext<?, ?, ?> ctx) {
102         if (ctx.getRootVersion() == YangVersion.VERSION_1_1) {
103             // FIXME once Java 9 is available, change this to StringBuilder as Matcher.appendReplacement() and
104             // Matcher.appendTail() will accept StringBuilder parameter in Java 9
105             final StringBuffer result = new StringBuffer();
106             final String prefix = YANG_XPATH_FUNCTIONS_PREFIX + ":";
107             final Matcher matcher = YANG_XPATH_FUNCTIONS_PATTERN.matcher(path);
108             while (matcher.find()) {
109                 matcher.appendReplacement(result, prefix + matcher.group());
110             }
111
112             matcher.appendTail(result);
113             return result.toString();
114         }
115
116         return path;
117     }
118
119     public static String trimPrefix(final String identifier) {
120         final List<String> namesParts = COLON_SPLITTER.splitToList(identifier);
121         if (namesParts.size() == 2) {
122             return namesParts.get(1);
123         }
124         return identifier;
125     }
126
127     @SuppressWarnings("checkstyle:illegalCatch")
128     public static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
129         // FIXME: is the path trimming really necessary??
130         final List<QName> qNames = new ArrayList<>();
131         for (final String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
132             try {
133                 final QName qName = StmtContextUtils.qnameFromArgument(ctx, nodeName);
134                 qNames.add(qName);
135             } catch (final RuntimeException e) {
136                 throw new SourceException(ctx.getStatementSourceReference(), e,
137                         "Failed to parse node '%s' in path '%s'", nodeName, path);
138             }
139         }
140
141         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
142     }
143
144     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
145             final StatementSourceReference ref) {
146         return stringFromStringContext(context, YangVersion.VERSION_1, ref);
147     }
148
149     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context,
150             final YangVersion yangVersion, final StatementSourceReference ref) {
151         final StringBuilder sb = new StringBuilder();
152         List<TerminalNode> strings = context.STRING();
153         if (strings.isEmpty()) {
154             strings = Collections.singletonList(context.IDENTIFIER());
155         }
156         for (final TerminalNode stringNode : strings) {
157             final String str = stringNode.getText();
158             final char firstChar = str.charAt(0);
159             final char lastChar = str.charAt(str.length() - 1);
160             if (firstChar == '"' && lastChar == '"') {
161                 final String innerStr = str.substring(1, str.length() - 1);
162                 /*
163                  * Unescape escaped double quotes, tabs, new line and backslash
164                  * in the inner string and trim the result.
165                  */
166                 checkDoubleQuotedString(innerStr, yangVersion, ref);
167                 sb.append(ESCAPED_TAB.matcher(
168                     ESCAPED_LF.matcher(
169                         ESCAPED_BACKSLASH.matcher(
170                             ESCAPED_DQUOT.matcher(innerStr).replaceAll("\\\""))
171                         .replaceAll("\\\\"))
172                     .replaceAll("\\\n"))
173                     .replaceAll("\\\t"));
174             } else if (firstChar == '\'' && lastChar == '\'') {
175                 /*
176                  * According to RFC6020 a single quote character cannot occur in
177                  * a single-quoted string, even when preceded by a backslash.
178                  */
179                 sb.append(str.substring(1, str.length() - 1));
180             } else {
181                 checkUnquotedString(str, yangVersion, ref);
182                 sb.append(str);
183             }
184         }
185         return sb.toString();
186     }
187
188     private static void checkUnquotedString(final String str, final YangVersion yangVersion,
189             final StatementSourceReference ref) {
190         if (yangVersion == YangVersion.VERSION_1_1) {
191             SourceException.throwIf(ANYQUOTE_MATCHER.matchesAnyOf(str), ref,
192                 "YANG 1.1: unquoted string (%s) contains illegal characters", str);
193         }
194     }
195
196     private static void checkDoubleQuotedString(final String str, final YangVersion yangVersion,
197             final StatementSourceReference ref) {
198         if (yangVersion == YangVersion.VERSION_1_1) {
199             for (int i = 0; i < str.length() - 1; i++) {
200                 if (str.charAt(i) == '\\') {
201                     switch (str.charAt(i + 1)) {
202                         case 'n':
203                         case 't':
204                         case '\\':
205                         case '\"':
206                             i++;
207                             break;
208                         default:
209                             throw new SourceException(ref, "YANG 1.1: illegal double quoted string (%s). In double "
210                                     + "quoted string the backslash must be followed by one of the following character "
211                                     + "[n,t,\",\\], but was '%s'.", str, str.charAt(i + 1));
212                     }
213                 }
214             }
215         }
216     }
217
218     @Nullable
219     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
220             final SchemaNodeIdentifier node) {
221         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class,
222             node);
223     }
224
225     public static @Nonnull Boolean parseBoolean(final StmtContext<?, ?, ?> ctx, final String input) {
226         if ("true".equals(input)) {
227             return Boolean.TRUE;
228         } else if ("false".equals(input)) {
229             return Boolean.FALSE;
230         } else {
231             throw new SourceException(ctx.getStatementSourceReference(),
232                 "Invalid '%s' statement %s '%s', it can be either 'true' or 'false'",
233                 ctx.getPublicDefinition().getStatementName(), ctx.getPublicDefinition().getArgumentName(), input);
234         }
235     }
236
237     public static String internBoolean(final String input) {
238         if ("true".equals(input)) {
239             return "true";
240         } else if ("false".equals(input)) {
241             return "false";
242         } else {
243             return input;
244         }
245     }
246 }