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.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;
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;
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("/[^/].*");
68 private static final ThreadLocal<XPathFactory> XPATH_FACTORY = new ThreadLocal<XPathFactory>() {
70 protected XPathFactory initialValue() {
71 return XPathFactory.newInstance();
76 throw new UnsupportedOperationException();
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.
83 public static void detachFromCurrentThread() {
84 XPATH_FACTORY.remove();
87 public static Collection<SchemaNodeIdentifier.Relative> transformKeysStringToKeyNodes(final StmtContext<?, ?, ?> ctx,
89 List<String> keyTokens = SPACE_SPLITTER.splitToList(value);
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();
97 Set<SchemaNodeIdentifier.Relative> keyNodes = new HashSet<>();
99 for (String keyToken : keyTokens) {
101 SchemaNodeIdentifier.Relative keyNode = (Relative) SchemaNodeIdentifier.Relative.create(false,
102 Utils.qNameFromArgument(ctx, keyToken));
103 keyNodes.add(keyNode);
109 private static String trimSingleLastSlashFromXPath(final String path) {
110 return path.replaceAll("/$", "");
113 static RevisionAwareXPath parseXPath(final StmtContext<?, ?, ?> ctx, final String path) {
114 final XPath xPath = XPATH_FACTORY.get().newXPath();
115 xPath.setNamespaceContext(StmtNamespaceContext.create(ctx));
117 final String trimmed = trimSingleLastSlashFromXPath(path);
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);
125 return new RevisionAwareXPathImpl(path, PATH_ABS.matcher(path).matches());
128 public static QName trimPrefix(final QName identifier) {
129 String prefixedLocalName = identifier.getLocalName();
130 String[] namesParts = prefixedLocalName.split(":");
132 if (namesParts.length == 2) {
133 String localName = namesParts[1];
134 return QName.create(identifier.getModule(), localName);
140 public static String getPrefixFromArgument(final String prefixedLocalName) {
141 String[] namesParts = prefixedLocalName.split(":");
142 if (namesParts.length == 2) {
143 return namesParts[0];
148 public static boolean isValidStatementDefinition(final PrefixToModule prefixes, final QNameToStatementDefinition stmtDef,
149 final QName identifier) {
150 if (stmtDef.get(identifier) != null) {
153 String prefixedLocalName = identifier.getLocalName();
154 String[] namesParts = prefixedLocalName.split(":");
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) {
163 if (stmtDef.get(QName.create(YangConstants.RFC6020_YIN_MODULE, localName)) != null) {
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))) {
177 final QName qName = Utils.qNameFromArgument(ctx, nodeName);
179 } catch (Exception e) {
180 throw new IllegalArgumentException(
181 String.format("Failed to parse node '%s' in path '%s'", nodeName, path), e);
185 return SchemaNodeIdentifier.create(qNames, PATH_ABS.matcher(path).matches());
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());
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;
206 sb.append(quoteMatcher.removeFrom(str.substring(1, str.length() - 1)));
208 return sb.toString();
211 public static QName qNameFromArgument(StmtContext<?, ?, ?> ctx, final String value) {
212 if (Strings.isNullOrEmpty(value)) {
213 return ctx.getPublicDefinition().getStatementName();
217 QNameModule qNameModule = null;
218 String localName = null;
220 String[] namesParts = value.split(":");
221 switch (namesParts.length) {
223 localName = namesParts[0];
224 qNameModule = getRootModuleQName(ctx);
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)) {
235 qNameModule = getRootModuleQName(ctx);
237 if (qNameModule == null
238 && Iterables.getLast(ctx.getCopyHistory()) == StmtContext.TypeOfCopy.ADDED_BY_AUGMENTATION) {
239 ctx = ctx.getOriginalCtx();
240 qNameModule = getModuleQNameByPrefix(ctx, prefix);
245 Preconditions.checkArgument(qNameModule != null, "Error in module '%s': can not resolve QNameModule for '%s'.",
246 ctx.getRoot().rawStatementArgument(), value);
248 QNameModule resultQNameModule = qNameModule.getRevision() == null ? QNameModule.create(
249 qNameModule.getNamespace(), SimpleDateFormatUtil.DEFAULT_DATE_REV) : qNameModule;
251 return QName.create(resultQNameModule, localName);
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);
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);
266 public static QNameModule getRootModuleQName(final StmtContext<?, ?, ?> ctx) {
272 StmtContext<?, ?, ?> rootCtx = ctx.getRoot();
273 QNameModule qNameModule = null;
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);
283 return qNameModule.getRevision() == null ? QNameModule.create(qNameModule.getNamespace(),
284 SimpleDateFormatUtil.DEFAULT_DATE_REV) : qNameModule;
288 public static StatementContextBase<?, ?, ?> findNode(final StmtContext<?, ?, ?> rootStmtCtx,
289 final SchemaNodeIdentifier node) {
290 return (StatementContextBase<?, ?, ?>) rootStmtCtx.getFromNamespace(SchemaNodeIdentifierBuildNamespace.class, node);
293 public static boolean isUnknownNode(final StmtContext<?, ?, ?> stmtCtx) {
294 return stmtCtx.getPublicDefinition().getDeclaredRepresentationClass()
295 .isAssignableFrom(UnknownStatementImpl.class);
298 public static Deviation.Deviate parseDeviateFromString(final String deviate) {
300 // Yang constants should be lowercase so we have throw if value does not
302 String deviateUpper = deviate.toUpperCase();
303 Preconditions.checkArgument(!Objects.equals(deviate, deviateUpper),
304 "String %s is not valid deviate argument", deviate);
306 // but Java enum is uppercase so we cannot use lowercase here
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);
314 public static Status parseStatus(final String value) {
316 Status status = null;
319 status = Status.CURRENT;
322 status = Status.DEPRECATED;
325 status = Status.OBSOLETE;
328 LOG.warn("Invalid 'status' statement: " + value);
334 public static Date getLatestRevision(final RootStatementContext<?, ?, ?> root) {
335 return getLatestRevision(root.declaredSubstatements());
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
343 if (revision == null && subStmt.getStatementArgument() != null) {
344 revision = (Date) subStmt.getStatementArgument();
345 } else if (subStmt.getStatementArgument() != null && ((Date) subStmt.getStatementArgument()).compareTo
347 revision = (Date) subStmt.getStatementArgument();
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);