BUG-4556: Introduce StmtContext.getSchemaPath()
[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.parser.spi.meta.StmtContextUtils.firstAttributeOf;
11 import com.google.common.base.CharMatcher;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.Iterables;
16 import java.util.ArrayList;
17 import java.util.Arrays;
18 import java.util.Collection;
19 import java.util.Date;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Objects;
23 import java.util.Set;
24 import java.util.regex.Pattern;
25 import javax.annotation.Nullable;
26 import javax.xml.xpath.XPath;
27 import javax.xml.xpath.XPathExpressionException;
28 import javax.xml.xpath.XPathFactory;
29 import org.antlr.v4.runtime.tree.TerminalNode;
30 import org.opendaylight.yangtools.antlrv4.code.gen.YangStatementParser;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.common.QNameModule;
33 import org.opendaylight.yangtools.yang.common.SimpleDateFormatUtil;
34 import org.opendaylight.yangtools.yang.common.YangConstants;
35 import org.opendaylight.yangtools.yang.model.api.Deviation;
36 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
38 import org.opendaylight.yangtools.yang.model.api.Status;
39 import org.opendaylight.yangtools.yang.model.api.stmt.BelongsToStatement;
40 import org.opendaylight.yangtools.yang.model.api.stmt.ModuleStatement;
41 import org.opendaylight.yangtools.yang.model.api.stmt.RevisionStatement;
42 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
43 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Relative;
44 import org.opendaylight.yangtools.yang.model.api.stmt.SubmoduleStatement;
45 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
46 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContext;
47 import org.opendaylight.yangtools.yang.parser.spi.meta.StmtContextUtils;
48 import org.opendaylight.yangtools.yang.parser.spi.source.BelongsToPrefixToModuleName;
49 import org.opendaylight.yangtools.yang.parser.spi.source.ImpPrefixToModuleIdentifier;
50 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleCtxToModuleQName;
51 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleIdentifierToModuleQName;
52 import org.opendaylight.yangtools.yang.parser.spi.source.ModuleNameToModuleQName;
53 import org.opendaylight.yangtools.yang.parser.spi.source.PrefixToModule;
54 import org.opendaylight.yangtools.yang.parser.spi.source.QNameToStatementDefinition;
55 import org.opendaylight.yangtools.yang.parser.stmt.reactor.RootStatementContext;
56 import org.opendaylight.yangtools.yang.parser.stmt.reactor.StatementContextBase;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 public final class Utils {
61     private static final Logger LOG = LoggerFactory.getLogger(Utils.class);
62     private static final CharMatcher DOUBLE_QUOTE_MATCHER = CharMatcher.is('"');
63     private static final CharMatcher SINGLE_QUOTE_MATCHER = CharMatcher.is('\'');
64     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings().trimResults();
65     private static final Splitter SPACE_SPLITTER = Splitter.on(' ').omitEmptyStrings().trimResults();
66     private static final Pattern PATH_ABS = Pattern.compile("/[^/].*");
67
68     private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
69         @Override
70         protected XPathFactory initialValue() {
71             return XPathFactory.newInstance();
72         }
73     };
74
75     private Utils() {
76         throw new UnsupportedOperationException();
77     }
78
79     /**
80      * Cleanup any resources attached to the current thread. Threads interacting with this class can cause thread-local
81      * caches to them. Invoke this method if you want to detach those resources.
82      */
83     public static void detachFromCurrentThread() {
84         XPATH_FACTORY.remove();
85     }
86
87     public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(final StmtContext<?, ?, ?> ctx,
88             final String value) {
89         List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
90
91         // to detect if key contains duplicates
92         if ((new HashSet<>(keyTokens)).size() < keyTokens.size()) {
93             // FIXME: report all duplicate keys
94             throw new IllegalArgumentException();
95         }
96
97         Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
98
99         for (String keyToken : keyTokens) {
100
101             SchemaNodeIdentifier.Relative keyNode = (Relative) SchemaNodeIdentifier.Relative.create(false,
102                     Utils.qNameFromArgument(ctx, keyToken));
103             keyNodes.add(keyNode);
104         }
105
106         return keyNodes;
107     }
108
109     private static String trimSingleLastSlashFromXPath(final String path) {
110         return path.replaceAll("/$", "");
111     }
112
113     static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
114         final XPath xPath = XPATH_FACTORY.get().newXPath();
115         xPath.setNamespaceContext(StmtNamespaceContext.create(ctx));
116
117         final String trimmed = trimSingleLastSlashFromXPath(path);
118         try {
119             // TODO: we could capture the result and expose its 'evaluate' method
120             xPath.compile(trimmed);
121         } catch (XPathExpressionException e) {
122             LOG.warn("Argument \"{}\" is not valid XPath string at \"{}\"", path, ctx.getStatementSourceReference(), e);
123         }
124
125         return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
126     }
127
128     public static QName trimPrefix(final QName identifier) {
129         String prefixedLocalName = identifier.getLocalName();
130         String[] namesParts = prefixedLocalName.split(":");
131
132         if (namesParts.length == 2) {
133             String localName = namesParts[1];
134             return QName.create(identifier.getModule(), localName);
135         }
136
137         return identifier;
138     }
139
140     public static String getPrefixFromArgument(final String prefixedLocalName) {
141         String[] namesParts = prefixedLocalName.split(":");
142         if (namesParts.length == 2) {
143             return namesParts[0];
144         }
145         return null;
146     }
147
148     public static boolean isValidStatementDefinition(final PrefixToModule prefixes, final QNameToStatementDefinition stmtDef,
149             final QName identifier) {
150         if (stmtDef.get(identifier) != null) {
151             return true;
152         } else {
153             String prefixedLocalName = identifier.getLocalName();
154             String[] namesParts = prefixedLocalName.split(":");
155
156             if (namesParts.length == 2) {
157                 String prefix = namesParts[0];
158                 String localName = namesParts[1];
159                 if (prefixes != null && prefixes.get(prefix) != null
160                         && stmtDef.get(QName.create(YangConstants.RFC6020_YIN_MODULE, localName)) != null) {
161                     return true;
162                 } else {
163                     if (stmtDef.get(QName.create(YangConstants.RFC6020_YIN_MODULE, localName)) != null) {
164                         return true;
165                     }
166                 }
167             }
168         }
169         return false;
170     }
171
172     static SchemaNodeIdentifier nodeIdentifierFromPath(final StmtContext<?, ?, ?> ctx, final String path) {
173         // FIXME: is the path trimming really necessary??
174         final List<QName> qNames = new ArrayList<>();
175         for (String nodeName : SLASH_SPLITTER.split(trimSingleLastSlashFromXPath(path))) {
176             try {
177                 final QName qName = Utils.qNameFromArgument(ctx, nodeName);
178                 qNames.add(qName);
179             } catch (Exception e) {
180                 throw new IllegalArgumentException(
181                     String.format("Failed to parse node '%s' in path '%s'", nodeName, path), e);
182             }
183         }
184
185         return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
186     }
187
188     public static String stringFromStringContext(final YangStatementParser.ArgumentContext context) {
189         StringBuilder sb = new StringBuilder();
190         List<TerminalNode> strings = context.STRING();
191         if (strings.isEmpty()) {
192             strings = Arrays.asList(context.IDENTIFIER());
193         }
194         for (TerminalNode stringNode : strings) {
195             final String str = stringNode.getText();
196             char firstChar = str.charAt(0);
197             final CharMatcher quoteMatcher;
198             if (SINGLE_QUOTE_MATCHER.matches(firstChar)) {
199                 quoteMatcher = SINGLE_QUOTE_MATCHER;
200             } else if (DOUBLE_QUOTE_MATCHER.matches(firstChar)) {
201                 quoteMatcher = DOUBLE_QUOTE_MATCHER;
202             } else {
203                 sb.append(str);
204                 continue;
205             }
206             sb.append(quoteMatcher.removeFrom(str.substring(1, str.length() - 1)));
207         }
208         return sb.toString();
209     }
210
211     public static QName qNameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
212         if (Strings.isNullOrEmpty(value)) {
213             return ctx.getPublicDefinition().getStatementName();
214         }
215
216         String prefix;
217         QNameModule qNameModule = null;
218         String localName = null;
219
220         String[] namesParts = value.split(":");
221         switch (namesParts.length) {
222         case 1:
223             localName = namesParts[0];
224             qNameModule = getRootModuleQName(ctx);
225             break;
226         default:
227             prefix = namesParts[0];
228             localName = namesParts[1];
229             qNameModule = getModuleQNameByPrefix(ctx, prefix);
230             // in case of unknown statement argument, we're not going to parse it
231             if (qNameModule == null
232                     && ctx.getPublicDefinition().getDeclaredRepresentationClass()
233                     .isAssignableFrom(UnknownStatementImpl.class)) {
234                 localName = value;
235                 qNameModule = getRootModuleQName(ctx);
236             }
237             if (qNameModule == null
238                     && Iterables.getLast(ctx.getCopyHistory()) == StmtContext.TypeOfCopy.ADDED_BY_AUGMENTATION) {
239                 ctx = ctx.getOriginalCtx();
240                 qNameModule = getModuleQNameByPrefix(ctx, prefix);
241             }
242             break;
243         }
244
245         Preconditions.checkArgument(qNameModule != null, "Error in module '%s': can not resolve QNameModule for '%s'.",
246                 ctx.getRoot().rawStatementArgument(), value);
247
248         QNameModule resultQNameModule = qNameModule.getRevision() == null ? QNameModule.create(
249                 qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV) : qNameModule;
250
251         return QName.create(resultQNameModule, localName);
252     }
253
254     public static QNameModule getModuleQNameByPrefix(final StmtContext<?, ?, ?> ctx, final String prefix) {
255         QNameModule qNameModule;
256         ModuleIdentifier impModIdentifier = ctx.getRoot().getFromNamespace(ImpPrefixToModuleIdentifier.class, prefix);
257         qNameModule = ctx.getFromNamespace(ModuleIdentifierToModuleQName.class, impModIdentifier);
258
259         if (qNameModule == null && StmtContextUtils.producesDeclared(ctx.getRoot(), SubmoduleStatement.class)) {
260             String moduleName = ctx.getRoot().getFromNamespace(BelongsToPrefixToModuleName.class, prefix);
261             qNameModule = ctx.getFromNamespace(ModuleNameToModuleQName.class, moduleName);
262         }
263         return qNameModule;
264     }
265
266     public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
267
268         if (ctx == null) {
269             return null;
270         }
271
272         StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
273         QNameModule qNameModule = null;
274
275         if (StmtContextUtils.producesDeclared(rootCtx, ModuleStatement.class)) {
276             qNameModule = rootCtx.getFromNamespace(ModuleCtxToModuleQName.class, rootCtx);
277         } else if (StmtContextUtils.producesDeclared(rootCtx, SubmoduleStatement.class)) {
278             String belongsToModuleName = firstAttributeOf(rootCtx.substatements(),
279                     BelongsToStatement.class);
280             qNameModule = rootCtx.getFromNamespace(ModuleNameToModuleQName.class, belongsToModuleName);
281         }
282
283         return qNameModule.getRevision() == null ? QNameModule.create(qNameModule.getNamespace(),
284                 SimpleDateFormatUtil.DEFAULT_DATE_REV) : qNameModule;
285     }
286
287     @Nullable
288     public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
289             final SchemaNodeIdentifier node) {
290         return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class, node);
291     }
292
293     public static boolean isUnknownNode(final StmtContext<?, ?, ?> stmtCtx) {
294         return stmtCtx.getPublicDefinition().getDeclaredRepresentationClass()
295                 .isAssignableFrom(UnknownStatementImpl.class);
296     }
297
298     public static Deviation.Deviate parseDeviateFromString(final String deviate) {
299
300         // Yang constants should be lowercase so we have throw if value does not
301         // suit this
302         String deviateUpper = deviate.toUpperCase();
303         Preconditions.checkArgument(!Objects.equals(deviate, deviateUpper),
304             "String %s is not valid deviate argument", deviate);
305
306         // but Java enum is uppercase so we cannot use lowercase here
307         try {
308             return Deviation.Deviate.valueOf(deviateUpper);
309         } catch (IllegalArgumentException e) {
310             throw new IllegalArgumentException(String.format("String %s is not valid deviate argument", deviate), e);
311         }
312     }
313
314     public static Status parseStatus(final String value) {
315
316         Status status = null;
317         switch (value) {
318         case "current":
319             status = Status.CURRENT;
320             break;
321         case "deprecated":
322             status = Status.DEPRECATED;
323             break;
324         case "obsolete":
325             status = Status.OBSOLETE;
326             break;
327         default:
328             LOG.warn("Invalid 'status' statement: " + value);
329         }
330
331         return status;
332     }
333
334     public static Date getLatestRevision(final RootStatementContext<?, ?, ?> root) {
335         return getLatestRevision(root.declaredSubstatements());
336     }
337
338     public static Date getLatestRevision(final Iterable<? extends StmtContext<?, ?, ?>> subStmts) {
339         Date revision = null;
340         for (StmtContext<?, ?, ?> subStmt : subStmts) {
341             if (subStmt.getPublicDefinition().getDeclaredRepresentationClass().isAssignableFrom(RevisionStatement
342                     .class)) {
343                 if (revision == null && subStmt.getStatementArgument() != null) {
344                     revision = (Date) subStmt.getStatementArgument();
345                 } else if (subStmt.getStatementArgument() != null && ((Date) subStmt.getStatementArgument()).compareTo
346                         (revision) > 0) {
347                     revision = (Date) subStmt.getStatementArgument();
348                 }
349             }
350         }
351         return revision;
352     }
353
354     public static boolean isModuleIdentifierWithoutSpecifiedRevision(final Object o) {
355         return (o instanceof ModuleIdentifier)
356                 && (((ModuleIdentifier) o).getRevision() == SimpleDateFormatUtil.DEFAULT_DATE_IMP ||
357                         ((ModuleIdentifier) o).getRevision() == SimpleDateFormatUtil.DEFAULT_BELONGS_TO_DATE);
358     }
359 }