Example usage for org.w3c.dom Element setTextContent

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

Introduction

In this page you can find the example usage for org.w3c.dom Element 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:io.fabric8.tooling.archetype.builder.ArchetypeBuilder.java

/**
 * Creates new element as child of <code>parent</code> and sets its text content
 *
 * @param doc//www.  j a v a2  s  . c o m
 * @param parent
 * @param name
 * @param content
 * @param beforeNames
 * @return
 */
protected Element replaceOrAddElementText(Document doc, Element parent, String name, String content,
        List<String> beforeNames) {
    Element element = replaceOrAddElement(doc, parent, name, beforeNames);
    element.setTextContent(content);
    return element;
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

@Test
public void testRSTS_JAXWS_Client() throws Exception {
    ServletTester servletTester = new ServletTester();
    servletTester.addServlet(MyTestServlet.class, "/");

    Security.addProvider(new BouncyCastleProvider());

    KeyPair keyPair = generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=localhost", notBefore, notAfter);
    File tmpP12File = File.createTempFile("ssl-", ".p12");
    LOG.debug("p12 file: " + tmpP12File.getAbsolutePath());
    persistKey(tmpP12File, keyPair.getPrivate(), certificate, "secret".toCharArray(), "secret".toCharArray());

    SslSocketConnector sslSocketConnector = new SslSocketConnector();
    sslSocketConnector.setKeystore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststore(tmpP12File.getAbsolutePath());
    sslSocketConnector.setTruststoreType("pkcs12");
    sslSocketConnector.setKeystoreType("pkcs12");
    sslSocketConnector.setPassword("secret");
    sslSocketConnector.setKeyPassword("secret");
    sslSocketConnector.setTrustPassword("secret");
    sslSocketConnector.setMaxIdleTime(30000);
    int sslPort = getFreePort();
    sslSocketConnector.setPort(sslPort);

    servletTester.getContext().getServer().addConnector(sslSocketConnector);
    String sslLocation = "https://localhost:" + sslPort + "/";

    servletTester.start();/*from ww w. j a v  a2  s.co m*/
    String location = servletTester.createSocketConnector(true);

    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManager trustManager = new TestTrustManager(certificate);
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    SSLContext.setDefault(sslContext);

    try {
        LOG.debug("running R-STS test...");
        RSTSClient client = new RSTSClient(sslLocation);
        SecurityToken inputSecurityToken = new SecurityToken();
        byte[] key = new byte[256 / 8];
        SecureRandom random = new SecureRandom();
        random.nextBytes(key);
        inputSecurityToken.setKey(key);
        inputSecurityToken.setAttachedReference("_" + UUID.randomUUID().toString());
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document document = documentBuilder.newDocument();
        Element tokenElement = document.createElement("Token");
        tokenElement.setTextContent("hello world");
        inputSecurityToken.setToken(tokenElement);

        client.getSecurityToken(inputSecurityToken, "https://auth.beta.agiv.be/ClaimsAwareService/Service.svc");
    } finally {
        servletTester.stop();
    }
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

Document decorate(Document doc, String uri) {
    Element root = doc.getDocumentElement();
    Element instance = (Element) root.getElementsByTagName(ELEMENT_INSTANCE).item(0);
    Element uriElement = doc.createElement(ELEMENT_URI);
    uriElement.setTextContent(uri == null ? NULL_VALUE : uri);
    root.insertBefore(uriElement, instance);
    return doc;/*  ww  w .jav a 2 s  . c  om*/
}

From source file:edu.duke.cabig.c3pr.webservice.studyimportexport.impl.StudyImportExportImpl.java

/**
 * Creates the soap fault./* w  ww.j a  v a2 s  . c o  m*/
 *
 * @param msg the msg
 * @return the sOAP fault
 */
private SOAPFault createSOAPFault(String msg) {
    try {
        SOAPFactory factory = SOAPFactory.newInstance();
        SOAPFault fault = factory.createFault();
        fault.setFaultString(msg);
        fault.setFaultCode(new QName(SOAP_NS, SOAP_FAULT_CODE));
        Detail detail = fault.addDetail();
        final Element detailEntry = detail.getOwnerDocument().createElementNS(SERVICE_NS, STUDY_IMPORT_FAULT);
        detail.appendChild(detailEntry);

        final Element detailMsg = detail.getOwnerDocument().createElementNS(SERVICE_NS, FAULT_MESSAGE);
        detailMsg.setTextContent(msg);
        detailEntry.appendChild(detailMsg);
        return fault;
    } catch (SOAPException e) {
        log.error(ExceptionUtils.getFullStackTrace(e));
        throw new WebServiceException(e);
    }

}

From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java

public Element setVet(String sName) {
    Element eVet = null;//from w  w  w.  j a  va  2 s .c  o m
    if (sName == null || sName.trim().length() == 0)
        sName = "Not Entered";
    if (isValidDoc() && sName != null && sName.trim().length() > 0) {
        eVet = doc.createElement("Veterinarian");
        Node after = childNodeByNames(root,
                "MovementPurpose,Origin,Destination,Consignor,Consignee,Accessions,Animal,GroupLot,Attachment");
        root.insertBefore(eVet, after);
        Element person = doc.createElement("Person");
        eVet.appendChild(person);
        Element name = doc.createElement("Name");
        person.appendChild(name);
        name.setTextContent(sName);
    }
    return eVet;
}

From source file:com.twinsoft.convertigo.beans.steps.LDAPAuthenticationStep.java

@Override
protected void createStepNodeValue(Document doc, Element stepNode) throws EngineException {
    // Remove currently authenticated user from session
    getSequence().context.removeAuthenticatedUser();

    String serverUrls = server.getSingleString(this);
    if (serverUrls == null || serverUrls.isEmpty()) {
        throw new EngineException("Invalid LDAP servers : null or empty");
    }/*www  .  jav  a  2 s  . c o  m*/

    // Server URL list
    StringTokenizer st = new StringTokenizer(serverUrls, ",", false);
    List<String> servers = new ArrayList<String>();
    while (st.hasMoreTokens()) {
        servers.add(st.nextToken().trim());
    }

    // Search/Bind LDAP database for given user
    Boolean authenticated = false;
    String userDn = null;

    String userLogin = login.getSingleString(this);
    String userPassword = password.getSingleString(this);
    if (userLogin != null) {

        // Create TWSLDAP object
        TWSLDAP twsLDAP = new TWSLDAP();

        // Loop through server URLs
        int nbServers = servers.size();
        for (String serverUrl : servers) {
            userDn = null;

            if (serverUrl.isEmpty()) {
                Engine.logBeans.warn("(LDAPAuthenticationStep) Ignoring invalid LDAP server: empty URL");
                continue;
            } else if (!serverUrl.startsWith("ldap://") && !serverUrl.startsWith("ldaps://")) {
                Engine.logBeans.warn("(LDAPAuthenticationStep) Ignoring invalid LDAP server \"" + serverUrl
                        + "\": URL must start with \"ldap://\"");
                continue;
            }

            // Search database
            if (getBindingPolicy().equals(LdapBindingPolicy.SearchAndBind)) {
                String searchLogin = adminLogin.getSingleString(this);
                String searchPassword = adminPassword.getSingleString(this);
                String searchBase = basePath.getSingleString(this);

                if (searchLogin != null) {
                    int countLimit = 0, timeLimit = 0;
                    String searchHost = getHost(serverUrl);
                    String searchFilter = getFilter(userLogin);
                    String[] searchAttributes = attributes.getStringArray(this);

                    // Avoid null password
                    searchPassword = searchPassword == null ? "" : searchPassword;

                    // Search database for given user
                    Engine.logBeans.trace("(LDAPAuthenticationStep) LDAP search start");
                    twsLDAP.search(searchHost, searchLogin, searchPassword, searchBase, searchFilter,
                            searchAttributes, timeLimit, countLimit);
                    String errorMsg = twsLDAP.errorMessage != null ? " (Error: " + twsLDAP.errorMessage + ")"
                            : "";
                    boolean bFound = twsLDAP.hasMoreResults();
                    Engine.logBeans.debug("(LDAPAuthenticationStep) LDAP search: host:" + searchHost
                            + ", searchBase:" + searchBase + ", filter:" + searchFilter + "; user "
                            + (bFound ? "found" : "NOT found") + errorMsg);
                    Engine.logBeans.trace("(LDAPAuthenticationStep) LDAP search end");

                    if (bFound) {
                        userDn = twsLDAP.getNextResult().toLowerCase()
                                + (searchBase == null ? "" : "," + searchBase.toLowerCase());
                        Matcher mRDN = pRDN.matcher(userDn);

                        while (mRDN.find()) {
                            Element rdn = doc.createElement("rdn");
                            rdn.setAttribute("name", mRDN.group(1));
                            rdn.setTextContent(mRDN.group(2));
                            stepNode.appendChild(rdn);
                        }

                        for (String attribute : searchAttributes) {
                            if (StringUtils.isNotBlank(attribute)) {
                                String[] values = twsLDAP.getResultEx(attribute);
                                if (values != null) {
                                    for (String value : values) {
                                        Element attr = doc.createElement("attribute");
                                        attr.setAttribute("name", attribute);
                                        attr.setTextContent(value);
                                        stepNode.appendChild(attr);
                                    }
                                }
                            }
                        }
                    } else {
                        if (nbServers > 1) {
                            continue; // loop
                        }
                    }
                } else {
                    Engine.logBeans.warn(
                            "(LDAPAuthenticationStep) Invalid LDAP admin Login \"" + searchLogin + "\" !");
                }
            }

            // Bind database with given/found user
            String errorMsg = "";
            Engine.logBeans.trace("(LDAPAuthenticationStep) LDAP bind start");
            String bindLogin = userDn == null ? userLogin : userDn;
            String bindPassword = userPassword;
            if (bindPassword != null && !bindPassword.isEmpty()) {
                authenticated = twsLDAP.bind(serverUrl, bindLogin, bindPassword);
                errorMsg = twsLDAP.errorMessage != null ? " (Error: " + twsLDAP.errorMessage + ")" : "";
            } else {
                authenticated = false;
                errorMsg = "; invalid password";
            }
            Engine.logBeans.debug("(LDAPAuthenticationStep) LDAP bind: user \"" + bindLogin
                    + "\"; authenticated=" + authenticated.toString() + errorMsg);
            Engine.logBeans.trace("(LDAPAuthenticationStep) LDAP bind end");

            // Set authenticated user on session
            if (authenticated) {
                // use given login
                String sessionLogin = userLogin;
                if (userDn != null && !isNTAccount(userLogin) && !isEMailAccount(userLogin)
                        && !isDistinguishedName(userLogin)) {
                    // use found distinguished name
                    if (isFilter(userLogin)) {
                        sessionLogin = userDn;
                    }
                }
                getSequence().context.setAuthenticatedUser(sessionLogin);
                break; // exit loop
            }
            // else loop
        }
    } else {
        Engine.logBeans.warn("Invalid LDAP user Login \"" + userLogin + "\" !");
    }

    Element user = doc.createElement("userDn");
    user.setTextContent(userDn == null ? "" : userDn);
    stepNode.appendChild(user);

    if (userLogin != null && authenticated) {
        user = doc.createElement("authenticatedUserID");
        user.setTextContent(userLogin);
        stepNode.appendChild(user);
    }
}

From source file:de.bund.bfr.pmfml.numl.ResultComponent.java

/**
 * Builds a {@link ReferenceNuMLNode} using the RIS tag set.
 *//*from www  .  ja va  2s  . c om*/
public ReferenceNuMLNode(final Reference reference, final Document doc) {

    // Reference container
    node = doc.createElementNS(DC_URI, TAG);

    if (reference.isSetAuthor()) {
        final Element authorNode = doc.createElement(SPEC.getAuthor());
        authorNode.setTextContent(reference.getAuthor());
        node.appendChild(authorNode);
    }

    if (reference.isSetYear()) {
        final Element yearNode = doc.createElement(SPEC.getYear());
        yearNode.setTextContent(reference.getYear().toString());
        node.appendChild(yearNode);
    }

    if (reference.isSetTitle()) {
        final Element titleNode = doc.createElement(SPEC.getTitle());
        titleNode.setTextContent(reference.getTitle());
        node.appendChild(titleNode);
    }

    if (reference.isSetAbstractText()) {
        final Element abstractNode = doc.createElement(SPEC.getAbstract());
        abstractNode.setTextContent(reference.getAbstractText());
        node.appendChild(abstractNode);
    }

    if (reference.isSetJournal()) {
        final Element journalNode = doc.createElement(SPEC.getJournal());
        journalNode.setTextContent(reference.getJournal());
        node.appendChild(journalNode);
    }

    if (reference.isSetVolume()) {
        final Element volumeNode = doc.createElement(SPEC.getVolume());
        volumeNode.setTextContent(reference.getVolume());
        node.appendChild(volumeNode);
    }

    if (reference.isSetIssue()) {
        final Element issueNode = doc.createElement(SPEC.getIssue());
        issueNode.setTextContent(reference.getIssue());
        node.appendChild(issueNode);
    }

    if (reference.isSetPage()) {
        final Element pageNode = doc.createElement(SPEC.getPage());
        pageNode.setTextContent(reference.getPage().toString());
        node.appendChild(pageNode);
    }

    if (reference.isSetApprovalMode()) {
        final Element approvalNode = doc.createElement(SPEC.getApproval());
        approvalNode.setTextContent(reference.getApprovalMode().toString());
        node.appendChild(approvalNode);
    }

    if (reference.isSetWebsite()) {
        final Element websiteNode = doc.createElement(SPEC.getWebsite());
        websiteNode.setTextContent(reference.getWebsite());
        node.appendChild(websiteNode);
    }

    if (reference.isSetType()) {
        final Element typeNode = doc.createElement(SPEC.getType());
        typeNode.setTextContent(reference.getType().toString());
        node.appendChild(typeNode);
    }

    if (reference.isSetComment()) {
        final Element commentNode = doc.createElement(SPEC.getComment());
        commentNode.setTextContent(reference.getComment());
        node.appendChild(commentNode);
    }
}

From source file:de.bund.bfr.pmfml.numl.ResultComponent.java

public Element toNode(final Document doc) {

    final Element node = doc.createElement(ELEMENT_NAME);
    node.setAttribute(ID, strProps.get(ID));

    final Element annotation = doc.createElement(ANNOTATION);
    node.appendChild(annotation);//from   w ww .  j a  v a  2s  . c om

    final Element metadata = doc.createElement(METADATA);
    annotation.appendChild(metadata);

    if (condID != null) {
        final Element condIdNode = doc.createElement(CONDID);
        condIdNode.setTextContent(condID.toString());
        metadata.appendChild(condIdNode);
    }

    if (strProps.containsKey(COMBASEID)) {
        final Element combaseIdNode = doc.createElement(COMBASEID);
        combaseIdNode.setTextContent(strProps.get(COMBASEID));
        metadata.appendChild(combaseIdNode);
    }

    if (strProps.containsKey(CREATOR_GIVEN_NAME)) {
        final Element creatorGivenNameNode = doc.createElement(CREATOR_GIVEN_NAME);
        creatorGivenNameNode.setTextContent(strProps.get(CREATOR_GIVEN_NAME));
        metadata.appendChild(creatorGivenNameNode);
    }

    if (strProps.containsKey(CREATOR_FAMILY_NAME)) {
        final Element creatorFamilyNameNode = doc.createElement(CREATOR_FAMILY_NAME);
        creatorFamilyNameNode.setTextContent(strProps.get(CREATOR_FAMILY_NAME));
        metadata.appendChild(creatorFamilyNameNode);
    }

    if (strProps.containsKey(CREATOR_CONTACT)) {
        final Element creatorContactNode = doc.createElement(CREATOR_CONTACT);
        creatorContactNode.setTextContent(strProps.get(CREATOR_CONTACT));
        metadata.appendChild(creatorContactNode);
    }

    if (strProps.containsKey(CREATED_DATE)) {
        final Element createdDateNode = doc.createElement(CREATED_DATE);
        createdDateNode.setTextContent(strProps.get(CREATED_DATE));
        metadata.appendChild(createdDateNode);
    }

    if (strProps.containsKey(MODIFIED_DATE)) {
        final Element modifiedDateNode = doc.createElement(MODIFIED_DATE);
        modifiedDateNode.setTextContent(strProps.get(MODIFIED_DATE));
        metadata.appendChild(modifiedDateNode);
    }

    if (modelType != null) {
        final Element modelTypeNode = doc.createElement(MODEL_TYPE);
        modelTypeNode.setTextContent(modelType.name());
        metadata.appendChild(modelTypeNode);
    }

    if (strProps.containsKey(RIGHTS)) {
        final Element rightsNode = doc.createElement(RIGHTS);
        rightsNode.setTextContent(strProps.get(RIGHTS));
        metadata.appendChild(rightsNode);
    }

    if (notes != null) {
        final Element notesNode = doc.createElement("notes");
        notesNode.setTextContent(notes);
        metadata.appendChild(notesNode);
    }

    if (references != null) {
        for (final Reference reference : getReferences()) {
            metadata.appendChild(new ReferenceNuMLNode(reference, doc).node);
        }
    }

    final Element dimensionDescriptionNode = doc.createElement(DIMENSION_DESCRIPTION);
    dimensionDescriptionNode.appendChild(dimensionDescription.toNode(doc));
    node.appendChild(dimensionDescriptionNode);

    final Element dimensionNode = doc.createElement(DIMENSION);
    for (final Tuple tuple : getDimensions()) {
        dimensionNode.appendChild(tuple.toNode(doc));
    }
    node.appendChild(dimensionNode);

    return node;
}

From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java

public void addPDFAttachement(byte[] pdfBytes, String sFileName) {
    if (isValidDoc() && pdfBytes != null && pdfBytes.length > 0) {
        String sPDF64 = new String(Base64.encodeBase64(pdfBytes));
        try {//from  w  ww. j  a v a2 s.c  om
            Element attach = doc.createElement("Attachment");
            root.appendChild(attach);
            attach.setAttribute("DocType", "PDF CVI");
            attach.setAttribute("MimeType", "application/pdf");
            attach.setAttribute("Filename", sFileName);
            Element payload = doc.createElement("Payload");
            attach.appendChild(payload);
            payload.setTextContent(sPDF64);
        } catch (Exception e) {
            logger.error("Should not see this error for unsupported encoding", e);
        }
    }
}

From source file:edu.clemson.lph.civet.xml.StdeCviXmlBuilder.java

public void addMetadataAttachement(CviMetaDataXml metaData) {
    String sXML = metaData.getXmlString();
    try {/* w  w w. j  a  va2s.c o  m*/
        byte[] xmlBytes = sXML.getBytes("UTF-8");
        if (isValidDoc() && xmlBytes != null && xmlBytes.length > 0) {
            String sMetadata64 = javax.xml.bind.DatatypeConverter.printBase64Binary(xmlBytes);
            Element attach = doc.createElement("Attachment");
            root.appendChild(attach);
            attach.setAttribute("DocType", "Other");
            attach.setAttribute("MimeType", "text/xml");
            attach.setAttribute("Filename", "CviMetadata.xml");
            Element payload = doc.createElement("Payload");
            attach.appendChild(payload);
            payload.setTextContent(sMetadata64);
        }
    } catch (UnsupportedEncodingException e1) {
        logger.error(e1);
    } catch (Exception e) {
        logger.error("Should not see this error for unsupported encoding", e);
    }
}