Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  *
  *
  * This file incorporates work covered by the following copyright and
  * permission notice:
  *
  * Copyright 2004 The Apache Software Foundation
  *
  * Licensed 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.List;
 
 

Support for tag handlers that evaluate XPath expressions.

Author(s):
Shawn Bayern
Ramesh Mandava ( ramesh.mandava@sun.com )
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) {
         = pc;
    }    
    
    //*********************************************************************
    // 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";
    
    //*********************************************************************
    // Support for XPath evaluation
    
    private PageContext pageContext;
    private static HashMap exprCache;
    private static JSTLXPathNamespaceContext jstlXPathNamespaceContext = null;
    private static final String XPATH_FACTORY_CLASS_NAME = JSTLXPathFactory.class.getName();
    private static XPathFactory XPATH_FACTORY;
    static {
        try {
        } catch (XPathFactoryConfigurationException xpce) {
            xpce.printStackTrace();
        }
    }
    
    
Initialize globally useful data.
    private synchronized static void staticInit() {
        if ( == null) {
            // register supported namespaces
             = new JSTLXPathNamespaceContext();
            .addNamespace("pageScope");
            .addNamespace("requestScope");
            .addNamespace("sessionScope");
            .addNamespace("applicationScope");
            .addNamespace("param");
            .addNamespace("initParam");
            .addNamespace("header");
            .addNamespace("cookie");
            
            
            // create a HashMap to cache the expressions
             = new HashMap();
        }
    }
    
    static DocumentBuilderFactory dbf = null;
    static DocumentBuilder db = null;
    static Document d = null;
    
    static Document getDummyDocument( ) {
        try {
            if (  == null ) {
                 = DocumentBuilderFactory.newInstance();
                .setNamespaceAwaretrue );
                .setValidatingfalse );
            }
             = .newDocumentBuilder();
            DOMImplementation dim = .getDOMImplementation();
             = dim.createDocument("http://java.sun.com/jstl""dummyroot"null); 
            //d = db.newDocument();
            return ;
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }
     static Document getDummyDocumentWithoutRoot( ) {
        try {
            if (  == null ) {
                 = DocumentBuilderFactory.newInstance();
                .setNamespaceAwaretrue );
                .setValidatingfalse );
            }
             = .newDocumentBuilder();
             = .newDocument();
            return ;
        } catch ( Exception e ) {
            e.printStackTrace();
        }
        return null;
    }
    
    // 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 nString xpathStringthrows JspTagException {
        // p("******** valueOf(" + n + ", " + xpathString + ")");
        staticInit();
        Node contextNode = adaptParamsForXalan(nxpathString.trim(), jxvr);
        XPath xpath = .newXPath();
        xpath.setXPathVariableResolver(jxvr);
        try {
            return xpath.evaluate(xpathStringcontextNode);
        } catch (XPathExpressionException ex) {
            throw new JspTagException(ex.toString(), ex);
        }
    }
    
    
    
