Tuesday, May 29, 2012

Some handy utility methods for XPath

Some handy utility methods for XPath:

import com.collaxa.cube.xml.xpath.SimpleNamespaceContext;
import java.util.*;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.*;
import oracle.bpel.services.common.util.XMLUtil;
import oracle.tip.pc.infra.exception.PCException;

import oracle.xml.xpath.JXPathFactory;
import org.w3c.dom.*;

    public class XPathUtils
{

    public XPathUtils()
    {
    }

    public static NodeList selectNodes(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static NodeList selectNodes(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static NodeList selectNodes(Element pElement, String xpathExpression, NamespaceContext namespaceContext)
        throws Exception
    {
        XPath xPath = createXPath(namespaceContext);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        NodeList value = (NodeList)xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static Object evaluate(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Object value = xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static Object evaluate(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Object value = xPath.evaluate(xpathExpression, doc, XPathConstants.NODESET);
        return value;
    }

    public static Object selectSingleNode(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Node value = (Node)xPath.evaluate(xpathExpression, doc, XPathConstants.NODE);
        return value;
    }

    public static Object selectSingleNode(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Node value = (Node)xPath.evaluate(xpathExpression, doc, XPathConstants.NODE);
        return value;
    }

    public static String valueOf(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
           
        String value = (String)xPath.evaluate(xpathExpression, doc, XPathConstants.STRING);
        return value;
    }

    public static String valueOf(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        String value = (String)xPath.evaluate(xpathExpression, doc, XPathConstants.STRING);
        return value;
    }

    public static Number numberValueOf(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Number nValue = (Number)xPath.evaluate(xpathExpression, doc, XPathConstants.NUMBER);
        return nValue;
    }

    public static Number numberValueOf(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Number nValue = (Number)xPath.evaluate(xpathExpression, doc, XPathConstants.NUMBER);
        return nValue;
    }


    public static boolean booleanValueOf(Element pElement, String xpathExpression)
        throws Exception
    {
        XPath xPath = createXPath();
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Boolean bValue = (Boolean)xPath.evaluate(xpathExpression, doc, XPathConstants.BOOLEAN);
        return bValue.booleanValue();
    }

    public static boolean booleanValueOf(Element pElement, String xpathExpression, Map prefixNamespaceMapping)
        throws Exception
    {
        XPath xPath = createXPath(prefixNamespaceMapping);
        Document doc = null;
        if(pElement instanceof Document)
            doc = (Document)pElement;
        else
            doc = pElement != null ? pElement.getOwnerDocument() : null;
        Boolean bValue = (Boolean)xPath.evaluate(xpathExpression, doc, XPathConstants.BOOLEAN);
        return bValue.booleanValue();
    }

    private static XPath createXPath()
        throws Exception
    {
        return getXPath(null);
    }

    private static XPath createXPath(NamespaceContext namespaceContext)
    {
        return getXPath(namespaceContext);
    }

    private static XPath createXPath(Map namespaceMapping)
    {
        XPath xpath = null;
        NamespaceContext nc = null;
        if(namespaceMapping != null)
        {
            if(namespaceMapping.containsKey(""))
                namespaceMapping.remove("");
            nc = new SimpleNamespaceContext(namespaceMapping);
        }
        xpath = getXPath(nc);
        return xpath;
    }

    public static XPath getXPath(NamespaceContext nsContext)
    {
        JXPathFactory xpfac = new JXPathFactory();
        XPath xpath = xpfac.newXPath();
        if(nsContext != null)
            xpath.setNamespaceContext(nsContext);
        return xpath;
    }
   
   
   public static  String getNodeValue(NodeList nodes) {
        Node node = nodes.item(0);
        String value = null;
        if(nodes.getLength()>0){
        NodeList children = node.getChildNodes();
        int length = children.getLength();
        if (length == 1) {
            Node textNode = children.item(0);
            value = textNode.getNodeValue();
        }
        }
        return value;
       
    }
   
   
   public static  int getNodeType(String xpath) {
        String lastPart = xpath.substring(xpath.lastIndexOf("/") + 1);
        return !lastPart.startsWith("@") ? 1 : 2;
    }
   
   public static  Node getNode(Element payload, String xpath,
                 Map nameSpaceMap) throws PCException {
        Node node = null;

        NodeList nodes;
        try {
            nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, nameSpaceMap);
        } catch (Exception e) {
            return null;
        }
        if (nodes == null || nodes.getLength() == 0)
            return null;
        if (nodes.getLength() == 1) {
            node = nodes.item(0);
        } else {
            Object obj[] = { xpath };
            throw new PCException(10175, obj);
        }

        return node;
    }
   
    public static Node appendChildNode(Element payload, Map nameSpaceMap, String xpath,
                        Node parentNode) throws PCException {
       if (parentNode == null) {
           Object obj[] = { xpath + "(cannot append to empty parent)" };
           throw new PCException(10175, obj);
       }
       short nodeType = (short)getNodeType(xpath);
       String lastPart = xpath.substring(xpath.lastIndexOf("/") + 1);
       if (lastPart.startsWith("@"))
           lastPart = lastPart.substring(1);
       int colon = lastPart.indexOf(58);
       String localNS = null;
       if (colon > 0)
           localNS = lastPart.substring(0, colon);
       String localName = lastPart.substring(colon + 1);
       Node node;
       if (nodeType == 2) {
           if (localNS == null)
               node = parentNode.getOwnerDocument().createAttribute(localName);
           else
               node = parentNode.getOwnerDocument().createAttributeNS((String)nameSpaceMap.get(localNS), localName);
       } else if (nodeType == 1) {
           if (localNS == null)
               node = parentNode.getOwnerDocument().createElement(localName);
           else
               node = parentNode.getOwnerDocument().createElementNS((String)nameSpaceMap.get(localNS),
                                             localName);
       } else {
           Object obj[] = { xpath + "(cannot determine node type)" };
           throw new PCException(10175, obj);
       }
       parentNode.appendChild(node);
       return node;
    }
   
    public static Map getNamespaces(Element rootElement) {
        NamedNodeMap attrs = rootElement.getFirstChild().getAttributes();
        int len = attrs.getLength();
        Hashtable namespaces = new Hashtable();
        namespaces.put("ns0", "http://xmlns.oracle.com/bpel/workflow/task");
        for (int i = 0; i < len; i++) {
            Node node = attrs.item(i);
            String name = node.getNodeName();
            if (name.startsWith("xmlns:ns")) {
                String key = name.substring(name.indexOf(":") + 1);
                namespaces.put(key, node.getNodeValue());
            }
        }

        return namespaces;
    }
   
    public static void setNodeValue(Element payload, Map namespacemap, String xpath,
                      String value) throws Exception {
        Node node = null;
        NodeList nodes = null;
        NodeList children =null;
        int length = 0;
        try {
            nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, namespacemap);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
       
        node = nodes.item(0);
       
        if(nodes.getLength()>0){
        children = node.getChildNodes();
        length = children.getLength();
       
       
        if (length == 1) {
            Node textNode = children.item(0);
            String oldValue = textNode.getNodeValue();               
            value=value==null?"":value;
            oldValue=oldValue==null?"":oldValue;
           
            if (!oldValue.equals(value)) {
                textNode.setNodeValue(value);
            }
        } else if (length == 0 && value != null && !value.equals("")) {
            Node valueNode = node.getOwnerDocument().createTextNode(value);
            node.appendChild(valueNode);
            }
        }
    }
    public static Node createNode(Element payload, Map nameSpaceMap,
                    String xpath) throws PCException {
        if (xpath == "/ns0:task/ns0:payload") {
            Object obj[] = { xpath };
            throw new PCException(10175, obj);
        }
        String parentXPath = xpath.substring(0, xpath.lastIndexOf("/"));
       
        Node parentNode = getNode(payload, parentXPath, nameSpaceMap);
        if (parentNode == null)
            parentNode = createNode(payload, nameSpaceMap, parentXPath);
        return appendChildNode(payload, nameSpaceMap, xpath, parentNode);
    }
   
    public static void removeNode(Element payload, String xpath,Map nameSpaceMap) throws Exception
    {
      NodeList nodes=null;
   
      try
      {
        nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, nameSpaceMap);      
        for(int i=0;i<nodes.getLength();i++)
        {
          nodes.item(i).getParentNode().removeChild(nodes.item(i)) ;
        }
      }
      catch (Exception e)
      {
        e.printStackTrace();
        throw e;
      }
    }
   
    public static boolean isNodePresent(Element payload, Map namespacemap, String xpath)
    {
        NodeList nodes = null;
        try {
            nodes = XPathUtils.selectNodes(XMLUtil.getDocumentElement(payload), xpath, namespacemap);
        } catch (Exception e) {
           e.printStackTrace();
        }
       
        if(nodes.getLength()==0)
          return false;  
        else
         return true;
    }
}

No comments:

Post a Comment