Example usage for org.w3c.dom Node TEXT_NODE

List of usage examples for org.w3c.dom Node TEXT_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node TEXT_NODE.

Prototype

short TEXT_NODE

To view the source code for org.w3c.dom Node TEXT_NODE.

Click Source Link

Document

The node is a Text node.

Usage

From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java

/**
 * Process the mappings after xsl transformation
 * //from  www.  ja  v  a  2 s  .  co m
 * @param xrefElement
 * @return the processed Element
 */
private Element processMappings(Element xrefElement) throws XtentisException {

    try {

        String xrefcluster = xrefElement.getAttribute("xrefCluster"); //$NON-NLS-1$

        String xrefIn = xrefElement.getAttribute("xrefIn"); //$NON-NLS-1$
        String xrefOut = xrefElement.getAttribute("xrefOut"); //$NON-NLS-1$
        String xrefIgnore = xrefElement.getAttribute("xrefIgnore"); //$NON-NLS-1$
        String xrefDefault = xrefElement.getAttribute("xrefDefault"); //$NON-NLS-1$

        Logger.getLogger(XSLTTransformerPluginBean.class)
                .debug("\n xrefIgnore=" + xrefIgnore + "\n xrefDefault=" + xrefDefault); //$NON-NLS-1$ //$NON-NLS-2$

        // parse xrefbein dockey1:xrefkey1,dockey2:xrefkey2
        String[] mappings = xrefIn.split(","); //$NON-NLS-1$
        HashMap<String, String> itemvals = new HashMap<String, String>();
        for (int j = 0; j < mappings.length; j++) {
            String[] relations = mappings[j].split("="); //$NON-NLS-1$
            String docpath = relations[0];
            String xrefpath = relations[1];
            String itemval = ""; //$NON-NLS-1$
            try {
                if (docpath.startsWith("[")) // hardcoded value //$NON-NLS-1$
                    itemval = docpath.substring(1, docpath.length() - 1);
                else
                    itemval = Util.getFirstTextNode(xrefElement, docpath);
            } catch (Exception x) {
                throw new XtentisException(
                        "Value for business element '" + xrefElement.getNodeName() + '/' + docpath //$NON-NLS-1$
                                + "' cannot be found!"); //$NON-NLS-1$
            }
            if (itemval == null)
                itemval = ""; //$NON-NLS-1$
            String content = stripeOuterBracket(itemval);
            if (content.split(",").length >= mappings.length) //$NON-NLS-1$
                itemvals.put(xrefpath, content.split(",")[j]); //$NON-NLS-1$
            else
                itemvals.put(xrefpath, ""); //$NON-NLS-1$
        }

        WhereAnd wAnd = new WhereAnd();

        Collection<Map.Entry<String, String>> c = itemvals.entrySet();
        int i = 0;
        for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) {
            i++;
            Map.Entry<String, String> entry = iter.next();
            wAnd.add(new WhereCondition(entry.getKey(), WhereCondition.EQUALS, entry.getValue(),
                    WhereCondition.PRE_NONE, false));
        }

        ArrayList<String> resList = Util.getItemCtrl2Local().xPathsSearch(new DataClusterPOJOPK(xrefcluster),
                null, new ArrayList<String>(Arrays.asList(new String[] { xrefOut })), wAnd, -1, // spell
                0, // start
                1, // limit
                false);

        String val = ""; //$NON-NLS-1$

        if ((resList == null) || (resList.size() == 0)) {
            if (xrefIgnore.equals("true") || xrefIgnore.equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$
                if (xrefDefault != null)
                    val = xrefDefault;
                else
                    val = ""; //$NON-NLS-1$
            } else {
                String ks = ""; //$NON-NLS-1$
                c = itemvals.entrySet();
                for (Iterator<Map.Entry<String, String>> iter = c.iterator(); iter.hasNext();) {
                    Map.Entry<String, String> entry = iter.next();
                    ks += " " + entry.getKey() + "=\"" + entry.getValue() + "\""; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                }
                throw new XtentisException("Foreign keys values not found for: " + ks); //$NON-NLS-1$
            }
        } else {
            // read result
            Pattern p = Pattern.compile("<.*?>(.*?)</.*>", Pattern.DOTALL); //$NON-NLS-1$
            Matcher m = p.matcher(resList.iterator().next());

            if (m.matches())
                val = StringEscapeUtils.unescapeXml(m.group(1));
            else {
                Pattern p2 = Pattern.compile("<.*?/>", Pattern.DOTALL); //$NON-NLS-1$
                Matcher m2 = p2.matcher(resList.iterator().next());
                if (!m2.matches() && !(xrefIgnore.equals("true") || xrefIgnore.equals("1"))) { //$NON-NLS-1$ //$NON-NLS-2$
                    throw new XtentisException("Result values were not understood for crossref element"); //$NON-NLS-1$
                }
            }
        }

        NodeList l = xrefElement.getChildNodes();
        for (int j = 0; j < l.getLength(); j++) {
            switch (l.item(j).getNodeType()) {
            case Node.TEXT_NODE:
                l.item(j).setNodeValue(val);
                break;
            case Node.ELEMENT_NODE:
                xrefElement.removeChild(l.item(j));
                break;
            default:

            }
        }

        xrefElement.removeAttribute("xrefCluster"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefIgnore"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefDefault"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefIn"); //$NON-NLS-1$
        xrefElement.removeAttribute("xrefOut"); //$NON-NLS-1$

        return xrefElement;
    } catch (Exception e) {
        String err = "Unable to process the mappings for the element '" + xrefElement.getLocalName() + "'"; //$NON-NLS-1$ //$NON-NLS-2$
        LOG.error(err, e);
        throw new XtentisException(err);
    }
}

