Example usage for org.dom4j Element remove

List of usage examples for org.dom4j Element remove

Introduction

In this page you can find the example usage for org.dom4j Element remove.

Prototype

boolean remove(Text text);

Source Link

Document

Removes the given Text if the node is an immediate child of this element.

Usage

From source file:org.openxml4j.opc.signature.RelationshipTransform.java

License:Apache License

@SuppressWarnings("unchecked")
public static void RemoveAllNameSpacesExceptRelationship(Element elem) {

    // if the default namespace is not correct or if it has a prefix
    // fix it by setting to correct value without prefix
    if (elem.getNamespace().getStringValue() != PackageNamespaces.RELATIONSHIPS
            || elem.getNamespace().getPrefix() != "") {
        elem.setQName(new QName(elem.getName(),
                DocumentFactory.getInstance().createNamespace("", PackageNamespaces.RELATIONSHIPS)));
    }//ww w  .  ja v a 2 s.  com

    // remove all additional namespace declarations
    List<Namespace> additionalNameSpaces = elem.additionalNamespaces();
    for (Namespace nms : additionalNameSpaces) {
        elem.remove(nms);
    }
}

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

License:Open Source License

private void prune(Element element) {
    Attribute attribute = element.attribute(MARK_ATTRIBUTE);
    if (attribute == null) {
        element.detach();/*  ww w . j  av a  2  s  .  co m*/
    } else {
        element.remove(attribute);
        final List<Element> elementsToRemove = new ArrayList<Element>();
        for (Iterator i = element.elementIterator(); i.hasNext();) {
            final Element e = (Element) i.next();
            attribute = e.attribute(MARK_ATTRIBUTE);
            if (attribute == null)
                elementsToRemove.add(e);
            else
                prune(e);
        }
        for (final Element elementToRemove : elementsToRemove)
            elementToRemove.detach();
    }
}

From source file:org.orbeon.oxf.processor.sql.SQLProcessor.java

License:Open Source License

protected void execute(final PipelineContext context, XMLReceiver xmlReceiver) {
    try {/* ww w . j  a  va2s .  co m*/
        // Cache, read and interpret the config input
        Config config = readCacheInputAsObject(context, getInputByName(INPUT_CONFIG),
                new CacheableInputReader<Config>() {
                    public Config read(PipelineContext context, ProcessorInput input) {
                        // Read the config input document
                        Node config = readInputAsDOM4J(context, input);
                        Document configDocument = config.getDocument();

                        // Extract XPath expressions and also check whether any XPath expression is used at all
                        // NOTE: This could be done through streaming below as well
                        // NOTE: For now, just match <sql:param select="/*" type="xs:base64Binary"/>
                        List xpathExpressions = new ArrayList();
                        boolean useXPathExpressions = false;
                        for (Iterator i = XPathUtils.selectIterator(configDocument,
                                "//*[namespace-uri() = '" + SQL_NAMESPACE_URI + "' and @select]"); i
                                        .hasNext();) {
                            Element element = (Element) i.next();
                            useXPathExpressions = true;
                            String typeAttribute = element.attributeValue("type");
                            if ("xs:base64Binary".equals(typeAttribute)) {
                                String selectAttribute = element.attributeValue("select");
                                xpathExpressions.add(selectAttribute);
                            }
                        }

                        // Normalize spaces. What this does is to coalesce adjacent text nodes, and to remove
                        // resulting empty text, unless the text is contained within a sql:text element.
                        configDocument.accept(new VisitorSupport() {
                            private boolean endTextSequence(Element element, Text previousText) {
                                if (previousText != null) {
                                    String value = previousText.getText();
                                    if (value == null || value.trim().equals("")) {
                                        element.remove(previousText);
                                        return true;
                                    }
                                }
                                return false;
                            }

                            @Override
                            public void visit(Element element) {
                                // Don't touch text within sql:text elements
                                if (!SQL_NAMESPACE_URI.equals(element.getNamespaceURI())
                                        || !"text".equals(element.getName())) {
                                    Text previousText = null;
                                    for (int i = 0, size = element.nodeCount(); i < size;) {
                                        Node node = element.node(i);
                                        if (node instanceof Text) {
                                            Text text = (Text) node;
                                            if (previousText != null) {
                                                previousText.appendText(text.getText());
                                                element.remove(text);
                                            } else {
                                                String value = text.getText();
                                                // Remove empty text nodes
                                                if (value == null || value.length() < 1) {
                                                    element.remove(text);
                                                } else {
                                                    previousText = text;
                                                    i++;
                                                }
                                            }
                                        } else {
                                            if (!endTextSequence(element, previousText))
                                                i++;
                                            previousText = null;
                                        }
                                    }
                                    endTextSequence(element, previousText);
                                }
                            }
                        });
                        // Create SAXStore
                        try {
                            final SAXStore store = new SAXStore();
                            final LocationSAXWriter locationSAXWriter = new LocationSAXWriter();
                            locationSAXWriter.setContentHandler(store);
                            locationSAXWriter.write(configDocument);
                            // Return the normalized document
                            return new Config(store, useXPathExpressions, xpathExpressions);
                        } catch (SAXException e) {
                            throw new OXFException(e);
                        }
                    }
                });

        // Either read the whole input as a DOM, or try to serialize
        Node data = null;
        XPathXMLReceiver xpathReceiver = null;

        // Check if the data input is connected
        boolean hasDataInput = getConnectedInputs().get(INPUT_DATA) != null;
        if (!hasDataInput && config.useXPathExpressions)
            throw new OXFException(
                    "The data input must be connected when the configuration uses XPath expressions.");
        if (!hasDataInput || !config.useXPathExpressions) {
            // Just use an empty document
            data = Dom4jUtils.NULL_DOCUMENT;
        } else {
            // There is a data input connected and there are some XPath expressions operating on it
            boolean useXPathContentHandler = false;
            if (config.xpathExpressions.size() > 0) {
                // Create XPath content handler
                final XPathXMLReceiver _xpathReceiver = new XPathXMLReceiver();
                // Add expressions and check whether we can try to stream
                useXPathContentHandler = true;
                for (Iterator i = config.xpathExpressions.iterator(); i.hasNext();) {
                    String expression = (String) i.next();
                    boolean canStream = _xpathReceiver.addExpresssion(expression, false);// FIXME: boolean nodeSet
                    if (!canStream) {
                        useXPathContentHandler = false;
                        break;
                    }
                }
                // Finish setting up the XPathContentHandler
                if (useXPathContentHandler) {
                    _xpathReceiver.setReadInputCallback(new Runnable() {
                        public void run() {
                            readInputAsSAX(context, INPUT_DATA, _xpathReceiver);
                        }
                    });
                    xpathReceiver = _xpathReceiver;
                }
            }
            // If we can't stream, read everything in
            if (!useXPathContentHandler)
                data = readInputAsDOM4J(context, INPUT_DATA);
        }

        // Try to read datasource input if any
        Datasource datasource = null;
        {
            List datasourceInputs = (List) getConnectedInputs().get(INPUT_DATASOURCE);
            if (datasourceInputs != null) {
                if (datasourceInputs.size() > 1)
                    throw new OXFException("At most one one datasource input can be connected.");
                ProcessorInput datasourceInput = (ProcessorInput) datasourceInputs.get(0);
                datasource = Datasource.getDatasource(context, this, datasourceInput);
            }
        }

        // Replay the config SAX store through the interpreter
        config.configInput.replay(
                new RootInterpreter(context, getPropertySet(), data, datasource, xpathReceiver, xmlReceiver));
    } catch (OXFException e) {
        throw e;
    } catch (Exception e) {
        throw new OXFException(e);
    }
}

