View Javadoc
1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.ast.xpath.saxon;
5   
6   import net.sf.saxon.om.NodeInfo;
7   import net.sf.saxon.om.SequenceIterator;
8   import net.sf.saxon.trans.XPathException;
9   import net.sf.saxon.type.Type;
10  import net.sf.saxon.value.BooleanValue;
11  import net.sf.saxon.value.EmptySequence;
12  import net.sf.saxon.value.Int64Value;
13  import net.sf.saxon.value.StringValue;
14  import net.sf.saxon.value.Value;
15  import net.sourceforge.pmd.lang.ast.xpath.Attribute;
16  
17  /**
18   * A Saxon OM Attribute node for an AST Node Attribute.
19   */
20  public class AttributeNode extends AbstractNodeInfo {
21      protected final Attribute attribute;
22      protected final int id;
23      protected Value value;
24  
25      public AttributeNode(Attribute attribute, int id) {
26  	this.attribute = attribute;
27  	this.id = id;
28      }
29  
30      @Override
31      public int getNodeKind() {
32  	return Type.ATTRIBUTE;
33      }
34  
35      @Override
36      public String getLocalPart() {
37  	return attribute.getName();
38      }
39  
40      @Override
41      public String getURI() {
42  	return "";
43      }
44  
45      @Override
46      public Value atomize() throws XPathException {
47  	if (value == null) {
48  	    Object v = attribute.getValue();
49  	    // TODO Need to handle the full range of types, is there something Saxon can do to help?
50  	    if (v instanceof String) {
51  		value = new StringValue((String) v);
52  	    } else if (v instanceof Boolean) {
53  		value = BooleanValue.get(((Boolean) v).booleanValue());
54  	    } else if (v instanceof Integer) {
55  		value = Int64Value.makeIntegerValue((Integer) v);
56  	    } else if (v == null) {
57  		value = EmptySequence.getInstance();
58  	    } else {
59  		throw new RuntimeException("Unable to create ValueRepresentaton for attribute value: " + v
60  			+ " of type " + v.getClass());
61  	    }
62  	}
63  	return value;
64      }
65  
66      @Override
67      public CharSequence getStringValueCS() {
68  	return attribute.getStringValue();
69      }
70  
71      @Override
72      public SequenceIterator getTypedValue() throws XPathException {
73  	return atomize().iterate();
74      }
75  
76      @Override
77      public int compareOrder(NodeInfo other) {
78  	return Integer.signum(this.id - ((AttributeNode) other).id);
79      }
80  }