view artifacts/src/main/java/org/dive4elements/river/artifacts/common/AbstractCommonExporter.java @ 8999:e3b3ce32c825

Work on uinfo
author gernotbelger
date Thu, 12 Apr 2018 19:15:42 +0200
parents
children 460fcc128794
line wrap: on
line source
/** Copyright (C) 2017 by Bundesanstalt für Gewässerkunde
 * Software engineering by
 *  Björnsen Beratende Ingenieure GmbH
 *  Dr. Schumacher Ingenieurbüro für Wasser und Umwelt
 *
 * This file is Free Software under the GNU AGPL (>=v3)
 * and comes with ABSOLUTELY NO WARRANTY! Check out the
 * documentation coming with Dive4Elements River for details.
 */
package org.dive4elements.river.artifacts.common;

import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.dive4elements.artifacts.CallMeta;
import org.dive4elements.artifacts.common.utils.Config;
import org.dive4elements.river.artifacts.model.CalculationResult;
import org.dive4elements.river.artifacts.resources.Resources;
import org.dive4elements.river.artifacts.sinfo.util.MetaAndTableJRDataSource;
import org.dive4elements.river.artifacts.sinfo.util.RiverInfo;
import org.dive4elements.river.exports.AbstractExporter;

import au.com.bytecode.opencsv.CSVWriter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRElement;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRPrintPage;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRProperties;
import net.sf.jasperreports.engine.xml.JRSaxParserFactory;
import net.sf.jasperreports.engine.xml.JRXmlLoader;

/**
 * @author Gernot Belger
 */
public abstract class AbstractCommonExporter<RESULT extends AbstractCalculationResult, RESULTS extends AbstractCalculationResults<RESULT>> extends AbstractExporter {

    /** The storage that contains the current calculation result. */
    protected static enum ExportMode {
        pdf, csv
    }

    /** The log used in this exporter. */
    protected abstract Logger getLog();

    protected RESULTS data = null;

    public RESULTS getData() {
        return this.data;
    }

    @Override
    protected void addData(final Object d) {
        /* reset */
        this.data = null;

        if (d instanceof CalculationResult) {

            final Object dat = ((CalculationResult) d).getData();
            if (dat != null) {
                @SuppressWarnings("unchecked")
                final RESULTS result = (RESULTS) dat;
                this.data = result;
            }
        }
    }

    /**
     * Formats header with unit and label: msg [unit] (label)
     */
    protected String msgUnitLabel(final String key, final String unit, final String label) {
        final String msg = msg(key);
        return String.format("%s [%s] (%s)", msg, unit, label);
    }

    @Override
    protected void writeCSVData(final CSVWriter writer) {
        getLog().info("writeCSVData");

        /* fetch calculation results */
        final RESULTS results = this.data;

        /* write as csv */
        writeCSVGlobalMetadata(writer, results);
        writer.writeNext(new String[] { "" }); // break line HERE to avoid redundance
        final RiverInfo river = results.getRiver();
        // FIXME :with comment if not first result
        writeCSVHeader(writer, results, river);
        writer.writeNext(new String[] { "" }); // break line HERE to avoid redundance

        for (final RESULT result : results.getResults()) {
            writeCSVResult(writer, results, result);
            writer.writeNext(new String[] { "" }); // break line HERE after each resultset
        }

    }

    protected abstract void writeCSVHeader(final CSVWriter writer, final RESULTS results, final RiverInfo river);

    /**
     * Add metadata that is once written to the top of the file.
     */
    protected abstract void writeCSVGlobalMetadata(final CSVWriter writer, final RESULTS results);

    protected void writeCSVMetaEntry(final CSVWriter writer, final String message, final Object... messageArgs) {

        final CallMeta meta = this.context.getMeta();

        writer.writeNext(new String[] { Resources.getMsg(meta, message, message, messageArgs) });
    }

