XPathUtil.java

Index Score
org.apache.taglibs.standard.tag.common.xml
Jakarta Taglibs

View: Reasons, Metrics, Source Code

These are the metrics that contribute to the Enerjy Score for this file, ranked by impact. So the metrics listed at the top influence the score to a greater extent that the metrics listed at the bottom.

MetricDescription
LINE_COMMENTNumber of line comments
EXEC_COMMENTSComments in executable code
SIZESize of the file in bytes
JAVA0133JAVA0133 Non-synchronized method overrides synchronized method
JAVA0108JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
EXITSProcedure exits
LOOPSNumber of loops
OPERANDSNumber of operands
LOGICAL_LINESNumber of statements
ELOCEffective lines of code
PROGRAM_LENGTHHalstead program length
JAVA0115JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
OPERATORSNumber of operators
JAVA0110JAVA0110 Incorrect javadoc: no @return tag
RETURNSNumber of return points from functions
UNIQUE_OPERANDSNumber of unique operands
LINESNumber of lines in the source file
LOCLines of code
PROGRAM_VOCABHalstead program vocabulary
BLOCKSNumber of blocks
JAVA0128JAVA0128 Public constructor in non-public class
JAVA0266JAVA0266 Use of System.out
INTERFACE_COMPLEXITYInterface complexity
COMPARISONSNumber of comparison operators
DECL_COMMENTSComments in declarations
CYCLOMATICCyclomatic complexity
JAVA0049JAVA0049 Nested block at depth N (maximum: M)
JAVA0265JAVA0265 Use of Throwable.printStackTrace()
COMMENTSComment lines
NEST_DEPTHMaximum nesting depth
WHITESPACENumber of whitespace lines
JAVA0171JAVA0171 Unused local variable
JAVA0117JAVA0117 Missing javadoc: method 'method'
JAVA0029JAVA0029 Private method not used
JAVA0270JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
PARAMSNumber of formal parameter declarations
UNIQUE_OPERATORSNumber of unique operators
JAVA0143JAVA0143 Synchronized method
JAVA0166JAVA0166 Generic exception caught
JAVA0082JAVA0082 Unnecessary widening cast
PROGRAM_VOLUMEHalstead program volume
FUNCTIONSNumber of function declarations
JAVA0035JAVA0035 Missing braces in for statement
JAVA0278JAVA0278 Unnecessary use of Boolean constructor
JAVA0126JAVA0126 Method declares unchecked exception in throws
JAVA0173JAVA0173 Unused method parameter
JAVA0068JAVA0068 Modifiers not declared in recommended order
JAVA0145JAVA0145 Tab character used in source file
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.taglibs.standard.tag.common.xml; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Vector; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.Tag; import javax.servlet.jsp.tagext.TagSupport; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.TransformerException; import org.apache.taglibs.standard.resources.Resources; import org.apache.xml.utils.QName; import org.apache.xpath.VariableStack; import org.apache.xpath.XPathContext; import org.apache.xpath.objects.XBoolean; import org.apache.xpath.objects.XNodeSetForDOM; import org.apache.xpath.objects.XNumber; import org.apache.xpath.objects.XObject; import org.apache.xpath.objects.XString; import org.w3c.dom.DOMImplementation; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * <p>Support for tag handlers that evaluate XPath expressions.</p> * * @author Shawn Bayern * @author Ramesh Mandava ( ramesh.mandava@sun.com ) * @author Pierre Delisle ( pierre.delisle@sun.com ) */ // would ideally be a base class, but some of our user handlers already // have their own parents public class XPathUtil { //********************************************************************* // Constructor /** * Constructs a new XPathUtil object associated with the given * PageContext. */ public XPathUtil(PageContext pc) { pageContext = pc; } int globalVarSize=0; public Vector getVariableQNames ( ) { globalVarSize = 0; Vector variableVector = new Vector ( ); // Now construct attributes in different scopes Enumeration enum_ = pageContext.getAttributeNamesInScope( PageContext.PAGE_SCOPE ); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( PAGE_NS_URL, PAGE_P, varName); //Adding both namespace qualified QName and just localName variableVector.addElement( varQName ); globalVarSize++; variableVector.addElement( new QName(null, varName ) ); globalVarSize++; } enum_ = pageContext.getAttributeNamesInScope( PageContext.REQUEST_SCOPE ); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( REQUEST_NS_URL,REQUEST_P, varName); //Adding both namespace qualified QName and just localName variableVector.addElement( varQName ); globalVarSize++; variableVector.addElement( new QName(null, varName ) ); globalVarSize++; } if (pageContext.getSession() != null) { // we may have a page directive preventing session creation/access // do not attempt to retrieve attribute names in session scope // @see [ http://issues.apache.org/bugzilla/show_bug.cgi?id=35216 ] enum_ = pageContext.getAttributeNamesInScope( PageContext.SESSION_SCOPE ); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( SESSION_NS_URL, SESSION_P,varName); //Adding both namespace qualified QName and just localName variableVector.addElement( varQName ); globalVarSize++; variableVector.addElement( new QName(null, varName ) ); globalVarSize++; } } enum_ = pageContext.getAttributeNamesInScope( PageContext.APPLICATION_SCOPE ); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( APP_NS_URL, APP_P,varName ); //Adding both namespace qualified QName and just localName variableVector.addElement( varQName ); globalVarSize++; variableVector.addElement( new QName(null, varName ) ); globalVarSize++; } enum_ = pageContext.getRequest().getParameterNames(); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( PARAM_NS_URL, PARAM_P,varName ); //Adding both namespace qualified QName and just localName variableVector.addElement( varQName ); globalVarSize++; } enum_ = pageContext.getServletContext().getInitParameterNames(); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( INITPARAM_NS_URL, INITPARAM_P,varName ); //Adding both namespace qualified QName and just localName variableVector.addElement( varQName ); globalVarSize++; } enum_ = ((HttpServletRequest)pageContext.getRequest()).getHeaderNames(); while ( enum_.hasMoreElements() ) { String varName = (String)enum_.nextElement(); QName varQName = new QName ( HEADER_NS_URL, HEADER_P,varName ); //Adding namespace qualified QName variableVector.addElement( varQName ); globalVarSize++; } Cookie[] c= ((HttpServletRequest)pageContext.getRequest()).getCookies(); if ( c!= null ) { for (int i = 0; i < c.length; i++) { String varName = c[i].getName(); QName varQName = new QName ( COOKIE_NS_URL, COOKIE_P,varName ); //Adding namespace qualified QName variableVector.addElement( varQName ); globalVarSize++; } } return variableVector; } //********************************************************************* // Support for JSTL variable resolution // The URLs private static final String PAGE_NS_URL = "http://java.sun.com/jstl/xpath/page"; private static final String REQUEST_NS_URL = "http://java.sun.com/jstl/xpath/request"; private static final String SESSION_NS_URL = "http://java.sun.com/jstl/xpath/session"; private static final String APP_NS_URL = "http://java.sun.com/jstl/xpath/app"; private static final String PARAM_NS_URL = "http://java.sun.com/jstl/xpath/param"; private static final String INITPARAM_NS_URL = "http://java.sun.com/jstl/xpath/initParam"; private static final String COOKIE_NS_URL = "http://java.sun.com/jstl/xpath/cookie"; private static final String HEADER_NS_URL = "http://java.sun.com/jstl/xpath/header"; // The prefixes private static final String PAGE_P = "pageScope"; private static final String REQUEST_P = "requestScope"; private static final String SESSION_P = "sessionScope"; private static final String APP_P = "applicationScope"; private static final String PARAM_P = "param"; private static final String INITPARAM_P = "initParam"; private static final String COOKIE_P = "cookie"; private static final String HEADER_P = "header"; /** * org.apache.xpath.VariableStack defines a class to keep track of a stack * for template arguments and variables. * JstlVariableContext customizes it so it handles JSTL custom * variable-mapping rules. */ protected class JstlVariableContext extends org.apache.xpath.VariableStack { public JstlVariableContext( ) { super(); } /** * Get a variable as an XPath object based on it's qualified name. * We override the base class method so JSTL's custom variable-mapping * rules can be applied. * * @param xctxt The XPath context. @@@ we don't use it... * (from xalan: which must be passed in order to lazy evaluate variables.) * @param qname The qualified name of the variable. */ public XObject getVariableOrParam( XPathContext xctxt, org.apache.xml.utils.QName qname) throws javax.xml.transform.TransformerException, UnresolvableException { //p( "***********************************getVariableOrParam begin****"); String namespace = qname.getNamespaceURI(); String prefix = qname.getPrefix(); String localName = qname.getLocalName(); //p("namespace:prefix:localname=>"+ namespace // + ":" + prefix +":" + localName ); try { Object varObject = getVariableValue(namespace,prefix,localName); //XObject varObject = myvs.getVariableOrParam( xpathSupport, varQName); XObject newXObject = new XObject( varObject); if ( Class.forName("org.w3c.dom.Document").isInstance( varObject) ) { NodeList nl= ((Document)varObject).getChildNodes(); // To allow non-welformed document Vector nodeVector = new Vector(); for ( int i=0; i<nl.getLength(); i++ ) { Node currNode = nl.item(i); if ( currNode.getNodeType() == Node.ELEMENT_NODE ) { nodeVector.addElement( currNode); } } JSTLNodeList jstlNodeList = new JSTLNodeList( nodeVector); newXObject = new XNodeSetForDOM( jstlNodeList, xctxt ); return newXObject; } if ( Class.forName( "org.apache.taglibs.standard.tag.common.xml.JSTLNodeList").isInstance( varObject) ) { JSTLNodeList jstlNodeList = (JSTLNodeList)varObject; if ( ( jstlNodeList.getLength() == 1 ) && (!Class.forName("org.w3c.dom.Node").isInstance( jstlNodeList.elementAt(0) ) ) ) { varObject = jstlNodeList.elementAt(0); //Now we need to allow this primitive type to be coverted // to type which Xalan XPath understands } else { return new XNodeSetForDOM ( jstlNodeList ,xctxt ); } } if (Class.forName("org.w3c.dom.Node").isInstance( varObject)) { newXObject = new XNodeSetForDOM ( new JSTLNodeList( (Node)varObject ),xctxt ); } else if ( Class.forName("java.lang.String").isInstance( varObject)){ newXObject = new XString ( (String)varObject ); } else if ( Class.forName("java.lang.Boolean").isInstance( varObject) ) { newXObject = new XBoolean ( (Boolean)varObject ); } else if ( Class.forName("java.lang.Number").isInstance( varObject) ) { newXObject = new XNumber ( (Number)varObject ); } return newXObject; // myvs.setGlobalVariable( i, newXObject ); } catch ( ClassNotFoundException cnfe ) { // This shouldn't happen (FIXME: LOG) System.out.println("CLASS NOT FOUND EXCEPTION :" + cnfe ); } //System.out.println("*****getVariableOrParam returning *null*" ); return null ; } /** * Retrieve an XPath's variable value using JSTL's custom * variable-mapping rules */ public Object getVariableValue( String namespace, String prefix, String localName) throws UnresolvableException { // p("resolving: ns=" + namespace + " prefix=" + prefix + " localName=" + localName); // We can match on namespace with Xalan but leaving as is // [ I 'd prefer to match on namespace, but this doesn't appear // to work in Jaxen] if (prefix == null || prefix.equals("")) { return notNull( pageContext.findAttribute(localName), prefix, localName); } else if (prefix.equals(PAGE_P)) { return notNull( pageContext.getAttribute(localName,PageContext.PAGE_SCOPE), prefix, localName); } else if (prefix.equals(REQUEST_P)) { return notNull( pageContext.getAttribute(localName, PageContext.REQUEST_SCOPE), prefix, localName); } else if (prefix.equals(SESSION_P)) { return notNull( pageContext.getAttribute(localName, PageContext.SESSION_SCOPE), prefix, localName); } else if (prefix.equals(APP_P)) { return notNull( pageContext.getAttribute(localName, PageContext.APPLICATION_SCOPE), prefix, localName); } else if (prefix.equals(PARAM_P)) { return notNull( pageContext.getRequest().getParameter(localName), prefix, localName); } else if (prefix.equals(INITPARAM_P)) { return notNull( pageContext.getServletContext(). getInitParameter(localName), prefix, localName); } else if (prefix.equals(HEADER_P)) { HttpServletRequest hsr = (HttpServletRequest) pageContext.getRequest(); return notNull( hsr.getHeader(localName), prefix, localName); } else if (prefix.equals(COOKIE_P)) { HttpServletRequest hsr = (HttpServletRequest) pageContext.getRequest(); Cookie[] c = hsr.getCookies(); for (int i = 0; i < c.length; i++) if (c[i].getName().equals(localName)) return c[i].getValue(); throw new UnresolvableException("$" + prefix + ":" + localName); } else { throw new UnresolvableException("$" + prefix + ":" + localName); } } /** * Validate that the Object returned is not null. If it is * null, throw an exception. */ private Object notNull(Object o, String prefix, String localName) throws UnresolvableException { if (o == null) { throw new UnresolvableException("$" + (prefix==null?"":prefix+":") + localName); } //p("resolved to: " + o); return o; } } //********************************************************************* // Support for XPath evaluation private PageContext pageContext; private static HashMap exprCache; private static JSTLPrefixResolver jstlPrefixResolver = null; /** Initialize globally useful data. */ private synchronized static void staticInit() { if (jstlPrefixResolver == null) { // register supported namespaces jstlPrefixResolver = new JSTLPrefixResolver(); jstlPrefixResolver.addNamespace("pageScope", PAGE_NS_URL); jstlPrefixResolver.addNamespace("requestScope", REQUEST_NS_URL); jstlPrefixResolver.addNamespace("sessionScope", SESSION_NS_URL); jstlPrefixResolver.addNamespace("applicationScope", APP_NS_URL); jstlPrefixResolver.addNamespace("param", PARAM_NS_URL); jstlPrefixResolver.addNamespace("initParam", INITPARAM_NS_URL); jstlPrefixResolver.addNamespace("header", HEADER_NS_URL); jstlPrefixResolver.addNamespace("cookie", COOKIE_NS_URL); // create a HashMap to cache the expressions exprCache = new HashMap(); } } static DocumentBuilderFactory dbf = null; static DocumentBuilder db = null; static Document d = null; static Document getDummyDocument( ) { try { if ( dbf == null ) { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware( true ); dbf.setValidating( false ); } db = dbf.newDocumentBuilder(); DOMImplementation dim = db.getDOMImplementation(); d = dim.createDocument("http://java.sun.com/jstl", "dummyroot", null); //d = db.newDocument(); return d; } catch ( Exception e ) { e.printStackTrace(); } return null; } static Document getDummyDocumentWithoutRoot( ) { try { if ( dbf == null ) { dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware( true ); dbf.setValidating( false ); } db = dbf.newDocumentBuilder(); d = db.newDocument(); return d; } catch ( Exception e ) { e.printStackTrace(); } return null; } private static Document getDocumentForNode(Node node) { Document doc = getDummyDocumentWithoutRoot(); Node importedNode = doc.importNode(node, true); doc.appendChild(importedNode); return doc; } // The following variable is used for holding the modified xpath string // when adapting parameter for Xalan XPath engine, where we need to have // a Non null context node. String modifiedXPath = null; /** * Evaluate an XPath expression to a String value. */ public String valueOf(Node n, String xpath) throws JspTagException { //p("******** valueOf(" + n + ", " + xpath + ")"); staticInit(); // @@@ but where do we set the Pag4eContext for the varaiblecontext? JstlVariableContext vs = new JstlVariableContext(); XPathContext xpathSupport = new XPathContext(); xpathSupport.setVarStack( vs); Vector varVector = fillVarStack(vs, xpathSupport); Node contextNode = adaptParamsForXalan( vs, n, xpath.trim() ); xpath = modifiedXPath; //p("******** valueOf: modified xpath: " + xpath); XObject result = JSTLXPathAPI.eval( contextNode, xpath, jstlPrefixResolver,xpathSupport, varVector); //p("******Result TYPE => " + result.getTypeString() ); String resultString = result.str(); //p("******** valueOf: after eval: " + resultString); return resultString; } /** * Evaluate an XPath expression to a boolean value. */ public boolean booleanValueOf(Node n, String xpath) throws JspTagException { staticInit(); JstlVariableContext vs = new JstlVariableContext(); XPathContext xpathSupport = new XPathContext(); xpathSupport.setVarStack( vs); Vector varVector = fillVarStack(vs, xpathSupport); Node contextNode = adaptParamsForXalan( vs, n, xpath.trim() ); xpath = modifiedXPath; XObject result = JSTLXPathAPI.eval( contextNode, xpath, jstlPrefixResolver, xpathSupport, varVector); try { return result.bool(); } catch (TransformerException ex) { throw new JspTagException( Resources.getMessage("XPATH_ERROR_XOBJECT", ex.toString()), ex); } } /** * Evaluate an XPath expression to a List of nodes. */ public List selectNodes(Node n, String xpath) throws JspTagException { staticInit(); JstlVariableContext vs = new JstlVariableContext(); XPathContext xpathSupport = new XPathContext(); xpathSupport.setVarStack( vs); Vector varVector = fillVarStack(vs, xpathSupport); Node contextNode = adaptParamsForXalan( vs, n, xpath.trim() ); xpath = modifiedXPath; XObject result = JSTLXPathAPI.eval( contextNode, xpath, jstlPrefixResolver,xpathSupport, varVector); try { NodeList nl= JSTLXPathAPI.getNodeList(result); return new JSTLNodeList( nl ); } catch ( JspTagException e ) { try { //If result can't be converted to NodeList we receive exception // In this case we may have single primitive value as the result // Populating List with this value ( String, Boolean or Number ) //System.out.println("JSTLXPathAPI.getNodeList thrown exception:"+ e); Vector vector = new Vector(); Object resultObject = null; if ( result.getType()== XObject.CLASS_BOOLEAN ) { resultObject = new Boolean( result.bool()); } else if ( result.getType()== XObject.CLASS_NUMBER ) { resultObject = new Double( result.num()); } else if ( result.getType()== XObject.CLASS_STRING ) { resultObject = result.str(); } vector.add( resultObject ); return new JSTLNodeList ( vector ); } catch ( TransformerException te ) { throw new JspTagException(te.toString(), te); } } } /** * Evaluate an XPath expression to a single node. */ public Node selectSingleNode(Node n, String xpath) throws JspTagException { //p("selectSingleNode of XPathUtil = passed node:" + // "xpath => " + n + " : " + xpath ); staticInit(); JstlVariableContext vs = new JstlVariableContext(); XPathContext xpathSupport = new XPathContext(); xpathSupport.setVarStack( vs); Vector varVector = fillVarStack(vs, xpathSupport); Node contextNode = adaptParamsForXalan( vs, n, xpath.trim() ); xpath = modifiedXPath; return (Node) JSTLXPathAPI.selectSingleNode( contextNode, xpath, jstlPrefixResolver,xpathSupport ); } /** Returns a locally appropriate context given a node. */ private VariableStack getLocalContext() { // set up instance-specific contexts VariableStack vc = new JstlVariableContext(); return vc; } //********************************************************************* // Adapt XPath expression for integration with Xalan /** * To evaluate an XPath expression using Xalan, we need * to create an XPath object, which wraps an expression object and provides * general services for execution of that expression. * * An XPath object can be instantiated with the following information: * - XPath expression to evaluate * - SourceLocator * (reports where an error occurred in the XML source or * transformation instructions) * - PrefixResolver * (resolve prefixes to namespace URIs) * - type * (one of SELECT or MATCH) * - ErrorListener * (customized error handling) * * Execution of the XPath expression represented by an XPath object * is done via method execute which takes the following parameters: * - XPathContext * The execution context * - Node contextNode * The node that "." expresses * - PrefixResolver namespaceContext * The context in which namespaces in the XPath are supposed to be * expanded. * * Given all of this, if no context node is set for the evaluation * of the XPath expression, one must be set so Xalan * can successfully evaluate a JSTL XPath expression. * (it will not work if the context node is given as a varialbe * at the beginning of the expression) * * @@@ Provide more details... */ protected Node adaptParamsForXalan( JstlVariableContext jvc, Node n, String xpath ) { Node boundDocument = null; modifiedXPath = xpath; String origXPath = xpath ; boolean whetherOrigXPath = true; // If contextNode is not null then just pass the values to Xalan XPath // unless this is an expression that starts off with an xml document if ( n != null && !xpath.startsWith("$") ) { return n; } if ( xpath.startsWith("$") ) { // JSTL uses $scopePrefix:varLocalName/xpath expression String varQName= xpath.substring( xpath.indexOf("$")+1); if ( varQName.indexOf("/") > 0 ) { varQName = varQName.substring( 0, varQName.indexOf("/")); } String varPrefix = null; String varLocalName = varQName; if ( varQName.indexOf( ":") >= 0 ) { varPrefix = varQName.substring( 0, varQName.indexOf(":") ); varLocalName = varQName.substring( varQName.indexOf(":")+1 ); } if ( xpath.indexOf("/") > 0 ) { xpath = xpath.substring( xpath.indexOf("/")); } else { xpath = "/*"; whetherOrigXPath = false; } try { Object varObject=jvc.getVariableValue( null,varPrefix, varLocalName); //System.out.println( "varObject => : its Class " +varObject + // ":" + varObject.getClass() ); if ( Class.forName("org.w3c.dom.Document").isInstance( varObject ) ) { //boundDocument = ((Document)varObject).getDocumentElement(); boundDocument = ((Document)varObject); } else { //System.out.println("Creating a Dummy document to pass " + // " onto as context node " ); if ( Class.forName("org.apache.taglibs.standard.tag.common.xml.JSTLNodeList").isInstance( varObject ) ) { Document newDocument = getDummyDocument(); JSTLNodeList jstlNodeList = (JSTLNodeList)varObject; if ( jstlNodeList.getLength() == 1 ) { if ( Class.forName("org.w3c.dom.Node").isInstance( jstlNodeList.elementAt(0) ) ) { Node node = (Node)jstlNodeList.elementAt(0); boundDocument = getDocumentForNode(node); if ( whetherOrigXPath ) { xpath="/*" + xpath; } } else { //Nodelist with primitive type Object myObject = jstlNodeList.elementAt(0); //p("Single Element of primitive type"); //p("Type => " + myObject.getClass()); xpath = myObject.toString(); //p("String value ( xpathwould be this) => " + xpath); boundDocument = newDocument; } } else { Element dummyroot = newDocument.getDocumentElement(); for ( int i=0; i< jstlNodeList.getLength(); i++ ) { Node currNode = (Node)jstlNodeList.item(i); Node importedNode = newDocument.importNode( currNode, true ); //printDetails ( newDocument); dummyroot.appendChild( importedNode ); //p( "Details of the document After importing"); //printDetails ( newDocument); } boundDocument = newDocument; // printDetails ( boundDocument ); //Verify :As we are adding Document element we need // to change the xpath expression.Hopefully this // won't change the result xpath = "/*" + xpath; } } else if ( Class.forName("org.w3c.dom.Node").isInstance( varObject ) ) { boundDocument = getDocumentForNode((Node)varObject); if (whetherOrigXPath) { xpath = "/*" + xpath; } } else { boundDocument = getDummyDocument(); xpath = origXPath; } } } catch ( UnresolvableException ue ) { // FIXME: LOG System.out.println("Variable Unresolvable :" + ue.getMessage()); ue.printStackTrace(); } catch ( ClassNotFoundException cnf ) { // Will never happen } } else { //System.out.println("Not encountered $ Creating a Dummydocument 2 "+ // "pass onto as context node " ); boundDocument = getDummyDocument(); } modifiedXPath = xpath; //System.out.println("Modified XPath::boundDocument =>" + modifiedXPath + // "::" + boundDocument ); return boundDocument; } //********************************************************************* // /** ** @@@ why do we have to pass varVector in the varStack first, and then * to XPath object? */ private Vector fillVarStack(JstlVariableContext vs, XPathContext xpathSupport) throws JspTagException { org.apache.xpath.VariableStack myvs = xpathSupport.getVarStack(); Vector varVector = getVariableQNames(); for ( int i=0; i<varVector.size(); i++ ) { QName varQName = (QName)varVector.elementAt(i); try { XObject variableValue = vs.getVariableOrParam( xpathSupport, varQName ); //p("&&&&Variable set to => " + variableValue.toString() ); //p("&&&&Variable type => " + variableValue.getTypeString() ); myvs.setGlobalVariable( i, variableValue ); } catch ( TransformerException te ) { throw new JspTagException(te.toString(), te); } } return varVector; } //********************************************************************* // Static support for context retrieval from parent <forEach> tag public static Node getContext(Tag t) throws JspTagException { ForEachTag xt = (ForEachTag) TagSupport.findAncestorWithClass( t, ForEachTag.class); if (xt == null) return null; else return (xt.getContext()); } //********************************************************************* // Utility methods private static void p(String s) { System.out.println("[XPathUtil] " + s); } public static void printDetails(Node n) { System.out.println("\n\nDetails of Node = > " + n ) ; System.out.println("Name:Type:Node Value = > " + n.getNodeName() + ":" + n.getNodeType() + ":" + n.getNodeValue() ) ; System.out.println("Namespace URI : Prefix : localName = > " + n.getNamespaceURI() + ":" +n.getPrefix() + ":" + n.getLocalName()); System.out.println("\n Node has children => " + n.hasChildNodes() ); if ( n.hasChildNodes() ) { NodeList nl = n.getChildNodes(); System.out.println("Number of Children => " + nl.getLength() ); for ( int i=0; i<nl.getLength(); i++ ) { Node childNode = nl.item(i); printDetails( childNode ); } } } } class JSTLNodeList extends Vector implements NodeList { Vector nodeVector; public JSTLNodeList ( Vector nodeVector ) { this.nodeVector = nodeVector; } public JSTLNodeList ( NodeList nl ) { nodeVector = new Vector(); //System.out.println("[JSTLNodeList] nodelist details"); for ( int i=0; i<nl.getLength(); i++ ) { Node currNode = nl.item(i); //XPathUtil.printDetails ( currNode ); nodeVector.add(i, nl.item(i) ); } } public JSTLNodeList ( Node n ) { nodeVector = new Vector(); nodeVector.addElement( n ); } public Node item ( int index ) { return (Node)nodeVector.elementAt( index ); } public Object elementAt ( int index ) { return nodeVector.elementAt( index ); } public Object get ( int index ) { return nodeVector.get( index ); } public int getLength ( ) { return nodeVector.size( ); } public int size ( ) { //System.out.println("JSTL node list size => " + nodeVector.size() ); return nodeVector.size( ); } // Can implement other Vector methods to redirect those methods to // the vector in the variable param. As we are not using them as part // of this implementation we are not doing that here. If this changes // then we need to override those methods accordingly }

