Example usage for org.w3c.dom Element getOwnerDocument

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

Introduction

In this page you can find the example usage for org.w3c.dom Element getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.apache.servicemix.jbi.deployer.utils.ManagementSupport.java

private static void appendTaskResultDetails(Element root, Message fmkMsg) {
    Element taskResultDetails = createChild(root, TASK_RESULT_DETAILS);
    createChild(taskResultDetails, TASK_ID, fmkMsg.getTask());
    createChild(taskResultDetails, TASK_RESULT, fmkMsg.getResult());
    if (fmkMsg.getType() != null) {
        createChild(taskResultDetails, MESSAGE_TYPE, fmkMsg.getType());
    }/*from   www  .j  a  v a 2 s .c  o m*/
    // task-status-message
    if (fmkMsg.getMessage() != null) {
        Element taskStatusMessage = createChild(taskResultDetails, TASK_STATUS_MSG);
        Element msgLocInfo = createChild(taskStatusMessage, MSG_LOC_INFO);
        createChild(msgLocInfo, LOC_TOKEN);
        createChild(msgLocInfo, LOC_MESSAGE, fmkMsg.getMessage());
    }
    // exception-info
    if (fmkMsg.getException() != null) {
        Element exceptionInfo = createChild(taskResultDetails, EXCEPTION_INFO);
        createChild(exceptionInfo, NESTING_LEVEL, "1");
        createChild(exceptionInfo, LOC_TOKEN);
        createChild(exceptionInfo, LOC_MESSAGE, fmkMsg.getException().getMessage());
        Element stackTrace = createChild(exceptionInfo, STACK_TRACE);
        StringWriter sw2 = new StringWriter();
        PrintWriter pw = new PrintWriter(sw2);
        fmkMsg.getException().printStackTrace(pw);
        pw.close();
        stackTrace.appendChild(root.getOwnerDocument().createCDATASection(sw2.toString()));
    }
}

From source file:org.apache.servicemix.jbi.runtime.impl.utils.DOMUtil.java

/**
 * Adds the child element with the given text
 *///from  w w w  .  j a  va  2s. c  om
public static void addChildElement(Element element, String name, Object textValue) {
    Document document = element.getOwnerDocument();
    Element child = document.createElement(name);
    element.appendChild(child);
    if (textValue != null) {
        String text = textValue.toString();
        child.appendChild(document.createTextNode(text));
    }
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

public void rewrite(Gadget gadget, MutableContent mutableContent) throws RewritingException {
    // Don't touch sanitized gadgets.
    if (gadget.sanitizeOutput()) {
        return;// w  w w .j a v  a  2  s  . co  m
    }

    try {
        Document document = mutableContent.getDocument();

        Element head = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "head");

        // Insert new content before any of the existing children of the head element
        Node firstHeadChild = head.getFirstChild();

        // Only inject default styles if no doctype was specified.
        if (document.getDoctype() == null) {
            Element defaultStyle = document.createElement("style");
            defaultStyle.setAttribute("type", "text/css");
            head.insertBefore(defaultStyle, firstHeadChild);
            defaultStyle.appendChild(defaultStyle.getOwnerDocument().createTextNode(DEFAULT_CSS));
        }

        injectBaseTag(gadget, head);
        injectGadgetBeacon(gadget, head, firstHeadChild);
        injectFeatureLibraries(gadget, head, firstHeadChild);

        // This can be one script block.
        Element mainScriptTag = document.createElement("script");
        GadgetContext context = gadget.getContext();
        MessageBundle bundle = messageBundleFactory.getBundle(gadget.getSpec(), context.getLocale(),
                context.getIgnoreCache(), context.getContainer());
        injectMessageBundles(bundle, mainScriptTag);
        injectDefaultPrefs(gadget, mainScriptTag);
        injectPreloads(gadget, mainScriptTag);

        // We need to inject our script before any developer scripts.
        head.insertBefore(mainScriptTag, firstHeadChild);

        Element body = (Element) DomUtil.getFirstNamedChildNode(document.getDocumentElement(), "body");

        body.setAttribute("dir", bundle.getLanguageDirection());

        injectOnLoadHandlers(body);

        mutableContent.documentChanged();
    } catch (GadgetException e) {
        throw new RewritingException(e.getLocalizedMessage(), e, e.getHttpStatusCode());
    }
}

From source file:org.apache.shindig.gadgets.rewrite.ConcatVisitor.java

