Example usage for org.w3c.dom Element getParentNode

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

Introduction

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

Prototype

public Node getParentNode();

Source Link

Document

The parent of this node.

Usage

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

/**
 * Rewrite the CSS content in a style DOM node.
 * @param styleNode Rewrite the CSS content of this node
 * @param source Uri of content/*from   w  ww .j a v  a  2 s.c o m*/
 * @param uriMaker a UriMaker
 * @param extractImports If true remove the import statements from the output and return their
 *            referenced URIs.
 * @param gadgetContext The gadgetContext
 * @return Empty list of extracted import URIs.
 */
public List<String> rewrite(Element styleNode, Uri source, UriMaker uriMaker, boolean extractImports,
        GadgetContext gadgetContext) throws RewritingException {
    try {
        CssTree.StyleSheet stylesheet = cssParser.parseDom(styleNode.getTextContent(), source);
        List<String> imports = rewrite(stylesheet, source, uriMaker, extractImports, gadgetContext);
        // Write the rewritten CSS back into the element
        String content = cssParser.serialize(stylesheet);
        if (StringUtils.isEmpty(content) || StringUtils.isWhitespace(content)) {
            // Remove the owning node
            styleNode.getParentNode().removeChild(styleNode);
        } else {
            styleNode.setTextContent(content);
        }
        return imports;
    } catch (GadgetException ge) {
        if (ge.getCause() instanceof ParseException) {
            LOG.log(Level.WARNING, "Caja CSS parse failure: " + ge.getCause().getMessage() + " for " + source);
            return Collections.emptyList();
        } else {
            throw new RewritingException(ge, ge.getHttpStatusCode());
        }
    }
}

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

/**
 * Post-processes the gadget content after rendering templates.
 * /* ww w .j  a va 2s. c o m*/
 * @param templateContext TemplateContext to operate on
 * @param needsFeature Should the templates feature be made available to 
 * client?
 * @param head Head element of the gadget's document
 * @param libraries Keeps track of all libraries, and which got used
 * @param allTemplates A list of all the template nodes
 * @param libraries A list of all registered libraries
 */
private void postProcess(TemplateContext templateContext, boolean needsFeature, Element head,
        List<Element> allTemplates, List<TemplateLibrary> libraries) {
    // Inject all the needed library assets.
    // TODO: inject library assets that aren't used on the server, but will
    // be needed on the client
    for (TemplateResource resource : templateContext.getResources()) {
        injectTemplateLibraryAssets(resource, head);
    }

    // If we don't need the feature, remove it and all templates from the gadget
    if (!needsFeature) {
        templateContext.getGadget().removeFeature(TEMPLATES_FEATURE_NAME);
        for (Element template : allTemplates) {
            Node parent = template.getParentNode();
            if (parent != null) {
                parent.removeChild(template);
            }
        }
    } else {
        // If the feature is to be kept, inject the libraries.
        // Library assets will be generated on the client.
        // TODO: only inject the templates, not the full scripts/styles
        for (TemplateLibrary library : libraries) {
            injectTemplateLibrary(library, head);
        }
    }
}

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?
 */// w  w  w  . ja  v a 2s .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.ItsImportServlet.java

/**
 * Store the element and its attribute. The child node of global rules are
 * specially handled so they will not be traversed.
 *
 * @param path//from   w  ww.  j a  v a2  s . c o  m
 *         the target path
 * @param resourceType
 *         the resourceType
 * @param doc
 *         the document
 * @param file
 *        the file.
 * @param isExternalDoc
 *         true if this is for storing global rules for external documents
 */
