view gnv-artifacts/src/main/java/de/intevation/gnv/state/profile/horizontalcrosssection/HorizontalCrossSectionMeshOutputState.java @ 474:ab29e4ff2fda

Added area interpolation needed for "Horizontalschnitt" gnv-artifacts/trunk@540 c6561f87-3c4e-4783-a992-168aeb5c3f6f
author Sascha L. Teichmann <sascha.teichmann@intevation.de>
date Thu, 14 Jan 2010 10:34:05 +0000
parents 06887e2e3f7a
children 211cad2fb5ba
line wrap: on
line source
/**
 *
 */
package de.intevation.gnv.state.profile.horizontalcrosssection;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import org.apache.log4j.Logger;

import org.jfree.chart.ChartTheme;

import org.w3c.dom.Node;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Envelope;
import com.vividsolutions.jts.geom.Polygon;

import au.com.bytecode.opencsv.CSVWriter;

import de.intevation.gnv.artifacts.cache.CacheFactory;
import de.intevation.gnv.artifacts.context.GNVArtifactContext;

import de.intevation.gnv.chart.Chart;
import de.intevation.gnv.chart.ChartLabels;

import de.intevation.gnv.geobackend.base.Result;

import de.intevation.gnv.geobackend.base.query.QueryExecutor;
import de.intevation.gnv.geobackend.base.query.QueryExecutorFactory;
import de.intevation.gnv.geobackend.base.query.exception.QueryException;

import de.intevation.gnv.state.InputData;

import de.intevation.gnv.state.exception.StateException;

import de.intevation.gnv.state.timeseries.TimeSeriesOutputState;

import de.intevation.gnv.statistics.Statistics;

import de.intevation.gnv.utils.StringUtils;
import de.intevation.gnv.utils.WKTUtils;

import de.intevation.artifactdatabase.Config;

import de.intevation.artifacts.CallContext;

import de.intevation.gnv.geobackend.sde.datasources.RasterObject;

/**
 * @author Tim Englich         (tim.englich@intevation.de)
 * @author Sascha L. Teichmann (sascha.teichmann@intevation.de)
 */