From source file:com.zeroio.webdav.WebdavServlet.java

/**
 * PROPFIND Method.// ww  w. j  ava  2s. c  om
 *
 * @param context Description of the Parameter
 * @throws ServletException Description of the Exception
 * @throws IOException      Description of the Exception
 */
protected void doPropfind(ActionContext context) throws ServletException, IOException {

    String path = getRelativePath(context.getRequest());

    //fix for windows clients
    if (path.equals("/files")) {
        path = "";
    }

    if (path.endsWith("/")) {
        path = path.substring(0, path.length() - 1);
    }

    if ((path.toUpperCase().startsWith("/WEB-INF")) || (path.toUpperCase().startsWith("/META-INF"))) {
        context.getResponse().sendError(WebdavStatus.SC_FORBIDDEN);
        return;
    }

    if (path.indexOf("/.") > -1 || path.indexOf(".DS_Store") > -1) {
        //Fix for MACOSX finder. Do not allow requests for files starting with a period
        return;
    }
    //System.out.println("METHOD PROPFIND....PATH: " + path);
    // Properties which are to be displayed.
    Vector properties = null;
    // Propfind depth by default 1 for performance reasons
    int depth = 1;
    // Propfind type
    int type = FIND_ALL_PROP;

    String depthStr = context.getRequest().getHeader("Depth");
    if (depthStr == null) {
        depth = INFINITY;
    } else {
        if (depthStr.equals("0")) {
            depth = 0;
        } else if (depthStr.equals("1")) {
            depth = 1;
        } else if (depthStr.equals("infinity")) {
            depth = INFINITY;
        }
    }

    /*
     *  Read the request xml and determine all the properties
     */
    Node propNode = null;
    DocumentBuilder documentBuilder = getDocumentBuilder();
    try {
        Document document = documentBuilder.parse(new InputSource(context.getRequest().getInputStream()));
        // Get the root element of the document
        Element rootElement = document.getDocumentElement();
        NodeList childList = rootElement.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                if (currentNode.getNodeName().endsWith("prop")) {
                    type = FIND_BY_PROPERTY;
                    propNode = currentNode;
                }
                if (currentNode.getNodeName().endsWith("propname")) {
                    type = FIND_PROPERTY_NAMES;
                }
                if (currentNode.getNodeName().endsWith("allprop")) {
                    type = FIND_ALL_PROP;
                }
                break;
            }
        }
    } catch (Exception e) {
        // Most likely there was no content : we use the defaults.
        // TODO : Enhance that !
        //e.printStackTrace(System.out);
    }

    if (type == FIND_BY_PROPERTY) {
        properties = new Vector();
        if (!properties.contains("creationdate")) {
            //If the request did not contain creationdate property then add this to requested properties
            //to make the information available for clients
            properties.addElement("creationdate");
        }
        NodeList childList = propNode.getChildNodes();
        for (int i = 0; i < childList.getLength(); i++) {
            Node currentNode = childList.item(i);
            switch (currentNode.getNodeType()) {
            case Node.TEXT_NODE:
                break;
            case Node.ELEMENT_NODE:
                String nodeName = currentNode.getNodeName();
                String propertyName = null;
                if (nodeName.indexOf(':') != -1) {
                    propertyName = nodeName.substring(nodeName.indexOf(':') + 1);
                } else {
                    propertyName = nodeName;
                }
                // href is a live property which is handled differently
                properties.addElement(propertyName);
                break;
            }
        }
    }

    // Properties have been determined
    // Retrieve the resources

    Connection db = null;
    boolean exists = true;
    boolean status = true;
    Object current = null;
    Object child = null;
    ModuleContext resources = null;
    SystemStatus thisSystem = null;
    StringBuffer xmlsb = new StringBuffer();
    try {
        db = this.getConnection(context);
        resources = getCFSResources(db, context);
        if (resources == null) {
            context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
        thisSystem = this.getSystemStatus(context);
        current = resources.lookup(thisSystem, db, path);
        if (current instanceof ModuleContext) {
            //System.out.println( ((ModuleContext) current).toString());
        }
    } catch (NamingException e) {
        //e.printStackTrace(System.out);
        exists = false;
        int slash = path.lastIndexOf('/');
        if (slash != -1) {
            String parentPath = path.substring(0, slash);
            Vector currentLockNullResources = (Vector) lockNullResources.get(parentPath);
            if (currentLockNullResources != null) {
                Enumeration lockNullResourcesList = currentLockNullResources.elements();
                while (lockNullResourcesList.hasMoreElements()) {
                    String lockNullPath = (String) lockNullResourcesList.nextElement();
                    if (lockNullPath.equals(path)) {
                        context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
                        context.getResponse().setContentType("text/xml; charset=UTF-8");
                        // Create multistatus object
                        XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
                        generatedXML.writeXMLHeader();
                        generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(),
                                XMLWriter.OPENING);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                        generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
                        generatedXML.sendData();
                        //e.printStackTrace(System.out);
                        return;
                    }
                }
            }
        }
    } catch (SQLException e) {
        e.printStackTrace(System.out);
        context.getResponse().sendError(CFS_SQLERROR, e.getMessage());
        status = false;
    } finally {
        this.freeConnection(db, context);
    }

    if (!status) {
        return;
    }

    if (!exists) {
        context.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND, path);
        return;
    }

    context.getResponse().setStatus(WebdavStatus.SC_MULTI_STATUS);
    context.getResponse().setContentType("text/xml; charset=UTF-8");
    // Create multistatus object
    ////System.out.println("Creating Multistatus Object");

    XMLWriter generatedXML = new XMLWriter(context.getResponse().getWriter());
    generatedXML.writeXMLHeader();
    generatedXML.writeElement(null, "multistatus" + generateNamespaceDeclarations(), XMLWriter.OPENING);

    //System.out.println("Depth: " + depth);
    if (depth == 0) {
        parseProperties(context, resources, generatedXML, path, type, properties);
    } else {
        // The stack always contains the object of the current level
        Stack stack = new Stack();
        stack.push(path);
        // Stack of the objects one level below
        Stack stackBelow = new Stack();

        while ((!stack.isEmpty()) && (depth >= 0)) {
            String currentPath = (String) stack.pop();
            try {
                if (!currentPath.equals(path)) {
                    //object at url currentPath not yet looked up. so perform lookup at url currentPath
                    child = resources.lookup(currentPath);
                    parseProperties(context, resources, generatedXML, currentPath, type, properties);
                }
            } catch (NamingException e) {
                e.printStackTrace(System.out);
                continue;
            }

            if (!status) {
                return;
            }

            if ((current instanceof ModuleContext) && depth > 0) {
                // Get a list of all the resources at the current path and store them
                // in the stack
                try {
                    NamingEnumeration enum1 = ((ModuleContext) current).list("");
                    int count = 0;
                    while (enum1.hasMoreElements()) {
                        NameClassPair ncPair = (NameClassPair) enum1.nextElement();
                        String newPath = currentPath;
                        if (!(newPath.endsWith("/"))) {
                            newPath += "/";
                        }
                        newPath += ncPair.getName();
                        //System.out.println("STACKING CHILD: " + newPath);
                        stackBelow.push(newPath);
                        count++;
                    }
                    if (currentPath.equals(path) && count == 0) {
                        // This directory does not have any files or folders.
                        //System.out.println("DIRECTORY HAS NO FILES OR FOLDERS...");
                        parseProperties(context, resources, generatedXML, properties);
                    }
                } catch (NamingException e) {
                    //e.printStackTrace(System.out);
                    context.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, path);
                    return;
                }

                // Displaying the lock-null resources present in that collection
                String lockPath = currentPath;
                if (lockPath.endsWith("/")) {
                    lockPath = lockPath.substring(0, lockPath.length() - 1);
                }
                Vector currentLockNullResources = (Vector) lockNullResources.get(lockPath);
                if (currentLockNullResources != null) {
                    Enumeration lockNullResourcesList = currentLockNullResources.elements();
                    while (lockNullResourcesList.hasMoreElements()) {
                        String lockNullPath = (String) lockNullResourcesList.nextElement();
                        System.out.println("Lock null path: " + lockNullPath);
                        parseLockNullProperties(context.getRequest(), generatedXML, lockNullPath, type,
                                properties);
                    }
                }
            }
            if (stack.isEmpty()) {
                depth--;
                stack = stackBelow;
                stackBelow = new Stack();
            }
            xmlsb.append(generatedXML.toString());
            //System.out.println("xml : " + generatedXML.toString());
            generatedXML.sendData();
        }
    }

    Iterator locks = lockNullResources.keySet().iterator();
    while (locks.hasNext()) {
        String lockpath = (String) locks.next();
        //System.out.println("LOCK PATH: " + lockpath);
    }

    generatedXML.writeElement(null, "multistatus", XMLWriter.CLOSING);
    xmlsb.append(generatedXML.toString());
    generatedXML.sendData();
    //System.out.println("xml: " + xmlsb.toString());
}

