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:org.apache.shindig.gadgets.templates.tags.FlashTagHandler.java

public void process(Node result, Element tag, TemplateProcessor processor) {
    SwfObjectConfig config;/*from   w  w w  .  j  a  v  a 2  s .c  o  m*/
    try {
        config = getSwfConfig(tag, processor);
    } catch (RuntimeException re) {
        // Record the processing error into the output
        Element err = result.getOwnerDocument().createElement("span");
        err.setTextContent("Failed to process os:Flash tag: " + StringEscapeUtils.escapeHtml(re.getMessage()));
        result.appendChild(err);
        return;
    }

    // Bind the security token to the flashvars if its available
    String st = processor.getTemplateContext().getGadget().getContext().getParameter("st");
    if (!StringUtils.isEmpty(st)) {
        String stVar = "st=" + Utf8UrlCoder.encode(st);
        if (StringUtils.isEmpty(config.flashvars)) {
            config.flashvars = stVar;
        } else {
            config.flashvars += '&' + stVar;
        }
    }

    // Restrict the content if sanitization is enabled
    if (processor.getTemplateContext().getGadget().sanitizeOutput()) {
        config.allowscriptaccess = SwfObjectConfig.ScriptAccess.never;
        config.swliveconnect = false;
        config.allownetworking = SwfObjectConfig.NetworkAccess.internal;
        // TODO - Implement container control over autoplay on views
    }

    // Create a div wrapper around the provided alternate content
    Element altHolder = result.getOwnerDocument().createElement("div");
    String altContentId = ALT_CONTENT_PREFIX + idGenerator.incrementAndGet();
    altHolder.setAttribute("id", altContentId);
    result.appendChild(altHolder);

    // Add the alternate content to the holder
    NodeList alternateContent = tag.getChildNodes();
    if (alternateContent.getLength() > 0) {
        processor.processChildNodes(altHolder, tag);
    }

    // Create the call to swfobject
    String swfObjectCall = buildSwfObjectCall(config, altContentId);
    Element script = result.getOwnerDocument().createElement("script");
    script.setAttribute("type", "text/javascript");
    result.appendChild(script);

    if (config.play == SwfObjectConfig.Play.immediate) {
        // Call swfobject immediately
        script.setTextContent(swfObjectCall);
    } else {
        // Add onclick handler to trigger call to swfobject
        script.setTextContent("function " + altContentId + "(){ " + swfObjectCall + " }");
        altHolder.setAttribute("onclick", altContentId + "()");
    }

    // Bypass sanitization for the holder tag and the call to swfobject
    SanitizingGadgetRewriter.bypassSanitization(altHolder, false);
    SanitizingGadgetRewriter.bypassSanitization(script, false);
    ensureSwfobject(result.getOwnerDocument(), processor);
}

From source file:org.apache.shindig.gadgets.templates.tags.FlashTagHandler.java

/**
 * Ensure that the swfobject JS is inlined
 *//*from  w ww  . jav  a 2  s  . c  om*/
void ensureSwfobject(Document doc, TemplateProcessor processor) {
    // TODO: This should probably be a function of the rewriter.
    Element head = (Element) DomUtil.getFirstNamedChildNode(doc.getDocumentElement(), "head");
    NodeList childNodes = head.getChildNodes();
    for (int i = 0; i < childNodes.getLength(); i++) {
        Node node = childNodes.item(i);
        if (node.getUserData(SWFOBJECT) != null) {
            return;
        }
    }
    Element swfobject = doc.createElement("script");
    swfobject.setAttribute("type", "text/javascript");
    List<FeatureResource> resources = featureRegistry.getFeatureResources(
            processor.getTemplateContext().getGadget().getContext(), ImmutableSet.of(SWFOBJECT), null);
    for (FeatureResource resource : resources) {
        // Emits all content for feature SWFOBJECT, which has no downstream dependencies.
        swfobject.setTextContent(resource.getContent());
    }
    swfobject.setUserData(SWFOBJECT, SWFOBJECT, null);
    head.appendChild(swfobject);
    SanitizingGadgetRewriter.bypassSanitization(swfobject, false);
}

