Example usage for org.dom4j Element add

List of usage examples for org.dom4j Element add

Introduction

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

Prototype

void add(Namespace namespace);

Source Link

Document

Adds the given Namespace to this element.

Usage

From source file:at.jabberwocky.impl.core.io.PacketReader.java

private Document parseDocument() throws DocumentException, IOException, XmlPullParserException {
    DocumentFactory df = docFactory;//from  w w  w  .  j a v  a  2  s.co  m
    Document document = df.createDocument();
    Element parent = null;
    XmlPullParser pp = parser;
    int count = 0;
    while (true) {
        int type = -1;
        type = pp.nextToken();
        switch (type) {
        case XmlPullParser.PROCESSING_INSTRUCTION: {
            String text = pp.getText();
            int loc = text.indexOf(" ");
            if (loc >= 0) {
                document.addProcessingInstruction(text.substring(0, loc), text.substring(loc + 1));
            } else {
                document.addProcessingInstruction(text, "");
            }
            break;
        }
        case XmlPullParser.COMMENT: {
            if (parent != null) {
                parent.addComment(pp.getText());
            } else {
                document.addComment(pp.getText());
            }
            break;
        }
        case XmlPullParser.CDSECT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addCDATA(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;

        }
        case XmlPullParser.ENTITY_REF: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have an entityref outside of the root document");
                }
            }
            break;
        }
        case XmlPullParser.END_DOCUMENT: {
            return document;
        }
        case XmlPullParser.START_TAG: {
            QName qname = (pp.getPrefix() == null) ? df.createQName(pp.getName(), pp.getNamespace())
                    : df.createQName(pp.getName(), pp.getPrefix(), pp.getNamespace());
            Element newElement = null;
            // Do not include the namespace if this is the start tag of a new packet
            // This avoids including "jabber:client", "jabber:server" or
            // "jabber:component:accept"
            if ("jabber:client".equals(qname.getNamespaceURI())
                    || "jabber:server".equals(qname.getNamespaceURI())
                    || "jabber:component:accept".equals(qname.getNamespaceURI())
                    || "http://jabber.org/protocol/httpbind".equals(qname.getNamespaceURI())) {
                newElement = df.createElement(pp.getName());
            } else {
                newElement = df.createElement(qname);
            }
            int nsStart = pp.getNamespaceCount(pp.getDepth() - 1);
            int nsEnd = pp.getNamespaceCount(pp.getDepth());
            for (int i = nsStart; i < nsEnd; i++) {
                if (pp.getNamespacePrefix(i) != null) {
                    newElement.addNamespace(pp.getNamespacePrefix(i), pp.getNamespaceUri(i));
                }
            }
            for (int i = 0; i < pp.getAttributeCount(); i++) {
                QName qa = (pp.getAttributePrefix(i) == null) ? df.createQName(pp.getAttributeName(i))
                        : df.createQName(pp.getAttributeName(i), pp.getAttributePrefix(i),
                                pp.getAttributeNamespace(i));
                newElement.addAttribute(qa, pp.getAttributeValue(i));
            }
            if (parent != null) {
                parent.add(newElement);
            } else {
                document.add(newElement);
            }
            parent = newElement;
            count++;
            break;
        }
        case XmlPullParser.END_TAG: {
            if (parent != null) {
                parent = parent.getParent();
            }
            count--;
            if (count < 1) {
                return document;
            }
            break;
        }
        case XmlPullParser.TEXT: {
            String text = pp.getText();
            if (parent != null) {
                parent.addText(text);
            } else {
                if (text.trim().length() > 0) {
                    throw new DocumentException("Cannot have text content outside of the root document");
                }
            }
            break;
        }
        default:
        }
    }
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param searchResults/*from   w  ww . j a  va  2s  . co  m*/
 * 
 * @return {@link Document} containing the {@link SearchResults} in XML form.
 */