public class HorizontalCrossSectionMeshOutputState 
extends      TimeSeriesOutputState
{
    private static Logger log = Logger
        .getLogger(HorizontalCrossSectionMeshOutputState.class);
    
    /**
     * The UID of this Class
     */
    private static final long serialVersionUID = 3233620652465061860L;
    
    private String ijkQueryID = null;

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

    @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 horizontalcrosssection chart from cache.");
            chart = (Chart) getChartFromCache(uuid, callContext);
        }

        if (chart != null)
            return chart;

        log.info("Chart not in cache yet.");
        
        log.warn("This sort of chart is not implemented yet.");
        
        InputData meshPolygon = inputData.get("mesh_polygon");
        String meshPolygonWkt = null;
        if (meshPolygon != null){
            meshPolygonWkt = meshPolygon.getValue();
            
        }
        log.debug("Used Polygon: "+meshPolygonWkt);

        return chart;
    }
    
    /**
     * @see de.intevation.gnv.state.OutputStateBase#getChartResult(java.lang.String, de.intevation.artifacts.CallContext)
     */
    @Override
    protected Object getChartResult(String uuid, CallContext callContext) {
        log.debug("HorizontalProfileMeshCrossOutputState.getChartResult");
        Collection<Result> result = null;
        if (CacheFactory.getInstance().isInitialized()) {
            String key = uuid + super.getID();
            log.debug("Hash for Queryelements: " + key);
            net.sf.ehcache.Element value = CacheFactory.getInstance().getCache().get(key);
            if (value != null) {
                result = (Collection<Result>) (value.getObjectValue());
            }else{

                InputData meshPolygon = inputData.get("mesh_polygon");
                InputData meshId   = inputData.get("meshid");

                if (meshPolygon == null) {
                    log.error("mesh_polygon is not defined");
                    throw new IllegalStateException("missing mesh_linestring");
                }

                if (meshId == null) {
                    log.error("meshid is not defined");
                    throw new IllegalStateException("missing meshid");
                }

                Polygon p = WKTUtils.toPolygon(meshPolygon.getValue());

                if (p == null) {
                    log.error("no valid polygon");
                    throw new IllegalStateException("no valid polygon");
                }

                try {
                    Envelope env  = p.getEnvelopeInternal();

                    Coordinate [] coords = new Coordinate [] {
                        new Coordinate(env.getMinX(), env.getMinY()),
                        new Coordinate(env.getMinX(), env.getMaxY()),
                        new Coordinate(env.getMaxX(), env.getMaxY()),
                        new Coordinate(env.getMaxX(), env.getMinY()) };

                    String additionWhere =
                        WKTUtils.worldEnvelopeCoordinatesToIndex(
                            coords,
                            result,
                            meshId.getValue(),
                            ijkQueryID);

                    String[] addedFilterValues = StringUtils.append(
                        generateFilterValuesFromInputData(),
                        additionWhere);

                    QueryExecutor queryExecutor = QueryExecutorFactory
                        .getInstance()
                        .getQueryExecutor();

                    result = process(
                        Arrays.asList(coords),
                        numSamples(callContext),
                        queryExecutor.executeQuery(
                            queryID,
                            addedFilterValues),
                            p);
                }
                catch (QueryException e) {
                    log.error(e,e);
                }

                if (CacheFactory.getInstance().isInitialized()) {
                    CacheFactory.getInstance().getCache().put(new net.sf.ehcache.Element(key, result));
                }
            }
        }
        return result;
    }
    
    public static Collection<Result> process(
            List<Coordinate>   path,
            int                numSamples,
            Collection<Result> input,
            Polygon polygon
        ) {
        // TODO: IMPLEMENT ME INTEGRATE POLYGONCLIPPING
        return null;
    }

    /**
     * @see de.intevation.gnv.state.timeseries.TimeSeriesOutputState#getStatisticsGenerator()
     */
    @Override
    protected Statistics getStatisticsGenerator() {
        return null; //Statistics are not supported for this kind of OutputState.
    }
    
    /**
     * @see de.intevation.gnv.state.timeseries.TimeSeriesOutputState#createCSV(java.io.OutputStream,
     *      java.util.Collection)
     */
    @Override
    protected void createCSV(
        OutputStream       outputStream,
        Collection<Result> chartResult
    ) throws UnsupportedEncodingException, IOException, StateException 
    {
        /*
        if (chartResult != null) {
            try {
                CSVWriter writer = new CSVWriter(new OutputStreamWriter(
                        outputStream, "ISO-8859-1"), ','); 
                // USE THIS ENCODING BECAUSE OF
                // PROBLEMS WITH EXCEL AND UTF-8
                Iterator<Result> it = chartResult.iterator();
                while (it.hasNext()) {
                    Result result = it.next();
                    int i = 0;
                    String[] entries = new String[5];
                    entries[i++] = result.getString("SHAPE");
                    entries[i++] = result.getString("YORDINATE");
                    entries[i++] = result.getString("IPOSITION");
                    entries[i++] = result.getString("JPOSITION");
                    entries[i++] = result.getString("KPOSITION");
                    writer.writeNext(entries);
                }
                writer.close();
            } catch (Exception e) {
                log.error(e,e);
                throw new StateException(
                "Exception occured while parsing an Point from WKT.");
            }
        } else {
            log.error("No Data given for generating an CSV-File.");
            throw new StateException(
                    "No Data given for generating an CSV-File.");
        }
        */
    }
    
    /**
     * @see de.intevation.gnv.state.timeseries.TimeSeriesOutputState#setup(org.w3c.dom.Node)
     */
    @Override
    public void setup(Node configuration) {
        super.setup(configuration);
        this.ijkQueryID = Config.getStringXPath(configuration,"queryID-ijk");
        
    }
    
    private static int numSamples(CallContext callContext) {
        GNVArtifactContext context =
            (GNVArtifactContext)callContext.globalContext();
        Integer samples = (Integer)context.get(
            GNVArtifactContext.HORIZONTAL_CROSS_SECTION_SAMPLES_KEY);
        return samples != null
            ? samples.intValue()
            : GNVArtifactContext.DEFAULT_HORIZONTAL_CROSS_SECTION_SAMPLES;
    }

    private static File shapefileDirectory(CallContext callContext) {
        GNVArtifactContext context =
            (GNVArtifactContext)callContext.globalContext();
        File dir = (File)context.get(
            GNVArtifactContext.HORIZONTAL_CROSS_SECTION_RESULT_SHAPEFILE_PATH_KEY);
        return dir != null
            ? dir
            : GNVArtifactContext.DEFAULT_HORIZONTAL_CROSS_SECTION_PROFILE_SHAPEFILE_PATH;
    }

    private static int getGroundInterpolation(CallContext callContext) {
        GNVArtifactContext context = 
            (GNVArtifactContext)callContext.globalContext();

        String interpolation = (String)context.get(
            GNVArtifactContext.HORIZONTAL_CROSS_SECTION_GROUND_INTERPOLATION_KEY);

        return RasterObject.getInterpolationType(interpolation);
    }
}
// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org