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:net.sf.jclal.experiment.ExperimentBuilder.java

private int expandAttributesIterateAtributes(Element element, int[] configurationSchema) {
    NamedNodeMap attributes = element.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {
        Node attribute = attributes.item(i);

        if (attribute.getNodeValue().equals("multi")) {
            NodeList list = element.getElementsByTagName(attribute.getNodeName());

            for (int j = 0; j < configurationSchema.length; j++) {
                if (configurationSchema[j] != -1) {
                    attribute.setNodeValue(list.item(configurationSchema[j]).getFirstChild().getNodeValue());
                    configurationSchema[j] = -1;
                    break;
                }/*from   ww w  .j a  va 2 s .  com*/
            }

            list = element.getChildNodes();

            for (int j = 0; j < list.getLength(); j++) {
                if (list.item(j).getNodeName().equals(attribute.getNodeName())) {
                    element.removeChild(list.item(j));
                }
            }

            return 1;
        }
    }

    return 0;
}

From source file:com.rover12421.shaka.apktool.lib.AndrolibResourcesAj.java

private boolean horizontalScrollView_check(String errInfo) throws Exception {
    if (errInfo.indexOf("'@android:style/Widget.HorizontalScrollView'") > 0) {
        Pattern xmlPathPattern = Pattern.compile(
                "(.+?):\\d+:.+?(Error retrieving parent for item).+?'@android:style/Widget.HorizontalScrollView'");
        Matcher xmlPathMatcher = xmlPathPattern.matcher(errInfo);
        if (xmlPathMatcher.find()) {
            String xmlPathStr = xmlPathMatcher.group(1);
            File xmlPathFile = new File(xmlPathStr);
            if (xmlPathFile.exists()) {
                LogHelper.warning("Find HorizontalScrollView exception xml : " + xmlPathStr);
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document document = documentBuilder.parse(xmlPathStr);
                NodeList list = document.getChildNodes().item(0).getChildNodes();
                for (int i = 0; i < list.getLength(); i++) {
                    Node node = list.item(i);
                    if (node.getAttributes() != null) {
                        Node attr = node.getAttributes().getNamedItem("parent");
                        if (attr != null
                                && attr.getNodeValue().equals("@android:style/Widget.HorizontalScrollView")) {
                            /**
                             * HorizontalScrollView??aaptScrollView
                             *//*from  w  ww.j  a  v  a2 s  . c o m*/
                            attr.setNodeValue("@android:style/Widget.ScrollView");
                            /**
                             * ? android:scrollbars  android:fadingEdge 
                             * ??,
                             * ?????
                             */
                            Element scrollbars = document.createElement("item");
                            scrollbars.setAttribute("name", "android:scrollbars");
                            scrollbars.setNodeValue("horizontal");

                            Element fadingEdge = document.createElement("item");
                            fadingEdge.setAttribute("name", "android:fadingEdge");
                            fadingEdge.setNodeValue("horizontal");
                            Element element = (Element) node;
                            NodeList items = element.getElementsByTagName("item");
                            for (int j = 0; j < items.getLength(); j++) {
                                Element item = (Element) items.item(j);
                                if (item.getAttribute("name").equals("android:scrollbars")) {
                                    scrollbars = null;
                                }
                                if (item.getAttribute("name").equals("android:fadingEdge")) {
                                    fadingEdge = null;
                                }
                            }

                            if (scrollbars != null) {
                                node.appendChild(scrollbars);
                            }

                            if (fadingEdge != null) {
                                node.appendChild(fadingEdge);
                            }
                        }
                    }
                }

                /**
                 * ?xml
                 */
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                transformer.transform(new DOMSource(document), new StreamResult(xmlPathStr));

                return true;
            }
        }
    }

    return false;
}

From source file:com.dinochiesa.edgecallouts.EditXmlNode.java

private void append(NodeList nodes, Node newNode, short newNodeType) {
    Node currentNode = nodes.item(0);
    switch (newNodeType) {
    case Node.ATTRIBUTE_NODE:
        Element parent = ((Attr) currentNode).getOwnerElement();
        parent.setAttributeNode((Attr) newNode);
        break;//  ww  w . ja  v a2  s  . c  o  m
    case Node.ELEMENT_NODE:
        currentNode.appendChild(newNode);
        break;
    case Node.TEXT_NODE:
        if (currentNode.getNodeType() != Node.TEXT_NODE) {
            throw new IllegalStateException("wrong source node type.");
        }
        String v = currentNode.getNodeValue();
        currentNode.setNodeValue(v + newNode.getNodeValue());
        break;
    }
}

From source file:com.bekwam.mavenpomupdater.MainViewController.java

