View Javadoc

    1   package net.sourceforge.pmd.jaxen;
    2
    3   import net.sourceforge.pmd.ast.Node;
    4   import net.sourceforge.pmd.ast.TypeNode;
    5
    6   import org.jaxen.Context;
    7   import org.jaxen.Function;
    8   import org.jaxen.FunctionCallException;
    9   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()).registerFunction(null, "typeof", new TypeOfFunction());
    19      }
    20
    21      // TEST //ClassOrInterfaceType[typeof(@Image, 'java.lang.String')]
    22      public Object call(Context context, List args) throws FunctionCallException {
    23          if (args.isEmpty()) {
    24              return Boolean.FALSE;
    25          }
    26          Node n = (Node) context.getNodeSet().get(0);
    27          if (n instanceof TypeNode) {
    28              List attributes = (List) args.get(0);
    29              Attribute attr = (Attribute) attributes.get(0);
    30              Class type = ((TypeNode) n).getType();
    31              String typeName = (String) args.get(1);
    32              String shortName = (args.size() > 2) ? (String) args.get(2) : "";
    33              if (type == null) {
    34                  return typeName.equals(attr.getValue()) || shortName.equals(attr.getValue());
    35              }
    36              if (type.getName().equals(typeName) || type.getName().equals(attr.getValue())) {
    37                  return Boolean.TRUE;
    38              }
    39              List<Class> implementors = Arrays.asList(type.getInterfaces());
    40              if (implementors.contains(type)) {
    41                  return Boolean.TRUE;
    42              }
    43              Class superC = type.getSuperclass();
    44              while (superC != null && !superC.equals(Object.class)) {
    45                  if (superC.getName().equals(typeName)) {
    46                      return Boolean.TRUE;
    47                  }
    48                  superC = superC.getSuperclass();
    49              }
    50          }
    51          return Boolean.FALSE;
    52      }
    53  }