Evaluate an XPath expression to a boolean value.
    public boolean booleanValueOf(Node nString xpathString)
    throws JspTagException {
        
        staticInit();
        Node contextNode = adaptParamsForXalan(nxpathString.trim(), jxvr);
        xpathString = ;
        
        XPath xpath = .newXPath();
        xpath.setXPathVariableResolver(jxvr);
        try {
            return ((Booleanxpath.evaluate(
              xpathStringcontextNode.)).booleanValue();
        } catch (XPathExpressionException 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 nString xpathString)  
        throws JspTagException {
        
        staticInit();
        Node contextNode = adaptParamsForXalan(nxpathString.trim(), jxvr);
        xpathString = ;
        
        try {
            XPath xpath = .newXPath();
            xpath.setNamespaceContext();
            xpath.setXPathVariableResolver(jxvr);
            Object nl = xpath.evaluate(
                xpathStringcontextNode.);
            return new JSTLNodeListnl );
        } catch (XPathExpressionException ex ) {
            throw new JspTagException(ex.toString(), ex);
        }
    }
    
    
Evaluate an XPath expression to a single node.
    public Node selectSingleNode(Node nString xpathString)
    throws JspTagException {
        //p("selectSingleNode of XPathUtil = passed node:" +
        //   "xpathString => " + n + " : " + xpathString );
        
        staticInit();
        Node contextNode = adaptParamsForXalan(nxpathString.trim(), jxvr);
        xpathString = ;
        
        try {
            XPath xpath = .newXPath();
            xpath.setNamespaceContext();
            xpath.setXPathVariableResolver(jxvr);
            return (Nodexpath.evaluate(
                xpathStringcontextNode.);
        } catch (XPathExpressionException ex) {
            throw new JspTagException(ex.toString(), ex);            
        }
    }
    
    //*********************************************************************
    // 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(Node n
                                       String xpath
                                       XPathVariableResolver jxvr) {
        Node boundDocument = null;
        
         = xpath;
        String origXPath = xpath;
        boolean whetherOrigXPath = true;
        
        // If contextNode is not null then  just pass the values to Xalan XPath
        if ( n != null ) {
            return n;
        }
        
        if (  xpath.startsWith("$")  ) {
            // JSTL uses $scopePrefix:varLocalName/xpath expression
            String varQName=  xpath.substringxpath.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.substringvarQName.indexOf(":")+1 );
            }
            
            if ( xpath.indexOf("/") > 0 ) {
                xpath = xpath.substringxpath.indexOf("/"));
            } else  {
                xpath = "/*";
                whetherOrigXPath = false
            }
           
            
            try {
                Object varObject=((JSTLXPathVariableResolverjxvr).getVariableValue(""varPrefix,
                    varLocalName);
                //p( "varObject => : its Class " +varObject +
                // ":" + varObject.getClass() );
                
                if ( Class.forName("org.w3c.dom.Document").isInstance(
                    varObject ) )  {
                    //boundDocument = ((Document)varObject).getDocumentElement();
                    boundDocument = ((Document)varObject);
                } else {
                    
                    //p("Creating a Dummy document to pass " +
                    // " onto as context node " );
                    
                    if ( Class.forName("org.apache.taglibs.standard.tag.common.xml.JSTLNodeList").isInstancevarObject ) ) {
                        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);
                                Document doc = getDummyDocumentWithoutRoot();
                                Node importedNode = doc.importNodenodetrue);
                                doc.appendChild (importedNode );
                                boundDocument = doc;
                                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; ijstlNodeList.getLength(); i++ ) {
                                Node currNode = (Node)jstlNodeList.item(i);
                            
                                Node importedNode = newDocument.importNode(
                                    currNodetrue );
                                //printDetails ( newDocument);
                                dummyroot.appendChildimportedNode );
                                //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 = (Node)varObject;
                    } else {
                        boundDocument = getDummyDocument();
                        xpath = origXPath;
                    }
                    
                    
                }
            } catch ( UnresolvableException ue ) {
                // FIXME: LOG
                // p("Variable Unresolvable :" + ue.getMessage());
                ue.printStackTrace();
            } catch ( ClassNotFoundException cnf ) {
                // Will never happen
            }
        } else { 
            //p("Not encountered $ Creating a Dummydocument 2 "+
            //   "pass onto as context node " );
            boundDocument = getDummyDocument();
        }
     
         = xpath;
        //p("Modified XPath::boundDocument =>" + modifiedXPath +
        //    "::" + boundDocument );
         
        return boundDocument;
    }
    
    //*********************************************************************
    // 
    
    
    //*********************************************************************
    // Static support for context retrieval from parent <forEach> tag
    
    public static Node getContext(Tag tthrows JspTagException {
        ForEachTag xt =
        (ForEachTag) TagSupport.findAncestorWithClass(
        tForEachTag.class);
        if (xt == null)
            return null;
        else
            return (xt.getContext());
    }
    
    //*********************************************************************
    // Utility methods
    
    private static void p(String s) {
        ..println("[XPathUtil] " + s);
    }
    
    public static void printDetails(Node n) {
        p("\n\nDetails of Node = > " + n ) ;
        p("Name:Type:Node Value = > " + n.getNodeName() +
        ":" + n.getNodeType() + ":" + n.getNodeValue()  ) ;
        p("Namespace URI : Prefix : localName = > " +
        n.getNamespaceURI() + ":" +n.getPrefix() + ":" + n.getLocalName());
        p("\n Node has children => " + n.hasChildNodes() );
        if ( n.hasChildNodes() ) {
            NodeList nl = n.getChildNodes();
            p("Number of Children => " + nl.getLength() );
            for ( int i=0; i<nl.getLength(); i++ ) {
                Node childNode = nl.item(i);
                printDetailschildNode );
            }
        }
    }    
class JSTLNodeList extends Vector implements NodeList   {
    
    public JSTLNodeList ( Vector nodeVector ) {
        this. = nodeVector;
    }
    public JSTLNodeList ( NodeList nl ) {
         = new Vector();
        //p("[JSTLNodeList] nodelist details");
        for ( int i=0; i<nl.getLength(); i++ ) {
            Node currNode = nl.item(i);
            //XPathUtil.printDetails ( currNode );
            .add(inl.item(i) );
        }
    }
    public JSTLNodeList ( Node n ) {
         = new Vector();
        .addElementn );
    }
    public JSTLNodeList (Object o) {
         = new Vector();
        
        if (o instanceof NodeList) {
            NodeList nl = (NodeList)o;
            for ( int i=0; i<nl.getLength(); i++ ) {
                Node currNode = nl.item(i);
                //XPathUtil.printDetails ( currNode );
                .add(inl.item(i) );
            }
        } else {
            .addElemento );
        }
    }
    public Node item ( int index ) {
        return (Node).elementAtindex );
    }
    public Object elementAt ( int index ) {
        return .elementAtindex );
    }
    public Object get ( int index ) {
        return .getindex );
    }
    public int getLength (  ) {
        return .size( );
    }
    public int size (  ) {
        //p("JSTL node list size => " + nodeVector.size() );
        return .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  
}
         



New to GrepCode? Check out our FAQ X