public void doUpdate() {

    for (POMObject p : tblPOMS.getItems()) {

        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] p=" + p.getAbsPath());
        }//from w  ww .ja  v  a  2  s.  c  o m

        if (p.getParseError()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because of a parse error on scanning");
            }
            continue;
        }

        if (!p.getUpdate()) {
            if (log.isDebugEnabled()) {
                log.debug("[DO UPDATE] skipping update of p=" + p.getAbsPath()
                        + " because user excluded it from update");
            }
            continue;
        }

        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(false);
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(p.getAbsPath());

            if (p.getParentVersion() != null && p.getParentVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/parent/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getParentVersion());
                }
            }

            if (p.getVersion() != null && p.getVersion().length() > 0) {
                XPath xpath = XPathFactory.newInstance().newXPath();
                XPathExpression expression = xpath.compile("//project/version/text()");
                Node node = (Node) expression.evaluate(doc, XPathConstants.NODE);

                if (StringUtils.isNotEmpty(tfNewVersion.getText())) {
                    node.setNodeValue(tfNewVersion.getText());
                } else { // editing individual table cells
                    node.setNodeValue(p.getVersion());
                }
            }

            TransformerFactory tFactory = TransformerFactory.newInstance();
            Transformer transformer = tFactory.newTransformer();

            String workingFileName = p.getAbsPath() + ".mpu";
            FileWriter fw = new FileWriter(workingFileName);
            DOMSource source = new DOMSource(doc);
            StreamResult result = new StreamResult(fw);
            transformer.transform(source, result);
            fw.close();

            Path src = FileSystems.getDefault().getPath(workingFileName);
            Path target = FileSystems.getDefault().getPath(p.getAbsPath());

            Files.copy(src, target, StandardCopyOption.REPLACE_EXISTING);

            Files.delete(src);

        } catch (Exception exc) {
            log.error("error updating poms", exc);
        }
    }

    if (StringUtils.isNotEmpty(tfRootDir.getText())) {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] issuing rescan command");
        }
        scan();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("[DO UPDATE] did an update, but there is not value in root; clearing");
        }
        tblPOMS.getItems().clear();
    }
    tblPOMSDirty = false;
    tfNewVersion.setDisable(false);
}

From source file:com.crawljax.plugins.adi.Report.java

/**
 * Taken from ErrorReport./*  ww w .  ja v a  2s. c  o m*/
 */
private Document addMarker(String id, Document doc, String xpath) {
    try {

        String prefixMarker = "###BEGINMARKER" + id + "###";
        String suffixMarker = "###ENDMARKER###";

        NodeList nodeList = XPathHelper.evaluateXpathExpression(doc, xpath);

        if (nodeList.getLength() == 0 || nodeList.item(0) == null) {
            return doc;
        }

        Node element = nodeList.item(0);

        if (element.getNodeType() == Node.ELEMENT_NODE) {
            Node beginNode = doc.createTextNode(prefixMarker);
            Node endNode = doc.createTextNode(suffixMarker);

            element.getParentNode().insertBefore(beginNode, element);
            if (element.getNextSibling() == null) {
                element.getParentNode().appendChild(endNode);
            } else {
                element.getParentNode().insertBefore(endNode, element.getNextSibling());
            }
        } else if (element.getNodeType() == Node.TEXT_NODE && element.getTextContent() != null) {
            element.setTextContent(prefixMarker + element.getTextContent() + suffixMarker);
        } else if (element.getNodeType() == Node.ATTRIBUTE_NODE) {
            element.setNodeValue(prefixMarker + element.getTextContent() + suffixMarker);
        }

        return doc;
    } catch (Exception e) {
        return doc;
    }
}

From source file:dk.statsbiblioteket.doms.central.connectors.fedora.FedoraRest.java

