Example usage for org.w3c.dom Node setNodeValue

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

Introduction

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

Prototype

public void setNodeValue(String nodeValue) throws DOMException;

Source Link

Document

The value of this node, depending on its type; see the table above.

Usage

From source file:org.ow2.proactive_grid_cloud_portal.scheduler.server.SubmitEditServlet.java

private void upload(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("text/html");

    String sessionId = null;//from w  w w . ja  v a  2s.  c  o m
    String job = null;
    HashMap<String, String> varMap = new HashMap<String, String>();
    File editedJob = null;
    File jobDesc = null;

    @SuppressWarnings("rawtypes")
    Enumeration e = request.getParameterNames();
    while (e.hasMoreElements()) {
        Object o = e.nextElement();
        String key = o.toString();
        String val = request.getParameter(key);

        if (key.equals("job")) {
            job = val;
        } else if (key.equals("sessionId")) {
            sessionId = val;
        } else if (key.startsWith("var_")) {
            String name = key.substring(4);
            varMap.put(name, val);
        }
    }

    try {
        if (job == null) {
            response.getWriter().write("Parameter 'job' is null");
            return;
        }
        if (sessionId == null) {
            response.getWriter().write("Parameter 'sessionId' is null");
            return;
        }

        try {
            jobDesc = File.createTempFile("portal_job_edit", "xml");
            jobDesc.deleteOnExit();
            IOUtils.write(job, new FileOutputStream(jobDesc));

            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
            Document doc = docBuilder.parse(jobDesc);

            Node vars = doc.getElementsByTagName("variables").item(0);

            /* edit the job variables using XML DOM */
            if (vars != null) {
                NodeList varChildren = vars.getChildNodes();
                for (int i = 0; i < varChildren.getLength(); i++) {
                    Node var = varChildren.item(i);
                    if (var != null) {
                        if (var.getAttributes() != null) {

                            String name = null;
                            Node nodeVal = null;
                            for (int j = 0; j < var.getAttributes().getLength(); j++) {
                                Node attr = var.getAttributes().item(j);

                                if (attr.getNodeName().equals("name")) {
                                    name = attr.getNodeValue();
                                }
                                if (attr.getNodeName().equals("value")) {
                                    nodeVal = attr;
                                }
                            }

                            String match = varMap.get(name);
                            if (match != null && nodeVal != null) {
                                nodeVal.setNodeValue(match);
                            }
                        }
                    }
                }
            }

            // write the document to a string
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                editedJob = File.createTempFile("portal_edit_res", "xml");
                editedJob.deleteOnExit();
                StreamResult result = new StreamResult(editedJob);
                DOMSource source = new DOMSource(doc);
                transformer.transform(source, result);
            } catch (Exception e1) {
                response.getWriter().write("Error while writing the job descriptor's DOM: " + e1.getMessage());
            }

        } catch (ParserConfigurationException e1) {
            response.getWriter().write("Error initializing DOM parser " + e1.getMessage());
        } catch (SAXException e1) {
            response.getWriter().write("Error parsing job descriptor: " + e1.getMessage());
        }

        // submission at last....
        try {
            String responseS = ((SchedulerServiceImpl) Service.get()).submitXMLFile(sessionId, editedJob);
            if (responseS == null || responseS.length() == 0) {
                response.getWriter().write("Job submission returned without a value!");
            } else {
                response.getWriter().write(responseS);
            }
        } catch (RestServerException e1) {
            String msg = e1.getMessage().replace("<", "&lt;").replace(">", "&gt;");
            response.getWriter().print(msg);
        } catch (ServiceException e2) {
            String msg = e2.getMessage().replace("<", "&lt;").replace(">", "&gt;");
            response.getWriter().print(msg);
        }

    } catch (IOException e1) {
        LOGGER.warn("Failed to write back to client", e1);
    } finally {
        if (jobDesc != null)
            jobDesc.delete();
        if (editedJob != null)
            editedJob.delete();
    }
}

From source file:org.owasp.webscarab.plugin.saml.SamlModel.java