From source file:com.enonic.esl.xml.XMLTool.java

public static String getNodeText(Node node) {
    if (node == null) {
        return null;
    } else if (node.getNodeType() == Node.TEXT_NODE) {
        return ((Text) node).getData();
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        return ((Attr) node).getValue();
    } else {/*w w w .java 2s . c om*/
        return getElementText((Element) node);
    }
}

From source file:com.twinsoft.convertigo.engine.translators.WebServiceTranslator.java

private SOAPElement addSoapElement(Context context, SOAPEnvelope se, SOAPElement soapParent, Node node)
        throws Exception {
    String prefix = node.getPrefix();
    String namespace = node.getNamespaceURI();
    String nodeName = node.getNodeName();
    String localName = node.getLocalName();
    String value = node.getNodeValue();

    boolean includeResponseElement = true;
    if (context.sequenceName != null) {
        includeResponseElement = ((Sequence) context.requestedObject).isIncludeResponseElement();
    }//from   ww w  .  j  a  va2  s . com

    SOAPElement soapElement = null;
    if (node.getNodeType() == Node.ELEMENT_NODE) {
        Element element = (Element) node;

        boolean toAdd = true;
        if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
            toAdd = false;
        }
        if ("http://schemas.xmlsoap.org/soap/envelope/".equals(element.getParentNode().getNamespaceURI())
                || "http://schemas.xmlsoap.org/soap/envelope/".equals(namespace)
                || nodeName.toLowerCase().endsWith(":envelope") || nodeName.toLowerCase().endsWith(":body")
        //element.getParentNode().getNodeName().toUpperCase().indexOf("NS0:") != -1 ||
        //nodeName.toUpperCase().indexOf("NS0:") != -1
        ) {
            toAdd = false;
        }

        if (toAdd) {
            if (prefix == null || prefix.equals("")) {
                soapElement = soapParent.addChildElement(nodeName);
            } else {
                soapElement = soapParent.addChildElement(se.createName(localName, prefix, namespace));
            }
        } else {
            soapElement = soapParent;
        }

        if (soapElement != null) {
            if (soapParent.equals(se.getBody()) && !soapParent.equals(soapElement)) {
                if (XsdForm.qualified == context.project.getSchemaElementForm()) {
                    if (soapElement.getAttribute("xmlns") == null) {
                        soapElement.addAttribute(se.createName("xmlns"), context.project.getTargetNamespace());
                    }
                }
            }

            if (element.hasAttributes()) {
                String attrType = element.getAttribute("type");
                if (("attachment").equals(attrType)) {
                    if (context.requestedObject instanceof AbstractHttpTransaction) {
                        AttachmentDetails attachment = AttachmentManager.getAttachment(element);
                        if (attachment != null) {
                            byte[] raw = attachment.getData();
                            if (raw != null)
                                soapElement.addTextNode(Base64.encodeBase64String(raw));
                        }

                        /* DON'T WORK YET *\
                        AttachmentPart ap = responseMessage.createAttachmentPart(new ByteArrayInputStream(raw), element.getAttribute("content-type"));
                        ap.setContentId(key);
                        ap.setContentLocation(element.getAttribute("url"));
                        responseMessage.addAttachmentPart(ap);
                        \* DON'T WORK YET */
                    }
                }

                if (!includeResponseElement && "response".equalsIgnoreCase(localName)) {
                    // do not add attributes
                } else {
                    NamedNodeMap attributes = element.getAttributes();
                    int len = attributes.getLength();
                    for (int i = 0; i < len; i++) {
                        Node item = attributes.item(i);
                        addSoapElement(context, se, soapElement, item);
                    }
                }
            }

            if (element.hasChildNodes()) {
                NodeList childNodes = element.getChildNodes();
                int len = childNodes.getLength();
                for (int i = 0; i < len; i++) {
                    Node item = childNodes.item(i);
                    switch (item.getNodeType()) {
                    case Node.ELEMENT_NODE:
                        addSoapElement(context, se, soapElement, item);
                        break;
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        String text = item.getNodeValue();
                        text = (text == null) ? "" : text;
                        soapElement.addTextNode(text);
                        break;
                    default:
                        break;
                    }
                }
            }
        }
    } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
        if (prefix == null || prefix.equals("")) {
            soapElement = soapParent.addAttribute(se.createName(nodeName), value);
        } else {
            soapElement = soapParent.addAttribute(se.createName(localName, prefix, namespace), value);
        }
    }
    return soapElement;
}