From source file:org.orbeon.oxf.xforms.action.actions.XFormsInsertAction.java

License:Open Source License

private static List<Node> doInsert(Node insertionNode, List<Node> clonedNodes, XFormsInstance modifiedInstance,
        boolean doDispatch) {
    final List<Node> insertedNodes = new ArrayList<Node>(clonedNodes.size());
    if (insertionNode instanceof Element) {
        // Insert inside an element
        final Element insertContextElement = (Element) insertionNode;

        int otherNodeIndex = 0;
        for (Node clonedNode : clonedNodes) {

            if (clonedNode != null) {// NOTE: we allow passing some null nodes so we check on null
                if (clonedNode instanceof Attribute) {
                    // Add attribute to element

                    // NOTE: In XML, attributes are unordered. dom4j handles them as a list so has order, but the
                    // XForms spec shouldn't rely on attribute order. We could try to keep the order, but it is harder
                    // as we have to deal with removing duplicate attributes and find a reasonable insertion strategy.
                    final Attribute clonedAttribute = (Attribute) clonedNode;
                    final Attribute existingAttribute = insertContextElement
                            .attribute(clonedAttribute.getQName());

                    if (existingAttribute != null)
                        insertContextElement.remove(existingAttribute);

                    insertContextElement.add(clonedAttribute);

                    if (existingAttribute != null) {

                        // Dispatch xxforms-replace event if required and possible
                        // NOTE: For now, still dispatch xforms-insert for backward compatibility.
                        if (doDispatch && modifiedInstance != null) {
                            final DocumentWrapper documentWrapper = (DocumentWrapper) modifiedInstance
                                    .documentInfo();

                            Dispatch.dispatchEvent(new XXFormsReplaceEvent(modifiedInstance,
                                    documentWrapper.wrap(existingAttribute),
                                    documentWrapper.wrap(clonedAttribute)));
                        }//w  w w  .ja  va 2  s  .co m
                    }

                    insertedNodes.add(clonedAttribute);

                } else if (!(clonedNode instanceof Document)) {
                    // Add other node to element
                    Dom4jUtils.content(insertContextElement).add(otherNodeIndex++, clonedNode);
                    insertedNodes.add(clonedNode);
                } else {
                    // "If a cloned node cannot be placed at the target location due to a node type conflict, then the
                    // insertion for that particular clone node is ignored."
                }
            }
        }
        return insertedNodes;
    } else if (insertionNode instanceof Document) {
        final Document insertContextDocument = (Document) insertionNode;

        // "If there is more than one cloned node to insert, only the first node that does not cause a conflict is
        // considered."
        for (Node clonedNode : clonedNodes) {
            // Only an element can be inserted at the root of an instance
            if (clonedNode instanceof Element) {

                final Element formerRootElement = insertContextDocument.getRootElement();
                insertContextDocument.setRootElement((Element) clonedNode);

                // Dispatch xxforms-replace event if required and possible
                // NOTE: For now, still dispatch xforms-insert for backward compatibility.
                if (doDispatch && modifiedInstance != null) {
                    final DocumentWrapper documentWrapper = (DocumentWrapper) modifiedInstance.documentInfo();

                    Dispatch.dispatchEvent(
                            new XXFormsReplaceEvent(modifiedInstance, documentWrapper.wrap(formerRootElement),
                                    documentWrapper.wrap(insertContextDocument.getRootElement())));
                }

                insertedNodes.add(clonedNode);
                return insertedNodes;
            }
        }

        // NOTE: The spec does not allow inserting comments and PIs at the root of an instance document at this
        // point.

        return insertedNodes;
    } else {
        throw new OXFException("Unsupported insertion node type: " + insertionNode.getClass().getName());
    }
}