private boolean isDigested(NodeList nodes, VerifyReference[] references) {
    for (int idx = 0; idx < nodes.getLength(); idx++) {
        Node node = nodes.item(idx);
        //this._logger.log(Level.FINE, "node name: {0}", node.getLocalName());
        boolean changed = false;
        if (node.getNodeType() == Node.TEXT_NODE) {
            String originalTextValue = node.getNodeValue();
            String changedTextValue = originalTextValue + "foobar";
            node.setNodeValue(changedTextValue);
            changed = false; // need to have impact anyway
            for (int referenceIdx = 0; referenceIdx < references.length; referenceIdx++) {
                VerifyReference reference = references[referenceIdx];
                changed |= reference.hasChanged();
            }/*from w w  w.  j  av  a  2  s .  c  om*/
            if (false == changed) {
                return false;
            }
            node.setNodeValue(originalTextValue);
        } else if (node.getNodeType() == Node.ELEMENT_NODE) {
            Element element = (Element) node;

            NamedNodeMap attributes = element.getAttributes();
            for (int attributeIdx = 0; attributeIdx < attributes.getLength(); attributeIdx++) {
                Node attributeNode = attributes.item(attributeIdx);
                String originalAttributeValue = attributeNode.getNodeValue();
                String changedAttributeValue = originalAttributeValue + "foobar";
                attributeNode.setNodeValue(changedAttributeValue);
                for (int referenceIdx = 0; referenceIdx < references.length; referenceIdx++) {
                    VerifyReference reference = references[referenceIdx];
                    changed |= reference.hasChanged();
                }

                attributeNode.setNodeValue(originalAttributeValue);
            }
            changed |= isDigested(element.getChildNodes(), references);
        } else if (node.getNodeType() == Node.COMMENT_NODE) {
            // not always digested by the ds:References
        } else {
            throw new RuntimeException("unsupported node type: " + node.getNodeType());
        }
        if (false == changed) {
            return false;
        }
    }
    return true;
}

From source file:org.sakaiproject.warehouse.util.db.DbLoader.java

protected void replaceDataTypes(Document tablesDoc) {
    Element tables = tablesDoc.getDocumentElement();
    NodeList types = tables.getElementsByTagName("type");

    for (int i = 0; i < types.getLength(); i++) {
        Node type = (Node) types.item(i);
        NodeList typeChildren = type.getChildNodes();

        for (int j = 0; j < typeChildren.getLength(); j++) {
            Node text = (Node) typeChildren.item(j);
            String genericType = text.getNodeValue();

            // Replace generic type with mapped local type
            text.setNodeValue(getLocalDataTypeName(genericType));
        }/*from www  .  j  ava2  s .  c o m*/
    }
}

From source file:org.springframework.batch.core.jsr.configuration.xml.JsrBeanDefinitionDocumentReader.java

private void transformDocument(Element root) {
    DocumentTraversal traversal = (DocumentTraversal) root.getOwnerDocument();
    NodeIterator iterator = traversal.createNodeIterator(root, NodeFilter.SHOW_ELEMENT, null, true);

    BeanDefinitionRegistry registry = getBeanDefinitionRegistry();
    Map<String, Integer> referenceCountMap = new HashMap<String, Integer>();

    for (Node n = iterator.nextNode(); n != null; n = iterator.nextNode()) {
        NamedNodeMap map = n.getAttributes();

        if (map.getLength() > 0) {
            for (int i = 0; i < map.getLength(); i++) {
                Node node = map.item(i);

                String nodeName = node.getNodeName();
                String nodeValue = node.getNodeValue();
                String resolvedValue = resolveValue(nodeValue);
                String newNodeValue = resolvedValue;

                if ("ref".equals(nodeName)) {
                    if (!referenceCountMap.containsKey(resolvedValue)) {
                        referenceCountMap.put(resolvedValue, 0);
                    }//w w w. ja  va  2 s.  c  o m

                    boolean isClass = isClass(resolvedValue);
                    Integer referenceCount = referenceCountMap.get(resolvedValue);

                    // possibly fully qualified class name in ref tag in the JSL or pointer to bean/artifact ref.
                    if (isClass && !registry.containsBeanDefinition(resolvedValue)) {
                        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
                                .genericBeanDefinition(resolvedValue).getBeanDefinition();
                        beanDefinition.setScope("step");
                        registry.registerBeanDefinition(resolvedValue, beanDefinition);

                        newNodeValue = resolvedValue;
                    } else {
                        if (registry.containsBeanDefinition(resolvedValue)) {
                            referenceCount++;
                            referenceCountMap.put(resolvedValue, referenceCount);

                            newNodeValue = resolvedValue + referenceCount;

                            BeanDefinition beanDefinition = registry.getBeanDefinition(resolvedValue);
                            registry.registerBeanDefinition(newNodeValue, beanDefinition);
                        }
                    }
                }

                if (!nodeValue.equals(newNodeValue)) {
                    node.setNodeValue(newNodeValue);
                }
            }
        } else {
            String nodeValue = n.getTextContent();
            String resolvedValue = resolveValue(nodeValue);

            if (!nodeValue.equals(resolvedValue)) {
                n.setTextContent(resolvedValue);
            }
        }
    }
}

From source file:org.tmpotter.filters.TestFilterBase.java

/**
 * Remove version and toolname, then compare.
 * @param f1/*from  w w w. ja va  2  s . c om*/
 * @param f2
 * @throws java.lang.Exception
 */