From source file:org.apache.sling.its.servlets.ItsServlet.java

/**
 * Process the properties of the current resource. Every property of the
 * current resource needs to be outputted to the document with the
 * exception of properties with the jcr and sling prefix.
 *
 * To adhere to the w3c id rule, there will be an extra id property that
 * needs to be generated.//from   www.j  av  a  2 s . c  o m
 *
 * @param resource
 *          the current resource
 * @param element
 *          the current element
 */
private void processAttributes(final Resource resource, final Element element) {
    final Document doc = element.getOwnerDocument();
    final ValueMap props = resource.adaptTo(ValueMap.class);
    final List<String> namespaces = Arrays
            .asList(props.get(SlingItsConstants.NAMESPACE_DECLARATION, new String[] {}));
    for (final String key : props.keySet()) {
        if (isValidProperty(key)) {
            final String value = (String) props.get(key);
            if (SlingItsConstants.TEXT_CONTENT.equals(key)) {
                element.setTextContent(value);
            } else if (SlingItsConstants.ITS_NOTE.equals(key)
                    && element.getNodeName().endsWith(SlingItsConstants.ITS_LOCNOTE_RULE)) {
                final Element locNoteElement = doc
                        .createElement(props.get(SlingItsConstants.NODE_PREFIX, String.class) + ":locNote");
                locNoteElement.setTextContent(value);
                element.appendChild(locNoteElement);
            } else if (namespaces.contains(key)) {
                element.setAttribute(SlingItsConstants.XMLNS + key, value);
            } else if (this.isHtml && StringUtils.equals(key, SlingItsConstants.XML_PRIMARY_TYPE_PROP)
                    && (!props.keySet().contains(SlingItsConstants.NODE_PREFIX))) {
                element.setAttribute(SlingItsConstants.HTML_PRIMARY_TYPE_PROP, value);
            } else if (this.isHtml && StringUtils.equals(key, JcrResourceConstants.SLING_RESOURCE_TYPE_PROPERTY)
                    && (!props.keySet().contains(SlingItsConstants.NODE_PREFIX))) {
                element.setAttribute(SlingItsConstants.HTML_RESOURCE_TYPE_PROP, value);
            } else {
                element.setAttribute(key, value);
            }
        }
    }
    if (!resource.getPath().startsWith(SlingItsConstants.ITS_GLOBAL_PATH)
            && !element.getNodeName().endsWith(SlingItsConstants.ITS_RULES) && !props.keySet().contains("id")
            && !props.keySet().contains("xml:id")) {
        element.setAttribute((this.isHtml ? "data-sling-its-id" : "sling-its:id"),
                getUniqueId(resource.getPath()));
    }
}

From source file:org.apache.tuscany.sca.implementation.bpel.ode.TuscanyProcessConfImpl.java

/**
 * Gets the variable initializer DOM sequence for a given property, in the context of a supplied
 * DOM model of the BPEL process/*from   w  w w. j av a 2  s.  c  o  m*/
 * @param bpelDOM - DOM representation of the BPEL process
 * @param property - SCA Property which relates to one of the variables in the BPEL process
 * @return - a DOM model representation of the XML statements required to initialize the
 * BPEL variable with the value of the SCA property.
 */
private Element getInitializerSequence(Document bpelDOM, ComponentProperty property) {
    // For an XML simple type (string, int, etc), the BPEL initializer sequence is:
    // <assign><copy><from><literal>value</literal></from><to variable="variableName"/></copy></assign>
    QName type = property.getXSDType();
    if (type != null) {
        if (mapper.isSimpleXSDType(type)) {
            // Simple types
            String NS_URI = bpelDOM.getDocumentElement().getNamespaceURI();
            String valueText = getPropertyValueText(property.getValue());
            Element literalElement = bpelDOM.createElementNS(NS_URI, "literal");
            literalElement.setTextContent(valueText);
            Element fromElement = bpelDOM.createElementNS(NS_URI, "from");
            fromElement.appendChild(literalElement);
            Element toElement = bpelDOM.createElementNS(NS_URI, "to");
            Attr variableAttribute = bpelDOM.createAttribute("variable");
            variableAttribute.setValue(property.getName());
            toElement.setAttributeNode(variableAttribute);
            Element copyElement = bpelDOM.createElementNS(NS_URI, "copy");
            copyElement.appendChild(fromElement);
            copyElement.appendChild(toElement);
            Element assignElement = bpelDOM.createElementNS(NS_URI, "assign");
            assignElement.appendChild(copyElement);
            return assignElement;
        } // end if
          // TODO Deal with Properties which have a non-simple type
    } else {
        // TODO Deal with Properties which have an element as the type
    } // end if

    return null;
}