From source file:com.enonic.esl.xml.XMLTool.java

/**
 * Retrieve a text from an element or attribute using an xpath expression.
 *
 * @param contextElement The root element that the xpath expression is to be applied on.
 * @param xpath          The xpath that selects the element or attribute containing the text.
 * @return The element text./*w  w w. j av a2s.c om*/
 */

public static String getElementText(Element contextElement, String xpath) {

    if (contextElement == null) {
        return null;
    }

    Node node = selectNode(contextElement, xpath);

    if (node != null) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            return ((Text) node).getData();
        } else if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
            return ((Attr) node).getValue();
        } else {
            return getElementText((Element) node);
        }
    }

    return null;
}

From source file:DOMProcessor.java

/** Converts the given DOM node into XML. Recursively converts
  * any child nodes. This version allows the XML version, encoding and stand-alone
  * status to be set./*from  w  ww  . jav  a  2 s.  c  o  m*/
  * @param node DOM Node to display.
  * @param version XML version, or null if default ('1.0') is to be used.
  * @param encoding XML encoding, or null if encoding is not to be specified.
  * @param standalone XML stand-alone status or null if not to be specified.
  */
private void outputNodeAsXML(Node node, String version, String encoding, Boolean standalone) {
    // Store node name, type and value.
    String name = node.getNodeName(), value = makeFriendly(node.getNodeValue());
    int type = node.getNodeType();

    // Ignore empty nodes (e.g. blank lines etc.)
    if ((value != null) && (value.trim().equals(""))) {
        return;
    }

    switch (type) {
    case Node.DOCUMENT_NODE: // Start of document.
    {
        if (version == null) {
            out.print("<?xml version=\"1.0\" ");
        } else {
            out.print("<?xml version=\"" + version + "\" ");
        }

        if (encoding != null) {
            out.print("encoding=\"" + encoding + "\" ");
        }

        if (standalone != null) {
            if (standalone.booleanValue()) {
                out.print("standalone=\"yes\" ");
            } else {
                out.print("standalone=\"no\" ");
            }
        }

        out.println("?>");

        // Output the document's child nodes.
        NodeList children = node.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            outputNodeAsXML(children.item(i));
        }
        break;
    }

    case Node.ELEMENT_NODE: // Document element with attributes.
    {
        // Output opening element tag.
        indent++;
        indent();
        out.print("<" + name);

        // Output any attributes the element might have.
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            out.print(" " + attribute.getNodeName() + "=\"" + attribute.getNodeValue() + "\"");
        }
        out.print(">");

        // Output any child nodes that exist.                    
        NodeList children = node.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            outputNodeAsXML(children.item(i));
        }

        break;
    }

    case Node.CDATA_SECTION_NODE: // Display text.
    case Node.TEXT_NODE: {
        out.print(value);
        break;
    }

    case Node.COMMENT_NODE: // Comment node.
    {
        indent++;
        indent();
        out.print("<!--" + value + "-->");
        indent--;
        break;
    }

    case Node.ENTITY_REFERENCE_NODE: // Entity reference nodes.
    {
        indent++;
        indent();
        out.print("&" + name + ";");
        indent--;
        break;
    }

    case Node.PROCESSING_INSTRUCTION_NODE: // Processing instruction.
    {
        indent++;
        indent();
        out.print("<?" + name);
        if ((value != null) && (value.length() > 0)) {
            out.print(" " + value);
        }
        out.println("?>");
        indent--;
        break;
    }
    }

    // Finally output closing tags for each element.
    if (type == Node.ELEMENT_NODE) {
        out.print("</" + node.getNodeName() + ">");
        indent--;
        if (node.getNextSibling() == null) {
            indent(); // Only throw new line if this is the last sibling.
        }
    }
}