@Override
public String newEmptyObject(String pid, List<String> oldIDs, List<String> collections, String logMessage)
        throws BackendMethodFailedException, BackendInvalidCredsException {
    InputStream emptyObjectStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("EmptyObject.xml");
    Document emptyObject = DOM.streamToDOM(emptyObjectStream, true);

    XPathSelector xpath = DOM.createXPathSelector("foxml", Constants.NAMESPACE_FOXML, "rdf",
            Constants.NAMESPACE_RDF, "d", Constants.NAMESPACE_RELATIONS, "dc", Constants.NAMESPACE_DC, "oai_dc",
            Constants.NAMESPACE_OAIDC);/*from w  w w. j a va  2 s  .  co  m*/
    //Set pid
    Node pidNode = xpath.selectNode(emptyObject, "/foxml:digitalObject/@PID");
    pidNode.setNodeValue(pid);

    Node rdfNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/@rdf:about");
    rdfNode.setNodeValue("info:fedora/" + pid);

    //add Old Identifiers to DC
    Node dcIdentifierNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/oai_dc:dc/dc:identifier");
    dcIdentifierNode.setTextContent(pid);
    Node parent = dcIdentifierNode.getParentNode();
    for (String oldID : oldIDs) {
        Node clone = dcIdentifierNode.cloneNode(true);
        clone.setTextContent(oldID);
        parent.appendChild(clone);
    }

    Node collectionRelationNode = xpath.selectNode(emptyObject,
            "/foxml:digitalObject/foxml:datastream/foxml:datastreamVersion/foxml:xmlContent/rdf:RDF/rdf:Description/d:isPartOfCollection");

    parent = collectionRelationNode.getParentNode();
    //remove the placeholder relationNode
    parent.removeChild(collectionRelationNode);

    for (String collection : collections) {
        Node clone = collectionRelationNode.cloneNode(true);
        clone.getAttributes().getNamedItem("rdf:resource").setNodeValue("info:fedora/" + collection);
        parent.appendChild(clone);
    }

    String emptyObjectAsString;
    try {
        emptyObjectAsString = DOM.domToString(emptyObject);
    } catch (TransformerException e) {
        //TODO This is not really a backend exception
        throw new BackendMethodFailedException("Failed to convert DC back to string", e);
    }
    WebResource.Builder request = restApi.path("/").path(urlEncode(pid)).queryParam("state", "I")
            .type(MediaType.TEXT_XML_TYPE);
    int tries = 0;
    while (true) {
        tries++;
        try {
            return request.post(String.class, emptyObjectAsString);
        } catch (UniformInterfaceException e) {
            try {
                handleResponseException(pid, tries, maxTriesPost, e);
            } catch (BackendInvalidResourceException e1) {
                //Ignore, never happens
                throw new RuntimeException(e1);
            }
        }
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

private void setNumLines(Node domNode, int lines) {
    Node markerSequenceNode = getFirstElementByName(domNode, "markerSequence");
    if (markerSequenceNode == null) {
        markerSequenceNode = new IIOMetadataNode("markerSequence");
        domNode.appendChild(markerSequenceNode);
    }/*from w ww .j av  a2s  .c  om*/

    Node sofNode = getFirstElementByName(markerSequenceNode, "sof");
    if (sofNode == null) {
        sofNode = new IIOMetadataNode("sof");
        markerSequenceNode.appendChild(sofNode);
    }

    Node attribute = getAttributeByName(sofNode, "numLines");
    if (attribute == null) {
        attribute = new IIOMetadataNode("numLines");
        sofNode.appendChild(attribute);
    }
    attribute.setNodeValue(Integer.toString(lines));
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

private void setSamplesPerLine(Node domNode, int samples) {
    Node markerSequenceNode = getFirstElementByName(domNode, "markerSequence");
    if (markerSequenceNode == null) {
        markerSequenceNode = new IIOMetadataNode("markerSequence");
        domNode.appendChild(markerSequenceNode);
    }/*w  w w .j  a  va  2  s.c o  m*/

    Node sofNode = getFirstElementByName(markerSequenceNode, "sof");
    if (sofNode == null) {
        sofNode = new IIOMetadataNode("sof");
        markerSequenceNode.appendChild(sofNode);
    }

    Node attribute = getAttributeByName(sofNode, "samplesPerLine");
    if (attribute == null) {
        attribute = new IIOMetadataNode("samplesPerLine");
        sofNode.appendChild(attribute);
    }
    attribute.setNodeValue(Integer.toString(samples));
}

From source file:com.icesoft.faces.context.BridgeFacesContext.java

protected void applyBrowserFormChanges(Map parameters, Document document, Element form) {
    NodeList inputElements = form.getElementsByTagName("input");
    int inputElementsLength = inputElements.getLength();
    for (int i = 0; i < inputElementsLength; i++) {
        Element inputElement = (Element) inputElements.item(i);
        String id = inputElement.getAttribute("id");
        if (!"".equals(id)) {
            String name = null;//from   w w  w .  ja  va 2s. co m
            if (parameters.containsKey(id)) {
                String value = ((String[]) parameters.get(id))[0];
                //empty string is implied (default) when 'value' attribute is missing
                if (!"".equals(value)) {
                    if (inputElement.hasAttribute("value")) {
                        inputElement.setAttribute("value", value);
                    } else if (inputElement.getAttribute("type").equals("checkbox")) {
                        inputElement.setAttribute("checked", "checked");
                    }
                } else {
                    inputElement.setAttribute("value", "");
                }
            } else if (!"".equals(name = inputElement.getAttribute("name")) && parameters.containsKey(name)) {
                String type = inputElement.getAttribute("type");
                if (type != null && type.equals("checkbox") || type.equals("radio")) {
                    String currValue = inputElement.getAttribute("value");
                    if (!"".equals(currValue)) {
                        boolean found = false;
                        // For multiple checkboxes, values can have length > 1,
                        // but for multiple radios, values would have at most length=1
                        String[] values = (String[]) parameters.get(name);
                        if (values != null) {
                            for (int v = 0; v < values.length; v++) {
                                if (currValue.equals(values[v])) {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (found) {
                            // For some reason, our multiple checkbox 
                            // components use checked="true", while
                            // our single checkbox components use
                            // checked="checked". The latter complying
                            // with the HTML specification.
                            // Also, radios use checked="checked"
                            if (type.equals("checkbox")) {
                                inputElement.setAttribute("checked", "true");
                            } else if (type.equals("radio")) {
                                inputElement.setAttribute("checked", "checked");
                            }
                        } else {
                            inputElement.removeAttribute("checked");
                        }
                    }
                }
            } else {
                if (inputElement.getAttribute("type").equals("checkbox")) {
                    ////inputElement.setAttribute("checked", "");
                    inputElement.removeAttribute("checked");
                }
            }
        }
    }

    NodeList textareaElements = form.getElementsByTagName("textarea");
    int textareaElementsLength = textareaElements.getLength();
    for (int i = 0; i < textareaElementsLength; i++) {
        Element textareaElement = (Element) textareaElements.item(i);
        String id = textareaElement.getAttribute("id");
        if (!"".equals(id) && parameters.containsKey(id)) {
            String value = ((String[]) parameters.get(id))[0];
            Node firstChild = textareaElement.getFirstChild();
            if (null != firstChild) {
                //set value on the Text node
                firstChild.setNodeValue(value);
            } else {
                //DOM brought back from compression may have no
                //child for empty TextArea
                if (value != null && value.length() > 0) {
                    textareaElement.appendChild(document.createTextNode(value));
                }
            }
        }
    }

    NodeList selectElements = form.getElementsByTagName("select");
    int selectElementsLength = selectElements.getLength();
    for (int i = 0; i < selectElementsLength; i++) {
        Element selectElement = (Element) selectElements.item(i);
        String id = selectElement.getAttribute("id");
        if (!"".equals(id) && parameters.containsKey(id)) {
            List values = Arrays.asList((String[]) parameters.get(id));

            NodeList optionElements = selectElement.getElementsByTagName("option");
            int optionElementsLength = optionElements.getLength();
            for (int j = 0; j < optionElementsLength; j++) {
                Element optionElement = (Element) optionElements.item(j);
                if (values.contains(optionElement.getAttribute("value"))) {
                    optionElement.setAttribute("selected", "selected");
                } else {
                    optionElement.removeAttribute("selected");
                }
            }
        }
    }
}

From source file:de.unigoettingen.sub.commons.contentlib.imagelib.JpegInterpreter.java

/************************************************************************************
 * set metadata to image/*w  w  w.ja v  a2s  .c o m*/
 * 
 * @param iomd the given {@link IIOMetadata} to set
 ************************************************************************************/
private void setMetadata(IIOMetadata iomd) {

    Node node = iomd.getAsTree("javax_imageio_jpeg_image_1.0");

    // set dimensions
    setSamplesPerLine(node, this.getWidth());
    setNumLines(node, this.getHeight());

    // what are child nodes?
    NodeList nl = node.getChildNodes();
    for (int j = 0; j < nl.getLength(); j++) {
        Node n = nl.item(j);

        if (n.getNodeName().equals("JPEGvariety")) {
            NodeList childNodes = n.getChildNodes();

            for (int k = 0; k < childNodes.getLength(); k++) {
                if (childNodes.item(k).getNodeName().equals("app0JFIF")) {

                    // get the attributes resUnits, Xdensity, and Ydensity
                    Node resUnitsNode = getAttributeByName(childNodes.item(k), "resUnits");
                    Node XdensityNode = getAttributeByName(childNodes.item(k), "Xdensity");
                    Node YdensityNode = getAttributeByName(childNodes.item(k), "Ydensity");
                    // overwrite values for that node
                    resUnitsNode.setNodeValue("1"); // it's dpi

                    int xres = (int) this.getXResolution();
                    int yres = (int) this.getYResolution();
                    if (xres == 0) {
                        xres = defaultXResolution;
                    }
                    if (yres == 0) {
                        yres = defaultYResolution;
                    }
                    XdensityNode.setNodeValue(String.valueOf(xres));
                    YdensityNode.setNodeValue(String.valueOf(yres));

                } // endif
            } // end id
            break; // don't need to change the other children
        } // end id

    } // end for

    // set the XML tree for the IIOMetadata object
    try {
        iomd.setFromTree("javax_imageio_jpeg_image_1.0", node);
    } catch (IIOInvalidTreeException e) {
        LOGGER.error(e); // To change body of catch statement
    }

}