The table below shows all metrics for XPathUtil.java.

MetricValueDescription
BLOCKS105.00Number of blocks
BLOCK_COMMENT16.00Number of block comment lines
COMMENTS200.00Comment lines
COMMENT_DENSITY 0.42Comment density
COMPARISONS68.00Number of comparison operators
CYCLOMATIC96.00Cyclomatic complexity
DECL_COMMENTS28.00Comments in declarations
DOC_COMMENT87.00Number of javadoc comment lines
ELOC475.00Effective lines of code
EXEC_COMMENTS51.00Comments in executable code
EXITS98.00Procedure exits
FUNCTIONS28.00Number of function declarations
HALSTEAD_DIFFICULTY94.55Halstead difficulty
HALSTEAD_EFFORT 0.00Halstead effort
INTERFACE_COMPLEXITY105.00Interface complexity
JAVA0001 0.00JAVA0001 Package name does not contain only lower case letters
JAVA0002 0.00JAVA0002 Package name does not begin with a top level domain name or country code
JAVA0003 0.00JAVA0003 Minimize use of on-demand (.*) imports
JAVA0004 0.00JAVA0004 Unnecessary import from java.lang
JAVA0005 0.00JAVA0005 Imports not in specified order
JAVA0006 0.00JAVA0006 Empty finally block
JAVA0007 0.00JAVA0007 Should not declare public field
JAVA0008 0.00JAVA0008 Empty catch block
JAVA0009 0.00JAVA0009 Protected member in final class
JAVA0010 0.00JAVA0010 Non-instantiable class does not contain a non-private static member
JAVA0011 0.00JAVA0011 Abstract class does not contain an abstract method
JAVA0012 0.00JAVA0012 Non-constructor method with same name as declaring class
JAVA0013 0.00JAVA0013 Non-blank final field is not static
JAVA0014 0.00JAVA0014 Class with only static members has non-private constructor
JAVA0015 0.00JAVA0015 Package class contains public nested type
JAVA0016 0.00JAVA0016 Abstract class contains public constructor
JAVA0017 0.00JAVA0017 Class name does not have required form
JAVA0018 0.00JAVA0018 Method name does not have required form
JAVA0019 0.00JAVA0019 Interface name does not have required form
JAVA0020 0.00JAVA0020 Field name does not have required form
JAVA0021 0.00JAVA0021 Interface method name does not have required form
JAVA0022 0.00JAVA0022 Static final field name does not have required form
JAVA0023 0.00JAVA0023 Empty finalize method
JAVA0024 0.00JAVA0024 Empty class
JAVA0025 0.00JAVA0025 Method override is empty
JAVA0026 0.00JAVA0026 Finalize method with parameters
JAVA0029 2.00JAVA0029 Private method not used
JAVA0030 0.00JAVA0030 Private field not used
JAVA0031 0.00JAVA0031 Case statement not properly closed
JAVA0032 0.00JAVA0032 Switch statement missing default
JAVA0033 0.00JAVA0033 default: not last case in switch statement
JAVA0034 3.00JAVA0034 Missing braces in if statement
JAVA0035 1.00JAVA0035 Missing braces in for statement
JAVA0036 0.00JAVA0036 Missing braces in while statement
JAVA0038 0.00JAVA0038 Non-case label in switch statement
JAVA0039 0.00JAVA0039 Break statement with label
JAVA0040 0.00JAVA0040 Switch statement contains N cases (maximum: M)
JAVA0041 0.00JAVA0041 Nested synchronized block
JAVA0042 0.00JAVA0042 Empty synchronized statement
JAVA0043 0.00JAVA0043 Inner class does not use outer class
JAVA0044 0.00JAVA0044 Serializable class with no instance variables
JAVA0045 0.00JAVA0045 Serializable class with only transient fields
JAVA0046 0.00JAVA0046 Name of class not derived from Exception ends with 'Exception'
JAVA0047 0.00JAVA0047 Serializable class derives from invalid base class
JAVA0048 0.00JAVA0048 Name of class derived from Exception does not end with 'Exception'
JAVA0049 3.00JAVA0049 Nested block at depth N (maximum: M)
JAVA0050 0.00JAVA0050 Class derives from java.lang.Error
JAVA0051 0.00JAVA0051 Class derives from java.lang.RuntimeException
JAVA0052 0.00JAVA0052 Class derives from java.lang.Throwable
JAVA0053 0.00JAVA0053 Unused label
JAVA0054 0.00JAVA0054 Inheritance depth N exceeds maximum M
JAVA0055 0.00JAVA0055 Class should be interface
JAVA0056 0.00JAVA0056 Unnecessary abstract modifier for interface or annotation
JAVA0057 0.00JAVA0057 Unnecessary default constructor
JAVA0058 1.00JAVA0058 Constructor calls super()
JAVA0059 0.00JAVA0059 Method override only calls super()
JAVA0061 0.00JAVA0061 Inaccessible member in anonymous class
JAVA0062 0.00JAVA0062 Public class missing public member or protected constructor
JAVA0063 0.00JAVA0063 Identifier name should not contain '$'
JAVA0064 0.00JAVA0064 N variations of identifier name (maximum: M)
JAVA0065 0.00JAVA0065 Unnecessary final modifier for method in final class
JAVA0066 0.00JAVA0066 Unnecessary modifier for interface nested type
JAVA0067 0.00JAVA0067 Array descriptor on identifier name
JAVA0068 1.00JAVA0068 Modifiers not declared in recommended order
JAVA0071 0.00JAVA0071 Strings compared with ==
JAVA0073 0.00JAVA0073 Integer division in floating-point context
JAVA0074 0.00JAVA0074 Use of Object.notify()
JAVA0075 0.00JAVA0075 Method parameter hides field
JAVA0076 0.00JAVA0076 Use of magic number
JAVA0077 0.00JAVA0077 Private field not used in declaring class
JAVA0078 0.00JAVA0078 Floating point values compared with ==
JAVA0079 0.00JAVA0079 Use of instance to reference static member
JAVA0080 0.00JAVA0080 Import declaration not used
JAVA0081 0.00JAVA0081 Boolean literal in comparison
JAVA0082 2.00JAVA0082 Unnecessary widening cast
JAVA0083 0.00JAVA0083 Unnecessary instanceof test
JAVA0084 0.00JAVA0084 Should use compound assignment operator
JAVA0085 0.00JAVA0085 Use of sun.* class
JAVA0087 0.00JAVA0087 Use of Thread.sleep()
JAVA0089 0.00JAVA0089 Use of restricted package
JAVA0092 0.00JAVA0092 Use of restricted type
JAVA0093 0.00JAVA0093 Redundant assignment
JAVA0094 0.00JAVA0094 Field hides a superclass field
JAVA0095 0.00JAVA0095 Uninitialized private field
JAVA0096 0.00JAVA0096 Field in nested class hides outer field
JAVA0098 0.00JAVA0098 Minimize use of implicit field initializers
JAVA0100 0.00JAVA0100 Class contains N non-final fields (maximum: M)
JAVA0101 0.00JAVA0101 Unnecessary modifier for field in interface
JAVA0102 0.00JAVA0102 Last statement in finalize() not super.finalize()
JAVA0103 0.00JAVA0103 Explicit call to finalize()
JAVA0104 0.00JAVA0104 finalize() only calls super.finalize()
JAVA0105 0.00JAVA0105 Duplicate import declaration
JAVA0106 0.00JAVA0106 Unnecessary import from current package
JAVA010820.00JAVA0108 Incorrect javadoc: no @param tag for 'parameter'
JAVA0109 0.00JAVA0109 Incorrect javadoc: no parameter 'parameter'
JAVA011010.00JAVA0110 Incorrect javadoc: no @return tag
JAVA0111 0.00JAVA0111 Incorrect javadoc: @return tag for void method
JAVA0112 0.00JAVA0112 Incorrect javadoc: no exception 'exception' in throws
JAVA0113 0.00JAVA0113 Incorrect javadoc: no @author tag
JAVA0114 1.00JAVA0114 Incorrect javadoc: no @version tag
JAVA0115 9.00JAVA0115 Incorrect javadoc: no @throws or @exception tag for 'exception'
JAVA0116 0.00JAVA0116 Missing javadoc: field 'field'
JAVA0117 7.00JAVA0117 Missing javadoc: method 'method'
JAVA0118 0.00JAVA0118 Missing javadoc: type 'type'
JAVA0119 0.00JAVA0119 Control variable changed within body of for loop
JAVA0123 0.00JAVA0123 Use all three components of for loop
JAVA0125 0.00JAVA0125 Continue statement with label
JAVA0126 0.00JAVA0126 Method declares unchecked exception in throws
JAVA0128 4.00JAVA0128 Public constructor in non-public class
JAVA0130 0.00JAVA0130 Non-static method does not use instance fields
JAVA0131 0.00JAVA0131 Compatible method does not override base
JAVA0132 0.00JAVA0132 Method overload with compatible signature
JAVA0133 3.00JAVA0133 Non-synchronized method overrides synchronized method
JAVA0135 0.00JAVA0135 Only one of Object.equals and Object.hashCode defined: missing 'method'
JAVA0136 0.00JAVA0136 N methods defined in class (maximum: M)
JAVA0137 0.00JAVA0137 Non-abstract class missing constructor
JAVA0138 0.00JAVA0138 N parameters defined for method (maximum: M)
JAVA0139 0.00JAVA0139 Definition of main other than public static void main(java.lang.String[])
JAVA0141 0.00JAVA0141 Unnecessary modifier for method in interface
JAVA0143 1.00JAVA0143 Synchronized method
JAVA0144 0.00JAVA0144 Line exceeds maximum M characters
JAVA0145 2.00JAVA0145 Tab character used in source file
JAVA0150 0.00JAVA0150 java.lang.Error (or subclass) thrown
JAVA0153 0.00JAVA0153 Inefficient conversion of integer to string
JAVA0159 0.00JAVA0159 Inefficient conversion of string to integer
JAVA0160 0.00JAVA0160 Method does not throw specified exception
JAVA0161 0.00JAVA0161 Conditional wait() not in loop
JAVA0163 0.00JAVA0163 Empty statement
JAVA0165 0.00JAVA0165 Conflicting return statement in finally block
JAVA0166 2.00JAVA0166 Generic exception caught
JAVA0167 0.00JAVA0167 ThreadDeath not rethrown
JAVA0169 0.00JAVA0169 Unnecessary catch block: exception 'exception'
JAVA0170 0.00JAVA0170 Caught exception not derived from java.lang.Exception
JAVA0171 2.00JAVA0171 Unused local variable
JAVA0173 1.00JAVA0173 Unused method parameter
JAVA0174 0.00JAVA0174 Assigned local variable never used
JAVA0175 0.00JAVA0175 Successive assignment to variable
JAVA0176 0.00JAVA0176 Local variable name does not have required form
JAVA0177 0.00JAVA0177 Variable declaration missing initializer
JAVA0179 0.00JAVA0179 Local variable hides visible field
JAVA0233 0.00JAVA0233 Definition of serialVersionUID other than 'private static final long serialVersionUID'
JAVA0234 1.00JAVA0234 Class is Serializable but does not define serialVersionUID
JAVA0235 0.00JAVA0235 Class defines serialVersionUID but does not implement Serializable
JAVA0236 0.00JAVA0236 Attempt to clone an object which does not implement Cloneable
JAVA0237 0.00JAVA0237 Class implements Cloneable but does not have public clone method
JAVA0238 0.00JAVA0238 Clone method does not call super.clone()
JAVA0239 0.00JAVA0239 Class declares 'readObject' or 'writeObject' but does not implement Serializable
JAVA0240 0.00JAVA0240 Serializable class which declares readObject or writeObject but not both
JAVA0241 0.00JAVA0241 'readObject' or 'writeObject' should be declared private in Serializable class
JAVA0242 0.00JAVA0242 Transient field in non-Serializable class
JAVA0243 0.00JAVA0243 'readResolve' or 'writeReplace' should be declared private or protected
JAVA0244 0.00JAVA0244 Field or method name in subclass differs only by case from inherited field or method
JAVA0245 0.00JAVA0245 JUnit TestCase with non-trivial constructor
JAVA0246 0.00JAVA0246 JUnit assertXXX statement missing message parameter
JAVA0247 0.00JAVA0247 JUnit 'setUp()' and 'tearDown()' should call super method
JAVA0248 0.00JAVA0248 JUnit method 'setUp' or 'tearDown' with incorrect signature
JAVA0249 0.00JAVA0249 JUnit TestCase 'suite()' should be declared static
JAVA0250 0.00JAVA0250 JUnit TestCase declares testXXX method with incorrect signature
JAVA0251 0.00JAVA0251 Use '%n' for line breaks in printf/format for platform independence
JAVA0252 0.00JAVA0252 'enum' is a Java 1.5 reserved word
JAVA0253 0.00JAVA0253 Not all enum constants consumed in switch statement
JAVA0254 0.00JAVA0254 Use enhanced for loop construct instead of Iterator
JAVA0255 0.00JAVA0255 Result of method invocation not used
JAVA0256 1.00JAVA0256 Assignment of external collection/array to field
JAVA0257 0.00JAVA0257 Use of 'Constant Interface' anti-pattern
JAVA0258 0.00JAVA0258 Implement Iterable for foreach compatibility
JAVA0259 0.00JAVA0259 Return of collection/array field
JAVA0260 0.00JAVA0260 Use 'enum' instead of Enumerated Type pattern
JAVA0261 0.00JAVA0261 Use specialized Enum collection types
JAVA0262 0.00JAVA0262 Use of char in integer context
JAVA0263 0.00JAVA0263 Long literal ends with 'l' instead of 'L'
JAVA0264 0.00JAVA0264 Integer math in long context - check for overflow
JAVA0265 3.00JAVA0265 Use of Throwable.printStackTrace()
JAVA0266 8.00JAVA0266 Use of System.out
JAVA0267 0.00JAVA0267 Use of System.err
JAVA0269 0.00JAVA0269 Contents of StringBuffer never used
JAVA0270 2.00JAVA0270 Use Java 5.0 enhanced for loop construct to iterate over all elements in an array
JAVA0271 0.00JAVA0271 Minimize use of on-demand (.*) static imports
JAVA0272 0.00JAVA0272 Thread.run() called
JAVA0273 0.00JAVA0273 Non-final derivative of Thread calls start() in constructor
JAVA0274 0.00JAVA0274 Serializable class has a synchronized readObject()
JAVA0275 0.00JAVA0275 Serializable class has a synchronized writeObject() and no other synchronized methods
JAVA0276 0.00JAVA0276 Unnecessary use of String constructor
JAVA0277 0.00JAVA0277 Iterator.next() implementation does not throw NoSuchElementException
JAVA0278 1.00JAVA0278 Unnecessary use of Boolean constructor
JAVA0279 0.00JAVA0279 Serialization method readObject or readObjectNoData calls an overridable method
JAVA0280 0.00JAVA0280 IllegalMonitorStateException caught
JAVA0281 0.00JAVA0281 Iterator.next() not called in loop
JAVA0282 0.00JAVA0282 Call to Iterator.next() in loop which does not test Iterator.hasNext()
JAVA0283 0.00JAVA0283 Control variable not updated in loop body
JAVA0284 0.00JAVA0284 Explicit garbage collection
JAVA0285 0.00JAVA0285 Dereference of potentially null variable
JAVA0286 0.00JAVA0286 Dereference of null variable
JAVA0287 0.00JAVA0287 Unnecessary null check
JAVA0288 0.00JAVA0288 Inconsistent null check
LINES896.00Number of lines in the source file
LINE_COMMENT97.00Number of line comments
LOC554.00Lines of code
LOGICAL_LINES306.00Number of statements
LOOPS14.00Number of loops
NEST_DEPTH 8.00Maximum nesting depth
OPERANDS1435.00Number of operands
OPERATORS2433.00Number of operators
PARAMS32.00Number of formal parameter declarations
PROGRAM_LENGTH3868.00Halstead program length
PROGRAM_VOCAB438.00Halstead program vocabulary
PROGRAM_VOLUME 0.00Halstead program volume
RETURNS73.00Number of return points from functions
SIZE35278.00Size of the file in bytes
UNIQUE_OPERANDS387.00Number of unique operands
UNIQUE_OPERATORS51.00Number of unique operators
WHITESPACE142.00Number of whitespace lines