From source file:org.pentaho.jfreereport.wizard.utility.report.ReportGenerationUtility.java

License:Open Source License

/**
 * NOTE: the templateDoc is the target of the merge.
 * /*w w  w . ja va2 s .  c o m*/
 * @param templateDoc
 * @param generatedDoc
 * @param mergeStream
 */
public static void mergeTemplate(Document templateDoc, Document generatedDoc, OutputStream mergeStream) {
    try {
        // replace parser-config settings in templateDoc from generatedDoc
        Element templateReportNode = ((Element) templateDoc.selectSingleNode("/report")); //$NON-NLS-1$
        Element generatedReportNode = ((Element) generatedDoc.selectSingleNode("/report")); //$NON-NLS-1$
        // move attributes from generated to template
        // blow away existing attributes first
        List templateAttributes = templateReportNode.attributes();
        for (int i = templateAttributes.size() - 1; i >= 0; i--) {
            Attribute attribute = (Attribute) templateAttributes.get(i);
            templateReportNode.remove(attribute);
        }
        // now move generated into template
        List generatedAttributes = generatedReportNode.attributes();
        for (int i = generatedAttributes.size() - 1; i >= 0; i--) {
            Attribute attribute = (Attribute) generatedAttributes.get(i);
            generatedReportNode.remove(attribute);
            templateReportNode.add(attribute);
        }
        List templateParserConfigProps = templateReportNode.selectNodes("parser-config/*"); //$NON-NLS-1$
        List generatedParserConfigProps = generatedReportNode.selectNodes("parser-config/*"); //$NON-NLS-1$
        Element templateParserConfigElement = (Element) templateReportNode.selectSingleNode("parser-config"); //$NON-NLS-1$
        Element generatedParserConfigElement = (Element) generatedReportNode.selectSingleNode("parser-config"); //$NON-NLS-1$
        // replace any empty elements in the generated doc with the corresponding contents of the template doc 
        for (int i = 0; i < generatedParserConfigProps.size(); i++) {
            Element generatedParserConfigProp = (Element) generatedParserConfigProps.get(i);
            Element templateParserConfigProp = (Element) templateParserConfigProps.get(i);

            String generatedText = generatedParserConfigProp.getText();
            if (!StringUtils.isEmpty(generatedText)) {
                generatedParserConfigElement.remove(generatedParserConfigProp);
                templateParserConfigElement.remove(templateParserConfigProp);
                templateParserConfigElement.add(generatedParserConfigProp);
            }
        }

        // replace items section in templateDoc from generatedDoc
        if (templateReportNode.selectSingleNode("items") != null) { //$NON-NLS-1$
            templateReportNode.remove(templateReportNode.selectSingleNode("items")); //$NON-NLS-1$
        }
        Element itemsElement = (Element) generatedReportNode.selectSingleNode("items"); //$NON-NLS-1$
        if (itemsElement != null) {
            generatedReportNode.remove(itemsElement);
            templateReportNode.add(itemsElement);
        }
        // GROUP MERGING
        List groups = templateReportNode.selectNodes("groups/*"); //$NON-NLS-1$
        // if groups has no elements, then we're just going to straight copy
        // the groups from the generated version
        // this is a new requirement per Kurtis Cruzada
        if (ReportSpecUtility.getNumberOfGroupsInTemplate(templateDoc) == 0) {
            // replace groups section in templateDoc from generatedDoc
            if (templateReportNode.selectSingleNode("groups") != null) { //$NON-NLS-1$
                templateReportNode.remove(templateReportNode.selectSingleNode("groups")); //$NON-NLS-1$
            }
            // might not have a top level groups node, add it
            if (generatedReportNode.selectSingleNode("groups") == null) { //$NON-NLS-1$
                generatedReportNode.addElement("groups"); //$NON-NLS-1$
            }
            Element groupElement = (Element) generatedReportNode.selectSingleNode("groups"); //$NON-NLS-1$
            if (groupElement != null) {
                generatedReportNode.remove(groupElement);
                templateReportNode.add(groupElement);
            }
        } else {
            // both sets of groups should be identical in number
            // each group based on index should correspond
            // for all group headers, append new content
            // for all group footers insert new content, push down old
            // both lists must have the same # of groups (this is a
            // requirement)
            List generatedGroups = generatedReportNode.selectNodes("groups/*"); //$NON-NLS-1$
            for (int i = 0; i < groups.size(); i++) {
                Element templateGroup = (Element) groups.get(i);
                for (int j = i + 1; j < generatedGroups.size(); j++) {
                    Element generatedGroup = (Element) generatedGroups.get(j);
                    Element templateGroupHeader = (Element) templateGroup.selectSingleNode("groupheader"); //$NON-NLS-1$
                    Element generatedGroupHeader = (Element) generatedGroup.selectSingleNode("groupheader"); //$NON-NLS-1$
                    Element templateGroupFooter = (Element) templateGroup.selectSingleNode("groupfooter"); //$NON-NLS-1$
                    Element generatedGroupFooter = (Element) generatedGroup.selectSingleNode("groupfooter"); //$NON-NLS-1$
                    try {
                        if (templateGroupHeader.attribute("pagebreak-before-print") != null) { //$NON-NLS-1$
                            templateGroupHeader.attribute("pagebreak-before-print").detach(); //$NON-NLS-1$
                        }
                        templateGroupHeader.addAttribute("pagebreak-before-print", //$NON-NLS-1$
                                (generatedGroupHeader.attributeValue("pagebreak-before-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                    } catch (Exception e) {
                        // e.printStackTrace();
                    }
                    try {
                        if (templateGroupHeader.attribute("pagebreak-after-print") != null) { //$NON-NLS-1$
                            templateGroupHeader.attribute("pagebreak-after-print").detach(); //$NON-NLS-1$
                        }
                        templateGroupHeader.addAttribute("pagebreak-after-print", //$NON-NLS-1$
                                (generatedGroupHeader.attributeValue("pagebreak-after-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                    } catch (Exception e) {
                        // e.printStackTrace();
                    }
                    try {
                        if (templateGroupFooter.attribute("pagebreak-before-print") != null) { //$NON-NLS-1$
                            templateGroupFooter.attribute("pagebreak-before-print").detach(); //$NON-NLS-1$
                        }
                        templateGroupFooter.addAttribute("pagebreak-before-print", //$NON-NLS-1$
                                (generatedGroupFooter.attributeValue("pagebreak-before-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                    } catch (Exception e) {
                        // e.printStackTrace();
                    }
                    try {
                        if (templateGroupFooter.attribute("pagebreak-after-print") != null) { //$NON-NLS-1$
                            templateGroupFooter.attribute("pagebreak-after-print").detach(); //$NON-NLS-1$
                        }
                        templateGroupFooter.addAttribute("pagebreak-after-print", //$NON-NLS-1$
                                (generatedGroupFooter.attributeValue("pagebreak-after-print")) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                    } catch (Exception e) {
                        // e.printStackTrace();
                    }
                    try {
                        if (templateGroupHeader.attribute("repeat") != null) { //$NON-NLS-1$
                            templateGroupHeader.attribute("repeat").detach(); //$NON-NLS-1$
                        }
                        templateGroupHeader.addAttribute("repeat", //$NON-NLS-1$
                                (generatedGroupHeader.attributeValue("repeat")) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                    } catch (Exception e) {
                        // e.printStackTrace();
                    }
                }
            }
            if (groups != null) {
                Element innermostGroup = null;
                int innermostFieldsInGroup = 0;
                for (int i = 0; i < groups.size(); i++) {
                    Element groupElement = (Element) groups.get(i);
                    List fields = groupElement.selectNodes("fields/*"); //$NON-NLS-1$
                    if (fields != null && fields.size() > 0 && fields.size() > innermostFieldsInGroup) {
                        innermostFieldsInGroup = fields.size();
                        innermostGroup = groupElement;
                    }
                }
                Element generatedInnermostGroup = null;
                if (generatedGroups != null) {
                    int generatedInnermostFieldsInGroup = 0;
                    for (int i = 0; i < generatedGroups.size(); i++) {
                        Element groupElement = (Element) generatedGroups.get(i);
                        List fields = groupElement.selectNodes("fields/*"); //$NON-NLS-1$
                        if (fields != null && fields.size() > 0
                                && fields.size() > generatedInnermostFieldsInGroup) {
                            generatedInnermostFieldsInGroup = fields.size();
                            generatedInnermostGroup = groupElement;
                        }
                    }
                }
                // at this point we have found the innermost group
                // this will be used for updating the group header/footer
                if (innermostGroup != null) {
                    // handle headers: append header if header exists, else
                    // create
                    Element groupHeader = (Element) innermostGroup.selectSingleNode("groupheader"); //$NON-NLS-1$
                    if (groupHeader == null) {
                        // direct header replacement with
                        // generatedInnermostGroup header
                        Element headerElement = (Element) generatedInnermostGroup
                                .selectSingleNode("groupheader"); //$NON-NLS-1$
                        if (headerElement != null) {
                            generatedInnermostGroup.remove(headerElement);
                            innermostGroup.add(headerElement);
                        }
                    } else {
                        // insertion: loop through elements of generated,
                        // append to header
                        List groupHeaderNodes = innermostGroup.selectNodes("groupheader/*"); //$NON-NLS-1$
                        List generatedGroupHeaderNodes = generatedInnermostGroup.selectNodes("groupheader/*"); //$NON-NLS-1$
                        Element generatedGroupHeader = (Element) generatedInnermostGroup
                                .selectSingleNode("groupheader"); //$NON-NLS-1$
                        // fix up header/footer breaking for innermost group
                        int y = 0;
                        for (int i = 0; i < groupHeaderNodes.size(); i++) {
                            Element element = (Element) groupHeaderNodes.get(i);
                            try {
                                y = Math.max(y, Integer.parseInt(element.attributeValue("y")) //$NON-NLS-1$
                                        + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$
                            } catch (Exception e) {
                                // NumberFormat exceptions, ignore
                            }
                            try {
                                y = Math.max(y, Integer.parseInt(element.attributeValue("y1")) //$NON-NLS-1$
                                        + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$
                            } catch (Exception e) {
                                // NumberFormat exceptions, ignore
                            }
                            try {
                                y = Math.max(y, Integer.parseInt(element.attributeValue("y2")) //$NON-NLS-1$
                                        + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$
                            } catch (Exception e) {
                                // NumberFormat exceptions, ignore
                            }
                        }
                        for (int i = 0; i < generatedGroupHeaderNodes.size(); i++) {
                            Element element = (Element) generatedGroupHeaderNodes.get(i);
                            generatedGroupHeader.remove(element);
                            if (element.attribute("y") != null) { //$NON-NLS-1$
                                int yValue = Integer.parseInt(element.attributeValue("y")); //$NON-NLS-1$
                                element.attribute("y").detach(); //$NON-NLS-1$
                                element.addAttribute("y", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                            } else if (element.attribute("y1") != null) { //$NON-NLS-1$
                                int yValue = Integer.parseInt(element.attributeValue("y1")); //$NON-NLS-1$
                                element.attribute("y1").detach(); //$NON-NLS-1$
                                element.addAttribute("y1", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                            } else if (element.attribute("y2") != null) { //$NON-NLS-1$
                                int yValue = Integer.parseInt(element.attributeValue("y2")); //$NON-NLS-1$
                                element.attribute("y2").detach(); //$NON-NLS-1$
                                element.addAttribute("y2", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                            }
                            groupHeader.add(element);
                        }
                    }
                    // handle footers:
                    Element groupFooter = (Element) innermostGroup.selectSingleNode("groupfooter"); //$NON-NLS-1$
                    if (groupFooter == null) {
                        // direct footer replacement with
                        // generatedInnermostGroup footer
                        Element footerElement = (Element) generatedInnermostGroup
                                .selectSingleNode("groupfooter"); //$NON-NLS-1$
                        if (footerElement != null) {
                            generatedInnermostGroup.remove(footerElement);
                            innermostGroup.add(footerElement);
                        }
                    } else {
                        // insertion: loop through elements of generated,
                        // inserting to
                        // template footer top (remove existing, add new,
                        // add existing back)
                        List groupFooterNodes = groupFooter.selectNodes("*"); //$NON-NLS-1$
                        // remove existing
                        for (int i = 0; i < groupFooterNodes.size(); i++) {
                            groupFooter.remove((Element) groupFooterNodes.get(i));
                        }
                        // add new
                        List generatedGroupFooterNodes = generatedInnermostGroup.selectNodes("groupfooter/*"); //$NON-NLS-1$
                        Element generatedGroupFooter = (Element) generatedInnermostGroup
                                .selectSingleNode("groupfooter"); //$NON-NLS-1$
                        int y = 0;
                        for (int i = 0; i < generatedGroupFooterNodes.size(); i++) {
                            Element element = (Element) generatedGroupFooterNodes.get(i);
                            generatedGroupFooter.remove(element);
                            groupFooter.add(element);
                            try {
                                y = Math.max(y, Integer.parseInt(element.attributeValue("y")) //$NON-NLS-1$
                                        + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$
                            } catch (Exception e) {
                                // NumberFormat exceptions, ignore
                            }
                            try {
                                y = Math.max(y, Integer.parseInt(element.attributeValue("y1")) //$NON-NLS-1$
                                        + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$
                            } catch (Exception e) {
                                // NumberFormat exceptions, ignore
                            }
                            try {
                                y = Math.max(y, Integer.parseInt(element.attributeValue("y2")) //$NON-NLS-1$
                                        + Integer.parseInt(element.attributeValue("height"))); //$NON-NLS-1$
                            } catch (Exception e) {
                                // NumberFormat exceptions, ignore
                            }
                        }
                        // add existing back, pushed down
                        for (int i = 0; i < groupFooterNodes.size(); i++) {
                            Element element = (Element) groupFooterNodes.get(i);
                            if (element.attribute("y") != null) { //$NON-NLS-1$
                                int yValue = Integer.parseInt(element.attributeValue("y")); //$NON-NLS-1$
                                element.attribute("y").detach(); //$NON-NLS-1$
                                element.addAttribute("y", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                            } else if (element.attribute("y1") != null) { //$NON-NLS-1$
                                int yValue = Integer.parseInt(element.attributeValue("y1")); //$NON-NLS-1$
                                element.attribute("y1").detach(); //$NON-NLS-1$
                                element.addAttribute("y1", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                            } else if (element.attribute("y2") != null) { //$NON-NLS-1$
                                int yValue = Integer.parseInt(element.attributeValue("y2")); //$NON-NLS-1$
                                element.attribute("y2").detach(); //$NON-NLS-1$
                                element.addAttribute("y2", (y + yValue) + ""); //$NON-NLS-1$ //$NON-NLS-2$
                            }
                            groupFooter.add((Element) groupFooterNodes.get(i));
                        }
                    }
                }
            }
            // need to merge 'dummy' group if we're doing grand totals
            for (int i = 0; i < generatedGroups.size(); i++) {
                Element generatedGroup = (Element) generatedGroups.get(i);
                if (generatedGroup.attributeValue(NAME_ATTRIBUTE_NAME).equals("dummy")) { //$NON-NLS-1$
                    for (int j = 0; j < groups.size(); j++) {
                        Element group = (Element) groups.get(j);
                        if (group.attributeValue(NAME_ATTRIBUTE_NAME).equals("dummy")) { //$NON-NLS-1$
                            Element groupsElement = (Element) templateReportNode.selectSingleNode("groups"); //$NON-NLS-1$
                            generatedGroup.detach();
                            group.detach();
                            groupsElement.add(generatedGroup);
                        }
                    }
                }
            }
        }
        // 'merge' functions section in templateDoc from generatedDoc
        Element functionsElement = (Element) templateReportNode.selectSingleNode("functions"); //$NON-NLS-1$
        Element generatedFunctionsElement = (Element) generatedReportNode.selectSingleNode("functions"); //$NON-NLS-1$
        if (generatedFunctionsElement != null) {
            List functionList = generatedFunctionsElement.selectNodes("function"); //$NON-NLS-1$
            for (int i = 0; i < functionList.size(); i++) {
                Element functionElement = (Element) functionList.get(i);
                generatedFunctionsElement.remove(functionElement);
                functionsElement.add(functionElement);
            }
        }
        // 'merge' expression section in templateDoc from generatedDoc
        Element expressionsElement = (Element) templateReportNode.selectSingleNode("functions"); //$NON-NLS-1$
        Element generatedExpressionsElement = (Element) generatedReportNode.selectSingleNode("functions"); //$NON-NLS-1$
        if (generatedExpressionsElement != null) {
            List expressionsList = generatedExpressionsElement.selectNodes("expression"); //$NON-NLS-1$
            for (int i = 0; i < expressionsList.size(); i++) {
                Element expressionElement = (Element) expressionsList.get(i);
                generatedExpressionsElement.remove(expressionElement);
                expressionsElement.add(expressionElement);
            }
        }
        // pump watermark if exists
        if (generatedReportNode.selectSingleNode("watermark") != null) { //$NON-NLS-1$
            Element watermarkNode = (Element) generatedReportNode.selectSingleNode("watermark"); //$NON-NLS-1$
            Element templateWatermarkNode = (Element) templateReportNode.selectSingleNode("watermark"); //$NON-NLS-1$
            if (templateWatermarkNode != null) {
                templateWatermarkNode.detach();
            }
            if (watermarkNode != null) {
                watermarkNode.detach();
            }
            templateReportNode.add(watermarkNode);
        }
        // push generatedDoc changes into templateDoc and write result to
        // mergeStream
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(mergeStream, format);
        writer.write(templateDoc);
        writer.close();
    } catch (Exception e) {
        getLogger().error(e.getMessage(), e);
    }
}

From source file:org.pentaho.platform.web.refactor.SubscriptionAdminUIComponent.java

License:Open Source License

/**
 * @return/*from  w ww  .  ja  v a  2 s.  co m*/
 * @throws Exception
 */
private void doListSchedules(Element root) throws Exception {
    root = root.addElement(SubscriptionAdminUIComponent.ACTION_SCHEDULE_SHOW_LIST);
    ISubscriptionScheduler subScheduler = PentahoSystem.get(ISubscriptionScheduler.class, this.getSession());

    List schedList = subscriptionRepository.getSchedules();
    Map jobMap = subScheduler.getScheduledJobMap();

    Element scheduledJobs = root.addElement("scheduledJobs"); //$NON-NLS-1$
    Element unScheduledJobs = root.addElement("unScheduledJobs"); //$NON-NLS-1$
    Element extraScheduledJobs = root.addElement("extraScheduledJobs"); //$NON-NLS-1$

    int pauseCounter = 0;
    int errorCounter = 0;

    for (int i = 0; i < schedList.size(); ++i) {
        ISchedule sched = (ISchedule) schedList.get(i);
        IScheduledJob schedJob = (IScheduledJob) jobMap.remove(sched.getScheduleReference());
        if (schedJob != null) {
            int jobState = schedJob.getExecutionState();
            if (jobState == IScheduledJob.STATE_PAUSED) {
                ++pauseCounter;
            } else if (jobState != IScheduledJob.STATE_NORMAL) {
                ++errorCounter;
            }
        }

        Element job = (schedJob == null) ? unScheduledJobs.addElement("job") : scheduledJobs.addElement("job"); //$NON-NLS-1$ //$NON-NLS-2$
        try {
            getJob(sched, schedJob, job);
        } catch (ActionInfoParseException e) {
            root.add(getInfoMessage(e.getMessage())); //$NON-NLS-1$
        }
    }

    for (Iterator it = jobMap.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        IScheduledJob schedJob = (IScheduledJob) entry.getValue();
        Element job = extraScheduledJobs.addElement("job"); //$NON-NLS-1$

        job.addElement("schedRef").addText(entry.getKey().toString()); //$NON-NLS-1$
        job.addElement("desc").addText(schedJob.getDescription()); //$NON-NLS-1$

        if (schedJob != null) {
            job.addAttribute("triggerState", Integer.toString(schedJob.getExecutionState())); //$NON-NLS-1$
            Date date = schedJob.getNextTriggerTime();
            job.addElement("nextFireTime") //$NON-NLS-1$
                    .addText((date == null) ? Messages.getString("SubscriptionAdminUIComponent.USER_NEVER") //$NON-NLS-1$
                            : date.toString());
            date = schedJob.getLastTriggerTime();
            job.addElement("prevFireTime") //$NON-NLS-1$
                    .addText((date == null) ? Messages.getString("SubscriptionAdminUIComponent.USER_NEVER") //$NON-NLS-1$
                            : date.toString());
            job.addElement("jobId").addText(schedJob.getUniqueId()); //$NON-NLS-1$
            String errorMsg = schedJob.getErrorMessage();
            if (errorMsg != null) {
                job.addElement("errorMsg").addText(errorMsg); //$NON-NLS-1$
            }
        } else {
            job.addAttribute("triggerState", Integer.toString(IScheduledJob.STATE_NONE)); //$NON-NLS-1$1$
        }
    }

    if (schedList.size() == 0) {
        root.add(getInfoMessage(
                Messages.getString("SubscriptionAdminUIComponent.USER_NO_SUBSCRIPTIONS_DEFINED"))); //$NON-NLS-1$
    } else if (scheduledJobs.elements().size() == 0) {
        root.remove(scheduledJobs);
    }

    if (errorCounter > 0) {
        root.add(getErrorMessage(errorCounter
                + Messages.getString("SubscriptionAdminUIComponent.USER_SCHEDULED_JOBS_ARE_IN_ERROR_STATE"))); //$NON-NLS-1$
    }

    if (pauseCounter > 0) {
        root.add(getWarningMessage(pauseCounter
                + Messages.getString("SubscriptionAdminUIComponent.USER_SCHEDULED_JOBS_ARE_PAUSED"))); //$NON-NLS-1$
    }

    if (unScheduledJobs.elements().size() == 0) {
        root.remove(unScheduledJobs);
    } else {
        root.add(getWarningMessage(
                Messages.getString("SubscriptionAdminUIComponent.USER_SUBSCRIPTIONS_NOT_SCHEDULED"))); //$NON-NLS-1$
    }

    if (extraScheduledJobs.elements().size() == 0) {
        root.remove(extraScheduledJobs);
    } else {
        root.add(getWarningMessage(
                Messages.getString("SubscriptionAdminUIComponent.SUBSCRIPTION_JOBS_WITHOUT_SUBSCRIPTION"))); //$NON-NLS-1$
    }
}

From source file:org.pentaho.supportutility.config.retriever.JackRabbitConfigRetriever.java

License:Open Source License

/**
 * removes password node/*from ww  w  .j a  v  a  2  s . co  m*/
 * 
 * @param element
 * @return boolean
 */
public static boolean removeNode(Element element) {

    for (int j = 0; j < element.nodeCount(); j++) {

        Node param = element.node(j);
        Element par = (Element) param;
        for (Iterator<?> n = par.attributeIterator(); n.hasNext();) {

            Attribute attribute = (Attribute) n.next();
            if (attribute.getName().equalsIgnoreCase("name")) {
                if (attribute.getStringValue().equals("password")) {
                    element.remove(param);
                }
            }
        }
    }

    return true;
}

From source file:org.projectforge.business.gantt.GanttChartDao.java

License:Open Source License

/**
 * Removes all unnecessary GanttObject elements from the DOM (those without any information rather than the id).
 *///from w  w  w . j a v  a2s . c om
private boolean removeUnnecessaryElements(final Element element) {
    if (CollectionUtils.isNotEmpty(element.elements()) == true) {
        for (final Object childObj : element.elements()) {
            final Element child = (Element) childObj;
            if (removeUnnecessaryElements(child) == true) {
                element.remove(child);
            }
        }
    }
    if (CollectionUtils.isNotEmpty(element.elements()) == true) {
        // Element has descendants.
        return false;
    }
    if (StringUtils.isBlank(element.getText()) == false) {
        // Element has non blank content.
        return false;
    }
    // Element has no descendants:
    if (CollectionUtils.isEmpty(element.attributes()) == true) {
        // Element has no attributes.
        return true;
    }
    if ("predecessor".equals(element.getName()) == true) {
        if (element.attribute(XmlObjectWriter.ATTR_ID) != null) {
            // Describes a complete Gantt task which is referenced, so full output is needed.
            return false;
        } else {
            final Attribute idAttr = element.attribute("id");
            final Attribute refIdAttr = element.attribute(XmlObjectWriter.ATTR_REF_ID);
            element.setAttributes(null);
            if (refIdAttr != null) {
                element.addAttribute(XmlObjectWriter.ATTR_REF_ID, refIdAttr.getValue());
            } else if (idAttr != null) {
                // External reference (no ref-id, but task id):
                element.addAttribute("id", idAttr.getValue());
            } else {
                // Should not occur.
                return true;
            }
            return false;
        }
    } else if (element.attributes().size() == 1 && element.attribute("id") != null) {
        // Element has only id attribute and is not a predecessor definition for tasks outside the current Gantt object tree.
        return true;
    }
    return false;
}

From source file:org.sipfoundry.openfire.vcard.provider.RestInterface.java

License:Contributor Agreement License

public static String refillMissingContactInfo(String vcardXml, String contactXml) {
    try {//from   ww  w. jav  a2 s.com
        SAXReader sreader = new SAXReader();

        Document contactDoc = sreader.read(new StringReader(contactXml));
        Element contactRootElement = contactDoc.getRootElement();

        Document vcardDoc = sreader.read(new StringReader(vcardXml));
        Element vcardRootElement = vcardDoc.getRootElement();

        for (Element el : (List<Element>) contactRootElement.elements()) {
            Element vElement;
            if ((vElement = vcardRootElement.element(el.getName())) == null) {
                logger.debug(" In refillMissingContactInfo Element = [" + el.getName() + "] not found!");
                vcardRootElement.add(el.createCopy());
            } else {
                String newStr = refillMissingContactInfo(vElement.asXML(), el.asXML());
                if ((newStr.compareTo(vElement.asXML()) != 0)) {
                    Document vcardSubDoc = sreader.read(new StringReader(newStr));
                    Element vcardSubRootElement = vcardSubDoc.getRootElement();
                    vcardRootElement.remove(vElement);
                    vcardRootElement.add(vcardSubRootElement.createCopy());
                }
            }
        }
        logger.debug("vcard XML string after refill is " + vcardRootElement.asXML());
        return vcardRootElement.asXML();
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return null;
    }

}

From source file:org.sipfoundry.openfire.vcard.provider.SipXVCardProvider.java

License:Contributor Agreement License

/**
 * Loads the vCard using the LDAP vCard Provider and re-adds the avatar from the database.
 *
 * @param username/*  w  w  w .j  a  va2 s  . c o  m*/
 * @return LDAP vCard re-added avatar element
 */
synchronized static Element mergeAvatar(String username, Element vcardFromSipX, Element vcardFromDB) {

    logger.info("merge avatar for user '" + username + "' ...");

    // get the vcard from ldap
    // Element vCardElement = super.loadVCard(username);

    // only add avatar if it doesn't exist already
    if (vcardFromDB != null && vcardFromDB.element(AVATAR_ELEMENT) != null) {
        Element avatarElement = getAvatarCopy(vcardFromDB);

        if (avatarElement != null) {
            if (getAvatar(vcardFromSipX) != null) {
                vcardFromSipX.remove(getAvatar(vcardFromSipX));
            }
            vcardFromSipX.add(avatarElement);
            logger.info("Avatar merged from DB into sipX vCard");
        } else {
            logger.info("No vCard found in database");
        }
    }

    return vcardFromSipX;
}