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.wso2.developerstudio.eclipse.registry.apim.views.RegistryBrowserAPIMView.java

private void renameSequence(final RegistryResourceNode regResourceNode)
        throws IOException, InvocationTargetException, InterruptedException {

    final String currentName = regResourceNode.getLastSegmentInPath().split("\\.")[0];
    InputDialog inputDialog = new InputDialog(Display.getCurrent().getActiveShell(),
            RENAME_RESOURCE_DIALOG_TITLE, NEW_NAME_LABEL, currentName, new IInputValidator() {
                public String isValid(String value) {
                    if (value == null || value.equals("")) {
                        return SPECIFY_A_NEW_NAME_TO_THE_RESOURCE;
                    } else if (value.equals(currentName)) {
                        return SPECIFY_A_NEW_NAME_TO_THE_RESOURCE;
                    } else {
                        return null;
                    }/*  w w  w .j  av  a  2  s .co m*/
                }
            });
    if (inputDialog.open() == InputDialog.OK) {
        String inputName = inputDialog.getValue();
        if (!inputName.contains(".xml")) {
            inputName = inputName + ".xml";
        }
        final String newName = inputName;

        new ProgressMonitorDialog(getSite().getShell()).run(true, true, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

                monitor.beginTask("", 100);
                monitor.worked(60);

                String newPath = regResourceNode.getParent()
                        + (regResourceNode.getParent().endsWith(DEFAULT_PATH) ? newName
                                : DEFAULT_PATH + newName);

                ArrayList<RegistryResourceNode> localResourceNodeList = regResourceNode
                        .getRegistryResourceNodeParent().getLocalResourceNodeList();
                for (RegistryResourceNode registryResourceNode : localResourceNodeList) {
                    if (newName.equals(registryResourceNode.getResourceName())) {

                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                MessageDialogUtils.error(Display.getCurrent().getActiveShell(), "",
                                        THIS_OPERATION_CANNOT_BE_PERFORMED_BECAUSE_THE + " '" + newName + "' "
                                                + " already exists!");

                            }
                        };

                        Display.getDefault().syncExec(runnable);
                        return;
                    }
                }

                File source = regResourceNode.getFile();
                Path tempDir = null;
                try {
                    tempDir = Files.createTempDirectory("tempfiles");
                } catch (IOException e) {
                    throw new InvocationTargetException(e);
                }
                String filePath = tempDir.toString() + File.separator + newName;
                File dest = new File(filePath);
                try {
                    copyFileToFile(source, dest);
                } catch (IOException e) {
                    throw new InvocationTargetException(e);
                }
                if (regResourceNode.isIsnew()) {
                    regResourceNode.setResourceName(newName);
                    regResourceNode.setNewFile(dest);
                } else if (regResourceNode.isRename()) {
                    regResourceNode.setNewPath(newPath);
                    regResourceNode.setResourceName(newName);
                } else {
                    regResourceNode.setOldPath(regResourceNode.getRegistryResourcePath());
                    regResourceNode.setNewPath(newPath);
                    regResourceNode.setRename(true);
                    regResourceNode.setNewFile(dest);
                    regResourceNode.setResourceName(newName);
                }

                Display.getDefault().syncExec(new Runnable() {
                    @SuppressWarnings({})
                    @Override
                    public void run() {
                        if (regResourceNode.getFileEditor() != null) {
                            if (regResourceNode.getFileEditor().isDirty()) {
                                if (MessageDialogUtils.question(
                                        regResourceNode.getFileEditor().getSite().getShell(),
                                        DO_YOU_WANT_TO_SAVE_CHANGES)) {
                                    regResourceNode.getFileEditor().doSave(new NullProgressMonitor());
                                }
                            }
                            closeEditor(regResourceNode);
                            updateSequenceName(regResourceNode.getNewFile());
                            openResourceInEditor(regResourceNode);
                        } else {
                            updateSequenceName(regResourceNode.getNewFile());
                        }
                    }

                    private void updateSequenceName(File file) {
                        try {
                            DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                            DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                            Document doc = docBuilder.parse(file);
                            Node sequence = doc.getElementsByTagName("sequence").item(0);
                            Node sequenceName = sequence.getAttributes().getNamedItem("name");
                            sequenceName.setNodeValue(newName);
                            TransformerFactory transformerFactory = TransformerFactory.newInstance();
                            Transformer transformer = transformerFactory.newTransformer();
                            DOMSource source = new DOMSource(doc);
                            StreamResult result = new StreamResult(file);
                            transformer.transform(source, result);
                        } catch (SAXException | IOException | ParserConfigurationException
                                | TransformerException e) {
                            log.error("Error while renaming sequence.", e);
                        }
                    }
                });

                monitor.worked(100);
                monitor.done();

            }
        });

    }
}

