view artifacts/src/main/java/org/dive4elements/river/artifacts/sinfo/flowdepth/FlowDepthExporter.java @ 8863:1009cab0f86b

Some work on flow depth exporter
author gernotbelger
date Fri, 19 Jan 2018 18:47:53 +0100
parents 7bbfb24e6eec
children 9f7a285b0ee3
line wrap: on
line source
/* Copyright (C) 2011, 2012, 2013 by Bundesanstalt für Gewässerkunde
 * Software engineering by Intevation GmbH
 *
 * 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.sinfo.flowdepth;

import java.io.OutputStream;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
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.FLYS;
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.exports.AbstractExporter;
import org.dive4elements.river.model.River;
import org.dive4elements.river.model.Unit;

import au.com.bytecode.opencsv.CSVWriter;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;

/**
 * Generates different output formats (csv, pdf) of data that resulted from a flow depths computation.
 *
 * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a>
 * @author Gernot Belger
 */
// REMARK: must be public because its registered in generators.xml
public class FlowDepthExporter extends AbstractExporter {

    /** The log used in this exporter.*/
    private static Logger log = Logger.getLogger(FlowDepthExporter.class);

    private static final String CSV_KM_HEADER = "sinfo.export.flow_depth.csv.header.km";
    private static final String CSV_FLOWDEPTH_HEADER = "sinfo.export.flow_depth.csv.header.flowdepth";
    private static final String CSV_FLOWDEPTHTKH_HEADER = "sinfo.export.flow_depth.csv.header.flowdepthTkh";
    private static final String CSV_TKH_HEADER = "sinfo.export.flow_depth.csv.header.tkh";
    private static final String CSV_WATERLEVEL_HEADER = "sinfo.export.flow_depth.csv.header.waterlevel";
    private static final String CSV_DISCHARGE_HEADER = "sinfo.export.flow_depth.csv.header.discharge";
    private static final String CSV_LABEL_HEADER = "sinfo.export.flow_depth.csv.header.label";
    private static final String CSV_GAUGE_HEADER = "sinfo.export.flow_depth.csv.header.gauge";
    private static final String CSV_MEAN_BED_HEIGHT_HEADER = "sinfo.export.flow_depth.csv.header.mean_bed_height";
    private static final String CSV_MEAN_BED_HEIGHT_HEADER_SHORT = "sinfo.export.flow_depth.csv.header.mean_bed_height.short";
    private static final String CSV_SOUNDING_HEADER = "sinfo.export.flow_depth.csv.header.sounding";
    private static final String CSV_LOCATION_HEADER = "sinfo.export.flow_depth.csv.header.location";
    
    private static final String CSV_META_HEADER_RESULT =
        "sinfo.export.flow_depth.csv.meta.header.result";

    private static final String CSV_META_HEADER_RESULT_LABEL =
            "sinfo.export.flow_depth.csv.meta.header.result.label";
    
    private static final String CSV_META_VERSION =
    		"sinfo.export.flow_depth.csv.meta.version";

    private static final String CSV_META_VERSION_LABEL =
            "sinfo.export.flow_depth.csv.meta.version.label";
    
    private static final String CSV_META_USER =
    		"sinfo.export.flow_depth.csv.meta.user";
    
    private static final String CSV_META_USER_LABEL =
            "sinfo.export.flow_depth.csv.meta.user.label";
    
    private static final String CSV_META_CREATION =
        "sinfo.export.flow_depth.csv.meta.creation";

    private static final String CSV_META_CREATION_LABEL =
            "sinfo.export.flow_depth.csv.meta.creation.label";
    
    private static final String CSV_META_RIVER =
        "sinfo.export.flow_depth.csv.meta.river";

    private static final String CSV_META_RIVER_LABEL =
            "sinfo.export.flow_depth.csv.meta.river.label";
    
    private static final String CSV_META_HEADER_SOUNDING =
    		"sinfo.export.flow_depth.csv.meta.header.sounding";

    private static final String CSV_META_HEADER_WATERLEVEL =
    		"sinfo.export.flow_depth.csv.meta.header.waterlevel";

    private static final String CSV_META_RANGE =
            "sinfo.export.flow_depth.csv.meta.range";

