01: package net.sourceforge.pmd.jaxen;
02:
03: import net.sourceforge.pmd.ast.Node;
04: import net.sourceforge.pmd.ast.TypeNode;
05:
06: import org.jaxen.Context;
07: import org.jaxen.Function;
08: import org.jaxen.FunctionCallException;
09: import org.jaxen.SimpleFunctionContext;
10: import org.jaxen.XPathFunctionContext;
11:
12: import java.util.Arrays;
13: import java.util.List;
14:
15: public class TypeOfFunction implements Function {
16:
17: public static void registerSelfInSimpleContext() {
18: ((SimpleFunctionContext) XPathFunctionContext.getInstance())
19: .registerFunction(null, "typeof", new TypeOfFunction());
20: }
21:
22: // TEST //ClassOrInterfaceType[typeof(@Image, 'java.lang.String')]
23: public Object call(Context context, List args)
24: throws FunctionCallException {
25: if (args.isEmpty()) {
26: return Boolean.FALSE;
27: }
28: Node n = (Node) context.getNodeSet().get(0);
29: if (n instanceof TypeNode) {
30: List attributes = (List) args.get(0);
31: Attribute attr = (Attribute) attributes.get(0);
32: Class type = ((TypeNode) n).getType();
33: String typeName = (String) args.get(1);
34: String shortName = (args.size() > 2) ? (String) args.get(2)
35: : "";
36: if (type == null) {
37: return typeName.equals(attr.getValue())
38: || shortName.equals(attr.getValue());
39: }
40: if (type.getName().equals(typeName)
41: || type.getName().equals(attr.getValue())) {
42: return Boolean.TRUE;
43: }
44: List<Class> implementors = Arrays.asList(type
45: .getInterfaces());
46: if (implementors.contains(type)) {
47: return Boolean.TRUE;
48: }
49: Class super C = type.getSuperclass();
50: while (super C != null && !super C.equals(Object.class)) {
51: if (superC.getName().equals(typeName)) {
52: return Boolean.TRUE;
53: }
54: superC = superC.getSuperclass();
55: }
56: }
57: return Boolean.FALSE;
58: }
59: }
|