/**
 * For css:/*  w ww .j  a  va  2 s .c o m*/
 * Link tags are first split into buckets separated by tags with mediaType == "all"
 * / title attribute different from their previous link tag / nodes that are
 * not 'link' tags.
 * This ensures that the buckets can be processed separately without losing title /
 * "all" mediaType information.
 *
 * Link tags with same mediaType are concatenated within each bucket.
 * This exercise ensures that css information is loaded in the same relative order
 * as that of the original html page, and that the css information within
 * mediaType=="all" is retained and applies to all media types.
 *
 * Look at the areLinkNodesBucketable method for details on mediaType=="all" and
 * title attribute
 *
 * Example: Assume we have the following node list. (all have same parent,
 * nodes between Node6 and Node12 are non link nodes, and hence did not come
 * to revisit() call)
 *    <link href="1.css" rel="stylesheet" type="text/css" media="screen">       -- Node1
 *    <link href="2.css" rel="stylesheet" type="text/css" media="print">        -- Node2
 *    <link href="3.css" rel="stylesheet" type="text/css" media="screen">       -- Node3
 *    <link href="4.css" rel="stylesheet" type="text/css" media="all">          -- Node4
 *    <link href="5.css" rel="stylesheet" type="text/css" media="all">          -- Node5
 *    <link href="6.css" rel="stylesheet" type="text/css" media="screen">       -- Node6
 *    <link href="12.css" rel="stylesheet" type="text/css" media="screen">      -- Node12
 *    <link href="13.css" rel="stylesheet" type="text/css" media="screen">      -- Node13
 *
 *    First we split to buckets bassed on the adjacency and other conditions.
 *    buckets - [ [ Node1, Node2, Node3 ], [ Node4, Node 5 ], [ Node6 ], [ Node12, Node13 ]
 *    Within each bucket we group them based on media type.
 *    batches - [ Node1, Node2, Node3 ] --> [ [Node1, Node3], [Node2] ]
 *            - [ Node4, Node 5 ] --> [ [ Node4, Node 5 ] ]
 *            - [ Node6 ] --> [ [ Node6 ] ]
 *            - [ Node12, Node13 ] --> [ [ Node12, Node13 ] ]
 *
 * Refer Tests for more examples.
 */
public boolean revisit(Gadget gadget, List<Node> nodes) throws RewritingException {
    // Collate Elements into Buckets.
    List<List<Element>> concatBuckets = Lists.newLinkedList();
    List<Element> curBucket = Lists.newLinkedList();
    Iterator<Node> nodeIter = nodes.iterator();
    Element cur = (Element) nodeIter.next();
    curBucket.add(cur);
    while (nodeIter.hasNext()) {
        Element next = (Element) nodeIter.next();
        if ((!split && cur != getSibling(next, true))
                || (type == ConcatUriManager.Type.CSS && !areLinkNodesBucketable(cur, next))) {
            // Break off current bucket and add to list of all.
            concatBuckets.add(curBucket);
            curBucket = Lists.newLinkedList();
        }
        curBucket.add(next);
        cur = next;
    }

    // Add leftovers.
    concatBuckets.add(curBucket);

    // Split the existing buckets based on media types into concat batches.
    List<List<Element>> concatBatches = Lists.newLinkedList();
    Iterator<List<Element>> batchesIter = concatBuckets.iterator();
    while (batchesIter.hasNext()) {
        splitBatchOnMedia(batchesIter.next(), concatBatches);
    }

    // Prepare batches of Uris to send to generate concat Uris
    List<List<Uri>> uriBatches = Lists.newLinkedList();
    batchesIter = concatBatches.iterator();
    while (batchesIter.hasNext()) {
        List<Element> batch = batchesIter.next();
        List<Uri> uris = Lists.newLinkedList();
        if (batch.isEmpty() || !getUris(type, batch, uris)) {
            batchesIter.remove();
            continue;
        }
        uriBatches.add(uris);
    }

    if (uriBatches.isEmpty()) {
        return false;
    }

    // Generate the ConcatUris, then correlate with original elements.
    List<ConcatUriManager.ConcatData> concatUris = uriManager
            .make(ConcatUriManager.ConcatUri.fromList(gadget, uriBatches, type), !split);

    Iterator<List<Element>> elemBatchIt = concatBatches.iterator();
    Iterator<List<Uri>> uriBatchIt = uriBatches.iterator();
    for (ConcatUriManager.ConcatData concatUri : concatUris) {
        List<Element> sourceBatch = elemBatchIt.next();
        List<Uri> sourceUris = uriBatchIt.next();

        // Regardless what happens, inject a copy of the first node,
        // with new (concat) URI, immediately ahead of the first elem.
        Element firstElem = sourceBatch.get(0);
        Element elemConcat = (Element) firstElem.cloneNode(true);
        elemConcat.setAttribute(type.getSrcAttrib(), concatUri.getUri().toString());
        firstElem.getParentNode().insertBefore(elemConcat, firstElem);

        // Now for all Elements, either A) remove them or B) replace each
        // with a <script> node with snippet of code configuring/evaluating
        // the resultant inserted code. This is useful for split-JS in particular,
        // and might also be used in spriting later.
        Iterator<Uri> uriIt = sourceUris.iterator();
        for (Element elem : sourceBatch) {
            Uri elemOrigUri = uriIt.next();
            String snippet = concatUri.getSnippet(elemOrigUri);
            if (!StringUtils.isEmpty(snippet)) {
                Node scriptNode = elem.getOwnerDocument().createElement("script");
                scriptNode.setTextContent(snippet);
                elem.getParentNode().insertBefore(scriptNode, elem);
            }
            elem.getParentNode().removeChild(elem);
        }
    }

    return true;
}

From source file:org.apache.shindig.gadgets.rewrite.TemplateRewriter.java

private void injectTemplateLibraryAssets(TemplateResource resource, Element head) {
    Element contentElement;/*w  w  w.  j av  a 2s  .  c  o  m*/
    switch (resource.getType()) {
    case JAVASCRIPT:
        contentElement = head.getOwnerDocument().createElement("script");
        contentElement.setAttribute("type", "text/javascript");
        break;
    case STYLE:
        contentElement = head.getOwnerDocument().createElement("style");
        contentElement.setAttribute("type", "text/css");
        break;
    default:
        throw new IllegalStateException("Unhandled type");
    }

    if (resource.isSafe()) {
        SanitizingGadgetRewriter.bypassSanitization(contentElement, false);
    }
    contentElement.setTextContent(resource.getContent());
    head.appendChild(contentElement);
}

From source file:org.apache.shindig.gadgets.rewrite.TemplateRewriter.java

private void injectTemplateLibrary(TemplateLibrary library, Element head) {
    try {// w ww .java  2 s.  c  o m
        String libraryContent = library.serialize();
        if (StringUtils.isEmpty(libraryContent)) {
            return;
        }

        Element scriptElement = head.getOwnerDocument().createElement("script");
        scriptElement.setAttribute("type", "text/javascript");
        StringBuilder buffer = new StringBuilder();
        buffer.append("opensocial.template.Loader.loadContent(");
        JsonSerializer.appendString(buffer, library.serialize());
        buffer.append(',');
        JsonSerializer.appendString(buffer, library.getLibraryUri().toString());
        buffer.append(");");
        scriptElement.setTextContent(buffer.toString());
        head.appendChild(scriptElement);
    } catch (IOException ioe) {
        // This should never happen.
    }
}

From source file:org.apache.shindig.gadgets.rewrite.TemplateRewriter.java

/**
 * Processes and renders inline templates.
 * @return Do we think the templates feature is still needed on the client?
 *//*from  w  w  w.ja  v a2s .c  o  m*/
private boolean executeTemplates(TemplateContext templateContext, MutableContent content,
        List<Element> allTemplates, TagRegistry registry) throws GadgetException {
    Map<String, Object> pipelinedData = content.getPipelinedData();

    // If true, client-side processing will be needed
    boolean needsFeature = false;
    List<Element> templates = Lists.newArrayList();
    for (Element element : allTemplates) {
        String tag = element.getAttribute("tag");
        String require = element.getAttribute("require");

        if (!checkRequiredData(require, pipelinedData.keySet())) {
            // Can't be processed on the server at all;  keep client-side processing
            needsFeature = true;
        } else if ("".equals(tag)) {
            templates.add(element);
        }
    }

    if (!templates.isEmpty()) {
        Gadget gadget = templateContext.getGadget();

        MessageBundle bundle = messageBundleFactory.getBundle(gadget.getSpec(), gadget.getContext().getLocale(),
                gadget.getContext().getIgnoreCache(), gadget.getContext().getContainer());
        MessageELResolver messageELResolver = new MessageELResolver(expressions, bundle);

        int autoUpdateID = 0;
        for (Element template : templates) {
            DocumentFragment result = processor.get().processTemplate(template, templateContext,
                    messageELResolver, registry);
            // TODO: sanitized renders should ignore this value
            if ("true".equals(template.getAttribute("autoUpdate"))) {
                // autoUpdate requires client-side processing.
                needsFeature = true;
                Element span = template.getOwnerDocument().createElement("span");
                String id = "template_auto" + (autoUpdateID++);
                span.setAttribute("id", "_T_" + id);
                template.setAttribute("name", id);
                template.getParentNode().insertBefore(span, template);
                span.appendChild(result);
            } else {
                template.getParentNode().insertBefore(result, template);
                template.getParentNode().removeChild(template);
            }
        }
        MutableContent.notifyEdit(content.getDocument());
    }
    return needsFeature;
}

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

/**
 * Process the child resource. Each child resource needs its own element
 * and append it to the document. After element has been created, the
 * attributes subsequently needs to be processed. However,
 * text-content-node resources do not need its own element. The
 * text-content property needs to be appended to the previous element.
 *
 * @param resource//from  ww w . ja  va2s  .  c  o  m
 *          the current resource
 * @param element
 *          the current element
 * @param resourceType
 *          the resourceType provided by the root element
 */
private void processChild(final Resource resource, final Element element, final String resourceType) {
    final ValueMap valueMap = resource.adaptTo(ValueMap.class);
    final String prefix = valueMap.get(SlingItsConstants.NODE_PREFIX, String.class);
    final String name = getElementName(resource, prefix);
    final Document doc = element.getOwnerDocument();
    final Element el = doc.createElement(name);
    if (name.equals(SlingItsConstants.TEXT_CONTENT_NODE)) {
        final Text text = doc.createTextNode(valueMap.get(SlingItsConstants.TEXT_CONTENT, StringUtils.EMPTY));
        element.appendChild(text);
    } else if (name.endsWith(SlingItsConstants.ITS_RULES) && this.isHtml
            && !element.getNodeName().equals("script") && StringUtils.isNotBlank(prefix)) {
        final Element scriptElement = doc.createElement("script");
        scriptElement.setAttribute("type", "application/its+xml");
        element.appendChild(scriptElement);
        scriptElement.appendChild(el);
        processAttributes(resource, el);
    } else {
        element.appendChild(el);
        processAttributes(resource, el);
    }

    if (name.endsWith(SlingItsConstants.ITS_RULES) && StringUtils.isNotBlank(prefix)
            && StringUtils.isNotBlank(resourceType)) {
        for (final String globalRulePath : SlingItsConstants.getGlobalRules().values()) {
            final Iterator<Resource> globalRules = resource.getResourceResolver().findResources(
                    "SELECT * FROM [nt:base] as t WHERE ISCHILDNODE([" + globalRulePath + resourceType
                            + "]) AND t.[node-prefix] LIKE '" + prefix + "' ORDER BY name(t) ASC",
                    Query.JCR_SQL2);
            while (globalRules.hasNext()) {
                processChild(globalRules.next(), el, resourceType);
            }
        }
    } else {
        final Iterator<Resource> iter = resource.listChildren();
        while (iter.hasNext()) {
            processChild(iter.next(), el, resourceType);
        }
    }
}

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   w w w . j a v  a  2s .com
 *
 * @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.ws.security.message.TestMessageTransformer.java

public static Element duplicateEncryptedDataInWsseHeader(Element saaj, boolean moveReferenceList) {
    if (moveReferenceList) {
        moveReferenceList(saaj);/* w w w .j av a 2  s. c  om*/
    }
    Element body = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Body"),
            true);
    Element encData = getFirstChildElement(body,
            new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), true);
    Element newEncData = createNewEncryptedData(encData);
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"),
            true);
    Element wsseHeader = getFirstChildElement(sh,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "Security"),
            true);

    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();

    String newId = newEncData.getAttributeNS(null, "Id");
    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    newWsseHeader.appendChild(newEncData);

    if (!moveReferenceList) {
        updateEncryptedKeyRefList(newWsseHeader, newId);
    }

    Node parent = wsseHeader.getParentNode();
    parent.removeChild(wsseHeader);
    parent.appendChild(newWsseHeader);
    print(saaj.getOwnerDocument());
    return newEncData;
}