ca.qc.cegepoutaouais.tge.pige.server.report.LateLoanReport.java Source code

Java tutorial

Introduction

Here is the source code for ca.qc.cegepoutaouais.tge.pige.server.report.LateLoanReport.java

Source

/*
 * Copyright 2010, 2011 Renaud Brub
 *
 * This file is part of PIGE.
 *
 * PIGE is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * PIGE is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PIGE.  If not, see <http://www.gnu.org/licenses/>.
 */
package ca.qc.cegepoutaouais.tge.pige.server.report;

import ca.qc.cegepoutaouais.tge.pige.dao.pojos.Loan;
import ca.qc.cegepoutaouais.tge.pige.dao.pojos.User;
import ca.qc.cegepoutaouais.tge.pige.server.Configurations;
import ca.qc.cegepoutaouais.tge.pige.server.LogHelper;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import java.util.Set;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xml.sax.InputSource;

/**
 * Rapport des emprunts en retards.
 *
 * @author Renaud Brub
 */
public class LateLoanReport extends Report implements HTMLFormat, PDFFormat {

    private static final Logger logger = LogHelper.getLogger(LateLoanReport.class);
    private final String TEMPLATE_FILENAME = "LateReportTemplate.html";
    final Properties locale = Configurations.getProperties();

    public LateLoanReport() {
        super();
    }

    @Override
    protected void prepareData() {
        ReportDataProvider dp = new ReportDataProvider();
        put("users", dp.getAllUserWithLateLoan());
        dp.calculateLoanStatistics(this);
        setFilename(locale.getProperty("msg.report.lateLoansReportFilename"));
    }

    @Override
    public void generateHTML() throws ReportException {
        logger.debug("Gnration du rapport des emprunts en retards au format HTML...");
        OutputStreamWriter writer = null;
        try {
            Document docRoot = generateReport();

            logger.debug("Conversion du rapport au format HTML.");
            writer = new OutputStreamWriter(getTempOutputStream());
            String doc = docRoot.asXML();
            writer.write(doc, 0, doc.length());
            writer.flush();

            setDocumentSize(getTempOutputStream().toByteArray().length);
            logger.debug("Calcul de la taille final du rapport: " + getDocumentSize());

            setHttpContentType("text/html");
            logger.debug("Gnration du rapport termine!");

        } catch (Exception ex) {
            throw new ReportException(ex);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (Exception ignored) {
                }
            }
        }
    }

    @Override
    public void generatePDF() throws ReportException {
        logger.debug("Gnration du rapport des emprunts en retards au format PDF...");
        try {
            logger.debug("Gnration du rapport.");

            Document docRoot = generateReport();

            logger.debug("Conversion du rapport au format PDF.");
            StringReader reader = new StringReader(docRoot.asXML());
            DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocument(docBuilder.parse(new InputSource(reader)), "");
            renderer.layout();
            renderer.createPDF(getTempOutputStream());

            setDocumentSize(getTempOutputStream().toByteArray().length);
            logger.debug("Calcul de la taille final du rapport: " + getDocumentSize());

            setHttpContentType("application/pdf");
            logger.debug("Gnration du rapport termine!");

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

    }

    protected Document generateReport() throws ReportException {
        try {
            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);
        }
    }

}