From source file:org.zaproxy.zap.extension.saml.SAMLMessage.java

/** Update XML document with any attributes that were changed */
private void updateXMLDocument() {
    XPathFactory xFactory = XPathFactory.newInstance();
    XPath xpath = xFactory.newXPath();
    for (Attribute attribute : attributeMap.values()) {
        try {/*from   w ww. j ava2 s.  c  om*/
            Node node = (Node) xpath.compile(attribute.getxPath()).evaluate(xmlDocument, XPathConstants.NODE);
            if (node != null) { // the attributes that aren't available will be giving null
                // values
                if (node instanceof Element) {
                    node.setTextContent(attribute.getValue().toString());
                } else if (node instanceof Attr) {
                    ((Attr) node).setValue(attribute.getValue().toString());
                } else {
                    node.setNodeValue(attribute.getValue().toString());
                }
            }
        } catch (XPathExpressionException e) {
            log.warn(attribute.getxPath() + " is not a valid XPath", e);
        }
    }
    if (SAMLConfiguration.getInstance().getXSWEnabled()) {
        try {
            NodeList nodeList = (NodeList) xpath.compile("/Response//Signature").evaluate(xmlDocument,
                    XPathConstants.NODESET);
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node item = nodeList.item(i);
                if (item instanceof Element) {
                    item.getParentNode().removeChild(item);
                }
            }
        } catch (XPathExpressionException e) {
            log.warn("'/Response//Signature' is not a valid XPath", e);
        }
    }
}

From source file:pl.psnc.synat.wrdz.common.metadata.mets.MetsMetadataBuilder.java

/**
 * Clears whitespaces between elements in XML document node. JAXB cannot do it because it does not known all context
 * - we don't restrict aou system to specific XML metadata namespaces.
 * //  www .  j  a v  a  2s. c o m
 * @param node
 *            node for which clear whitespaces
 */
private void clearWhitespacesBetweenElements(Node node) {
    if (node.hasChildNodes()) {
        NodeList childNodes = node.getChildNodes();
        if (!(childNodes.getLength() == 1 && childNodes.item(0).getNodeType() != Node.ELEMENT_NODE)) {
            for (int i = 0; i < childNodes.getLength(); i++) {
                clearWhitespacesBetweenElements(childNodes.item(i));
            }
        }
    } else {
        node.setNodeValue("");
    }
}

From source file:ru.runa.wf.web.FormPresentationUtils.java

private static void handleElements(NodeList nodeList, String hrefAttributeName, String htmlHref,
        PageContext pageContext, Long id) {
    String[] fileNameStructureElements = htmlHref.split("/");
    Map<String, Object> params = Maps.newHashMap();
    params.put(IdForm.ID_INPUT_NAME, id);

    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        Node hrefNode = node.getAttributes().getNamedItem(hrefAttributeName);
        if (hrefNode == null) {
            continue;
        }/*from  w  w w .  j  a  va2s  . c  o  m*/
        String href = hrefNode.getNodeValue();
        if (href == null || href.length() == 0 || href.startsWith("#") || href.startsWith("javascript")) {
            continue;
        }
        if (isHrefRelative(href)) {
            String url = getNormalizedUrlForElement(htmlHref, fileNameStructureElements, href);
            int anchorIndex = url.indexOf("#");
            String anchor = null;
            if (anchorIndex >= 0) {
                anchor = url.substring(anchorIndex + 1);
                url = url.substring(0, anchorIndex);
            }
            params.put(DefinitionFileForm.URL_INPUT_NAME, url);
            String newHref = Commons.getActionUrl(LoadProcessDefinitionHtmlFileAction.ACTION_PATH, params,
                    anchor, pageContext, PortletUrlType.Resource);
            hrefNode.setNodeValue(newHref);
        }
    }
}

From source file:test.unit.be.fedict.eid.applet.service.signer.AbstractXmlSignatureServiceTest.java