From source file:org.apache.ws.security.message.ModifiedRequestTest.java

/**
 * Test for when some EncryptedData CipherValue data is modified.
 */// w  w  w .j ava  2 s .  c om
@org.junit.Test
public void testModifiedEncryptedDataCipherValue() throws Exception {
    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setUserInfo("wss40");
    builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Crypto wssCrypto = CryptoFactory.getInstance("wss40.properties");
    Document encryptedDoc = builder.build(doc, wssCrypto, secHeader);

    Element body = WSSecurityUtil.findBodyElement(doc);
    Element cipherValue = WSSecurityUtil.findElement(body, "CipherValue", WSConstants.ENC_NS);
    String cipherText = cipherValue.getTextContent();

    StringBuilder stringBuilder = new StringBuilder(cipherText);
    int index = stringBuilder.length() / 2;
    char ch = stringBuilder.charAt(index);
    if (ch != 'A') {
        ch = 'A';
    } else {
        ch = 'B';
    }
    stringBuilder.setCharAt(index, ch);
    cipherValue.setTextContent(stringBuilder.toString());

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

    WSSecurityEngine newEngine = new WSSecurityEngine();
    try {
        newEngine.processSecurityHeader(doc, null, new KeystoreCallbackHandler(), wssCrypto);
        fail("Failure expected on a modified EncryptedData CipherValue");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}

From source file:org.apache.ws.security.message.ModifiedRequestTest.java

/**
 * Test for when some EncryptedKey CipherValue data is modified.
 *//*from w w  w .j  a  v  a  2 s .co m*/
@org.junit.Test
public void testModifiedEncryptedKeyCipherValue() throws Exception {
    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setUserInfo("wss40");
    builder.setKeyIdentifierType(WSConstants.BST_DIRECT_REFERENCE);
    builder.setSymmetricEncAlgorithm(WSConstants.TRIPLE_DES);
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);
    Crypto wssCrypto = CryptoFactory.getInstance("wss40.properties");
    Document encryptedDoc = builder.build(doc, wssCrypto, secHeader);

    Element encryptedKey = WSSecurityUtil.findElement(doc.getDocumentElement(), "EncryptedKey",
            WSConstants.ENC_NS);
    Element cipherValue = WSSecurityUtil.findElement(encryptedKey, "CipherValue", WSConstants.ENC_NS);
    String cipherText = cipherValue.getTextContent();

    StringBuilder stringBuilder = new StringBuilder(cipherText);
    int index = stringBuilder.length() / 2;
    char ch = stringBuilder.charAt(index);
    if (ch != 'A') {
        ch = 'A';
    } else {
        ch = 'B';
    }
    stringBuilder.setCharAt(index, ch);
    cipherValue.setTextContent(stringBuilder.toString());

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

    WSSecurityEngine newEngine = new WSSecurityEngine();
    try {
        newEngine.processSecurityHeader(doc, null, new KeystoreCallbackHandler(), wssCrypto);
        fail("Failure expected on a modified EncryptedData CipherValue");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}

From source file:org.apache.ws.security.message.ModifiedRequestTest.java

/**
 * Test for when an element that a Signature Reference points to is modified
 *//*from   w  w w .ja  v  a  2 s . c  om*/
@org.junit.Test
public void testModifiedSignatureReference() throws Exception {
    WSSecSignature builder = new WSSecSignature();
    builder.setUserInfo("16c73ab6-b892-458f-abf5-2f875f74882e", "security");
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    WSSecTimestamp timestamp = new WSSecTimestamp();
    timestamp.setTimeToLive(300);
    Document createdDoc = timestamp.build(doc, secHeader);

    List<WSEncryptionPart> parts = new ArrayList<WSEncryptionPart>();
    WSEncryptionPart encP = new WSEncryptionPart("Timestamp", WSConstants.WSU_NS, "");
    parts.add(encP);
    builder.setParts(parts);

    Document signedDoc = builder.build(createdDoc, crypto, secHeader);

    // Modify the Created text of the Timestamp element
    Element timestampElement = timestamp.getElement();
    Element createdValue = WSSecurityUtil.findElement(timestampElement, "Created", WSConstants.WSU_NS);
    DateFormat zulu = new XmlSchemaDateFormat();
    createdValue.setTextContent(zulu.format(new Date()));

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

    try {
        verify(signedDoc);
        fail("Failure expected on a modified Signature Reference");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getErrorCode() == 6);
        assertTrue(ex.getMessage().startsWith("The signature or decryption was invalid"));
    }
}