private void store(String path, final String resourceType, final Document doc, final File file,
        final boolean isExternalDoc) {
    final ITraversal itsEng = applyITSRules(doc, file, null, false);
    itsEng.startTraversal();
    Node node;
    while ((node = itsEng.nextNode()) != null) {
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            final Element element = (Element) node;
            // Use !backTracking() to get to the elements only once
            // and to include the empty elements (for attributes).
            if (itsEng.backTracking()) {
                if (!SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) {
                    path = backTrack(path);
                }
            } else {
                if (element.isSameNode(doc.getDocumentElement()) && !isExternalDoc) {
                    path += "/" + element.getNodeName();
                    output(path, null, null);
                    setAttributes(element, path);
                } else if (SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())) {
                    storeGlobalRule(element, resourceType, itsEng);
                } else if (!isExternalDoc
                        && !SlingItsConstants.getGlobalRules().containsKey(element.getLocalName())
                        && !(element.getParentNode().getLocalName().equals(SlingItsConstants.ITS_RULES)
                                && element.getParentNode().getPrefix() != null)) {
                    if (element.getLocalName().equals(SlingItsConstants.ITS_RULES)
                            && element.getPrefix() != null) {
                        this.hasGlobalRules = true;
                    }
                    if (element.getPrefix() != null) {
                        path += String.format("/%s(%d)", element.getLocalName(),
                                getCounter(path + "/" + element.getLocalName()));
                        element.setAttribute(SlingItsConstants.NODE_PREFIX, element.getPrefix());
                    } else if (element.getNodeName().equals("link")
                            && StringUtils.endsWith(element.getAttribute("rel"), "-rules")) {
                        path += String.format("/%s(%d)", SlingItsConstants.ITS_RULES,
                                getCounter(path + "/" + SlingItsConstants.ITS_RULES));
                        final String prefix = StringUtils.substringBefore(element.getAttribute("rel"),
                                "-rules");
                        element.setAttribute(SlingItsConstants.NODE_PREFIX, prefix);
                        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI,
                                SlingItsConstants.XMLNS + prefix, Namespaces.ITS_NS_URI);
                        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:h",
                                Namespaces.HTML_NS_URI);
                        element.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:jcr",
                                NamespaceRegistry.NAMESPACE_JCR);
                        this.hasGlobalRules = true;
                    } else {
                        path += String.format("/%s(%d)", element.getNodeName(),
                                getCounter(path + "/" + element.getNodeName()));
                    }
                    output(path, null, null);
                    setAttributes(element, path);
                    if (!element.hasChildNodes()) // Empty elements:
                    {
                        path = backTrack(path);
                    }
                }
            }
            break;
        case Node.TEXT_NODE:
            if (StringUtils.isNotBlank(node.getNodeValue()) && !isExternalDoc) {
                path += String.format("/%s(%d)", SlingItsConstants.TEXT_CONTENT_NODE,
                        getCounter(path + "/" + SlingItsConstants.TEXT_CONTENT_NODE));
                output(path, null, node.getNodeValue());
                path = backTrack(path);
            }
            break;
        default:
            break;
        }
    }
}

From source file:org.apache.sling.stanbol.ui.StanbolResourceViewer.java

