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.ofbiz.webtools.labelmanager.SaveLabelsToXmlFile.java

public static Map<String, Object> saveLabelsToXmlFile(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Locale locale = (Locale) context.get("locale");
    String fileName = (String) context.get("fileName");
    if (UtilValidate.isEmpty(fileName)) {
        Debug.logError("labelFileName cannot be empty", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }//from  w w w  .ja va 2s  .c o m
    String key = (String) context.get("key");
    String keyComment = (String) context.get("keyComment");
    String update_label = (String) context.get("update_label");
    String confirm = (String) context.get("confirm");
    String removeLabel = (String) context.get("removeLabel");
    List<String> localeNames = UtilGenerics.cast(context.get("localeNames"));
    List<String> localeValues = UtilGenerics.cast(context.get("localeValues"));
    List<String> localeComments = UtilGenerics.cast(context.get("localeComments"));
    String apacheLicenseText = null;
    try {
        apacheLicenseText = FileUtil.readString("UTF-8",
                FileUtil.getFile("component://webtools/config/APACHE2_HEADER_FOR_XML"));
    } catch (IOException e) {
        Debug.logWarning(e, "Unable to read Apache License text file", module);
    }
    try {
        LabelManagerFactory factory = LabelManagerFactory.getInstance();
        LabelFile labelFile = factory.getLabelFile(fileName);
        if (labelFile == null) {
            Debug.logError("Invalid file name: " + fileName, module);
            return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                    "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
        }
        synchronized (SaveLabelsToXmlFile.class) {
            factory.findMatchingLabels(null, fileName, null, null, false);
            Map<String, LabelInfo> labels = factory.getLabels();
            Set<String> labelsList = factory.getLabelsList();
            Set<String> localesFound = factory.getLocalesFound();
            for (String localeName : localeNames) {
                localesFound.add(localeName);
            }
            // Remove a Label
            if (UtilValidate.isNotEmpty(removeLabel)) {
                labels.remove(key + LabelManagerFactory.keySeparator + fileName);
            } else if (UtilValidate.isNotEmpty(confirm)) {
                LabelInfo label = labels.get(key + LabelManagerFactory.keySeparator + fileName);
                // Update a Label
                if (update_label.equalsIgnoreCase("Y")) {
                    if (UtilValidate.isNotEmpty(label)) {
                        factory.updateLabelValue(localeNames, localeValues, localeComments, label, key,
                                keyComment, fileName);
                    }
                    // Insert a new Label
                } else {
                    if (UtilValidate.isNotEmpty(label)) {
                        return ServiceUtil.returnError(
                                UtilProperties.getMessage(resource, "WebtoolsLabelManagerNewLabelExisting",
                                        UtilMisc.toMap("key", key, "fileName", fileName), locale));
                    } else {
                        if (UtilValidate.isEmpty(key)) {
                            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                    "WebtoolsLabelManagerNewLabelEmptyKey", locale));
                        } else {
                            int notEmptyLabels = factory.updateLabelValue(localeNames, localeValues,
                                    localeComments, null, key, keyComment, fileName);
                            if (notEmptyLabels == 0) {
                                return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                                        "WebtoolsLabelManagerNewLabelEmpty", locale));
                            }
                        }
                    }
                }
            }
            Document resourceDocument = UtilXml.makeEmptyXmlDocument("resource");
            Element resourceElem = resourceDocument.getDocumentElement();
            resourceElem.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
            resourceElem.setAttribute("xsi:noNamespaceSchemaLocation",
                    "http://ofbiz.apache.org/dtds/ofbiz-properties.xsd");
            for (String labelKey : labelsList) {
                LabelInfo labelInfo = labels.get(labelKey);
                if (!(labelInfo.getFileName().equalsIgnoreCase(fileName))) {
                    continue;
                }
                Element propertyElem = UtilXml.addChildElement(resourceElem, "property", resourceDocument);
                propertyElem.setAttribute("key", StringEscapeUtils.unescapeHtml(labelInfo.getLabelKey()));
                if (UtilValidate.isNotEmpty(labelInfo.getLabelKeyComment())) {
                    Comment labelKeyComment = resourceDocument
                            .createComment(StringEscapeUtils.unescapeHtml(labelInfo.getLabelKeyComment()));
                    Node parent = propertyElem.getParentNode();
                    parent.insertBefore(labelKeyComment, propertyElem);
                }
                for (String localeFound : localesFound) {
                    LabelValue labelValue = labelInfo.getLabelValue(localeFound);
                    String valueString = null;
                    if (labelValue != null) {
                        valueString = labelValue.getLabelValue();
                    }
                    if (UtilValidate.isNotEmpty(valueString)) {
                        valueString = StringEscapeUtils.unescapeHtml(valueString);
                        Element valueElem = UtilXml.addChildElementValue(propertyElem, "value", valueString,
                                resourceDocument);
                        valueElem.setAttribute("xml:lang", localeFound);
                        if (UtilValidate.isNotEmpty(labelValue.getLabelComment())) {
                            Comment labelComment = resourceDocument.createComment(
                                    StringEscapeUtils.unescapeHtml(labelValue.getLabelComment()));
                            Node parent = valueElem.getParentNode();
                            parent.insertBefore(labelComment, valueElem);
                        }
                    }
                }
                FileOutputStream fos = new FileOutputStream(labelFile.file);
                try {
                    if (apacheLicenseText != null) {
                        fos.write(apacheLicenseText.getBytes());
                    }
                    UtilXml.writeXmlDocument(resourceElem, fos, "UTF-8", !(apacheLicenseText == null), true, 4);
                } finally {
                    fos.close();
                    // clear cache to see immediately the new labels and
                    // translations in OFBiz
                    UtilCache.clearCache("properties.UtilPropertiesBundleCache");
                }
            }
        }
    } catch (Exception e) {
        Debug.logError(e, "Exception during save labels to xml file:", module);
        return ServiceUtil.returnFailure(UtilProperties.getMessage(resource,
                "saveLabelsToXmlFile.exceptionDuringSaveLabelsToXmlFile", locale));
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.openejb.server.axis.assembler.CommonsSchemaInfoBuilder.java

private static String getNamespaceForPrefix(String prefix, Element element) {
    NamedNodeMap attributes = element.getAttributes();
    for (int i = 0; i < attributes.getLength(); i++) {
        Node node = attributes.item(i);
        if (node instanceof Attr) {
            Attr attr = (Attr) node;
            if (XML_NS_NS.equals(attr.getNamespaceURI())) {
                // this is a namespace declaration, is it the one we are looking for?
                if (attr.getLocalName().equals(prefix)) {
                    return attr.getValue();
                }//from  w w  w  . j  av a  2s  .  c om
            }
        }
    }

    // try parent
    if (element.getParentNode() instanceof Element) {
        return getNamespaceForPrefix(prefix, (Element) element.getParentNode());
    }

    // didn't find it - just use prefix as the namespace
    return prefix;
}

From source file:org.apache.rahas.test.util.TestUtil.java

/**
 * TODO we need to move these common code to a new module. Otherwise code will be duplicated.
 * We cannot use following method from rampart-core as it creates a cyclic dependency. Therefore we have
 * to live with following.//ww  w  . java 2s .  c  o  m
* Creates a DOM Document using the SOAP Envelope.
* @param env An org.apache.axiom.soap.SOAPEnvelope instance
* @return Returns the DOM Document of the given SOAP Envelope.
* @throws Exception If an error occurred during conversion.
*/
public static Document getDocumentFromSOAPEnvelope(SOAPEnvelope env, boolean useDoom)
        throws WSSecurityException {
    try {
        if (env instanceof Element) {
            Element element = (Element) env;
            Document document = element.getOwnerDocument();
            // For outgoing messages, Axis2 only creates the SOAPEnvelope, but no document. If
            // the Axiom implementation also supports DOM, then the envelope (seen as a DOM
            // element) will have an owner document, but the document and the envelope have no
            // parent-child relationship. On the other hand, the input expected by WSS4J is
            // a document with the envelope as document element. Therefore we need to set the
            // envelope as document element on the owner document.
            if (element.getParentNode() != document) {
                document.appendChild(element);
            }
            // If the Axiom implementation supports DOM, then it is possible/likely that the
            // DOM API was used to create the object model (or parts of it). In this case, the
            // object model is not necessarily well formed with respect to namespaces because
            // DOM doesn't generate namespace declarations automatically. This is an issue
            // because WSS4J/Santuario expects that all namespace declarations are present.
            // If this is not the case, then signature values or encryptions will be incorrect.
            // To avoid this, we normalize the document. Note that if we disable the other
            // normalizations supported by DOM, this is generally not a heavy operation.
            // In particular, the Axiom implementation is not required to expand the object
            // model (including OMSourcedElements) because the Axiom builder is required to
            // perform namespace repairing, so that no modifications to unexpanded parts of
            // the message are required.
            DOMConfiguration domConfig = document.getDomConfig();
            domConfig.setParameter("split-cdata-sections", Boolean.FALSE);
            domConfig.setParameter("well-formed", Boolean.FALSE);
            domConfig.setParameter("namespaces", Boolean.TRUE);
            document.normalizeDocument();
            return document;
        }

        if (useDoom) {
            env.build();

            // Workaround to prevent a bug in AXIOM where
            // there can be an incomplete OMElement as the first child body
            OMElement firstElement = env.getBody().getFirstElement();
            if (firstElement != null) {
                firstElement.build();
            }

            //Get processed headers
            SOAPHeader soapHeader = env.getHeader();
            ArrayList processedHeaderQNames = new ArrayList();
            if (soapHeader != null) {
                Iterator headerBlocs = soapHeader.getChildElements();
                while (headerBlocs.hasNext()) {
                    SOAPHeaderBlock element = (SOAPHeaderBlock) headerBlocs.next();
                    if (element.isProcessed()) {
                        processedHeaderQNames.add(element.getQName());
                    }
                }
            }

            SOAPModelBuilder stAXSOAPModelBuilder = OMXMLBuilderFactory.createStAXSOAPModelBuilder(
                    OMAbstractFactory.getMetaFactory(OMAbstractFactory.FEATURE_DOM), env.getXMLStreamReader());
            SOAPEnvelope envelope = (stAXSOAPModelBuilder).getSOAPEnvelope();
            envelope.getParent().build();

            //Set the processed flag of the processed headers
            SOAPHeader header = envelope.getHeader();
            for (Iterator iter = processedHeaderQNames.iterator(); iter.hasNext();) {
                QName name = (QName) iter.next();
                Iterator omKids = header.getChildrenWithName(name);
                if (omKids.hasNext()) {
                    ((SOAPHeaderBlock) omKids.next()).setProcessed();
                }
            }

            Element envElem = (Element) envelope;
            return envElem.getOwnerDocument();
        } else {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            env.build();
            env.serialize(baos);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            factory.setNamespaceAware(true);
            return factory.newDocumentBuilder().parse(bais);
        }
    } catch (Exception e) {
        throw new WSSecurityException("Error in converting SOAP Envelope to Document", e);
    }
}

From source file:org.apache.rampart.util.RampartUtil.java

public static Element insertSiblingAfter(RampartMessageData rmd, Element child, Element sibling) {
    if (child == null) {
        return appendChildToSecHeader(rmd, sibling);
    } else {/*from   w  ww  . jav a2  s.com*/
        if (child.getOwnerDocument().equals(sibling.getOwnerDocument())) {

            if (child.getParentNode() == null && !child.getLocalName().equals("UsernameToken")) {
                rmd.getSecHeader().getSecurityHeader().appendChild(child);
            }
            ((OMElement) child).insertSiblingAfter((OMElement) sibling);
            return sibling;
        } else {
            Element newSib = (Element) child.getOwnerDocument().importNode(sibling, true);
            ((OMElement) child).insertSiblingAfter((OMElement) newSib);
            return newSib;
        }
    }
}

From source file:org.apache.rampart.util.RampartUtil.java

public static void handleEncryptedSignedHeaders(Vector encryptedParts, Vector signedParts, Document doc) {

    //TODO Is there a more efficient  way to do this ? better search algorithm 
    for (int i = 0; i < signedParts.size(); i++) {
        WSEncryptionPart signedPart = (WSEncryptionPart) signedParts.get(i);

        //This signed part is not a header
        if (signedPart.getNamespace() == null || signedPart.getName() == null) {
            continue;
        }//from  w w w  .j  a  v  a  2 s .  c o m

        for (int j = 0; j < encryptedParts.size(); j++) {
            WSEncryptionPart encryptedPart = (WSEncryptionPart) encryptedParts.get(j);

            if (encryptedPart.getNamespace() == null || encryptedPart.getName() == null) {
                continue;
            }

            if (signedPart.getName().equals(encryptedPart.getName())
                    && signedPart.getNamespace().equals(encryptedPart.getNamespace())) {

                String encDataID = encryptedPart.getEncId();
                Element encDataElem = WSSecurityUtil.findElementById(doc.getDocumentElement(), encDataID, null);

                if (encDataElem != null) {
                    Element encHeader = (Element) encDataElem.getParentNode();
                    String encHeaderId = encHeader.getAttributeNS(WSConstants.WSU_NS, "Id");

                    //For some reason the id might not be available
                    // so the part/element with empty/null id won't be recognized afterwards. 
                    if (encHeaderId != null && !"".equals(encHeaderId.trim())) {
                        signedParts.remove(signedPart);
                        WSEncryptionPart encHeaderToSign = new WSEncryptionPart(encHeaderId);
                        signedParts.add(encHeaderToSign);
                    }

                }
            }
        }

    }

}

From source file:org.apache.servicemix.jbi.deployer.descriptor.DescriptorFactory.java

/**
 * Recursive method to find a given attribute value
 */// w  w w. j a v  a2s  . c  o  m
public static String recursiveGetAttributeValue(Element element, String attributeName) {
    String answer = null;
    try {
        answer = element.getAttribute(attributeName);
    } catch (Exception e) {
        //if (log.isTraceEnabled()) {
        //    log.trace("Caught exception looking up attribute: " + attributeName + " on element: " + element + ". Cause: " + e, e);
        //}
    }
    if (answer == null || answer.length() == 0) {
        Node parentNode = element.getParentNode();
        if (parentNode instanceof Element) {
            return recursiveGetAttributeValue((Element) parentNode, attributeName);
        }
    }
    return answer;
}

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

/**
 * Recursive method to find a given attribute value
 *//*w  w w .  ja  v a 2s  .c  o  m*/
public static String recursiveGetAttributeValue(Element element, String attributeName) {
    String answer = null;
    try {
        answer = element.getAttribute(attributeName);
    } catch (Exception e) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Caught exception looking up attribute: " + attributeName + " on element: " + element
                    + ". Cause: " + e, e);
        }
    }
    if (answer == null || answer.length() == 0) {
        Node parentNode = element.getParentNode();
        if (parentNode instanceof Element) {
            return recursiveGetAttributeValue((Element) parentNode, attributeName);
        }
    }
    return answer;
}