From source file:com.connexta.arbitro.ctx.xacml3.XACML3EvaluationCtx.java

private Set<String> getChildXPaths(Node root, String xPath) {

    Set<String> xPaths = new HashSet<String>();
    NamespaceContext namespaceContext = null;

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();

    if (namespaceContext == null) {

        //see if the request root is in a namespace
        String namespace = null;/*from ww w  .  j  a v  a 2 s. com*/
        if (root != null) {
            namespace = root.getNamespaceURI();
        }
        // name spaces are used, so we need to lookup the correct
        // prefix to use in the search string
        NamedNodeMap namedNodeMap = root.getAttributes();

        Map<String, String> nsMap = new HashMap<String, String>();
        if (namedNodeMap != null) {
            for (int i = 0; i < namedNodeMap.getLength(); i++) {
                Node n = namedNodeMap.item(i);
                // we found the matching namespace, so get the prefix
                // and then break out
                String prefix = DOMHelper.getLocalName(n);
                String nodeValue = n.getNodeValue();
                nsMap.put(prefix, nodeValue);
            }
        }

        // if there is not any namespace is defined for content element, default XACML request
        //  name space would be there.
        if (XACMLConstants.REQUEST_CONTEXT_3_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_2_0_IDENTIFIER.equals(namespace)
                || XACMLConstants.REQUEST_CONTEXT_1_0_IDENTIFIER.equals(namespace)) {
            nsMap.put("xacml", namespace);
        }

        namespaceContext = new DefaultNamespaceContext(nsMap);
    }

    xpath.setNamespaceContext(namespaceContext);

    try {
        XPathExpression expression = xpath.compile(xPath);
        NodeList matches = (NodeList) expression.evaluate(root, XPathConstants.NODESET);
        if (matches != null && matches.getLength() > 0) {

            for (int i = 0; i < matches.getLength(); i++) {
                String text = null;
                Node node = matches.item(i);
                short nodeType = node.getNodeType();

                // see if this is straight text, or a node with data under
                // it and then get the values accordingly
                if ((nodeType == Node.CDATA_SECTION_NODE) || (nodeType == Node.COMMENT_NODE)
                        || (nodeType == Node.TEXT_NODE) || (nodeType == Node.ATTRIBUTE_NODE)) {
                    // there is no child to this node
                    text = node.getNodeValue();
                } else {

                    // the data is in a child node
                    text = "/" + DOMHelper.getLocalName(node);
                }
                String newXPath = '(' + xPath + ")[" + (i + 1) + ']';
                xPaths.add(newXPath);
            }
        }
    } catch (Exception e) {
        // TODO
    }

    return xPaths;
}

