view gnv-artifacts/src/main/java/de/intevation/gnv/state/profile/horizontal/HorizontalProfileOutputState.java @ 1115:f953c9a559d8

Added license file and license headers. gnv-artifacts/trunk@1260 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Ingo Weinzierl <ingo.weinzierl@intevation.de>
date Tue, 02 Nov 2010 17:46:55 +0000
parents e26935963871
children
line wrap: on
line source
/*
 * Copyright (c) 2010 by Intevation GmbH
 *
 * This program is free software under the LGPL (>=v2.1)
 * Read the file LGPL.txt coming with the software for details
 * or visit http://www.gnu.org/licenses/ if it does not exist.
 */

package de.intevation.gnv.state.profile.horizontal;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.jfree.chart.ChartTheme;

import de.intevation.artifacts.CallContext;
import de.intevation.gnv.artifacts.ressource.RessourceFactory;
import de.intevation.gnv.chart.Chart;
import de.intevation.gnv.chart.ChartLabels;
import de.intevation.gnv.chart.HorizontalProfileChart;
import de.intevation.gnv.exports.DefaultExport;
import de.intevation.gnv.exports.DefaultProfile;
import de.intevation.gnv.exports.ShapeDataCollector;
import de.intevation.gnv.exports.Export.Profile;
import de.intevation.gnv.geobackend.base.Result;
import de.intevation.gnv.state.InputData;
import de.intevation.gnv.state.State;
import de.intevation.gnv.state.describedata.KeyValueDescibeData;
import de.intevation.gnv.state.exception.StateException;
import de.intevation.gnv.state.timeseries.TimeSeriesOutputState;
import de.intevation.gnv.statistics.HorizontalProfileStatistics;
import de.intevation.gnv.statistics.Statistics;

/**
 * This <code>OutputState</code> is used for 'Horizontalprofile' products.
 *
 * @author <a href="mailto:tim.englich@intevation.de">Tim Englich</a>
 * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a>
 */