public static Document genoogleOutputToXML(List<SearchResults> searchResults) {
    assert searchResults != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Document doc = factory.createDocument();
    doc.setName("genoogle");

    Element output = doc.addElement(Genoogle.SOFTWARE_NAME);
    output.addAttribute("version", Genoogle.VERSION.toString());
    output.addAttribute("copyright", Genoogle.COPYRIGHT);

    Element iterationsElement = output.addElement("iterations");
    for (int i = 0; i < searchResults.size(); i++) {
        SearchResults searchResult = searchResults.get(i);

        Element iterationElement = iterationsElement.addElement("iteration");
        iterationElement.addAttribute("number", String.valueOf(i));

        SymbolList query = searchResult.getParams().getQuery();
        if (query instanceof RichSequence) {
            iterationElement.addAttribute("query", ((RichSequence) query).getHeader());
        }

        iterationElement.add(searchResultToXML(searchResult));
    }

    return doc;
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param searchResult/*from  w w w  .  j a v a 2  s  . c  o  m*/
 * 
 * @return {@link Document} containing the {@link SearchResults} in XML form.
 */
public static Document genoogleOutputToXML(SearchResults searchResult) {
    assert searchResult != null;
    Element output = genoogleXmlHeader();
    output.add(searchResultToXML(searchResult));

    return output.getDocument();
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param searchResult//  w ww  . j  av  a  2s .co m
 * @return {@link Element} containing the {@link SearchResults} at XML form.
 */
public static Element searchResultToXML(SearchResults searchResult) {
    assert searchResult != null;
    // TODO: Revise this behavor to throws the exception before.
    if (searchResult.hasFail()) {
        for (Throwable e : searchResult.getFails()) {
            e.printStackTrace(System.err);
        }
    }
    DocumentFactory factory = DocumentFactory.getInstance();
    Element resultsElement = factory.createElement("results");
    resultsElement.add(paramsToXML(searchResult.getParams()));
    resultsElement.add(hitsToXML(searchResult.getHits()));

    return resultsElement;
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param hits/*from ww  w. j a va  2  s  . c o  m*/
 * @return {@link Element} containing the {@link List} of {@link Hit} at XML form.
 */
public static Element hitsToXML(List<Hit> hits) {
    assert hits != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Element hitsElement = factory.createElement("hits");
    for (Hit hit : hits) {
        hitsElement.add(hitToXML(hit));
    }

    return hitsElement;
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param hit//w w  w  .j  a  v  a 2  s  . co  m
 * @return {@link Element} containing the {@link Hit} at XML form.
 */
public static Element hitToXML(Hit hit) {
    assert hit != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Element hitElement = factory.createElement("hit");
    hitElement.addAttribute("id", hit.getId());
    hitElement.addAttribute("gi", hit.getGi());
    hitElement.addAttribute("description", hit.getDescription());
    hitElement.addAttribute("accession", hit.getAccession());
    hitElement.addAttribute("length", Integer.toString(hit.getLength()));
    hitElement.addAttribute("databank", hit.getDatabankName());
    hitElement.add(hspsToXML(hit.getHSPs()));

    return hitElement;
}

From source file:bio.pih.genoogle.io.Output.java

/**
 * @param hsps//from  w  w  w  . j a v  a 2  s . c  om
 * @return {@link Element} containing the {@link List} of {@link HSP} at XML form.
 */
public static Element hspsToXML(List<HSP> hsps) {
    assert hsps != null;
    DocumentFactory factory = DocumentFactory.getInstance();

    Element hspsElement = factory.createElement("hsps");
    for (HSP hsp : hsps) {
        hspsElement.add(hspToXML(hsp));
    }

    return hspsElement;
}

From source file:BlastResultXMLsplit.BlastXMLsplit.java

public BlastXMLsplit(String filepath, int seqnumber)
        throws FileNotFoundException, IOException, ParserConfigurationException {
    SAXReader reader = new SAXReader();
    reader.setValidation(false);/*from   w ww .  j  a v  a2 s . c  om*/
    try {
        System.out.println("Xlmfile reading");
        Document document = reader.read(new FileInputStream(filepath));//XMLdocument?
        System.out.println("Xlmfile read done!");
        org.dom4j.DocumentFactory DocumentFactory = new org.dom4j.DocumentFactory();

        ArrayList str = new ArrayList();//??? 

        String fileoutpath;

        org.dom4j.Element rootElm = document.getRootElement();//
        File f = new File(filepath);
        int count = 1;
        List<org.dom4j.Element> blastOutput_iterations = rootElm.element("BlastOutput_iterations").elements();//?
        org.dom4j.Element BlastOutput_program = rootElm.element("BlastOutput_program");
        org.dom4j.Element BlastOutput_version = rootElm.element("BlastOutput_version");
        org.dom4j.Element BlastOutput_reference = rootElm.element("BlastOutput_reference");
        org.dom4j.Element BlastOutput_db = rootElm.element("BlastOutput_db");
        //?
        BlastOutput_program.getParent().remove(BlastOutput_program);
        BlastOutput_version.getParent().remove(BlastOutput_version);
        BlastOutput_reference.getParent().remove(BlastOutput_reference);
        BlastOutput_db.getParent().remove(BlastOutput_db);
        // org.dom4j.Element BlastOutput_query_def=rootElm.element("BlastOutput_query-def");
        //org.dom4j.Element BBlastOutput_query_len=rootElm.element("BlastOutput_query-len");

        org.dom4j.Element BlastOutput_param = rootElm.element("BlastOutput_param");
        rootElm.remove(BlastOutput_param);

        String Iteration_queryIDstr, Iteration_queryDefstr, Iteration_query_len;
        List<org.dom4j.Element> Iterationlist = null;
        int size = blastOutput_iterations.size();
        System.out.println("Your query seqcount is " + size + "\r\n Start dividing your file");
        for (int i = 0; i < size; i = i + seqnumber) {
            //??
            fileoutpath = f.getParent() + System.getProperty("file.separator") + count + ".xml";
            count++;
            System.out.println("The " + count + " is located in " + fileoutpath);
            FileOutputStream fos = new FileOutputStream(fileoutpath);
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(fos, format);
            // XMLWriter writer = new XMLWriter(new FileOutputStream(fileoutpath));
            //w??
            org.dom4j.Element firstelement = blastOutput_iterations.get(i);
            Iteration_queryIDstr = firstelement.element("Iteration_query-ID").getText();
            Iteration_queryDefstr = firstelement.element("Iteration_query-def").getText();
            Iteration_query_len = firstelement.element("Iteration_query-len").getText();

            //org.dom4j.DocumentFactory DocumentFactory = new org.dom4j.DocumentFactory();

            Document document2 = DocumentHelper.createDocument();
            ;
            org.dom4j.Element BlastOutputElement = document2.addElement("BlastOutput");
            //doc.setRootElement(BlastOutputElement);
            //;
            BlastOutputElement.add(BlastOutput_program);
            BlastOutputElement.add(BlastOutput_version);
            BlastOutputElement.add(BlastOutput_reference);
            BlastOutputElement.add(BlastOutput_db);
            BlastOutputElement.addElement("BlastOutput_query-ID");
            BlastOutputElement.element("BlastOutput_query-ID").setText(Iteration_queryIDstr);
            BlastOutputElement.addElement("BlastOutput_query-def");
            BlastOutputElement.element("BlastOutput_query-def").setText(Iteration_queryDefstr);
            BlastOutputElement.addElement("BlastOutput_query-len");
            BlastOutputElement.element("BlastOutput_query-len").setText(Iteration_query_len);
            //                Element BlastOutput_param_new=DocumentFactory.createElement("BlastOutput_param");
            //                for (Iterator it = BlastOutput_param.elementIterator(); it.hasNext();) {
            //                    Element tempele=(Element) it.next();
            //                    tempele.getParent().remove(tempele);
            //                    BlastOutput_param_new.add(tempele);
            //                }
            BlastOutputElement.add(BlastOutput_param);
            //BlastOutputElement.add(BlastOutput_param);
            if (i + seqnumber < blastOutput_iterations.size()) {
                Iterationlist = blastOutput_iterations.subList(i, i + seqnumber);
            } else {
                Iterationlist = blastOutput_iterations.subList(i, blastOutput_iterations.size() - 1);
            }
            //System.out.println(Iterationlist.size());
            //?query
            resetIterationlist(Iterationlist);
            //?BlastOutput_iterations

            Element BlastOutput_iterations = DocumentFactory.createElement("BlastOutput_iterations");
            //BlastOutputElement.addAttribute("BlastOutput_iterations");
            //org.dom4j.Element BlastOutput_iterations = new org.dom4j.Element("BlastOutput_iterations");
            for (int j = 0; j < Iterationlist.size(); j++) {
                Iterationlist.get(j).getParent().remove(Iterationlist.get(j));
                //System.out.println(j);
                BlastOutput_iterations.add(Iterationlist.get(j));
            }
            BlastOutputElement.add(BlastOutput_iterations);

            //
            writer.write(document2);
            writer.close();
            BlastOutput_program.getParent().remove(BlastOutput_program);
            BlastOutput_version.getParent().remove(BlastOutput_version);
            BlastOutput_reference.getParent().remove(BlastOutput_reference);
            BlastOutput_db.getParent().remove(BlastOutput_db);
            BlastOutput_param.getParent().remove(BlastOutput_param);
        }
    } catch (DocumentException ex) {
        Logger.getLogger(BlastXMLsplit.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ca.qc.cegepoutaouais.tge.pige.server.report.LateLoanReport.java

License:Open Source License

protected Document generateReport() throws ReportException {
    try {//from   w w w .j a  va2 s  .co  m
        String template = ReportHelper
                .convertStreamToString(ReportHelper.loadFileAsStream(TEMPLATE_BASE_PATH + TEMPLATE_FILENAME));
        String css = ReportHelper.convertStreamToString(
                ReportHelper.loadFileAsStream(TEMPLATE_BASE_PATH + TEMPLATE_STYLES_FILENAME));

        logger.debug("Inscription des donnes du rapport dans le modle.");

        template = MessageFormat.format(template, locale.getProperty("msg.report.lateLoansReportTitle"),
                MessageFormat.format(locale.getProperty("msg.report.reportGeneratedBy"), getAuthor(),
                        SimpleDateFormat.getDateInstance(SimpleDateFormat.LONG, Locale.CANADA_FRENCH)
                                .format(new Date())),
                locale.getProperty("msg.report.statistics"),
                locale.getProperty("msg.report.totalNumberOfLoans"),
                locale.getProperty("msg.report.numberOfLentLoans"),
                locale.getProperty("msg.report.numberOfLateLoans"), ((Integer) get("total-count")).toString(),
                ((Integer) get("lent-count")).toString(), ((Integer) get("late-count")).toString(),
                String.format("%2.2f", (Float) get("percent-lent")),
                String.format("%2.2f", (Float) get("percent-late")),
                locale.getProperty("msg.report.userListWithLateLoans"));

        Document docRoot = DocumentHelper.parseText(template);
        ReportHelper.applyStyleToHTML(docRoot, css);

        Element body = (Element) docRoot.selectSingleNode("//data");
        List<User> users = (List) get("users");
        StringBuilder builder = new StringBuilder("<div>");
        if (users.size() > 0) {
            for (User u : users) {
                builder.append(
                        "<table class='user-section' border='0' cellspacing='0' cellpadding='5px'><thead><tr><td class='user-section-header'>")
                        .append("[").append(u.getLoanNo()).append("] ").append(u.getLastname()).append(", ")
                        .append(u.getFirstname()).append("</td><td colspan='2' class='user-section-header'>")
                        .append(u.getEmail()).append("</td></tr><tr><td class='user-section-header'>")
                        .append("Quantit").append("</td><td class='user-section-header'>")
                        .append("Description").append("</td><td class='user-section-header'>")
                        .append("chance").append("</td></tr></thead><tbody>");
                Set<Loan> loans = u.getLoans();
                for (Loan l : loans) {
                    builder.append("<tr><td class='user-section-body'>").append(l.getQuantity())
                            .append("</td><td class='user-section-body'>").append(l.getDescription())
                            .append("</td><td class='user-section-body'>").append(l.getTerm().toString())
                            .append("</td></tr>");
                }
                builder.append("</tbody></table>");
            }
        } else {
            builder.append("<span>Aucun emprunt en retard!</span>");
        }
        builder.append("</div>");

        Document finalDoc = DocumentHelper.parseText(builder.toString());
        Element content = finalDoc.getRootElement();
        body.add(content);

        return docRoot;
    } catch (Exception ex) {
        throw new ReportException(ex);
    }
}

From source file:ca.qc.cegepoutaouais.tge.pige.server.report.ReportHelper.java

License:Open Source License

/**
 * Applique un style CSS  un document HTML.
 * La section 'head' du document HTML est extraite afin d'y insrer
 * le style CSS./*  w w w .j  a  v a 2  s .  c o  m*/
 *
 * @param htmlDoc document HTML  traiter
 * @param style style CSS  insrer
 * @throws ReportException
 */
public static void applyStyleToHTML(Document htmlDoc, String style) throws ReportException {
    Element headerTag = (Element) htmlDoc.selectSingleNode("//head");
    Element styleTag = DocumentHelper.createElement("style");
    styleTag.addText(style);
    headerTag.add(styleTag);
}