From source file:jef.tools.XMLUtils.java

/**
 * ?//from w w  w . jav  a2  s . c om
 * 
 * @param node
 *            
 * @param data
 *            
 * @return DOM
 */
public static Text setText(Node node, String data) {
    Document doc = null;
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        doc = (Document) node;
    } else {
        doc = node.getOwnerDocument();
    }
    clearChildren(node, Node.TEXT_NODE);
    Text t = doc.createTextNode(data);
    node.appendChild(t);
    return t;
}

From source file:edu.uams.clara.webapp.xml.processor.impl.DefaultXmlProcessorImpl.java

private synchronized String duplicate(final Document originalDom, final Element originalRootElement,
        final Element patchElement) throws Exception {

    boolean isdone = false;
    Element parentElement = null;

    DuplicateChildElementObject childElementObject = isChildElement(originalRootElement, patchElement);
    if (!childElementObject.isNeedDuplicate()) {
        isdone = true;//from  w w  w  . j a  va 2s.co m
        parentElement = childElementObject.getElement();
    } else if (childElementObject.getElement() != null) {
        parentElement = childElementObject.getElement();
    } else {
        parentElement = originalRootElement;
    }

    String son_name = patchElement.getNodeName();

    Element subITEM = null;
    if (!isdone) {
        subITEM = originalDom.createElement(son_name);

        if (patchElement.hasChildNodes()) {
            if (patchElement.getFirstChild().getNodeType() == Node.TEXT_NODE) {
                subITEM.setTextContent(patchElement.getTextContent());

            }
        }

        if (patchElement.hasAttributes()) {
            NamedNodeMap attributes = patchElement.getAttributes();
            for (int i = 0; i < attributes.getLength(); i++) {
                String attribute_name = attributes.item(i).getNodeName();
                String attribute_value = attributes.item(i).getNodeValue();
                subITEM.setAttribute(attribute_name, attribute_value);
            }
        }
        parentElement.appendChild(subITEM);
    } else {
        subITEM = parentElement;
    }

    NodeList sub_messageItems = patchElement.getChildNodes();
    int sub_item_number = sub_messageItems.getLength();
    logger.debug("patchEl: " + DomUtils.elementToString(patchElement) + "length: " + sub_item_number);
    if (sub_item_number == 0) {
        isdone = true;
    } else {
        for (int j = 0; j < sub_item_number; j++) {
            if (sub_messageItems.item(j).getNodeType() == Node.ELEMENT_NODE) {
                Element sub_messageItem = (Element) sub_messageItems.item(j);
                logger.debug("node name: " + DomUtils.elementToString(subITEM) + " node type: "
                        + subITEM.getNodeType());
                duplicate(originalDom, subITEM, sub_messageItem);
            }

        }
    }

    return (parentElement != null) ? DomUtils.elementToString(parentElement) : "";
}

