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.data.jaxen;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
14 import com.google.common.base.Splitter;
15 import java.util.AbstractMap.SimpleImmutableEntry;
16 import java.util.List;
17 import java.util.Map.Entry;
18 import java.util.Optional;
20 import org.eclipse.jdt.annotation.Nullable;
21 import org.jaxen.Context;
22 import org.jaxen.ContextSupport;
23 import org.jaxen.Function;
24 import org.jaxen.FunctionCallException;
25 import org.jaxen.FunctionContext;
26 import org.jaxen.UnresolvableException;
27 import org.jaxen.XPathFunctionContext;
28 import org.opendaylight.yangtools.yang.common.QName;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
30 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
33 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
36 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
38 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
41 import org.opendaylight.yangtools.yang.model.api.PathExpression;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.util.RegexUtils;
53 * A {@link FunctionContext} which contains also YANG-specific functions current(), re-match(), deref(),
54 * derived-from(), derived-from-or-self(), enum-value() and bit-is-set().
56 final class YangFunctionContext implements FunctionContext {
57 private static final Splitter COLON_SPLITTER = Splitter.on(':');
58 private static final Double DOUBLE_NAN = Double.NaN;
60 // Core XPath functions, as per http://tools.ietf.org/html/rfc6020#section-6.4.1
61 private static final FunctionContext XPATH_FUNCTION_CONTEXT = new XPathFunctionContext(false);
63 // Singleton instance of reuse
64 private static final YangFunctionContext INSTANCE = new YangFunctionContext();
66 private YangFunctionContext() {
69 static YangFunctionContext getInstance() {
74 public Function getFunction(final String namespaceURI, final String prefix, final String localName)
75 throws UnresolvableException {
79 return YangFunctionContext::bitIsSet;
81 return YangFunctionContext::current;
83 return YangFunctionContext::deref;
85 return YangFunctionContext::derivedFrom;
86 case "derived-from-or-self":
87 return YangFunctionContext::derivedFromOrSelf;
89 return YangFunctionContext::enumValueFunction;
91 return YangFunctionContext::reMatch;
97 return XPATH_FUNCTION_CONTEXT.getFunction(namespaceURI, prefix, localName);
100 // bit-is-set(node-set nodes, string bit-name) function as per
101 // https://tools.ietf.org/html/rfc7950#section-10.6.1
102 private static boolean bitIsSet(final Context context, final List<?> args) throws FunctionCallException {
103 if (args == null || args.size() != 1) {
104 throw new FunctionCallException("bit-is-set() takes two arguments: node-set nodes, string bit-name");
107 if (!(args.get(0) instanceof String)) {
108 throw new FunctionCallException("Argument bit-name of bit-is-set() function should be a String");
111 final String bitName = (String) args.get(0);
113 final NormalizedNodeContext currentNodeContext = verifyContext(context);
114 final TypedDataSchemaNode correspondingSchemaNode = getCorrespondingTypedSchemaNode(currentNodeContext);
116 final TypeDefinition<?> nodeType = correspondingSchemaNode.getType();
117 if (!(nodeType instanceof BitsTypeDefinition)) {
121 final Object nodeValue = currentNodeContext.getNode().body();
122 if (!(nodeValue instanceof Set)) {
126 final BitsTypeDefinition bitsType = (BitsTypeDefinition) nodeType;
127 checkState(containsBit(bitsType, bitName), "Bit %s does not belong to bits %s.", bitName, bitsType);
128 return ((Set<?>)nodeValue).contains(bitName);
131 // current() function, as per http://tools.ietf.org/html/rfc6020#section-6.4.1
132 private static NormalizedNodeContext current(final Context context, final List<?> args)
133 throws FunctionCallException {
134 if (!args.isEmpty()) {
135 throw new FunctionCallException("current() takes no arguments.");
138 return verifyContext(context);
141 // deref(node-set nodes) function as per https://tools.ietf.org/html/rfc7950#section-10.3.1
142 private static NormalizedNode deref(final Context context, final List<?> args) throws FunctionCallException {
143 if (!args.isEmpty()) {
144 throw new FunctionCallException("deref() takes only one argument: node-set nodes.");
147 final NormalizedNodeContext currentNodeContext = verifyContext(context);
148 final TypedDataSchemaNode correspondingSchemaNode = getCorrespondingTypedSchemaNode(currentNodeContext);
150 final Object nodeValue = currentNodeContext.getNode().body();
151 final TypeDefinition<?> type = correspondingSchemaNode.getType();
152 if (type instanceof InstanceIdentifierTypeDefinition) {
153 return nodeValue instanceof YangInstanceIdentifier
154 ? getNodeReferencedByInstanceIdentifier((YangInstanceIdentifier) nodeValue, currentNodeContext)
157 if (type instanceof LeafrefTypeDefinition) {
158 final PathExpression xpath = ((LeafrefTypeDefinition) type).getPathStatement();
159 return getNodeReferencedByLeafref(xpath, currentNodeContext, getSchemaContext(currentNodeContext),
160 correspondingSchemaNode, nodeValue);
165 // derived-from(node-set nodes, string identity) function as per https://tools.ietf.org/html/rfc7950#section-10.4.1
166 private static boolean derivedFrom(final Context context, final List<?> args) throws FunctionCallException {
167 final Entry<IdentitySchemaNode, IdentitySchemaNode> ids = commonDerivedFrom("derived-from", context, args);
168 return ids != null && isAncestorOf(ids.getKey(), ids.getValue());
171 // derived-from-or-self(node-set nodes, string identity) function as per
172 // https://tools.ietf.org/html/rfc7950#section-10.4.2
173 private static boolean derivedFromOrSelf(final Context context, final List<?> args) throws FunctionCallException {
174 final Entry<IdentitySchemaNode, IdentitySchemaNode> ids = commonDerivedFrom("derived-from-or-self", context,
176 return ids != null && (ids.getValue().equals(ids.getKey()) || isAncestorOf(ids.getKey(), ids.getValue()));
179 private static @Nullable Entry<IdentitySchemaNode, IdentitySchemaNode> commonDerivedFrom(final String functionName,
180 final Context context, final List<?> args) throws FunctionCallException {
181 if (args == null || args.size() != 1) {
182 throw new FunctionCallException(functionName + "() takes two arguments: node-set nodes, string identity");
184 if (!(args.get(0) instanceof String)) {
185 throw new FunctionCallException("Argument 'identity' of " + functionName
186 + "() function should be a String.");
189 final NormalizedNodeContext currentNodeContext = verifyContext(context);
190 final TypedDataSchemaNode correspondingSchemaNode = getCorrespondingTypedSchemaNode(currentNodeContext);
192 final SchemaContext schemaContext = getSchemaContext(currentNodeContext);
193 return correspondingSchemaNode.getType() instanceof IdentityrefTypeDefinition
194 && currentNodeContext.getNode().body() instanceof QName ? new SimpleImmutableEntry<>(
195 getIdentitySchemaNodeFromString((String) args.get(0), schemaContext, correspondingSchemaNode),
196 getIdentitySchemaNodeFromQName((QName) currentNodeContext.getNode().body(), schemaContext))
200 // enum-value(node-set nodes) function as per https://tools.ietf.org/html/rfc7950#section-10.5.1
201 private static Object enumValueFunction(final Context context, final List<?> args) throws FunctionCallException {
202 if (!args.isEmpty()) {
203 throw new FunctionCallException("enum-value() takes one argument: node-set nodes.");
206 final NormalizedNodeContext currentNodeContext = verifyContext(context);
207 final TypedDataSchemaNode correspondingSchemaNode = getCorrespondingTypedSchemaNode(currentNodeContext);
209 final TypeDefinition<?> nodeType = correspondingSchemaNode.getType();
210 if (!(nodeType instanceof EnumTypeDefinition)) {
214 final Object nodeValue = currentNodeContext.getNode().body();
215 if (!(nodeValue instanceof String)) {
219 final EnumTypeDefinition enumerationType = (EnumTypeDefinition) nodeType;
220 final String enumName = (String) nodeValue;
222 return getEnumValue(enumerationType, enumName);
225 // re-match(string subject, string pattern) function as per https://tools.ietf.org/html/rfc7950#section-10.2.1
226 private static boolean reMatch(final Context context, final List<?> args) throws FunctionCallException {
227 if (args == null || args.size() != 2) {
228 throw new FunctionCallException("re-match() takes two arguments: string subject, string pattern.");
230 final Object subject = args.get(0);
231 if (!(subject instanceof String)) {
232 throw new FunctionCallException("First argument of re-match() should be a String.");
234 final Object pattern = args.get(1);
235 if (!(pattern instanceof String)) {
236 throw new FunctionCallException("Second argument of re-match() should be a String.");
239 return ((String) subject).matches(RegexUtils.getJavaRegexFromXSD((String) pattern));
242 private static boolean isAncestorOf(final IdentitySchemaNode identity, final IdentitySchemaNode descendant) {
243 for (IdentitySchemaNode base : descendant.getBaseIdentities()) {
244 if (identity.equals(base) || isAncestorOf(identity, base)) {
251 private static IdentitySchemaNode getIdentitySchemaNodeFromQName(final QName identityQName,
252 final SchemaContext schemaContext) {
253 final Optional<Module> module = schemaContext.findModule(identityQName.getModule());
254 checkArgument(module.isPresent(), "Module for %s not found", identityQName);
255 return findIdentitySchemaNodeInModule(module.get(), identityQName);
258 private static IdentitySchemaNode getIdentitySchemaNodeFromString(final String identity,
259 final SchemaContext schemaContext, final TypedDataSchemaNode correspondingSchemaNode) {
260 final List<String> identityPrefixAndName = COLON_SPLITTER.splitToList(identity);
261 final Module module = schemaContext.findModule(correspondingSchemaNode.getQName().getModule()).get();
262 if (identityPrefixAndName.size() == 2) {
263 // prefix of local module
264 if (identityPrefixAndName.get(0).equals(module.getPrefix())) {
265 return findIdentitySchemaNodeInModule(module, QName.create(module.getQNameModule(),
266 identityPrefixAndName.get(1)));
269 // prefix of imported module
270 for (final ModuleImport moduleImport : module.getImports()) {
271 if (identityPrefixAndName.get(0).equals(moduleImport.getPrefix())) {
272 final Module importedModule = schemaContext.findModule(moduleImport.getModuleName(),
273 moduleImport.getRevision()).get();
274 return findIdentitySchemaNodeInModule(importedModule, QName.create(
275 importedModule.getQNameModule(), identityPrefixAndName.get(1)));
279 throw new IllegalArgumentException(String.format("Cannot resolve prefix '%s' from identity '%s'.",
280 identityPrefixAndName.get(0), identity));
283 if (identityPrefixAndName.size() == 1) {
285 return findIdentitySchemaNodeInModule(module, QName.create(module.getQNameModule(),
286 identityPrefixAndName.get(0)));
289 throw new IllegalArgumentException(String.format("Malformed identity argument: %s.", identity));
292 private static IdentitySchemaNode findIdentitySchemaNodeInModule(final Module module, final QName identityQName) {
293 for (final IdentitySchemaNode id : module.getIdentities()) {
294 if (identityQName.equals(id.getQName())) {
299 throw new IllegalArgumentException(String.format("Identity %s does not have a corresponding"
300 + " identity schema node in the module %s.", identityQName, module));
303 private static NormalizedNode getNodeReferencedByInstanceIdentifier(final YangInstanceIdentifier path,
304 final NormalizedNodeContext currentNodeContext) {
305 final NormalizedNodeNavigator navigator = (NormalizedNodeNavigator) currentNodeContext.getNavigator();
306 final NormalizedNode rootNode = navigator.getDocument().getRootNode();
307 final List<PathArgument> pathArguments = path.getPathArguments();
308 if (pathArguments.get(0).getNodeType().equals(rootNode.getNodeType())) {
309 final List<PathArgument> relPath = pathArguments.subList(1, pathArguments.size());
310 final Optional<NormalizedNode> possibleNode = NormalizedNodes.findNode(rootNode, relPath);
311 if (possibleNode.isPresent()) {
312 return possibleNode.get();
319 private static NormalizedNode getNodeReferencedByLeafref(final PathExpression xpath,
320 final NormalizedNodeContext currentNodeContext, final SchemaContext schemaContext,
321 final TypedDataSchemaNode correspondingSchemaNode, final Object nodeValue) {
322 final NormalizedNode referencedNode = xpath.isAbsolute() ? getNodeReferencedByAbsoluteLeafref(xpath,
323 currentNodeContext, schemaContext, correspondingSchemaNode) : getNodeReferencedByRelativeLeafref(xpath,
324 currentNodeContext, schemaContext, correspondingSchemaNode);
326 if (referencedNode instanceof LeafSetNode) {
327 return getReferencedLeafSetEntryNode((LeafSetNode<?>) referencedNode, nodeValue);
330 if (referencedNode instanceof LeafNode && referencedNode.body().equals(nodeValue)) {
331 return referencedNode;
337 private static NormalizedNode getNodeReferencedByAbsoluteLeafref(final PathExpression xpath,
338 final NormalizedNodeContext currentNodeContext, final SchemaContext schemaContext,
339 final TypedDataSchemaNode correspondingSchemaNode) {
340 final LeafrefXPathStringParsingPathArgumentBuilder builder = new LeafrefXPathStringParsingPathArgumentBuilder(
341 xpath.getOriginalString(), schemaContext, correspondingSchemaNode, currentNodeContext);
342 final List<PathArgument> pathArguments = builder.build();
343 final NormalizedNodeNavigator navigator = (NormalizedNodeNavigator) currentNodeContext.getNavigator();
344 final NormalizedNode rootNode = navigator.getDocument().getRootNode();
345 if (pathArguments.get(0).getNodeType().equals(rootNode.getNodeType())) {
346 final List<PathArgument> relPath = pathArguments.subList(1, pathArguments.size());
347 final Optional<NormalizedNode> possibleNode = NormalizedNodes.findNode(rootNode, relPath);
348 if (possibleNode.isPresent()) {
349 return possibleNode.get();
356 private static NormalizedNode getNodeReferencedByRelativeLeafref(final PathExpression xpath,
357 final NormalizedNodeContext currentNodeContext, final SchemaContext schemaContext,
358 final TypedDataSchemaNode correspondingSchemaNode) {
359 NormalizedNodeContext relativeNodeContext = currentNodeContext;
360 final StringBuilder xPathStringBuilder = new StringBuilder(xpath.getOriginalString());
361 // strip the relative path of all ../ at the beginning
362 while (xPathStringBuilder.indexOf("../") == 0) {
363 xPathStringBuilder.delete(0, 3);
364 relativeNodeContext = relativeNodeContext.getParent();
367 // add / to the beginning of the path so that it can be processed the same way as an absolute path
368 xPathStringBuilder.insert(0, '/');
369 final LeafrefXPathStringParsingPathArgumentBuilder builder = new LeafrefXPathStringParsingPathArgumentBuilder(
370 xPathStringBuilder.toString(), schemaContext, correspondingSchemaNode, currentNodeContext);
371 final List<PathArgument> pathArguments = builder.build();
372 final NormalizedNode relativeNode = relativeNodeContext.getNode();
373 return NormalizedNodes.findNode(relativeNode, pathArguments).orElse(null);
376 private static LeafSetEntryNode<?> getReferencedLeafSetEntryNode(final LeafSetNode<?> referencedNode,
377 final Object currentNodeValue) {
378 for (final LeafSetEntryNode<?> entryNode : referencedNode.body()) {
379 if (currentNodeValue.equals(entryNode.body())) {
388 private static boolean containsBit(final BitsTypeDefinition bitsType, final String bitName) {
389 for (BitsTypeDefinition.Bit bit : bitsType.getBits()) {
390 if (bitName.equals(bit.getName())) {
398 private static int getEnumValue(final EnumTypeDefinition enumerationType, final String enumName) {
399 for (final EnumTypeDefinition.EnumPair enumPair : enumerationType.getValues()) {
400 if (enumName.equals(enumPair.getName())) {
401 return enumPair.getValue();
405 throw new IllegalStateException(String.format("Enum %s does not belong to enumeration %s.",
406 enumName, enumerationType));
409 private static EffectiveModelContext getSchemaContext(final NormalizedNodeContext normalizedNodeContext) {
410 final ContextSupport contextSupport = normalizedNodeContext.getContextSupport();
411 verify(contextSupport instanceof NormalizedNodeContextSupport, "Unhandled context support %s",
412 contextSupport.getClass());
413 return ((NormalizedNodeContextSupport) contextSupport).getEffectiveModelContext();
416 private static TypedDataSchemaNode getCorrespondingTypedSchemaNode(final NormalizedNodeContext currentNodeContext) {
417 final DataSchemaNode schemaNode = currentNodeContext.getSchema().getDataSchemaNode();
418 checkState(schemaNode instanceof TypedDataSchemaNode, "Node %s must be a leaf or a leaf-list.",
419 currentNodeContext.getNode());
420 return (TypedDataSchemaNode) schemaNode;
423 private static NormalizedNodeContext verifyContext(final Context context) {
424 verify(context instanceof NormalizedNodeContext, "Unhandled context %s", context.getClass());
425 return (NormalizedNodeContext) context;