protected void compareTMX(File f1, File f2) throws Exception {
    XPathExpression exprVersion = XPathFactory.newInstance().newXPath()
            .compile("/tmx/header/@creationtoolversion");
    XPathExpression exprTool = XPathFactory.newInstance().newXPath().compile("/tmx/header/@creationtool");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(TmxReader2.TMX_DTD_RESOLVER);

    Document doc1 = builder.parse(f1);
    Document doc2 = builder.parse(f2);

    Node n;

    n = (Node) exprVersion.evaluate(doc1, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprVersion.evaluate(doc2, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprTool.evaluate(doc1, XPathConstants.NODE);
    n.setNodeValue("");

    n = (Node) exprTool.evaluate(doc2, XPathConstants.NODE);
    n.setNodeValue("");

    Diff myDiff = DiffBuilder.compare(Input.from(doc1)).withTest(Input.from(doc2)).checkForSimilar()
            .ignoreWhitespace().build();
    assertFalse(myDiff.hasDifferences());
}

From source file:org.wso2.carbon.bpmn.core.types.datatypes.xml.api.XMLDocument.java

/**
 * Function to set/replace/update an object (String / Element) to matching the xPath provided. (In case new element
 * is added, this api will clone it and merge the new node to the target location pointed by xPath and return the new cloned node)
 *
 * @param xPathStr xPath to the location object need to set
 * @param obj      String or Node/*from   ww  w  .  ja  v a2 s.c  om*/
 * @return returns the node get updated when the set object is String, or returns newly added Node in case object is Element
 * @throws XPathExpressionException If expression cannot be evaluated
 * @throws BPMNXmlException         is thrown due to : Provided XPath and object does not match, provided object is not a Node or String
 *                                  result is NodeList, not a Text node or Element
 */
public Node set(String xPathStr, Object obj) throws XPathExpressionException, BPMNXmlException {

    NodeList evalResult = (NodeList) Utils.evaluateXPath(this.doc, xPathStr, XPathConstants.NODESET);
    if (evalResult.getLength() == 1) {
        Node targetNode = evalResult.item(0);

        if (obj instanceof String && targetNode instanceof Text) { //if string is provided, assume that user
            //need to replace the node value
            targetNode.setNodeValue((String) obj);
            //return updated Text Node
            return targetNode;

        } else if ((obj instanceof Integer || obj instanceof Byte || obj instanceof Character
                || obj instanceof Short || obj instanceof Long || obj instanceof Float || obj instanceof Double
                || obj instanceof Boolean) && targetNode instanceof Text) {
            //need to replace the node value
            targetNode.setNodeValue(obj.toString());
            //return updated Text Node
            return targetNode;

        } else if (obj instanceof Element && targetNode instanceof Element
                && targetNode.getParentNode() != null) { //if the user provides Node object,
            // assume that need to replace the target node
            Node targetParent = targetNode.getParentNode();
            Node nextSibling = targetNode.getNextSibling();
            //remove the target node
            targetParent.removeChild(targetNode);
            //add new node
            Node newNode = doc.importNode((Node) obj, true);

            if (nextSibling != null) {
                //If next sibling exists we have to put the new node before it
                targetParent.insertBefore(newNode, nextSibling);
            } else {
                targetParent.appendChild(newNode);
            }
            //return new node
            return newNode;

        } else { //provided XPath and object to set does not match
            throw new BPMNXmlException("Provided XPath and provided object does not match");
        }

    } else if (evalResult.getLength() > 0) {

        throw new BPMNXmlException(
                "Error in provided xPath. Evaluation result is NodeList, not a Text node or Element");

    } else {
        throw new BPMNXmlException("Error in provided xPath. Evaluation result is not a Text node or Element");
    }

}

From source file:org.wso2.carbon.governance.registry.extensions.handlers.utils.WsdlUriProcessor.java

/**
 * Change all schema path locations to registry locations in each WSDL definitions
 * @throws org.wso2.carbon.registry.core.exceptions.RegistryException Thrown in case the schema
 * locations cannot be updated/* w  w w .  j  a  v  a2s  .c  o  m*/
 */
private void updateWSDLSchemaLocations() throws RegistryException {
    updateWSDLocations();
    for (WSDLInfo wsdlInfo : wsdls.values()) {
        Definition definition = wsdlInfo.getWSDLDefinition();
        Types types = definition.getTypes();
        if (types != null) {
            List extensibleElements = types.getExtensibilityElements();
            Schema schemaExtension;
            Object extensionObject;
            for (Object extensibleElement : extensibleElements) {
                extensionObject = extensibleElement;
                if (extensionObject instanceof Schema) {
                    // first get the schema object
                    schemaExtension = (Schema) extensionObject;
                    NodeList nodeList = schemaExtension.getElement().getChildNodes();
                    String tagName;
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        tagName = nodeList.item(i).getLocalName();
                        if (IMPORT_TAG.equals(tagName) || INCLUDE_TAG.equals(tagName)) {
                            NamedNodeMap nodeMap = nodeList.item(i).getAttributes();
                            Node attribute;
                            String attributeValue;
                            for (int j = 0; j < nodeMap.getLength(); j++) {
                                attribute = nodeMap.item(j);
                                if (attribute.getNodeName().equals("schemaLocation")) {
                                    attributeValue = attribute.getNodeValue();
                                    String schemaPath = schemaUriProcessor.getSchemaRegistryPath(
                                            wsdlInfo.getProposedRegistryURL(), attributeValue);
                                    if (schemaPath != null) {
                                        attribute.setNodeValue(schemaPath);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.wso2.carbon.ndatasource.ui.NDataSourceHelper.java

private static List<Node> getWhitespaceNodes(Element element) {
    List<Node> nodes = new ArrayList<Node>();
    for (Node node : getNodesAsList(element)) {
        if (node.getNodeType() == Node.TEXT_NODE) {
            node.setNodeValue(node.getNodeValue().trim());
            if (node.getNodeValue().length() == 0) {
                nodes.add(node);/*w w w  .j av a 2s  . c  om*/
            }
        }
    }
    return nodes;
}

From source file:org.wso2.carbon.registry.extensions.handlers.utils.WSDLProcessor.java

/**
 * Change all schema path locations to registry locations in each WSDL definitions
 * @throws org.wso2.carbon.registry.core.exceptions.RegistryException Thrown in case the schema
 * locations cannot be updated/*from ww w  .j  a  v  a2s . com*/
 */
private void updateWSDLSchemaLocations() throws RegistryException {
    updateWSDLocations();
    for (WSDLInfo wsdlInfo : wsdls.values()) {
        Definition definition = wsdlInfo.getWSDLDefinition();
        Types types = definition.getTypes();
        if (types != null) {
            List extensibleElements = types.getExtensibilityElements();
            Schema schemaExtension;
            Object extensionObject;
            for (Object extensibleElement : extensibleElements) {
                extensionObject = extensibleElement;
                if (extensionObject instanceof Schema) {
                    // first get the schema object
                    schemaExtension = (Schema) extensionObject;
                    NodeList nodeList = schemaExtension.getElement().getChildNodes();
                    String tagName;
                    for (int i = 0; i < nodeList.getLength(); i++) {
                        tagName = nodeList.item(i).getLocalName();
                        if (IMPORT_TAG.equals(tagName) || INCLUDE_TAG.equals(tagName)) {
                            NamedNodeMap nodeMap = nodeList.item(i).getAttributes();
                            Node attribute;
                            String attributeValue;
                            for (int j = 0; j < nodeMap.getLength(); j++) {
                                attribute = nodeMap.item(j);
                                if (attribute.getNodeName().equals("schemaLocation")) {
                                    attributeValue = attribute.getNodeValue();
                                    String schemaPath = schemaProcessor.getSchemaRegistryPath(
                                            wsdlInfo.getProposedRegistryURL(), attributeValue);
                                    if (schemaPath != null) {
                                        attribute.setNodeValue(schemaPath);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.wso2.carbon.tomcat.internal.ServerManager.java

/**
 * Resolves the secured attributes in the configuration
 * Here we have assumed that secured attributes in each connector
 * has the same secret value. As an example, if two connectors has
 * keystore password value, it must be same value.
 *
 * @param root <code>Element</code>
 * @param tempToken  secured attribute alias as <code>String</code> 
 *//*from   w  w  w. j a v  a 2  s  .  c o m*/
private void resolveSecuredConfig(Node root, String tempToken) {

    String token = null;
    NamedNodeMap nodeMap = root.getAttributes();
    if (tempToken == null) {
        tempToken = root.getNodeName();
    } else {
        tempToken = tempToken + "." + root.getNodeName();
    }
    if (nodeMap != null) {
        for (int j = 0; j < nodeMap.getLength(); j++) {
            Node node = nodeMap.item(j);
            if (node != null) {
                String attributeName = node.getNodeName();
                token = tempToken + "." + attributeName;
                if (resolver.isTokenProtected(token)) {
                    node.setNodeValue(resolver.resolve(token));
                    nodeMap.removeNamedItem(
                            SVNS + SecurityConstants.NS_SEPARATOR + SecurityConstants.SECURE_VAULT_ALIAS);
                }
            }
        }
    }

    NodeList nodeList = root.getChildNodes();
    for (int i = 0; i < nodeList.getLength(); i++) {
        resolveSecuredConfig(nodeList.item(i), tempToken);
    }
}