From source file:com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.java

/**
 * Build a map of ResultConfig objects from below a given XML element.
 *//*from w  w w . j  ava 2  s  .  c om*/
protected Map<String, ResultConfig> buildResults(Element element, PackageConfig.Builder packageContext) {
    NodeList resultEls = element.getElementsByTagName("result");

    Map<String, ResultConfig> results = new LinkedHashMap<String, ResultConfig>();

    for (int i = 0; i < resultEls.getLength(); i++) {
        Element resultElement = (Element) resultEls.item(i);

        if (resultElement.getParentNode().equals(element)
                || resultElement.getParentNode().getNodeName().equals(element.getNodeName())) {
            String resultName = resultElement.getAttribute("name");
            String resultType = resultElement.getAttribute("type");

            // if you don't specify a name on <result/>, it defaults to "success"
            if (StringUtils.isEmpty(resultName)) {
                resultName = Action.SUCCESS;
            }

            // there is no result type, so let's inherit from the parent package
            if (StringUtils.isEmpty(resultType)) {
                resultType = packageContext.getFullDefaultResultType();

                // now check if there is a result type now
                if (StringUtils.isEmpty(resultType)) {
                    // uh-oh, we have a problem
                    throw new ConfigurationException(
                            "No result type specified for result named '" + resultName
                                    + "', perhaps the parent package does not specify the result type?",
                            resultElement);
                }
            }

            ResultTypeConfig config = packageContext.getResultType(resultType);

            if (config == null) {
                throw new ConfigurationException(
                        "There is no result type defined for type '" + resultType + "' mapped with name '"
                                + resultName + "'." + "  Did you mean '" + guessResultType(resultType) + "'?",
                        resultElement);
            }

            String resultClass = config.getClazz();

            // invalid result type specified in result definition
            if (resultClass == null) {
                throw new ConfigurationException("Result type '" + resultType + "' is invalid");
            }

            Map<String, String> resultParams = XmlHelper.getParams(resultElement);

            if (resultParams.size() == 0) // maybe we just have a body - therefore a default parameter
            {
                // if <result ...>something</result> then we add a parameter of 'something' as this is the most used result param
                if (resultElement.getChildNodes().getLength() >= 1) {
                    resultParams = new LinkedHashMap<String, String>();

                    String paramName = config.getDefaultResultParam();
                    if (paramName != null) {
                        StringBuilder paramValue = new StringBuilder();
                        for (int j = 0; j < resultElement.getChildNodes().getLength(); j++) {
                            if (resultElement.getChildNodes().item(j).getNodeType() == Node.TEXT_NODE) {
                                String val = resultElement.getChildNodes().item(j).getNodeValue();
                                if (val != null) {
                                    paramValue.append(val);
                                }
                            }
                        }
                        String val = paramValue.toString().trim();
                        if (val.length() > 0) {
                            resultParams.put(paramName, val);
                        }
                    } else {
                        if (LOG.isWarnEnabled()) {
                            LOG.warn("no default parameter defined for result of type " + config.getName());
                        }
                    }
                }
            }

            // create new param map, so that the result param can override the config param
            Map<String, String> params = new LinkedHashMap<String, String>();
            Map<String, String> configParams = config.getParams();
            if (configParams != null) {
                params.putAll(configParams);
            }
            params.putAll(resultParams);

            ResultConfig resultConfig = new ResultConfig.Builder(resultName, resultClass).addParams(params)
                    .location(DomHelper.getLocationObject(element)).build();
            results.put(resultConfig.getName(), resultConfig);
        }
    }

    return results;
}