private boolean isDigested(NodeList nodes, VerifyReference[] references) {
    for (int idx = 0; idx < nodes.getLength(); idx++) {
        Node node = nodes.item(idx);
        LOG.debug("node name: " + 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();
            }//w  w  w.j a v a2  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
        } else {
            throw new RuntimeException("unsupported node type: " + node.getNodeType());
        }
        if (false == changed) {
            return false;
        }
    }
    return true;
}

From source file:tests.unit.configuration.ConfigurationTestCase.java

/**
 *
 *//*from   ww w  .j  av  a  2  s .co m*/
public void testConfiguration() {
    try {
        CryptoHelper.encrypt(null, "test", true);

        URL configURL = XMLConfig.load(CONFIGURATION_FILE);
        assertNotNull("Cannot load " + CONFIGURATION_FILE + " configuration.", configURL);
        URL retrievedURL = XMLConfig.getURL(CONFIGURATION_FILE);
        assertSame(configURL, retrievedURL);
        String[] files = XMLConfig.getLoadedFiles();
        assertTrue("Loaded files empty", (files != null) && (files.length > 0));

        Document confDocument = XMLConfig.getDocument(CONFIGURATION_FILE);
        Node testNode_KS = XMLConfig.getNode(confDocument, TEST_KS_XPATH);
        Node testNode_K = XMLConfig.getNode(confDocument, TEST_K_XPATH);

        Node originalKeystoreAttr = XMLConfig.getNode(testNode_KS, "@key-store-pwd");
        Node originalAliasAttr = XMLConfig.getNode(testNode_K, "@key-pwd");
        String originalKeystorePwd = originalKeystoreAttr.getNodeValue();
        String originalAliasPwd = originalAliasAttr.getNodeValue();

        String encryptedData = CryptoHelper.encrypt(null, originalKeystorePwd, true);
        originalKeystoreAttr.setNodeValue(encryptedData);
        encryptedData = CryptoHelper.encrypt(null, originalAliasPwd, true);
        originalAliasAttr.setNodeValue(encryptedData);

        System.out.println("Overwriting " + CONFIGURATION_FILE);
        DOMWriter writer = new DOMWriter();
        OutputStream out = new FileOutputStream(URLDecoder.decode(configURL.getPath(), "UTF-8"));
        writer.write(confDocument, out);
        out.close();

        System.out.println("Reloading " + CONFIGURATION_FILE);
        XMLConfig.reload(CONFIGURATION_FILE);

        String decrypted = XMLConfig.getDecrypted(CONFIGURATION_FILE, TEST_KS_XPATH + "/@key-store-pwd",
                XMLConfig.DEFAULT_KEY_ID, false);
        assertEquals(originalKeystorePwd, decrypted);

        String encrypted = XMLConfig.get(CONFIGURATION_FILE, TEST_KS_XPATH + "/@key-store-pwd");
        decrypted = XMLConfig.getDecrypted(encrypted);
        assertEquals(originalKeystorePwd, decrypted);
        assertEquals(encrypted, XMLConfig.getEncrypted(decrypted));

        confDocument = XMLConfig.getDocument(CONFIGURATION_FILE);
        testNode_KS = XMLConfig.getNode(confDocument, TEST_KS_XPATH);
        testNode_K = XMLConfig.getNode(confDocument, TEST_K_XPATH);
        Node encKeystoreAttr = XMLConfig.getNode(testNode_KS, "@key-store-pwd");
        Node encAliasAttr = XMLConfig.getNode(testNode_K, "@key-pwd");
        encKeystoreAttr.setNodeValue(originalKeystorePwd);
        encAliasAttr.setNodeValue(originalAliasPwd);
        out = new FileOutputStream(URLDecoder.decode(configURL.getPath(), "UTF-8"));
        writer.write(confDocument, out);

        XMLConfig.discard(CONFIGURATION_FILE);
        files = XMLConfig.getLoadedFiles();
        assertTrue("Discarded file " + CONFIGURATION_FILE + " is again returned",
                Arrays.binarySearch(files, CONFIGURATION_FILE) < 0);
    } catch (Exception exc) {
        exc.printStackTrace();
        fail("Exception occurred while testing configuration: " + exc.getMessage());
    }
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Migrate @class attributes which are missed by the main iteration
 * //from   w ww  . j  a v a2 s .c  o  m
 * @param document
 */
private void migrateClassAsAttribute(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;
    for (String className : classNameRuleMap.keySet()) {
        try {
            String targetClassName = classNameRuleMap.get(className);
            expr = xpath.compile("//*[@class='" + className + "']");
            NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < matchingNodes.getLength(); i++) {
                Node classAttr = matchingNodes.item(i).getAttributes().getNamedItem("class");
                classAttr.setNodeValue(targetClassName);
                LOGGER.trace("In element " + matchingNodes.item(i).getNodeName()
                        + " migrating @class attribute of " + className + " to " + targetClassName);
            }
        } catch (XPathExpressionException e) {
            LOGGER.error("XPathException encountered: ", e);
        }
    }
}