    private static final String CSV_META_RANGE_LABEL =
            "sinfo.export.flow_depth.csv.meta.range.label";
    
    private static final String CSV_META_HEIGHT_UNIT_RIVER = "sinfo.export.flow_depth.csv.meta.height_unit.river";
    
    private static final String JASPER_FILE     = "/jasper/sinfo.flowdepth.jasper";

    private static final String UNIT_M = "m";

    private static final String UNIT_CM = "cm";

    private static final String UNIT_CUBIC_M = "m³/s";

    /** The storage that contains the current calculation result.*/
    private FlowDepthCalculationResults data = null;

	/**
	 * Formats header with unit
	 */
	private String msgUnit(final String key, String unit ) {
	    
	    final String msg = msg(key);
	    return String.format("%s [%s]", msg, unit);
    }
    
    @Override
    protected void addData(Object d) {
    	/* reset */
    	data = null;

        if (d instanceof CalculationResult) {

        	final Object dat = ((CalculationResult)d).getData();
        	if( dat != null )
        		data = (FlowDepthCalculationResults)dat;
        }
    }
    
    @Override
    protected void writeCSVData(CSVWriter writer) {
        log.info("FlowDepthExporter.writeCSVData");

        /* fetch calculation results */
        final FlowDepthCalculationResults results = data;

        final boolean useTkh = results.isUseTkh();
        final River river = results.getRiver();

        /* write as csv */
        writeCSVMeta(writer, results);
        writeCSVHeader(writer, river, useTkh);

        for (final FlowDepthCalculationResult result : results.getResults()) {
        	writeCSVFlowDepthResult(writer, result, useTkh);
		}
    }

    private void writeCSVFlowDepthResult(final CSVWriter writer, final FlowDepthCalculationResult result, final boolean useTkh) {
        final Collection<FlowDepthRow> rows = result.getRows();
        for (final FlowDepthRow flowDepthRow : rows) {
        	writeCSVFlowDepthRow(writer, flowDepthRow, useTkh);
		}
	}

	private void writeCSVMeta(final CSVWriter writer, final FlowDepthCalculationResults results) {
        log.info("FlowDepthExporter.writeCSVMeta");

        final String calcModeLabel = results.getCalcModeLabel();
        final River river = results.getRiver();
        writeCSVMetaEntry(writer, CSV_META_HEADER_RESULT, msg( CSV_META_HEADER_RESULT_LABEL ), river.getName(), calcModeLabel );

		// "# FLYS-Version: "
        writeCSVMetaEntry(writer, CSV_META_VERSION, msg( CSV_META_VERSION_LABEL ), FLYS.VERSION );

		// "# Bearbeiter: "
        writeCSVMetaEntry(writer, CSV_META_USER, msg( CSV_META_USER_LABEL ), results.getUser() );

        // "# Datum der Erstellung: "
        final Locale locale = Resources.getLocale(context.getMeta());
        final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        writeCSVMetaEntry(writer, CSV_META_CREATION, msg( CSV_META_CREATION_LABEL ), df.format(new Date()) );

        // "# Gewässer: "
        writeCSVMetaEntry(writer, CSV_META_RIVER, msg( CSV_META_RIVER_LABEL ), river.getName() );

        // "# Höhensystem des Flusses: "
        final Unit wstUnit = river.getWstUnit();
        writeCSVMetaEntry(writer, CSV_META_HEIGHT_UNIT_RIVER, wstUnit.getName());

        // "# Ort/Bereich (km): "
        writeCSVMetaEntry(writer, CSV_META_RANGE, msg( CSV_META_RANGE_LABEL ), getKmFormatter().format(results.getFrom() ), getKmFormatter().format( results.getTo()));

        // "##METADATEN PEILUNG"
        writeCSVMetaEntry(writer, CSV_META_HEADER_SOUNDING );

        // FIXME: check: macht nicht viel sinn da es mehrere geben kann.. oder immer wieder wiederholen?
//        "# Jahr der Peilung: "
        // FIXME
//        "# Aufnahmeart: "
        // FIXME
//        "# Lagesystem: "
        // FIXME
//        "# Höhensystem: "
        // FIXME
//        "# ursprüngliches Höhensystem: "
        // FIXME
//        "##METADATEN WASSERSPIEGELLAGE"
        writeCSVMetaEntry(writer, CSV_META_HEADER_WATERLEVEL );
//        "# Bezeichnung der Wasserspiegellage: "
        // FIXME
//        "# Höhensystem der Wasserspiegellage: "
        // FIXME
//        "# Auswerter: "
        // FIXME
//        "# Bezugspegel: "
        // FIXME
//        "# Jahr/Zeitraum der Wasserspiegellage: "
        // FIXME

        // "# W/Pegel [cm]: " (nur bei Eingabe des Wasserstands am Pegel)
        // TODO: unklar, es wird kein W eingegeben

        // "# Q (m³/s): " (nur bei Eingabe des Durchflusses)        
        // TODO: unklar, es wird kein Q eingegeben

        writer.writeNext(new String[] { "" });
    }


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