From source file:org.apache.shindig.gadgets.parse.caja.CajaCssSanitizer.java

/**
 * Sanitize the CSS content of a style tag.
 * @param styleElem to sanitize//from  w  w  w . j  av a 2 s.  c o  m
 * @param linkContext url of containing content
 * @param gadgetContext The gadget context.
 * @param importRewriter to rewrite @imports to sanitizing proxy
 * @param imageRewriter to rewrite images to sanitizing proxy
 */
public void sanitize(Element styleElem, Uri linkContext, GadgetContext gadgetContext,
        ProxyUriManager importRewriter, ProxyUriManager imageRewriter) {
    String content = null;
    try {
        CssTree.StyleSheet stylesheet = parser.parseDom(styleElem.getTextContent(), linkContext);
        sanitize(stylesheet, linkContext, gadgetContext, importRewriter, imageRewriter);
        // Write the rewritten CSS back into the element
        content = parser.serialize(stylesheet);
    } catch (GadgetException ge) {
        // Failed to parse stylesheet so log and continue
        LOG.log(Level.INFO, "Failed to parse stylesheet", ge);
    }
    if (StringUtils.isEmpty(content)) {
        // Remove the owning node
        styleElem.getParentNode().removeChild(styleElem);
    } else {
        styleElem.setTextContent(content);
    }
}

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

/**
 * For css:/*w  w  w .  ja  v a2  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.CssRequestRewriter.java

/**
 * Rewrite the CSS content in a style DOM node.
 * @param styleNode Rewrite the CSS content of this node
 * @param source Uri of content//  w w w . j a  va  2s . c o  m
 * @param rewriter Rewrite urls
 * @param extractImports If true remove the import statements from the output and return their
 *            referenced URIs.
 * @return Empty list of extracted import URIs.
 */
public List<String> rewrite(Element styleNode, Uri source, LinkRewriter rewriter, boolean extractImports) {
    try {
        List<Object> stylesheet = cssParser.parse(styleNode.getTextContent());
        List<String> imports = rewrite(stylesheet, source, rewriter, extractImports);
        // 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) {
            logger.log(Level.WARNING,
                    "Caja CSS parse failure: " + ge.getCause().getMessage() + " for " + source);
            return Collections.emptyList();
        } else {
            throw new RuntimeException(ge);
        }
    }
}