Example usage for org.w3c.dom Node setTextContent

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

Introduction

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

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:com.amazon.pay.impl.PayLogUtil.java

/**
 *
 * @param data  - data to be sanitized./* w  ww.j av  a  2 s .  com*/
 * @param removedata - List of strings to be removed from the data object.
 * @return - an XML not containing 'removedata' lists of strings.
 *
 * @throws TransformerFactoryConfigurationError - Thrown when a problem with configuration with the Transformer Factories exists. This error will typically be thrown when the class of a transformation factory specified in the system properties cannot be found or instantiated.
 */
public String getSanitizedData(String data, List<String> removedata) throws AmazonClientException {

    try {
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(data));

        Document doc = db.parse(is);

        NodeList list = doc.getElementsByTagName("*");
        for (int i = 0; i < list.getLength(); i++) {
            //Get Node
            Node node = (Node) list.item(i);

            for (Iterator<String> j = removedata.iterator(); j.hasNext();) {
                String item = j.next();
                if (node.getNodeName().equalsIgnoreCase(item)) {
                    node.setTextContent("*** Removed ***");
                }
            }
        }

        StringWriter sw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(list.item(0)), new StreamResult(sw));

        String result = sw.toString();

        return result;
    } catch (ParserConfigurationException e) {
        throw new AmazonClientException("Encountered UnsupportedEncodingException:", e);
    } catch (SAXException e) {
        throw new AmazonClientException("Encountered SAXException:", e);
    } catch (IOException e) {
        throw new AmazonClientException("Encountered IOException:", e);
    } catch (TransformerConfigurationException e) {
        throw new AmazonClientException("Encountered a Transformer Configuration Exception:", e);
    } catch (TransformerException e) {
        throw new AmazonClientException("Encountered a Transformer Exception:", e);
    }
}

From source file:chat.viska.xmpp.plugins.webrtc.WebRtcPlugin.java

@Nonnull
public Completable sendIceCandidates(@Nonnull final Jid recipient, @Nonnull final String id,
        @Nonnull final Collection<IceCandidate> candidates) {
    final Document iq = Stanza.getIqTemplate(Stanza.IqType.SET, UUID.randomUUID().toString(),
            getSession().getNegotiatedJid(), recipient);
    final Element webrtc = (Element) iq.getDocumentElement().appendChild(iq.createElementNS(XMLNS, "webrtc"));
    webrtc.setAttribute("id", id);
    for (IceCandidate candidate : candidates) {
        final Element candidateElement = (Element) webrtc.appendChild(iq.createElement("ice-candidate"));
        candidateElement.setAttribute("sdpMLineIndex", Integer.toString(candidate.sdpMLineIndex));
        if (StringUtils.isNotBlank(candidate.sdpMid)) {
            candidateElement.setAttribute("sdpMid", candidate.sdpMid);
        }/* w w  w .j av  a 2 s .c  om*/
        if (StringUtils.isNotBlank(candidate.sdp)) {
            final Element sdpElement = (Element) candidateElement.appendChild(iq.createElement("sdp"));
            for (String line : candidate.sdp.split(REGEX_LINE_BREAK)) {
                final Node node = sdpElement.appendChild(iq.createElement("line"));
                node.setTextContent(line);
            }
        }
    }
    return this.context.sendIq(new XmlWrapperStanza(iq)).getResponse().toSingle().toCompletable();
}

From source file:de.escidoc.core.test.oai.oaiprovider.OaiproviderTestBase.java

/**
 * Inserts a unique label into the provided document by adding the current timestamp to the contained label.
 *
 * @param document The document.//from  ww  w. j  a  va 2  s  .c  o  m
 * @return The inserted login name.
 * @throws Exception If anything fails.
 */
protected String insertUniqueSetSpecification(final Document document) throws Exception {

    assertXmlExists("No specification found in template data. ", document, "/set-definition/specification");
    final Node specNode = selectSingleNode(document, "/set-definition/specification");
    String specification = specNode.getTextContent().trim();
    specification += System.currentTimeMillis();

    specNode.setTextContent(specification);

    return specification;
}

From source file:org.opencastproject.loadtest.impl.IngestJob.java