        CallMeta meta = context.getMeta();

        writer.writeNext(new String[] {
                Resources.getMsg(
                    meta,
                    message,
                    message,
                    messageArgs)
            });		
    }
    
	/**
     * Write the header, with different headings depending on whether at a
     * gauge or at a location.
	 * @param river 
	 * @param useTkh 
     */
    private void writeCSVHeader(
        final CSVWriter writer,
        final River river, 
        final boolean useTkh
    ) {
        log.info("FlowDepthExporter.writeCSVHeader");

        final Collection<String> header = new ArrayList<>(11);
        
        header.add(msg(CSV_KM_HEADER));
        header.add(msgUnit(CSV_FLOWDEPTH_HEADER, UNIT_M));
        if( useTkh )
        {
        	header.add(msgUnit(CSV_FLOWDEPTHTKH_HEADER, UNIT_M));
        	header.add(msgUnit(CSV_TKH_HEADER, UNIT_CM));
        }

        final String wstUnitName = river.getWstUnit().getName();
        header.add(msgUnit(CSV_WATERLEVEL_HEADER, wstUnitName));
        header.add(msgUnit(CSV_DISCHARGE_HEADER, UNIT_CUBIC_M));
        header.add(msg(CSV_LABEL_HEADER));
        header.add(msg(CSV_GAUGE_HEADER));
        header.add(msgUnit(CSV_MEAN_BED_HEIGHT_HEADER, wstUnitName));
        header.add(msg(CSV_SOUNDING_HEADER));
        header.add(msg(CSV_LOCATION_HEADER));

       writer.writeNext(header.toArray(new String[header.size()]));
    }

    /**
     * Format a row of a flow depth result into an array of string, both used by csv and pdf
     * @param useTkh 
     */
    private String[] formatFlowDepthRow(
    		final FlowDepthRow row, 
    		boolean useTkh ) {

    	final Collection<String> lines = new ArrayList<>(11);
    	
    	// Fluss-km
    	lines.add( getKmFormatter().format( row.getStation() ) );
    	
    	// Fließtiefe [m]
    	lines.add( getFlowDepthFormatter().format( row.getFlowDepth() ) );
    	
    	if( useTkh )
    	{
    		// Fließtiefe mit TKH [m]
    		lines.add( getFlowDepthFormatter().format( row.getFlowDepthWithTkh() ) );
    		
    		// TKH [cm]
    		lines.add( getTkhFormatter().format( row.getTkh() ) );
    	}
    	
    	// Wasserstand [NN + m]
    	lines.add( getW2Formatter().format( row.getWaterlevel() ) );
    	
    	// Q [m³/s]
    	lines.add( getQFormatter().format( row.getDischarge() ) );
    	
    	// Bezeichnung
    	lines.add( row.getWaterlevelLabel() );
    	
    	// Bezugspegel
    	lines.add( row.getGauge() );
    	
    	// Mittlere Sohlhöhe [NN + m]
    	lines.add( getMeanBedHeighFormatter().format( row.getMeanBedHeight( ) ) );
    	
    	// Peilung/Epoche
    	lines.add( row.getSoundageLabel() );

    	// Lage
    	lines.add( row.getLocation() );
    	
    	return lines.toArray(new String[lines.size()]);
    }
    /**
     * Write "rows" of csv data from wqkms with writer.
     * @param useTkh 
     */
    private void writeCSVFlowDepthRow(
        final CSVWriter writer,
        final FlowDepthRow row, 
        final boolean useTkh
    ) {
        log.debug("FlowDepthExporter.writeCSVFlowDepthRow");

        final String[] formattedRow = formatFlowDepthRow(row, useTkh);
        writer.writeNext( formattedRow );
    }

	@Override
    protected void writePDF(OutputStream outStream) {
        log.debug("write PDF");
        
        final JRDataSource source = 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 {
            final JasperPrint print = JasperFillManager.fillReport(
                confPath + JASPER_FILE,
                parameters,
                source);
            JasperExportManager.exportReportToPdfStream(print, outStream);
        }
        catch(JRException je) {
            log.warn("Error generating PDF Report!", je);
        }
    }

    private JRDataSource createJRData() {
    	
        /* fetch calculation results */
        final FlowDepthCalculationResults results = data;
    	
    	final MetaAndTableJRDataSource source = new MetaAndTableJRDataSource();
    	
        addJRMetaData(source, results);

        final boolean useTkh = results.isUseTkh();
        
        for (final FlowDepthCalculationResult result : results.getResults()) {
			addJRTableData(source, result, useTkh);
		}

        return source;
    }

	private void addJRMetaData(final MetaAndTableJRDataSource source, FlowDepthCalculationResults results) {

	    final River river = results.getRiver();
	    final String wstUnitName = river.getWstUnit().getName();

	    /* general metadata */
	    source.addMetaData("header", msg(CSV_META_HEADER_RESULT_LABEL));
	    source.addMetaData("calcMode", results.getCalcModeLabel());

	    source.addMetaData("version_label", msg(CSV_META_VERSION_LABEL));
        source.addMetaData("version", FLYS.VERSION);

        source.addMetaData("user_label", msg(CSV_META_USER_LABEL));
        source.addMetaData("user", results.getUser());
        
        final Locale locale = Resources.getLocale(context.getMeta());
        final DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, locale);
        source.addMetaData("date_label", msg(CSV_META_CREATION_LABEL));
        source.addMetaData("date", df.format(new Date()));

        source.addMetaData("river_label", msg(CSV_META_RIVER_LABEL) );
        source.addMetaData("river", river.getName());

        final String rangeValue = String.format( "%s - %s", getKmFormatter().format(results.getFrom() ), getKmFormatter().format( results.getTo()));
        source.addMetaData("range_label", msg(CSV_META_RANGE_LABEL));
        source.addMetaData("range", rangeValue);

        /* column headings */
        source.addMetaData("station_header", msg(CSV_KM_HEADER));
        source.addMetaData("flowdepth_header", msg(CSV_FLOWDEPTH_HEADER));
        source.addMetaData("flowdepth_tkh_header", msg(CSV_FLOWDEPTHTKH_HEADER));
        source.addMetaData("tkh_header", msg(CSV_TKH_HEADER));
        source.addMetaData("waterlevel_header", msg(CSV_WATERLEVEL_HEADER));
        source.addMetaData("river_unit", wstUnitName);
        source.addMetaData("discharge_header", msg(CSV_DISCHARGE_HEADER));
        source.addMetaData("waterlevel_name_header", msg(CSV_LABEL_HEADER));
        source.addMetaData("gauge_header", msg(CSV_GAUGE_HEADER));
        source.addMetaData("bedheight_header", msg(CSV_MEAN_BED_HEIGHT_HEADER_SHORT));
        source.addMetaData("sounding_name_header", msg(CSV_SOUNDING_HEADER));
        source.addMetaData("location_header", msg(CSV_LOCATION_HEADER));
    }

    private void addJRTableData(final MetaAndTableJRDataSource source, final FlowDepthCalculationResult result, final boolean useTkh) {
    	
    	final Collection<FlowDepthRow> rows = result.getRows();

    	for (final FlowDepthRow row : rows) {
    		
    		final String[] formattedRow = formatFlowDepthRow(row, useTkh);
    		source.addData(formattedRow);
		}
	}
}

http://dive4elements.wald.intevation.org