    private void writeCSVResult(final CSVWriter writer, final RESULTS results, final RESULT result) {

        writeCSVResultMetadata(writer, results, result);
        writer.writeNext(new String[] { "" }); // break line HERE to avoid redundance

        // final RiverInfo river = results.getRiver();
        //
        // writeCSVHeader(writer, results, river);
        /* now the value rows */
        final Collection<ResultRow> rows = result.getRows(); // war mal SInfoResultRow
        for (final ResultRow row : rows) {
            writeCSVRow(writer, results, result, row);
        }
    }

    /**
     * Add metadata that is written once per result set.
     */
    protected abstract void writeCSVResultMetadata(CSVWriter writer, RESULTS results, RESULT result);

    protected void writeCSVRow(final CSVWriter writer, final RESULTS results, final RESULT result, final ResultRow row) {
        getLog().debug("writeCSVFlowDepthRow");

        final String[] formattedRow = formatCSVRow(results, row);
        writer.writeNext(formattedRow);
    }

    protected final String[] formatCSVRow(final RESULTS results, final ResultRow row) {
        return formatRow(results, row, ExportMode.csv);
    }

    // protected abstract void tweakDesign()

    @Override
    protected void writePDF(final OutputStream outStream) {
        getLog().debug("write PDF");

        final JRDataSource source = createJRData();
        final JRDataSource source2 = createJRData();

        final String confPath = Config.getConfigDirectory().toString();

        // FIXME: distinguish between with and without tkh: we need two jasper reports!

        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("ReportTitle", "Exported Data");

        try {

            // JRProperties.setProperty(JRProperties.COMPILER_XML_VALIDATION, false);
            JRProperties.setProperty(JRSaxParserFactory.PROPERTY_REPORT_PARSER_FACTORY, JRReportSaxParserFactory.class.getName());

            final String jasperPath = confPath + getJasperFile();
            final JasperDesign test = JRXmlLoader.load(jasperPath);

            final JRElement element = test.getColumnHeader().getElementByKey("TEST");
            // element.setWidth(200);

            final JasperReport compiled = JasperCompileManager.compileReport(test);

            final JasperPrint print = JasperFillManager.fillReport(compiled, parameters, source);
            // JasperExportManager.exportReportToPdfStream(print, outStream);

            final JasperPrint print2 = JasperFillManager.fillReport(compiled, parameters, source2);

            final List<JRPrintPage> pages = print2.getPages();
            for (final JRPrintPage page : pages)
                print.addPage(page);

            JasperExportManager.exportReportToPdfStream(print, outStream);
        }
        catch (final JRException je) {
            getLog().warn("Error generating PDF Report!", je);
        }
    }

    protected abstract String getJasperFile();

    private JRDataSource createJRData() {

        /* fetch calculation results */
        final RESULTS results = this.data;

        final MetaAndTableJRDataSource source = new MetaAndTableJRDataSource();

        addJRMetaData(source, results);

        for (final RESULT result : results.getResults()) {
            addJRTableData(source, results, result);
        }

        return source;
    }

    protected abstract void addJRMetaData(final MetaAndTableJRDataSource source, final RESULTS results);

    protected void addJRTableData(final MetaAndTableJRDataSource source, final RESULTS results, final RESULT result) {

        final Collection<ResultRow> rows = result.getRows();

        for (final ResultRow row : rows) {

            final String[] formattedRow = formatPDFRow(results, row);
            source.addData(formattedRow);
        }
    }

    protected abstract String[] formatRow(RESULTS results, ResultRow row, ExportMode mode);

    protected final String[] formatPDFRow(final RESULTS results, final ResultRow row) {
        // @Override
        // protected String[] formatPDFRow(final FlowDepthDevelopmentCalculationResults results, final ResultRow row) {
        return formatRow(results, row, ExportMode.pdf);
        // }
    }

    protected abstract void writeCSVGlobalMetadataDefaults(final CSVWriter writer, final RESULTS results);

    protected abstract void addJRMetaDataDefaults(final MetaAndTableJRDataSource source, final RESULTS results);
}

http://dive4elements.wald.intevation.org