/**
 * Parse the episode.xml file and change the mediapackage id.
 * /*from ww w. j ava  2s  .c  o m*/
 * @param filepath
 *          The location of the episode.xml.
 */
private void changeEpisodeID(String filepath) {
    try {
        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(filepath);

        // Get the identifier element by tag name directly
        Node identifier = doc.getElementsByTagName("dcterms:identifier").item(0);
        identifier.setTextContent(id);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File(filepath));
        transformer.transform(source, result);
    } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
    } catch (TransformerException tfe) {
        tfe.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (SAXException sae) {
        sae.printStackTrace();
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.spec.DuplicateGerritListenersPreloadedProjectHudsonTestCase.java

/**
 * Adds a compareType and pattern node as child elements to the provided parent node.
 *
 * @param xml         the document to create xml elements from.
 * @param parent      the parent to add to
 * @param compareType the name of the compare type
 *                    (See {@link com.sonyericsson.hudson.plugins.gerrit.trigger.hudsontrigger.data.CompareType})
 * @param pattern     the pattern./*from   w w  w  .j a  v  a2  s  .  c  o m*/
 */
void setXmlConfig(Document xml, Node parent, String compareType, String pattern) {
    Node compareTypeN = xml.createElement("compareType");
    compareTypeN.setTextContent(compareType);
    parent.appendChild(compareTypeN);
    Node patternN = xml.createElement("pattern");
    patternN.setTextContent(pattern);
    parent.appendChild(patternN);
}

From source file:com.liferay.lms.service.impl.SCORMContentLocalServiceImpl.java

public boolean force(long scormId, String version) throws SystemException, PortalException, IOException {

    try {// ww  w .  j a  v a  2  s  . c o  m
        SCORMContent scorm = this.getSCORMContent(scormId);
        String filename = this.getBaseDir() + "/" + Long.toString(scorm.getCompanyId()) + "/"
                + Long.toString(scorm.getGroupId()) + "/" + scorm.getUuid() + "/imsmanifest.xml";

        File file = new File(filename);
        FileOutputStream outputStream = null;
        if (file.exists() && file.canRead() && file.canWrite()) {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            InputStream inputStream = new FileInputStream(file);
            org.w3c.dom.Document doc = documentBuilderFactory.newDocumentBuilder().parse(inputStream);
            NodeList nodeList = doc.getElementsByTagName("schemaversion");
            Node node = nodeList.item(0);
            if (node == null) {
                return false;
            }
            node.setTextContent(version);
            StringWriter stw = new StringWriter();
            Transformer serializer = TransformerFactory.newInstance().newTransformer();
            serializer.transform(new DOMSource(doc), new StreamResult(stw));
            String scormXml = stw.toString();

            outputStream = new FileOutputStream(file);
            outputStream.write(scormXml.getBytes());

            outputStream.flush();
            outputStream.close();

        }
        return true;
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

}

From source file:com.wandrell.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a signature.
 * <p>/* ww  w.  ja  va2  s.c  o  m*/
 * A valid SOAP message is required, this will be the message to be signed.
 * 
 * @param pathBase
 *            path to the SOAP message to sign
 * @param privateKeyAlias
 *            alias for the private key
 * @param privateKeyPass
 *            password for the private key
 * @param certificateAlias
 *            alias for the certificate
 * @param keystore
 *            key store for the signing
 * @return a singed SOAP message
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias,
        final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception {
    Element root = null;
    String BaseURI = new ClassPathResource(pathBase).getURI().toString();
    SOAPMessage soapMessage;
    Base64Converter base64 = new Base64Converter();
    String token;
    Node binaryToken;
    X509Certificate cert;
    PrivateKey privateKey;
    XMLSignature sig;

    soapMessage = getMessageToSign(pathBase);

    // get the private key used to sign, from the keystore
    privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    cert = (X509Certificate) keystore.getCertificate(certificateAlias);

    // create basic structure of signature
    Document doc = toDocument(soapMessage);

    org.apache.xml.security.Init.init();

    sig = getSignature(doc, BaseURI, cert, privateKey);

    // optional, but better
    root = doc.getDocumentElement();
    root.normalize();
    root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement());

    token = base64.encode(cert.getEncoded());

    binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0);
    binaryToken.setTextContent(token);

    // write signature to file
    XMLUtils.outputDOMc14nWithComments(doc, System.out);

    return toMessage(doc);
}

From source file:com.bernardomg.example.swss.test.util.factory.SecureSoapMessages.java

/**
 * Creates a SOAP message with a signature.
 * <p>/*from ww w  .  j a v a  2 s  . c o  m*/
 * A valid SOAP message is required, this will be the message to be signed.
 * 
 * @param pathBase
 *            path to the SOAP message to sign
 * @param privateKeyAlias
 *            alias for the private key
 * @param privateKeyPass
 *            password for the private key
 * @param certificateAlias
 *            alias for the certificate
 * @param keystore
 *            key store for the signing
 * @return a singed SOAP message
 * @throws Exception
 *             if any error occurs during the message creation
 */
public static final SOAPMessage getSignedMessage(final String pathBase, final String privateKeyAlias,
        final String privateKeyPass, final String certificateAlias, final KeyStore keystore) throws Exception {
    Element root = null;
    final String BaseURI = new ClassPathResource(pathBase).getURI().toString();
    SOAPMessage soapMessage;
    final Base64Converter base64 = new Base64Converter();
    String token;
    Node binaryToken;
    X509Certificate cert;
    PrivateKey privateKey;
    XMLSignature sig;

    soapMessage = getMessageToSign(pathBase);

    // get the private key used to sign, from the keystore
    privateKey = (PrivateKey) keystore.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    cert = (X509Certificate) keystore.getCertificate(certificateAlias);

    // create basic structure of signature
    final Document doc = toDocument(soapMessage);

    org.apache.xml.security.Init.init();

    sig = getSignature(doc, BaseURI, cert, privateKey);

    // optional, but better
    root = doc.getDocumentElement();
    root.normalize();
    root.getElementsByTagName("wsse:Security").item(0).appendChild(sig.getElement());

    token = base64.encode(cert.getEncoded());

    binaryToken = root.getElementsByTagName("wsse:BinarySecurityToken").item(0);
    binaryToken.setTextContent(token);

    // write signature to file
    XMLUtils.outputDOMc14nWithComments(doc, System.out);

    return toMessage(doc);
}

From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrProjectWizardIterator.java

private void pomConfigMvnPlugin(Document doc) throws DOMException, SAXException, IOException {
    // modify pom.xml content and add cfg to spring maven plugin
    NodeList nl = doc.getElementsByTagName("plugin");
    if (nl != null && nl.getLength() > 0) {
        for (int i = 0; i < nl.getLength(); i++) {
            Element el = (Element) nl.item(i);
            NodeList grpId = el.getElementsByTagName("groupId");
            NodeList artId = el.getElementsByTagName("artifactId");
            if (grpId.getLength() > 0 && artId.getLength() > 0
                    && "org.springframework.boot".equals(grpId.item(0).getTextContent())
                    && "spring-boot-maven-plugin".equals(artId.item(0).getTextContent())) {
                Node cfg = doc.createElement("configuration");
                Node frk = doc.createElement("fork");
                frk.setTextContent("true");
                cfg.appendChild(frk);//from   w  ww .  j av a2 s .com
                el.appendChild(cfg);
            }
        }
    }
}

From source file:com.photon.phresco.framework.impl.ConfigurationWriter.java

public void updateTestConfiguration(SettingsInfo settingsInfo, String browser, String resultConfigXml)
        throws PhrescoException {
    try {/*  www .j a va  2s .c  o m*/
        Node configNode = getNode("environment");
        Node node = getNode("environment/" + settingsInfo.getType());
        Node browserNode = getNode("environment/Browser");
        if (node != null) {
            configNode.removeChild(node);
        }

        if (browserNode != null) {
            browserNode.setTextContent(browser);
        } else {
            Element browserEle = getDocument().createElement("Browser");
            browserEle.setTextContent(browser);
            configNode.appendChild(browserEle);
        }
        configNode.appendChild(createConfigElement(settingsInfo));
    } catch (Exception e) {
        throw new PhrescoException("Configuration not found to delete");
    }
}