private void setContent(Node jcrNode, String newContent) throws IOException, RepositoryException {

    try {// ww  w .j a  va  2 s.c  om
        Document doc = Utils.getXMLDocument(jcrNode);
        Element docElem = doc.getDocumentElement();
        if (docElem.getNodeName().equalsIgnoreCase("html")) {
            Element newBody = parseBody(newContent);
            Element body = (Element) doc.getElementsByTagName("body").item(0);
            org.w3c.dom.Node importedNewBody = doc.importNode(newBody, true);
            body.getParentNode().replaceChild(importedNewBody, body);
        } else {
            InputSource inputSource = new InputSource(new StringReader(newContent));
            Document newContentDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                    .parse(inputSource);
            docElem = newContentDoc.getDocumentElement();
        }
        DOMSource domSource = new DOMSource(docElem);
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        //StringWriter out = new StringWriter();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(baos);
        transformer.transform(domSource, streamResult);
        //jcrNode.setProperty("jcr:content/jcr:data", out.toString());
        jcrNode.getProperty("jcr:content/jcr:data").setValue(new String(baos.toByteArray(), "utf-8"));
        jcrNode.save();
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerConfigurationException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Insert an initializer which supplies the value of an SCA property as specified by the
 * SCA Component using the BPEL process//from www  .  j a va 2  s  .  co  m
 * @param bpelDOM - a DOM model representation of the BPEL process
 * @param property - an SCA ComponentProperty element for the property
 * This DOM model is updated, with an initializer being added for the BPEL variable
 * corresponding to the SCA property
 */
private void insertSCAPropertyInitializer(Document bpelDOM, ComponentProperty property) {
    // Only insert a Property initializer where there is a value for the Property
    if (property.getValue() == null)
        return;

    Element insertionElement = findInitializerInsertionPoint(bpelDOM);
    if (insertionElement == null)
        return;

    Element initializer = getInitializerSequence(bpelDOM, property);
    if (initializer == null)
        return;

    // Insert the initializer sequence as the next sibling element of the insertion point
    Element parent = (Element) insertionElement.getParentNode();
    // Get the next sibling element, if there is one
    Node sibling = insertionElement.getNextSibling();
    while (sibling != null && sibling.getNodeType() != Node.ELEMENT_NODE) {
        sibling = sibling.getNextSibling();
    } // end while
      // Either insert at the end or before the next element
    if (sibling == null) {
        parent.appendChild(initializer);
    } else {
        parent.insertBefore(initializer, sibling);
    } // end if

}

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

public static Element duplicateEncryptedDataInWsseHeader(Element saaj, boolean moveReferenceList) {
    if (moveReferenceList) {
        moveReferenceList(saaj);/* w  ww .j a  v  a2s. co m*/
    }
    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;
}

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

public static Element duplicateEncryptedDataInWsseWrapperHeader(Element saaj, boolean moveReferenceList) {
    if (moveReferenceList) {
        moveReferenceList(saaj);//from  w  w w. j  a v a2s.co m
    }
    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 signature = getFirstChildElement(sh, new QName("http://www.w3.org/2000/09/xmldsig#", "Signature"),
            true);

    Node wsseHeader = signature.getParentNode();
    Node newWsseHeader = wsseHeader.cloneNode(false);
    Node cur = wsseHeader.getFirstChild();
    String newId = newEncData.getAttributeNS(null, "Id");
    while (!cur.isSameNode(signature)) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }
    Element wrapper = encData.getOwnerDocument().createElementNS(null, "a");
    wrapper.appendChild(newEncData);
    newWsseHeader.appendChild(wrapper);
    while (cur != null) {
        cur = copyHeadersAndUpdateRefList(cur, newWsseHeader, newId);
    }

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

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

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

public static Element addEncryptedDataWithEmbeddedEncryptedKeyInWsseHeader(Element saaj) {
    moveReferenceList(saaj);/*from  w w  w . j ava2s .  c  o  m*/
    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 = (Element) encData.cloneNode(true);
    String newId = newEncData.getAttributeNS(null, "Id") + "b";
    newEncData.setAttributeNS(null, "Id", newId);

    Element encKey = getFirstChildElement(saaj, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"),
            true);
    Element newEncKey = (Element) encKey.cloneNode(true);
    String newEcId = newEncKey.getAttributeNS(null, "Id") + "b";
    newEncKey.setAttributeNS(null, "Id", newEcId);

    Element keyInfo = getFirstChildElement(newEncData,
            new QName("http://www.w3.org/2000/09/xmldsig#", "KeyInfo"), true);
    Element str = getFirstChildElement(newEncData,
            new QName("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                    "SecurityTokenReference"),
            true);
    keyInfo.replaceChild(newEncKey, str);

    Element wsseHeader = getFirstChildElement(saaj,
            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();

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

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

}

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

private static void moveReferenceList(Element saaj) {
    Element sh = getFirstChildElement(saaj, new QName("http://schemas.xmlsoap.org/soap/envelope/", "Header"),
            true);/*from www .j  av a 2 s .  co  m*/
    Element encKey = getFirstChildElement(sh, new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedKey"),
            true);
    Element refList = getFirstChildElement(encKey,
            new QName("http://www.w3.org/2001/04/xmlenc#", "ReferenceList"), true);

    Node wsseHeader = encKey.getParentNode();
    encKey.removeChild(refList);
    wsseHeader.appendChild(refList);
}