From source file:org.apache.ws.security.saml.SAMLUtil.java

/**
* Create a TimeStamp object from the SAML assertion.
* @param assertion//from ww w. ja v a  2  s .c o m
* @return
* @throws WSSecurityException
*/
public static Timestamp getTimestampForSAMLAssertion(Element assertion) throws WSSecurityException {

    String[] validityPeriod = getValidityPeriod(assertion);
    // If either of the timestamps are missing, then return a null
    if (validityPeriod[0] == null || validityPeriod[1] == null) {
        return null;
    }

    try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        Document document = dbFactory.newDocumentBuilder().newDocument();
        Element element = document.createElement("SAMLTimestamp");

        Element createdElement = document.createElementNS(WSConstants.WSU_NS, WSConstants.CREATED_LN);
        createdElement.setTextContent(validityPeriod[0]);
        element.appendChild(createdElement);

        Element expiresElement = document.createElementNS(WSConstants.WSU_NS, WSConstants.EXPIRES_LN);
        expiresElement.setTextContent(validityPeriod[1]);
        element.appendChild(expiresElement);

        return new Timestamp(element);

    } catch (ParserConfigurationException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "SAMLTimeStampBuildError", null, e);
    } catch (WSSecurityException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "SAMLTimeStampBuildError", null, e);
    }
}

From source file:org.automagic.deps.doctor.editor.PomWriterImpl.java

@Override
public void addExplicitDependencyVersion(TransitiveDependency dependency) {

    Element versionElement = document.createElement("version");
    versionElement.setTextContent(dependency.getVersion().toString());

    Artifact artifact = dependency.getArtifact();
    Optional<Node> dependencyNode = Utils.getDependencyNode(artifact, document, "/project/dependencies");
    addIndentedNode(dependencyNode.get(), versionElement, 3);

}

From source file:org.bibsonomy.webapp.controller.ajax.ConceptController.java

protected String prepareResponseString(final String loginUserName, final List<Tag> pickedConcepts) {
    final StringWriter response = new StringWriter();

    try {//w w  w  . j av  a2  s.c o m
        final Document doc = DocumentBuilderFactoryImpl.newInstance().newDocumentBuilder().newDocument();

        // append root node
        final Element relations = doc.createElement("relations");
        relations.setAttribute("user", loginUserName);
        doc.appendChild(relations);

        // append all other informations
        for (final Tag tag : pickedConcepts) {
            final Element relation = doc.createElement("relation");
            relations.appendChild(relation);

            final Element upper = doc.createElement("upper");
            upper.setTextContent(tag.getName());
            relation.appendChild(upper);

            final Element lowers = doc.createElement("lowers");
            lowers.setAttribute("id", tag.getName());
            relation.appendChild(lowers);

            for (final Tag subTag : tag.getSubTags()) {
                final Element lower = doc.createElement("lower");
                lower.setTextContent(subTag.getName());
                lowers.appendChild(lower);
            }
        }

        new XMLSerializer(response, new OutputFormat(doc)).serialize(doc);

        // return it as string
        return response.toString();

    } catch (ParserConfigurationException ex) {
        log.error("Could not parse XML ", ex);
    } catch (IOException ex) {
        log.error("Could not serialize XML ", ex);
    }

    return null;
}