public class HorizontalProfileOutputState
extends      TimeSeriesOutputState
{
    public static final String [] HORIZONTAL_PROFILE_MESH_COLUMNS = {
        "SHAPE",
        "YORDINATE",
        "GROUP1",
        "MESHID"
    };

    public static final String [] HORIZONTAL_PROFILE_MEASUREMENT_COLUMNS = {
        "SHAPE",
        "YORDINATE",
        "GROUP1",
        "SURVEYID"
    };


    public static final String [] HORIZONTAL_MESH_CSV_COLUMN_LABEL = {
        "Longitude",
        "Latitude",
        "Value",
        "ParameterID",
        "MeshID"
    };


    public static final String [] HORIZONTAL_MEASUREMENT_CSV_COLUMN_LABEL = {
        "Longitude",
        "Latitude",
        "Value",
        "ParameterID",
        "SurveyID"
    };

    /**
     * The UID of this class
     */
    private static final long serialVersionUID = 4401516087492028840L;

    private static Logger log = Logger
    .getLogger(HorizontalProfileOutputState.class);

    public static final String DATE_FORMAT = "yyyy.MM.dd HH:mm:ss";

    public static final String [] CHART_TITLE_META = {
        "CRUISE",
        "DEPTH",
        "SHAPE"
    };


    public static final String [] CHART_TITLE_META_RESSOURCES = {
        "cruiseid",
        "depth",
        "coordinate"
    };

    public static final String [] TIMESERIES_CSV_PROFILE_NAMES = {
        "SHAPE",
        "YORDINATE",
        "GROUP1",
        "GROUP2",
        "GROUP3"
    };

    public static final Profile TIMESERIES_CSV_PROFILE =
        new DefaultProfile(
            null,
            ',',
            '"',
            '"',
            "CSV",
            "ISO-8859-1");

    /**
     * Constructor
     */
    public HorizontalProfileOutputState() {
        super();
        super.domainLable = "chart.horizontalprofile.title.xaxis";
    }


    /**
     * This method creates a chart and returns it.
     *
     * @param chartLables Labels used to decorate the chart.
     * @param theme The theme used to adjust the look of the chart.
     * @param parameters A collection with parameters this chart contains.
     * @param measurements A collection with measurement this chart contains.
     * @param dates A collection with dates this chart contains.
     * @param result The data collection used to be displayed in this chart.
     * @param locale The Locale used to determine the language.
     * @param uuid The uuid of the current artifact.
     * @param linesVisible A boolean property to determine the visibility of
     * lines connecting two points in a chart (not used in this chart type).
     * @param shapesVisible A boolean property to determine the visiblity of
     * datapoints in this chart (not used in this chart type).
     * @param callContext The CallContext object.
     * @return a <code>HorizontalProfileChart</code>.
     */
    @Override
    protected Chart getChart(
        ChartLabels  chartLables,
        ChartTheme   theme,
        Collection   parameters,
        Collection   measurements,
        Collection   dates,
        Object       result,
        Locale       locale,
        String       uuid,
        boolean      linesVisible,
        boolean      shapesVisible,
        CallContext  callContext
    ) {
        Chart chart = null;

        if (CACHE_CHART) {
            log.info("Try to get horizontalprofile chart from cache.");
            chart = (Chart) getChartFromCache(uuid, callContext);
        }

        if (chart != null)
            return chart;

        log.info("Chart not in cache yet.");
        chart = new HorizontalProfileChart(
            chartLables,
            theme,
            parameters,
            measurements,
            dates,
            (Collection)result,
            null,
            locale,
            linesVisible,
            shapesVisible
        );
        chart.generateChart();

        if (CACHE_CHART) {
            log.info("Put chart into cache.");
            purifyChart(chart, uuid);
        }

        return chart;
    }


    @Override
    protected Statistics getStatisticsGenerator() {
        return new HorizontalProfileStatistics();
    }


    @Override
    protected void createCSV(OutputStream out, Collection<Result> results)
    throws UnsupportedEncodingException, IOException, StateException
    {
        log.debug("Create csv export for horizontal profiles.");
        Iterator iter = results.iterator();
        Result   res  = iter.hasNext() ? (Result) iter.next() : null;

        if (res == null)
            return;

        Profile profile = null;
        int     dataid  = res.getInteger("DATAID").intValue();
        DefaultExport export = null;
        // on meshes
        if (dataid == 2) {
            profile =  new DefaultProfile(
                HORIZONTAL_MESH_CSV_COLUMN_LABEL,
                ',',
                '"',
                '"',
                "CSV",
                "ISO-8859-1");
            export = new DefaultExport(
                    new ShapeDataCollector(HORIZONTAL_PROFILE_MESH_COLUMNS));
        }

        // on measurements
        else {
            profile =  new DefaultProfile(
                HORIZONTAL_MEASUREMENT_CSV_COLUMN_LABEL,
                ',',
                '"',
                '"',
                "CSV",
                "ISO-8859-1");
            export = new DefaultExport(
                    new ShapeDataCollector(HORIZONTAL_PROFILE_MEASUREMENT_COLUMNS));
        }


        export.create(profile, out, results);
    }


    /**
     * Creates and returns the chart title.
     *
     * @param locale The Locale used to adjust the language of the title.
     * @param uuid The UUID of the current artifact.
     * @return the name of the selected fis.
     */
    @Override
    protected String createChartTitle(Locale locale, String uuid) {
        String fisName = getFisName(locale);
        log.debug("created title for horizontal profile chart: " + fisName);

        return fisName;
    }


    @Override
    protected String createChartSubtitle(Locale locale, String uuid) {
        log.debug("Create subtitle for horizontalprofile chart on meshes.");

        StringBuilder sb  = new StringBuilder();
        String ship       = getData(locale, "vehicleid");
        if (ship != null) {
            sb.append(ship);
        }

        String cruise = getData(locale, "cruiseid");
        if (cruise != null) {
            if (ship != null)
                sb.append("\n");

            sb.append(cruise);
        }

        String track = getData(locale, "trackid");
        if (track != null) {
            if (cruise != null)
                sb.append("\n");

            sb.append(track);
        }

        return sb.toString();
    }


    protected String getData(Locale locale, String data) {
        InputData input = null;

        State parent = this;
        do {
            input = inputData.get(data);

            if (input != null)
                break;
        }
        while ((parent = parent.getParent()) != null);

        if (input == null) {
            log.warn("No data found for: " + data);
           return null;
        }

        String value = input.getDescription(input.getValue());
        String title = RessourceFactory.getInstance().getRessource(
            locale, data, data);

        return (title + ": " + value);
    }


    /**
     * Creates a timeperiod taking account for all data items used in charts.
     *
     * @param locale The Locale used to adjust the language of the subtitle.
     * @param uuid The UUID of the current artifact.
     * @return a human readable timeperiod.
     */
    protected String createTimePeriod(Locale locale, String uuid) {
        log.debug("create time period for chart subtitle.");
        String subTitle = null;
        Date startDate  = null;
        Date endDate    = null;

        Collection          dates  = getDates(uuid);
        if (dates == null) {
            log.debug("No time period for subtitle.");
            return "";
        }

        SimpleDateFormat    format = new SimpleDateFormat(DATE_FORMAT);
        KeyValueDescibeData data   = null;

        Iterator iter = dates.iterator();
        while (iter.hasNext()) {
            try {
                data = (KeyValueDescibeData)iter.next();

                if (!data.isSelected())
                    continue;

                Date current = format.parse(data.getValue());
                long time    = current.getTime();

                if (startDate == null) {
                    startDate = current;
                    endDate   = current;
                }
                else if (time < startDate.getTime()) {
                    startDate = current;
                }
                else if (time > endDate.getTime()) {
                    endDate = current;
                }
            }
            catch (ParseException pe) {
                log.warn("Error while parsing date: " + data.getValue(), pe);
            }
        }

        if (startDate != null && endDate != null)
            subTitle = format.format(startDate)+" - "+format.format(endDate);

        subTitle = subTitle == null ? "" : subTitle;

        log.debug("created title for horizontal profile chart: " + subTitle);

        return subTitle;
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org