From source file:ua.utility.kfsdbupgrade.MaintainableXMLConversionServiceImpl.java

/**
 * Migrate @maintainableImplClass attributes which are missed by the main
 * iteration//from   w w  w.j av a  2 s . com
 * 
 * @param document
 */
/*
 * this has to be hacked around at the top-level before the DOM is even
 * created; leaving code in place to hopefully someday do this at the DOM
 * level
 */
@SuppressWarnings("unused")
private void migrateMaintainableImplClassAsAttribute(Document document) {
    XPath xpath = XPathFactory.newInstance().newXPath();
    XPathExpression expr = null;
    for (String className : classNameRuleMap.keySet()) {
        try {
            String targetClassName = classNameRuleMap.get(className);
            expr = xpath.compile("//*[@maintainableImplClass='" + className + "']");
            NodeList matchingNodes = (NodeList) expr.evaluate(document, XPathConstants.NODESET);
            for (int i = 0; i < matchingNodes.getLength(); i++) {
                Node classAttr = matchingNodes.item(i).getAttributes().getNamedItem("class");
                classAttr.setNodeValue(targetClassName);
                LOGGER.info("In element " + matchingNodes.item(i).getNodeName()
                        + " migrating @maintainableImplClass attribute of " + className + " to "
                        + targetClassName);
            }
        } catch (XPathExpressionException e) {
            LOGGER.error("XPathException encountered: ", e);
        }
    }
}

From source file:wssec.TestWSSecurityNew5.java

/**
 * A test for WSS-66 - the nonce string is null
 * http://issues.apache.org/jira/browse/WSS-66
 * "Possible security hole when PasswordDigest is used by client."
 *///  www .j av a2 s. co  m
public void testNullNonce() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "BAD_PASSWORD");

    Document doc = unsignedEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document utDoc = builder.build(doc, secHeader);

    //
    // Manually find the Nonce node and set the content to null
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagName("wsse:Nonce");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node childNode = nonceNode.getFirstChild();
    childNode.setNodeValue("");

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc);
        LOG.debug(outputString);
    }

    try {
        //
        // Verification should fail as the password is bad
        //
        verify(utDoc);
        throw new Exception("Expected failure due to a bad password");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION);
        // expected
    }
}

From source file:wssec.TestWSSecurityNew5.java

/**
 * A test for WSS-66 - the created string is null
 * http://issues.apache.org/jira/browse/WSS-66
 * "Possible security hole when PasswordDigest is used by client."
 */// w  w  w.  j a va2s  .  c  o  m
public void testNullCreated() throws Exception {
    WSSecUsernameToken builder = new WSSecUsernameToken();
    builder.setPasswordType(WSConstants.PASSWORD_DIGEST);
    builder.setUserInfo("wernerd", "BAD_PASSWORD");

    Document doc = unsignedEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Document utDoc = builder.build(doc, secHeader);

    //
    // Manually find the Created node and set the content to null
    //
    org.w3c.dom.Element elem = builder.getUsernameTokenElement();
    org.w3c.dom.NodeList list = elem.getElementsByTagName("wsu:Created");
    org.w3c.dom.Node nonceNode = list.item(0);
    org.w3c.dom.Node childNode = nonceNode.getFirstChild();
    childNode.setNodeValue("");

    if (LOG.isDebugEnabled()) {
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(utDoc);
        LOG.debug(outputString);
    }

    try {
        //
        // Verification should fail as the password is bad
        //
        verify(utDoc);
        throw new Exception("Expected failure due to a bad password");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == WSSecurityException.FAILED_AUTHENTICATION);
        // expected
    }
}