changeset 5379:61bf64b102bc mapgenfix

Merge with default branch
author Christian Lins <christian.lins@intevation.de>
date Fri, 22 Mar 2013 11:25:54 +0100
parents cfc5540a4eec (diff) 02f6741f80d4 (current diff)
children
files contrib/make_flys_release/confs/artifact-db.xml contrib/make_flys_release/confs/backend-db.xml contrib/make_flys_release/confs/datacage-db.xml contrib/make_flys_release/confs/floodmap.xml contrib/make_flys_release/confs/mapserver/fontset.txt contrib/make_flys_release/confs/rest-server.xml contrib/make_flys_release/confs/rivermap.xml contrib/make_flys_release/confs/seddb-db.xml contrib/make_flys_release/h2/artifacts-h2.sql contrib/make_flys_release/h2/datacage.sql contrib/make_flys_release/libs_oracle/ojdbc5.jar flys-artifacts/doc/conf/conf.xml flys-artifacts/src/main/java/de/intevation/flys/artifacts/WMSCatchmentArtifact.java flys-artifacts/src/main/java/de/intevation/flys/artifacts/WMSHwsArtifact.java flys-artifacts/src/main/java/de/intevation/flys/artifacts/states/FloodMapState.java flys-artifacts/src/main/java/de/intevation/flys/mapserver/RiverMapfileGenerator.java flys-artifacts/src/main/java/de/intevation/flys/wsplgen/FacetCreator.java flys-backend/contrib/hws_schema.diff flys-backend/contrib/import-gew.py flys-backend/contrib/import-kms.py flys-backend/contrib/shpimporter/catchments.py flys-backend/contrib/shpimporter/lines.py flys-backend/doc/schema/import-dems.sql flys-backend/src/main/java/de/intevation/flys/importer/ImportWaterlevel.java flys-backend/src/main/java/de/intevation/flys/importer/ImportWaterlevelDifference.java flys-backend/src/main/java/de/intevation/flys/importer/ImportWaterlevelDifferenceColumn.java flys-backend/src/main/java/de/intevation/flys/importer/ImportWaterlevelDifferenceValue.java flys-backend/src/main/java/de/intevation/flys/importer/ImportWaterlevelQRange.java flys-backend/src/main/java/de/intevation/flys/importer/ImportWaterlevelValue.java flys-backend/src/main/java/de/intevation/flys/model/Catchment.java flys-backend/src/main/java/de/intevation/flys/model/Hws.java flys-backend/src/main/java/de/intevation/flys/model/Line.java flys-backend/src/main/java/de/intevation/flys/model/Waterlevel.java flys-backend/src/main/java/de/intevation/flys/model/WaterlevelDifference.java flys-backend/src/main/java/de/intevation/flys/model/WaterlevelDifferenceColumn.java flys-backend/src/main/java/de/intevation/flys/model/WaterlevelDifferenceValue.java flys-backend/src/main/java/de/intevation/flys/model/WaterlevelQRange.java flys-backend/src/main/java/de/intevation/flys/model/WaterlevelValue.java flys-backend/src/main/java/de/intevation/flys/utils/DgmSqlConverter.java flys-client/src/main/webapp/images/arrow_down.png flys-client/src/main/webapp/images/arrow_first.png flys-client/src/main/webapp/images/arrow_last.png flys-client/src/main/webapp/images/arrow_up.png
diffstat 15 files changed, 1223 insertions(+), 258 deletions(-) [+]
line wrap: on
line diff
--- a/flys-artifacts/doc/conf/conf.xml	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/doc/conf/conf.xml	Fri Mar 22 11:25:54 2013 +0100
@@ -222,7 +222,7 @@
     <lifetime-listeners>
         <listener>de.intevation.flys.artifacts.datacage.Datacage</listener>
         <listener>de.intevation.flys.wsplgen.SchedulerSetup</listener>
-        <listener>de.intevation.flys.artifacts.map.RiverMapfileGeneratorStarter</listener>
+        <listener>de.intevation.flys.mapserver.RiverMapfileGeneratorStarter</listener>
     </lifetime-listeners>
 
     <backend-listeners>
--- a/flys-artifacts/doc/conf/mapserver/layer.vm	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/doc/conf/mapserver/layer.vm	Fri Mar 22 11:25:54 2013 +0100
@@ -19,7 +19,8 @@
     END
 
     PROJECTION
-        "init=epsg:$LAYER.getSrid()"
+        #"init=epsg:$LAYER.getSrid()"
+        "init=epsg:31467"
     END
 
     #if ( !$LAYER.getStyle() )
--- a/flys-artifacts/doc/conf/mapserver/shapefile_layer.vm	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/doc/conf/mapserver/shapefile_layer.vm	Fri Mar 22 11:25:54 2013 +0100
@@ -11,7 +11,8 @@
     #end
 
     PROJECTION
-        "init=epsg:$LAYER.getSrid()"
+        #"init=epsg:$LAYER.getSrid()"
+        "init=epsg:31467"
     END
 
     METADATA
--- a/flys-artifacts/src/main/java/de/intevation/flys/artifacts/map/PrintMap.java	Thu Mar 21 10:49:38 2013 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,131 +0,0 @@
-package de.intevation.flys.artifacts.map;
-
-import java.awt.Color;
-import java.awt.Rectangle;
-
-import java.io.File;
-import java.io.IOException;
-
-import java.awt.Graphics2D;
-import java.awt.image.BufferedImage;
-
-import java.util.List;
-
-import java.net.URL;
-import java.net.MalformedURLException;
-
-import javax.imageio.ImageIO;
-
-
-import org.geotools.data.ows.Layer;
-import org.geotools.data.ows.WMSCapabilities;
-import org.geotools.data.wms.WebMapServer;
-import org.geotools.geometry.jts.ReferencedEnvelope;
-import org.geotools.map.MapContext;
-import org.geotools.map.WMSMapLayer;
-import org.geotools.ows.ServiceException;
-import org.geotools.renderer.lite.StreamingRenderer;
-import org.geotools.renderer.GTRenderer;
-
-
-public class PrintMap {
-
-    public static final String DEFAULT_WMS = "http://map1.naturschutz.rlp.de/service_lanis/mod_wms/wms_getmap.php?mapfile=group_gdide&REQUEST=GetCapabilities&SERVICE=WMS";
-    public static final String DEFAULT_OUTFILE = "~/map.jpeg";
-
-    public static final String MAPSERVER = System.getProperty("wms", DEFAULT_WMS);
-    public static final String MAP_IMAGE = System.getProperty("outfile", DEFAULT_OUTFILE);
-
-
-    public static void main(String[] args) {
-        System.out.println("-> start PrintMap");
-        System.out.println("  -> Print layers of WMS: " + MAPSERVER);
-
-        try {
-            WebMapServer    server = getMapserver();
-            WMSMapLayer[] wmsLayer = getWMSLayers(server);
-
-            MapContext mapcontent = new MapContext( wmsLayer );
-            mapcontent.setTitle(" NEW MAP CONTENT TITLE ");
-
-            printMap(mapcontent);
-        }
-        catch (Exception e) {
-            e.printStackTrace();
-        }
-
-        System.out.println("-> finished PrintMap");
-    }
-
-
-    public static void printMap(MapContext map) throws Exception {
-        int imageWidth = 600;
-
-        GTRenderer renderer = new StreamingRenderer();
-        renderer.setContext(map);
-
-        Rectangle imageBounds = null;
-        ReferencedEnvelope mapBounds = null;
-
-        try {
-            mapBounds = map.getLayerBounds();
-            double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
-            imageBounds = new Rectangle(
-                0, 0,
-                imageWidth,
-                (int) Math.round(imageWidth * heightToWidth));
-
-        }
-        catch (Exception e) {
-            // failed to access map layers
-            throw new RuntimeException(e);
-        }
-
-        BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);
-        Graphics2D gr = image.createGraphics();
-        gr.setPaint(Color.WHITE);
-        gr.fill(imageBounds);
-
-        try {
-            renderer.paint(gr, imageBounds, mapBounds);
-            File fileToSave = new File(MAP_IMAGE);
-            ImageIO.write(image, "jpeg", fileToSave);
-        }
-        catch (IOException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-
-    public static WebMapServer getMapserver() throws MalformedURLException, IOException, ServiceException {
-        return new WebMapServer(getServerUrl());
-    }
-
-
-    public static URL getServerUrl() throws MalformedURLException {
-        return new URL(MAPSERVER);
-    }
-
-
-    public static WMSMapLayer[] getWMSLayers(WebMapServer server) {
-        if (server == null) {
-            System.out.println("WebMapServer == null");
-            throw new RuntimeException("WebMapServer == null");
-        }
-
-        WMSCapabilities capabilities = server.getCapabilities();
-
-        List<Layer> layers = capabilities.getLayerList();
-        WMSMapLayer[] wmslayers = new WMSMapLayer[layers.size()];
-
-        for (int i = 0, L = layers.size(); i < L; i++) {
-            Layer l = layers.get(i);
-
-            System.out.println("   -> add layer: " + l);
-            wmslayers[i] = new WMSMapLayer(server, l);
-        }
-
-        return wmslayers;
-    }
-}
-// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-artifacts/src/main/java/de/intevation/flys/artifacts/map/RiverMapfileGeneratorStarter.java	Thu Mar 21 10:49:38 2013 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-package de.intevation.flys.artifacts.map;
-
-import de.intevation.artifactdatabase.LifetimeListener;
-import de.intevation.artifacts.GlobalContext;
-import de.intevation.flys.utils.RiverMapfileGenerator;
-
-import org.apache.log4j.Logger;
-import org.w3c.dom.Document;
-
-/**
- * LifetimeListener that creates a Mapfile containing river axis layers.
- * The listener is called when the server has completed its startup.
- *
- * @author <a href="mailto:christian.lins@intevation.de">Christian Lins</a>
- */
-public class RiverMapfileGeneratorStarter implements LifetimeListener {
-
-    private static Logger logger = Logger.getLogger(RiverMapfileGeneratorStarter.class);
-
-    @Override
-    public void setup(Document document) {
-        // Nothing to setup here
-    }
-
-    /**
-     * Calls RiverMapfileGenerator.generate().
-     */
-    @Override
-    public void systemUp(GlobalContext globalContext) {
-        logger.debug("systemUp()");
-
-        RiverMapfileGenerator fmfg = new RiverMapfileGenerator();
-        fmfg.generate();
-    }
-
-    @Override
-    public void systemDown(GlobalContext globalContext) {
-        // No, we're not cleaning up our generated mapfile
-    }
-
-}
--- a/flys-artifacts/src/main/java/de/intevation/flys/artifacts/services/FileUploadService.java	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/artifacts/services/FileUploadService.java	Fri Mar 22 11:25:54 2013 +0100
@@ -6,7 +6,9 @@
 import de.intevation.artifacts.common.utils.FileTools;
 import de.intevation.artifacts.common.utils.XMLUtils;
 import de.intevation.artifacts.common.utils.XMLUtils.ElementCreator;
+import de.intevation.flys.mapserver.ArtifactMapfileGenerator;
 import de.intevation.flys.utils.FLYSUtils;
+import de.intevation.flys.utils.FileUtils;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -60,14 +62,17 @@
                     FLYSUtils.XPATH_FLOODMAP_SHAPEFILE_DIR);
 
                 File artifactDir = FileTools.getDirectory(shapePath, uuid);
-                FileOutputStream fos =
-                    new FileOutputStream(
-                    new File(artifactDir, "user-rgd.zip"));
+                File archive = new File(artifactDir, "user-rgd.zip");
+                FileOutputStream fos = new FileOutputStream(archive);
                 try {
                     fos.write(fileData);
 
                     // Write operation successful
                     status.setTextContent("Upload erfolgreich!"); // TODO: i18n
+
+                    FileUtils.extractZipfile(archive, artifactDir);
+                    ArtifactMapfileGenerator amfg = new ArtifactMapfileGenerator();
+                    amfg.generate();
                 }
                 finally {
                     fos.close();
--- a/flys-artifacts/src/main/java/de/intevation/flys/artifacts/states/FloodMapState.java	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/artifacts/states/FloodMapState.java	Fri Mar 22 11:25:54 2013 +0100
@@ -1,54 +1,24 @@
 package de.intevation.flys.artifacts.states;
 
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import org.apache.log4j.Logger;
-
-import org.apache.velocity.Template;
-
-import org.geotools.feature.FeatureCollection;
-import org.geotools.feature.FeatureCollections;
-
-import org.geotools.feature.simple.SimpleFeatureBuilder;
-
-import org.hibernate.HibernateException;
-
-import org.opengis.feature.simple.SimpleFeature;
-import org.opengis.feature.simple.SimpleFeatureType;
-
 import com.vividsolutions.jts.geom.Coordinate;
 import com.vividsolutions.jts.geom.Geometry;
 import com.vividsolutions.jts.geom.LineString;
 import com.vividsolutions.jts.geom.Polygon;
 
 import de.intevation.artifactdatabase.state.Facet;
-
 import de.intevation.artifacts.Artifact;
 import de.intevation.artifacts.CallContext;
 import de.intevation.artifacts.CallMeta;
 import de.intevation.artifacts.GlobalContext;
-
 import de.intevation.artifacts.common.utils.FileTools;
-
 import de.intevation.flys.artifacts.FLYSArtifact;
-
 import de.intevation.flys.artifacts.access.RangeAccess;
-
 import de.intevation.flys.artifacts.context.FLYSContext;
-
 import de.intevation.flys.artifacts.model.CalculationMessage;
 import de.intevation.flys.artifacts.model.CalculationResult;
 import de.intevation.flys.artifacts.model.FacetTypes;
 import de.intevation.flys.artifacts.model.LayerInfo;
 import de.intevation.flys.artifacts.model.WQKms;
-
 import de.intevation.flys.artifacts.model.map.HWS;
 import de.intevation.flys.artifacts.model.map.HWSContainer;
 import de.intevation.flys.artifacts.model.map.HWSFactory;
@@ -56,31 +26,44 @@
 import de.intevation.flys.artifacts.model.map.WSPLGENCalculation;
 import de.intevation.flys.artifacts.model.map.WSPLGENJob;
 import de.intevation.flys.artifacts.model.map.WSPLGENReportFacet;
-
 import de.intevation.flys.artifacts.resources.Resources;
-
 import de.intevation.flys.exports.WstWriter;
-
+import de.intevation.flys.mapserver.ArtifactMapfileGenerator;
+import de.intevation.flys.mapserver.MapfileGenerator;
 import de.intevation.flys.model.CrossSectionTrack;
 import de.intevation.flys.model.DGM;
 import de.intevation.flys.model.Floodplain;
 import de.intevation.flys.model.RiverAxis;
-
-import de.intevation.flys.utils.ArtifactMapfileGenerator;
 import de.intevation.flys.utils.FLYSUtils;
+import de.intevation.flys.utils.FileUtils;
 import de.intevation.flys.utils.GeometryUtils;
-import de.intevation.flys.utils.MapfileGenerator;
-
 import de.intevation.flys.wsplgen.FacetCreator;
 import de.intevation.flys.wsplgen.JobObserver;
 import de.intevation.flys.wsplgen.Scheduler;
 
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.apache.velocity.Template;
+import org.geotools.feature.FeatureCollection;
+import org.geotools.feature.FeatureCollections;
+import org.geotools.feature.simple.SimpleFeatureBuilder;
+import org.hibernate.HibernateException;
+import org.opengis.feature.simple.SimpleFeature;
+import org.opengis.feature.simple.SimpleFeatureType;
+
 public class FloodMapState
 extends      DefaultState
 implements   FacetTypes
 {
     /** The logger that is used in this state. */
-    private static Logger logger = Logger.getLogger(FloodMapState.class);
+    public static Logger logger = Logger.getLogger(FloodMapState.class);
 
 
     public static final String KEEP_ARTIFACT_DIR =
@@ -173,10 +156,10 @@
                 List<String> layers = wms.getLayers();
 
                 for (String layer: layers) {
-                    if (layer.startsWith(MapfileGenerator.MS_WSPLGEN_PREFIX)) {
+                    if (layer.startsWith(MapfileGenerator.MS_PREFIX_WSPLGEN)) {
                         wms.removeLayer(layer);
 
-                        String newLayer = MapfileGenerator.MS_WSPLGEN_PREFIX +
+                        String newLayer = MapfileGenerator.MS_PREFIX_WSPLGEN +
                             owner.identifier();
 
                         wms.addLayer(newLayer);
@@ -644,6 +627,8 @@
         boolean exists = archive.exists();
         logger.debug("shp file exists: " + exists);
         if (exists) {
+            FileUtils.extractZipfile(archive, dir);
+
             job.addLin(dir + "/" + WSPLGEN_USER_SHAPE);
             facetCreator.createShapeFacet(FacetCreator.I18N_USERSHAPE,
                 MapfileGenerator.MS_LAYER_PREFIX + "user-rgd",
@@ -1011,8 +996,5 @@
             }
         }
     }
-
-
-
 }
 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :
--- a/flys-artifacts/src/main/java/de/intevation/flys/exports/MapGenerator.java	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/exports/MapGenerator.java	Fri Mar 22 11:25:54 2013 +0100
@@ -3,7 +3,6 @@
 import com.vividsolutions.jts.geom.Envelope;
 
 import de.intevation.artifactdatabase.state.ArtifactAndFacet;
-import de.intevation.artifactdatabase.state.Facet;
 import de.intevation.artifactdatabase.state.Settings;
 import de.intevation.artifacts.Artifact;
 import de.intevation.artifacts.CallContext;
@@ -12,11 +11,10 @@
 import de.intevation.artifacts.common.utils.XMLUtils.ElementCreator;
 import de.intevation.flys.artifacts.FLYSArtifact;
 import de.intevation.flys.artifacts.model.FacetTypes;
-import de.intevation.flys.artifacts.model.map.WMSDBLayerFacet;
 import de.intevation.flys.artifacts.model.map.WMSLayerFacet;
 import de.intevation.flys.artifacts.model.map.WSPLGENLayerFacet;
 import de.intevation.flys.collections.FLYSArtifactCollection;
-import de.intevation.flys.utils.ArtifactMapfileGenerator;
+import de.intevation.flys.mapserver.ArtifactMapfileGenerator;
 import de.intevation.flys.utils.GeometryUtils;
 import de.intevation.flys.utils.ThemeUtil;
 
@@ -37,26 +35,17 @@
     private static Logger logger = Logger.getLogger(MapGenerator.class);
 
     protected FLYSArtifactCollection collection;
-
     protected Artifact master;
-
     protected Settings settings;
-
     protected Document request;
-
     protected OutputStream out;
-
     protected CallContext context;
-
     protected List<WMSLayerFacet> layers;
-
     protected Envelope maxExtent;
     protected Envelope initialExtent;
-
     protected String srid;
 
 
-
     @Override
     public void init(Document request, OutputStream out, CallContext context) {
         logger.debug("MapGenerator.init");
@@ -94,7 +83,7 @@
         logger.debug("MapGenerator.doOut: " +
             artifactFacet.getArtifact().identifier() + " | " + name);
         FLYSArtifact flys = (FLYSArtifact) artifactFacet.getArtifact();
-
+        /*
         Facet nativeFacet = artifactFacet.getFacet();
 
         if (nativeFacet instanceof WMSLayerFacet) {
@@ -123,6 +112,13 @@
         }
         else {
             logger.warn("Facet not supported: " + nativeFacet.getClass());
+        }*/
+        ArtifactMapfileGenerator amfg = new ArtifactMapfileGenerator();
+        try {
+            amfg.generate(ThemeUtil.createDynamicMapserverStyle(attr), context, flys);
+        }
+        catch (IOException e) {
+            logger.error(e.getMessage(), e);
         }
     }
 
@@ -132,29 +128,29 @@
         WMSLayerFacet wms,
         Document      attr
     ) {
-        try {
+        //try {
             if(wms instanceof WSPLGENLayerFacet) {
                 ArtifactMapfileGenerator mfg = new ArtifactMapfileGenerator();
-                mfg.createUeskLayer(
+               /* mfg.createUeskLayer(
                     flys,
                     (WSPLGENLayerFacet) wms,
                     ThemeUtil.createDynamicMapserverStyle(attr),
-                    context);
+                    context);*/
             }
             else {
                 logger.warn("Cannot create WSPLGEN layer from: " +
                             wms.getClass());
             }
-        }
-        catch (IOException ioe) {
+        //}
+        /*catch (IOException ioe) {
             logger.error(ioe, ioe);
-        }
+        }*/
     }
 
 
     protected void createBarriersLayer(FLYSArtifact flys, WMSLayerFacet wms) {
         ArtifactMapfileGenerator mfg = new ArtifactMapfileGenerator();
-
+/*
         try {
             mfg.createBarriersLayer(flys, wms);
         }
@@ -163,13 +159,13 @@
         }
         catch (IOException ioe) {
             logger.error(ioe, ioe);
-        }
+        }*/ // FIXME
     }
 
 
     protected void createUserShapeLayer(FLYSArtifact flys, WMSLayerFacet wms) {
         ArtifactMapfileGenerator mfg = new ArtifactMapfileGenerator();
-
+/*
         try {
             mfg.createUserShapeLayer(flys, wms);
         }
@@ -178,7 +174,7 @@
         }
         catch (IOException ioe) {
             logger.error(ioe, ioe);
-        }
+        }*/ // FIXME
     }
 
 
@@ -200,7 +196,7 @@
                 artDir.mkdir();
             }
 
-            if (wms instanceof WMSDBLayerFacet) {
+            /*if (wms instanceof WMSDBLayerFacet) {
                 mfg.createDatabaseLayer(
                     flys,
                     (WMSDBLayerFacet) wms,
@@ -208,7 +204,7 @@
             }
             else {
                 logger.warn("Cannot create DB layer from: " + wms.getClass());
-            }
+            }*/ // FIXME
         }
         catch (FileNotFoundException fnfe) {
             logger.error(fnfe, fnfe);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-artifacts/src/main/java/de/intevation/flys/mapserver/ArtifactMapfileGenerator.java	Fri Mar 22 11:25:54 2013 +0100
@@ -0,0 +1,384 @@
+package de.intevation.flys.mapserver;
+
+import de.intevation.artifacts.CallContext;
+import de.intevation.flys.artifacts.FLYSArtifact;
+import de.intevation.flys.artifacts.access.RiverAccess;
+import de.intevation.flys.artifacts.model.LayerInfo;
+import de.intevation.flys.artifacts.model.map.WMSDBLayerFacet;
+import de.intevation.flys.artifacts.model.map.WMSLayerFacet;
+import de.intevation.flys.artifacts.resources.Resources;
+import de.intevation.flys.utils.FLYSUtils;
+import de.intevation.flys.utils.GeometryUtils;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.apache.velocity.Template;
+import org.geotools.data.shapefile.ShpFiles;
+import org.geotools.data.shapefile.shp.ShapefileHeader;
+import org.geotools.data.shapefile.shp.ShapefileReader;
+
+public class ArtifactMapfileGenerator extends MapfileGenerator {
+
+    private static Logger logger = Logger.getLogger(ArtifactMapfileGenerator.class);
+
+    @Override
+    protected String getVelocityLogfile() {
+        return FLYSUtils.getXPathString(FLYSUtils.XPATH_FLOODMAP_VELOCITY_LOGFILE);
+    }
+
+    @Override
+    protected String getMapserverTemplatePath() {
+        return FLYSUtils.getXPathString(FLYSUtils.XPATH_FLOODMAP_MAPSERVER_TEMPLATE_PATH);
+    }
+
+    @Override
+    protected String getMapserverUrl() {
+        return FLYSUtils.getXPathString(FLYSUtils.XPATH_FLOODMAP_MAPSERVER_URL);
+    }
+
+    /**
+     * Generates flys.map file that contains layers of all
+     * projects and types (floodmap, user defined, barriers).
+     */
+    public void generate(String style, CallContext context, FLYSArtifact flys) throws IOException
+    {
+        // Get all directories below "shapefiles/"
+        File[] prjDirs = getProjectDirs();
+
+        // Look for appropriate shapefiles that we can use as layers
+        List<File> layerShapes = searchForLayerShapes(prjDirs);
+
+        List<String> layerSnippets = new ArrayList<String>();
+
+        // Generate layer snippet for each shapefile
+        for (File layerShape : layerShapes) {
+            String fileName  = layerShape.getName();
+            File   layerFile = null;
+
+            if (fileName.startsWith(MS_PREFIX_BARRIERS)) {
+
+            }
+            else if (fileName.startsWith(MS_PREFIX_USER)) {
+                layerFile = createUserShapeLayer(layerShape);
+            }
+            else if (fileName.startsWith(MS_PREFIX_WSPLGEN) &&
+                     style != null && context != null && flys != null) {
+                layerFile = createFloodmapLayer(layerShape, style, context, flys);
+            }
+
+            if (layerFile != null) {
+                layerSnippets.add(layerFile.getCanonicalPath());
+            }
+        }
+
+        writeMapfile(layerSnippets);
+    }
+
+    @Override
+    public void generate() throws IOException {
+        generate(null, null, null);
+    }
+
+    /**
+     * Creates a layer file used for Mapserver's mapfile which represents the
+     * floodmap.
+     */
+    protected File createFloodmapLayer(File file, String style, CallContext context, FLYSArtifact flys)
+            throws FileNotFoundException, IOException
+    {
+        String uuid = uuidFromPath(file.getAbsolutePath());
+        logger.debug("createUeskLayer");
+
+        LayerInfo layerinfo = new LayerInfo();
+        layerinfo.setName(MS_PREFIX_WSPLGEN + "-" + uuid);
+        layerinfo.setType("POLYGON");
+        layerinfo.setDirectory(uuid);
+        layerinfo.setData(WSPLGEN_RESULT_SHAPE);
+        layerinfo.setTitle(Resources.getMsg(Resources.getLocale(context.getMeta()),
+                                            "floodmap.uesk",
+                                            "Floodmap"));
+        layerinfo.setStyle(style);
+        RiverAccess access = new RiverAccess(flys);
+        String river = access.getRiver();
+        layerinfo.setSrid(FLYSUtils.getRiverDGMSrid(river));
+
+        String name = "floodmap.layer"; //MS_LAYER_PREFIX + wms.getName();
+
+        Template template = getTemplateByName(WSPLGEN_LAYER_TEMPLATE);
+        if (template == null) {
+            logger.warn("Template '" + WSPLGEN_LAYER_TEMPLATE + "' found.");
+            return null;
+        }
+
+        try {
+            File dir = new File(getShapefileBaseDir(), uuid);
+            File layerFile = new File(dir, name);
+            writeLayer(layerinfo, layerFile, template);
+            return layerFile;
+        }
+        catch (FileNotFoundException fnfe) {
+            logger.error(fnfe, fnfe);
+            logger.warn("Unable to write layer: " + name);
+            return null;
+        }
+    }
+
+
+    /**
+     * Creates a layer file used for Mapserver's mapfile which represents the
+     * user defined barriers.
+     *
+     * @param flys The FLYSArtifact that owns <i>wms</i>.
+     * @param wms The WMSLayerFacet that contains information for the layer.
+     */
+    protected void createBarriersLayer(FLYSArtifact flys, WMSLayerFacet wms)
+    throws FileNotFoundException, IOException
+    {
+        logger.debug("createBarriersLayer");
+
+        //String uuid = flys.identifier();
+        //File   dir  = new File(getShapefileBaseDir(), uuid);
+
+        createBarriersLineLayer(flys, wms);
+        createBarriersPolygonLayer(flys, wms);
+    }
+
+
+    protected void createBarriersLineLayer(
+        FLYSArtifact  flys,
+        WMSLayerFacet wms
+    )
+    throws FileNotFoundException, IOException
+    {
+        String uuid       = flys.identifier();
+        String group      = MS_PREFIX_BARRIERS + uuid;
+        String groupTitle = "I18N_BARRIERS_TITLE";
+
+        File dir  = new File(getShapefileBaseDir(), uuid);
+        File test = new File(dir, WSPLGEN_LINES_SHAPE);
+
+        if (!test.exists() || !test.canRead()) {
+            logger.debug("No barrier line layer existing.");
+            return;
+        }
+
+        LayerInfo lineInfo = new LayerInfo();
+        lineInfo.setName(MS_LINE_PREFIX + uuid);
+        lineInfo.setType("LINE");
+        lineInfo.setDirectory(uuid);
+        lineInfo.setData(WSPLGEN_LINES_SHAPE);
+        lineInfo.setTitle("I18N_LINE_SHAPE");
+        lineInfo.setGroup(group);
+        lineInfo.setGroupTitle(groupTitle);
+        lineInfo.setSrid(wms.getSrid());
+
+        String nameLines = MS_LAYER_PREFIX + wms.getName() + "-lines";
+
+        Template tpl = getTemplateByName(SHP_LAYER_TEMPLATE);
+        if (tpl == null) {
+            logger.warn("Template '" + SHP_LAYER_TEMPLATE + "' found.");
+            return;
+        }
+
+        try {
+            writeLayer(lineInfo, new File(dir, nameLines), tpl);
+        }
+        catch (FileNotFoundException fnfe) {
+            logger.error(fnfe, fnfe);
+            logger.warn("Unable to write layer: " + nameLines);
+        }
+    }
+
+    protected void createBarriersPolygonLayer(
+            FLYSArtifact  flys,
+            WMSLayerFacet wms
+        )
+        throws FileNotFoundException, IOException
+        {
+            String uuid       = flys.identifier();
+            String group      = uuid + MS_PREFIX_BARRIERS;
+            String groupTitle = "I18N_BARRIERS_TITLE";
+
+            File dir  = new File(getShapefileBaseDir(), uuid);
+            File test = new File(dir, WSPLGEN_POLYGONS_SHAPE);
+
+            if (!test.exists() || !test.canRead()) {
+                logger.debug("No barrier line layer existing.");
+                return;
+            }
+
+            LayerInfo polygonInfo = new LayerInfo();
+            polygonInfo.setName(MS_POLYGONS_PREFIX + uuid);
+            polygonInfo.setType("POLYGON");
+            polygonInfo.setDirectory(uuid);
+            polygonInfo.setData(WSPLGEN_POLYGONS_SHAPE);
+            polygonInfo.setTitle("I18N_POLYGON_SHAPE");
+            polygonInfo.setGroup(group);
+            polygonInfo.setGroupTitle(groupTitle);
+            polygonInfo.setSrid(wms.getSrid());
+
+            String namePolygons = MS_LAYER_PREFIX + wms.getName() + "-polygons";
+
+            Template tpl = getTemplateByName(SHP_LAYER_TEMPLATE);
+            if (tpl == null) {
+                logger.warn("Template '" + SHP_LAYER_TEMPLATE + "' found.");
+                return;
+            }
+
+            try {
+                writeLayer(polygonInfo, new File(dir, namePolygons), tpl);
+            }
+            catch (FileNotFoundException fnfe) {
+                logger.error(fnfe, fnfe);
+                logger.warn("Unable to write layer: " + namePolygons);
+            }
+        }
+
+        protected String uuidFromPath(String path) {
+            logger.debug("uuidFromPath(" + path + ")");
+            int i1 = 0;
+            int i2 = 0;
+
+            for(;;) {
+                int i = path.indexOf('/', i2 + 1);
+                if (i == -1) {
+                    return path.substring(i1 + 1, i2);
+                }
+                else {
+                    i1 = i2;
+                    i2 = i;
+                }
+            }
+        }
+
+        /**
+         * Creates a layer file used for Mapserver's mapfile which represents the
+         * shape files uploaded by the user.
+         */
+        protected File createUserShapeLayer(File file)
+        throws FileNotFoundException, IOException
+        {
+            String uuid = uuidFromPath(file.getAbsolutePath());
+            logger.debug("createUserShapeLayer(): uuid=" + uuid);
+
+            File   dir  = new File(getShapefileBaseDir(), uuid);
+            File   test = new File(dir, WSPLGEN_USER_SHAPE);
+
+            if (!test.exists() || !test.canRead()) {
+                logger.debug("No user layer existing.");
+                return null;
+            }
+
+            File userShape = new File(dir, WSPLGEN_USER_SHAPE);
+            ShpFiles sf = new ShpFiles(userShape);
+            ShapefileReader sfr = new ShapefileReader(sf, true, false, null);
+            ShapefileHeader sfh = sfr.getHeader();
+
+            String group      = uuid + MS_PREFIX_USER;
+            String groupTitle = "I18N_USER_SHAPE_TITLE";
+
+            LayerInfo info = new LayerInfo();
+            info.setName(MS_PREFIX_USER + uuid);
+            if (sfh.getShapeType().isLineType()) {
+                info.setType("LINE");
+            }
+            else if (sfh.getShapeType().isPolygonType()) {
+                info.setType("POLYGON");
+            }
+            else {
+                logger.debug("createUserShapeLayer(): unexpected geometry type");
+                return null;
+            }
+            info.setDirectory(uuid);
+            info.setData(WSPLGEN_USER_SHAPE);
+            info.setTitle("I18N_USER_SHAPE");
+            info.setGroup(group);
+            info.setGroupTitle(groupTitle);
+            //info.setSrid(wms.getSrid()); // FIXME: Required?
+
+            String nameUser = "user.layer"; //MS_LAYER_PREFIX + wms.getName();
+
+            Template tpl = getTemplateByName(SHP_LAYER_TEMPLATE);
+            if (tpl == null) {
+                logger.warn("Template '" + SHP_LAYER_TEMPLATE + "' found.");
+                return null;
+            }
+
+            File layerFile = new File(dir, nameUser);
+
+            try {
+                writeLayer(info, layerFile, tpl);
+            }
+            catch (FileNotFoundException fnfe) {
+                logger.error(fnfe, fnfe);
+                logger.warn("Unable to write layer: " + nameUser);
+            }
+            return layerFile;
+        }
+
+
+        /**
+         * Creates a layer file used for Mapserver's mapfile which represents
+         * geometries from database.
+         *
+         * @param flys The FLYSArtifact that owns <i>wms</i>.
+         * @param wms The WMSLayerFacet that contains information for the layer.
+         */
+        protected void createDatabaseLayer(
+            FLYSArtifact    flys,
+            WMSDBLayerFacet wms,
+            String          style
+        )
+        throws FileNotFoundException, IOException
+        {
+            logger.debug("createDatabaseLayer");
+
+            LayerInfo layerinfo = new LayerInfo();
+            layerinfo.setName(wms.getName() + "-" + flys.identifier());
+            layerinfo.setType(wms.getGeometryType());
+            layerinfo.setFilter(wms.getFilter());
+            layerinfo.setData(wms.getData());
+            layerinfo.setTitle(wms.getDescription());
+            layerinfo.setStyle(style);
+            if(wms.getExtent() != null) {
+                layerinfo.setExtent(GeometryUtils.jtsBoundsToOLBounds(wms.getExtent()));
+            }
+            layerinfo.setConnection(wms.getConnection());
+            layerinfo.setConnectionType(wms.getConnectionType());
+            layerinfo.setLabelItem(wms.getLabelItem());
+            layerinfo.setSrid(wms.getSrid());
+
+            String name = MS_LAYER_PREFIX + wms.getName();
+
+            Template template = getTemplateByName(DB_LAYER_TEMPLATE);
+            if (template == null) {
+                logger.warn("Template '" + DB_LAYER_TEMPLATE + "' found.");
+                return;
+            }
+
+            try {
+                File dir = new File(getShapefileBaseDir(), flys.identifier());
+                writeLayer(layerinfo, new File(dir, name), template);
+            }
+            catch (FileNotFoundException fnfe) {
+                logger.error(fnfe, fnfe);
+                logger.warn("Unable to write layer: " + name);
+            }
+        }
+
+        @Override
+        protected String getMapfilePath() {
+            return FLYSUtils.getXPathString(FLYSUtils.XPATH_FLOODMAP_MAPFILE_PATH);
+        }
+
+        @Override
+        protected String getMapfileTemplate() {
+            return FLYSUtils.getXPathString(FLYSUtils.XPATH_FLOODMAP_MAPFILE_TEMPLATE);
+        }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-artifacts/src/main/java/de/intevation/flys/mapserver/MapfileGenerator.java	Fri Mar 22 11:25:54 2013 +0100
@@ -0,0 +1,392 @@
+package de.intevation.flys.mapserver;
+
+import de.intevation.artifacts.common.utils.Config;
+import de.intevation.flys.artifacts.model.LayerInfo;
+import de.intevation.flys.utils.FLYSUtils;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileWriter;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+import org.apache.velocity.Template;
+import org.apache.velocity.VelocityContext;
+import org.apache.velocity.app.VelocityEngine;
+import org.apache.velocity.runtime.RuntimeConstants;
+
+/**
+ * This class iterates over a bunch of directories, searches for meta
+ * information coresponding to shapefiles and creates a mapfile which is used by
+ * a <i>MapServer</i>.
+ *
+ * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a>
+ */
+public abstract class MapfileGenerator
+{
+    public static final String WSPLGEN_RESULT_SHAPE   = "wsplgen.shp";
+    public static final String WSPLGEN_LINES_SHAPE    = "barrier_lines.shp";
+    public static final String WSPLGEN_POLYGONS_SHAPE = "barrier_polygons.shp";
+    public static final String WSPLGEN_USER_SHAPE     = "user-rgd.shp";
+
+    public static final String WSPLGEN_LAYER_TEMPLATE = "wsplgen_layer.vm";
+    public static final String SHP_LAYER_TEMPLATE = "shapefile_layer.vm";
+    public static final String DB_LAYER_TEMPLATE  = "db_layer.vm";
+    public static final String RIVERAXIS_LAYER_TEMPLATE = "riveraxis-layer.vm";
+
+    public static final String MS_PREFIX_WSPLGEN   = "wsplgen";
+    public static final String MS_PREFIX_BARRIERS  = "barriers-";
+    public static final String MS_LINE_PREFIX      = "lines-";
+    public static final String MS_POLYGONS_PREFIX  = "polygons-";
+    public static final String MS_LAYER_PREFIX     = "ms_layer-";
+    public static final String MS_PREFIX_USER = "user-";
+
+    private static Logger logger = Logger.getLogger(MapfileGenerator.class);
+
+    private File shapefileDirectory;
+
+    private VelocityEngine velocityEngine;
+
+
+    protected MapfileGenerator() {
+    }
+
+
+    /**
+     * Method to check the existance of a template file.
+     *
+     * @param templateID The name of a template.
+     * @return true, of the template exists - otherwise false.
+     */
+    protected boolean templateExists(String templateID){
+        Template template = getTemplateByName(templateID);
+        return template != null;
+    }
+
+
+    /**
+     * Starts the mapfile generation. This is the main entry point for
+     * the mapfile generation, all other methods of this class/package
+     * *should* be non-public.
+     * @throws Exception
+     */
+    public abstract void generate() throws Exception;
+
+
+    /**
+     * Returns the VelocityEngine used for the template mechanism.
+     *
+     * @return the velocity engine.
+     */
+    protected VelocityEngine getVelocityEngine() {
+        if (velocityEngine == null) {
+            velocityEngine = new VelocityEngine();
+            try {
+                setupVelocity(velocityEngine);
+            }
+            catch (Exception e) {
+                logger.error(e, e);
+                return null;
+            }
+        }
+        return velocityEngine;
+    }
+
+
+    /**
+     * Initialize velocity.
+     *
+     * @param engine Velocity engine.
+     * @throws Exception if an error occured while initializing velocity.
+     */
+    protected void setupVelocity(VelocityEngine engine)
+    throws Exception
+    {
+        engine.setProperty(
+            "input.encoding",
+            "UTF-8");
+
+        engine.setProperty(
+            RuntimeConstants.RUNTIME_LOG,
+            getVelocityLogfile());
+
+        engine.setProperty(
+            "resource.loader",
+            "file");
+
+        engine.setProperty(
+            "file.resource.loader.path",
+            getMapserverTemplatePath());
+
+        engine.init();
+    }
+
+    protected abstract String getVelocityLogfile();
+
+    protected abstract String getMapserverTemplatePath();
+
+    protected abstract String getMapserverUrl();
+
+    protected VelocityContext getVelocityContext() {
+        VelocityContext context = new VelocityContext();
+
+        try {
+            context.put("MAPSERVERURL",
+                getMapserverUrl());
+            context.put("SHAPEFILEPATH",
+                getShapefileBaseDir().getCanonicalPath());
+            context.put("CONFIGDIR",
+                Config.getConfigDirectory().getCanonicalPath());
+        }
+        catch (FileNotFoundException fnfe) {
+            // this is bad
+            logger.warn(fnfe, fnfe);
+        }
+        catch (IOException ioe) {
+            // this is also bad
+            logger.warn(ioe, ioe);
+        }
+
+        return context;
+    }
+
+
+    /**
+     * Returns a template specified by <i>model</i>.
+     *
+     * @param model The name of the template.
+     * @return a template.
+     */
+    protected Template getTemplateByName(String model) {
+        if (model.indexOf(".vm") < 0) {
+            model = model.concat(".vm");
+        }
+
+        try {
+            VelocityEngine engine = getVelocityEngine();
+            if (engine == null) {
+                logger.error("Error while fetching VelocityEngine.");
+                return null;
+            }
+
+            return engine.getTemplate(model);
+        }
+        catch (Exception e) {
+            logger.warn(e, e);
+        }
+
+        return null;
+    }
+
+
+    /**
+     * Returns the mapfile  template.
+     *
+     * @return the mapfile template.
+     * @throws Exception if an error occured while reading the configuration.
+     */
+    protected Template getMapfileTemplateObj()
+    throws Exception
+    {
+        String mapfileName = getMapfileTemplate();
+        return getTemplateByName(mapfileName);
+    }
+
+    protected abstract String getMapfilePath();
+
+    protected abstract String getMapfileTemplate();
+
+
+    /**
+     * Returns the base directory storing the shapefiles.
+     *
+     * @return the shapefile base directory.
+     *
+     * @throws FileNotFoundException if no shapefile path is found or
+     * configured.
+     */
+    public File getShapefileBaseDir()
+            throws FileNotFoundException, IOException
+    {
+        if (shapefileDirectory == null) {
+            String path = FLYSUtils.getXPathString(
+                FLYSUtils.XPATH_FLOODMAP_SHAPEFILE_DIR);
+
+            if (path != null) {
+                shapefileDirectory = new File(path);
+            }
+
+            if (shapefileDirectory == null) {
+                throw new FileNotFoundException("No shapefile directory given");
+            }
+
+            if (!shapefileDirectory.exists()) {
+                shapefileDirectory.mkdirs();
+            }
+        }
+
+        return shapefileDirectory;
+    }
+
+
+    protected File[] getProjectDirs()
+            throws FileNotFoundException, IOException
+    {
+        File   baseDir      = getShapefileBaseDir();
+        File[] artifactDirs = baseDir.listFiles();
+
+        logger.debug("getProjectDirs(): found " + artifactDirs.length + " project directories");
+        return artifactDirs;
+    }
+
+
+    /**
+     * Search in all given directories for shapefiles that can be used
+     * as barrier, user oder wsplgen layers.
+     * @param dirs
+     * @return
+     */
+    protected List<File> searchForLayerShapes(File[] dirs) {
+        List<File> shapes = new ArrayList<File>();
+
+        for (File dir: dirs) {
+            File[] layerFiles = dir.listFiles(new FilenameFilter() {
+                @Override
+                public boolean accept(File directory, String name) {
+                    return name.endsWith(".shp") &&
+                            (name.startsWith(MS_PREFIX_BARRIERS) ||
+                             name.startsWith(MS_PREFIX_USER)     ||
+                             name.startsWith(MS_PREFIX_WSPLGEN));
+                }
+            });
+
+            for (File layer: layerFiles) {
+                shapes.add(layer);
+            }
+        }
+
+        logger.debug("searchForLayerShapes(): found " + shapes.size() + " shapefiles");
+        return shapes;
+    }
+
+
+    /**
+     * Creates a layer snippet which might be included in the mapfile.
+     *
+     * @param layerinfo A LayerInfo object that contains all necessary
+     * information to build a Mapserver LAYER section.
+     * @param dir The base dir for the LAYER snippet.
+     * @param filename The name of the file that is written.
+     * @param tpl The Velocity template which is used to create the LAYER
+     * section.
+     */
+    protected void writeLayer(
+        LayerInfo layerInfo,
+        File      layerFile,
+        Template  tpl
+    )
+    throws    FileNotFoundException
+    {
+        if (logger.isDebugEnabled()) {
+            logger.debug("Write layer for:");
+            logger.debug("   directory/file: " + layerFile.getName());
+        }
+
+        Writer writer = null;
+
+        try {
+            writer = new FileWriter(layerFile);
+
+            VelocityContext context = getVelocityContext();
+            context.put("LAYER", layerInfo);
+
+            tpl.merge(context, writer);
+        }
+        catch (FileNotFoundException fnfe) {
+            logger.error(fnfe, fnfe);
+        }
+        catch (IOException ioe) {
+            logger.error(ioe, ioe);
+        }
+        catch (Exception e) {
+            logger.error(e, e);
+        }
+        finally {
+            try {
+                if (writer != null) {
+                    writer.close();
+                }
+            }
+            catch (IOException ioe) {
+                logger.debug(ioe, ioe);
+            }
+        }
+    }
+
+
+    /**
+     * Creates a mapfile with the layer information stored in <i>layers</i>.
+     *
+     * @param layers Layer information.
+     */
+    protected void writeMapfile(List<String> layers) {
+        String tmpMapName = "mapfile" + new Date().getTime();
+
+        File mapfile = new File(getMapfilePath());
+
+        File   tmp     = null;
+        Writer writer  = null;
+
+        try {
+            tmp = new File(mapfile.getParent(), tmpMapName);
+            tmp.createNewFile();
+
+            writer = new FileWriter(tmp);
+
+            VelocityContext context = getVelocityContext();
+            context.put("LAYERS", layers);
+
+            Template mapTemplate = getMapfileTemplateObj();
+            if (mapTemplate == null) {
+                logger.warn("No mapfile template found.");
+                return;
+            }
+
+            mapTemplate.merge(context, writer);
+
+            // we need to create a temporary mapfile first und rename it into
+            // real mapfile because we don't run into race conditions on this
+            // way. (iw)
+            tmp.renameTo(mapfile);
+        }
+        catch (FileNotFoundException fnfe) {
+            logger.error(fnfe, fnfe);
+        }
+        catch (IOException ioe) {
+            logger.error(ioe, ioe);
+        }
+        catch (Exception e) {
+            logger.error(e, e);
+        }
+        finally {
+            try {
+                if (writer != null) {
+                    writer.close();
+                }
+
+                if (tmp.exists()) {
+                    tmp.delete();
+                }
+            }
+            catch (IOException ioe) {
+                logger.debug(ioe, ioe);
+            }
+        }
+    }
+}
+// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-artifacts/src/main/java/de/intevation/flys/mapserver/RiverMapfileGenerator.java	Fri Mar 22 11:25:54 2013 +0100
@@ -0,0 +1,140 @@
+package de.intevation.flys.mapserver;
+
+import com.vividsolutions.jts.geom.Envelope;
+import com.vividsolutions.jts.geom.MultiLineString;
+
+import de.intevation.flys.artifacts.model.LayerInfo;
+import de.intevation.flys.artifacts.model.RiverFactory;
+import de.intevation.flys.model.River;
+import de.intevation.flys.model.RiverAxis;
+import de.intevation.flys.utils.FLYSUtils;
+import de.intevation.flys.utils.MapUtils;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.log4j.Logger;
+import org.apache.velocity.Template;
+
+public class RiverMapfileGenerator extends MapfileGenerator {
+
+    public static final String XPATH_RIVERMAP_RIVER_PROJECTION =
+            "/artifact-database/rivermap/river[@name=$name]/srid/@value";
+
+    public static final String XPATH_RIVERMAP_SHAPEFILE_DIR =
+            "/artifact-database/rivermap/shapefile-path/@value";
+
+    public static final String XPATH_RIVERMAP_VELOCITY_LOGFILE =
+            "/artifact-database/rivermap/velocity/logfile/@path";
+
+    public static final String XPATH_RIVERMAP_MAPSERVER_URL =
+            "/artifact-database/rivermap/mapserver/server/@path";
+
+    public static final String XPATH_RIVERMAP_MAPFILE_PATH =
+            "/artifact-database/rivermap/mapserver/mapfile/@path";
+
+    public static final String XPATH_RIVERMAP_MAPFILE_TEMPLATE =
+            "/artifact-database/rivermap/mapserver/map-template/@path";
+
+    public static final String XPATH_RIVERMAP_MAPSERVER_TEMPLATE_PATH =
+            "/artifact-database/rivermap/mapserver/templates/@path";
+
+    public static final Pattern DB_URL_PATTERN =
+        Pattern.compile("(.*)\\/\\/(.*):([0-9]+)\\/([a-zA-Z]+)");
+
+    public static final Pattern DB_PSQL_URL_PATTERN =
+        Pattern.compile("(.*)\\/\\/(.*):([0-9]+)\\/([a-zA-Z0-9]+)");
+
+    private static Logger logger = Logger.getLogger(RiverMapfileGenerator.class);
+
+    /**
+     * Generate river axis mapfile.
+     */
+    @Override
+    public void generate() {
+        logger.debug("generate()");
+
+        List<River>  rivers     = RiverFactory.getRivers();
+        List<String> riverFiles = new ArrayList<String>();
+
+        for (River river : rivers) {
+            // We expect that every river has only one RiverAxis.
+            // This is not correct but currently the case here, see
+            // RiverAxis.java.
+            List<RiverAxis> riverAxis = RiverAxis.getRiverAxis(river.getName());
+            if (riverAxis == null) {
+                logger.warn("River " + river.getName() + " has no river axis!");
+                continue;
+            }
+            MultiLineString geom = riverAxis.get(0).getGeom();
+            Envelope extent = geom.getEnvelopeInternal();
+
+            createRiverAxisLayer(
+                    river.getName(),
+                    river.getId(),
+                    Integer.toString(geom.getSRID()),
+                    extent.getMinX() + " " +
+                    extent.getMinY() + " " +
+                    extent.getMaxX() + " " +
+                    extent.getMaxY());
+
+            riverFiles.add("river-" + river.getName() + ".map");
+        }
+        writeMapfile(riverFiles);
+    }
+
+    protected void createRiverAxisLayer(String riverName, int riverID, String srid, String extend) {
+        LayerInfo layerInfo = new LayerInfo();
+        layerInfo.setName(riverName);
+        layerInfo.setConnection(MapUtils.getConnection());
+        layerInfo.setConnectionType(MapUtils.getConnectionType());
+        layerInfo.setSrid(srid);
+        layerInfo.setExtent(extend);
+        layerInfo.setType("line");
+        layerInfo.setData("geom FROM river_axes");      // FIXME: Use templates for that
+        layerInfo.setFilter("river_id = " + riverID);
+        layerInfo.setTitle(riverName + " RiverAxis");
+
+        File layerFile = new File("river-" + riverName + ".map");
+        Template template = getTemplateByName("riveraxis-layer.vm");
+        if (template == null) {
+            logger.warn("Template riveraxis-layer.vm not found.");
+            return;
+        }
+
+        try {
+            writeLayer(layerInfo, layerFile, template);
+        }
+        catch (FileNotFoundException e) {
+            logger.warn(e.getLocalizedMessage(), e);
+        }
+    }
+
+    @Override
+    protected String getVelocityLogfile() {
+        return FLYSUtils.getXPathString(XPATH_RIVERMAP_VELOCITY_LOGFILE);
+    }
+
+    @Override
+    protected String getMapserverTemplatePath() {
+        return FLYSUtils.getXPathString(XPATH_RIVERMAP_MAPSERVER_TEMPLATE_PATH);
+    }
+
+    @Override
+    protected String getMapserverUrl() {
+        return FLYSUtils.getXPathString(XPATH_RIVERMAP_MAPSERVER_URL);
+    }
+
+    @Override
+    protected String getMapfilePath() {
+        return FLYSUtils.getXPathString(XPATH_RIVERMAP_MAPFILE_PATH);
+    }
+
+    @Override
+    protected String getMapfileTemplate() {
+        return FLYSUtils.getXPathString(XPATH_RIVERMAP_MAPFILE_TEMPLATE);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-artifacts/src/main/java/de/intevation/flys/mapserver/RiverMapfileGeneratorStarter.java	Fri Mar 22 11:25:54 2013 +0100
@@ -0,0 +1,40 @@
+package de.intevation.flys.mapserver;
+
+import de.intevation.artifactdatabase.LifetimeListener;
+import de.intevation.artifacts.GlobalContext;
+
+import org.apache.log4j.Logger;
+import org.w3c.dom.Document;
+
+/**
+ * LifetimeListener that creates a Mapfile containing river axis layers.
+ * The listener is called when the server has completed its startup.
+ *
+ * @author <a href="mailto:christian.lins@intevation.de">Christian Lins</a>
+ */
+public class RiverMapfileGeneratorStarter implements LifetimeListener {
+
+    private static Logger logger = Logger.getLogger(RiverMapfileGeneratorStarter.class);
+
+    @Override
+    public void setup(Document document) {
+        // Nothing to setup here
+    }
+
+    /**
+     * Calls RiverMapfileGenerator.generate().
+     */
+    @Override
+    public void systemUp(GlobalContext globalContext) {
+        logger.debug("systemUp()");
+
+        RiverMapfileGenerator fmfg = new RiverMapfileGenerator();
+        fmfg.generate();
+    }
+
+    @Override
+    public void systemDown(GlobalContext globalContext) {
+        // No, we're not cleaning up our generated mapfile
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-artifacts/src/main/java/de/intevation/flys/utils/FileUtils.java	Fri Mar 22 11:25:54 2013 +0100
@@ -0,0 +1,66 @@
+package de.intevation.flys.utils;
+
+import de.intevation.artifacts.common.utils.FileTools;
+import de.intevation.flys.artifacts.states.FloodMapState;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Various utility methods for handling of files and directories.
+ * @author <a href="mailto:christian.lins@intevation.de">Christian Lins</a>
+ */
+public class FileUtils {
+
+    public static boolean extractZipfile(File archive, File dir) {
+        try {
+            File tmpDir = new File(dir, "usr_tmp");
+            FileTools.extractArchive(archive, tmpDir);
+            FileUtils.moveFiles(tmpDir, dir);
+
+            return true;
+        }
+        catch (IOException ioe) {
+            FloodMapState.logger.warn("Zip archive " + dir + "/" + FloodMapState.WSPLGEN_USER_ZIP + " could not be extracted.");
+            return false;
+        }
+    }
+
+    public static void moveFiles(File source, final File target)
+    throws IOException
+    {
+        if (!source.exists()) {
+            return;
+        }
+        if (!target.exists()) {
+            target.mkdir();
+        }
+        FileTools.walkTree(source, new FileTools.FileVisitor() {
+            @Override
+            public boolean visit(File file) {
+                if (!file.isDirectory()) {
+                    String name = file.getName();
+                    String suffix = "";
+                    int pos = name.lastIndexOf('.');
+                    if (pos > 0 && pos < name.length() - 1) {
+                        suffix = name.substring(pos + 1);
+                    }
+                    else {
+                        return true;
+                    }
+                    try {
+                        FileTools.copyFile(file, new File(target, FloodMapState.WSPLGEN_USER_FILENAME + "." + suffix));
+                    }
+                    catch (IOException ioe) {
+                        FloodMapState.logger.warn ("Error while copying file " + file.getName());
+                        return true;
+                    }
+                }
+                return true;
+            }
+        });
+
+        FileTools.deleteRecursive(source);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/flys-artifacts/src/main/java/de/intevation/flys/utils/PrintMap.java	Fri Mar 22 11:25:54 2013 +0100
@@ -0,0 +1,131 @@
+package de.intevation.flys.utils;
+
+import java.awt.Color;
+import java.awt.Rectangle;
+
+import java.io.File;
+import java.io.IOException;
+
+import java.awt.Graphics2D;
+import java.awt.image.BufferedImage;
+
+import java.util.List;
+
+import java.net.URL;
+import java.net.MalformedURLException;
+
+import javax.imageio.ImageIO;
+
+
+import org.geotools.data.ows.Layer;
+import org.geotools.data.ows.WMSCapabilities;
+import org.geotools.data.wms.WebMapServer;
+import org.geotools.geometry.jts.ReferencedEnvelope;
+import org.geotools.map.MapContext;
+import org.geotools.map.WMSMapLayer;
+import org.geotools.ows.ServiceException;
+import org.geotools.renderer.lite.StreamingRenderer;
+import org.geotools.renderer.GTRenderer;
+
+
+public class PrintMap {
+
+    public static final String DEFAULT_WMS = "http://map1.naturschutz.rlp.de/service_lanis/mod_wms/wms_getmap.php?mapfile=group_gdide&REQUEST=GetCapabilities&SERVICE=WMS";
+    public static final String DEFAULT_OUTFILE = "~/map.jpeg";
+
+    public static final String MAPSERVER = System.getProperty("wms", DEFAULT_WMS);
+    public static final String MAP_IMAGE = System.getProperty("outfile", DEFAULT_OUTFILE);
+
+
+    public static void main(String[] args) {
+        System.out.println("-> start PrintMap");
+        System.out.println("  -> Print layers of WMS: " + MAPSERVER);
+
+        try {
+            WebMapServer    server = getMapserver();
+            WMSMapLayer[] wmsLayer = getWMSLayers(server);
+
+            MapContext mapcontent = new MapContext( wmsLayer );
+            mapcontent.setTitle(" NEW MAP CONTENT TITLE ");
+
+            printMap(mapcontent);
+        }
+        catch (Exception e) {
+            e.printStackTrace();
+        }
+
+        System.out.println("-> finished PrintMap");
+    }
+
+
+    public static void printMap(MapContext map) throws Exception {
+        int imageWidth = 600;
+
+        GTRenderer renderer = new StreamingRenderer();
+        renderer.setContext(map);
+
+        Rectangle imageBounds = null;
+        ReferencedEnvelope mapBounds = null;
+
+        try {
+            mapBounds = map.getLayerBounds();
+            double heightToWidth = mapBounds.getSpan(1) / mapBounds.getSpan(0);
+            imageBounds = new Rectangle(
+                0, 0,
+                imageWidth,
+                (int) Math.round(imageWidth * heightToWidth));
+
+        }
+        catch (Exception e) {
+            // failed to access map layers
+            throw new RuntimeException(e);
+        }
+
+        BufferedImage image = new BufferedImage(imageBounds.width, imageBounds.height, BufferedImage.TYPE_INT_RGB);
+        Graphics2D gr = image.createGraphics();
+        gr.setPaint(Color.WHITE);
+        gr.fill(imageBounds);
+
+        try {
+            renderer.paint(gr, imageBounds, mapBounds);
+            File fileToSave = new File(MAP_IMAGE);
+            ImageIO.write(image, "jpeg", fileToSave);
+        }
+        catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+
+    public static WebMapServer getMapserver() throws MalformedURLException, IOException, ServiceException {
+        return new WebMapServer(getServerUrl());
+    }
+
+
+    public static URL getServerUrl() throws MalformedURLException {
+        return new URL(MAPSERVER);
+    }
+
+
+    public static WMSMapLayer[] getWMSLayers(WebMapServer server) {
+        if (server == null) {
+            System.out.println("WebMapServer == null");
+            throw new RuntimeException("WebMapServer == null");
+        }
+
+        WMSCapabilities capabilities = server.getCapabilities();
+
+        List<Layer> layers = capabilities.getLayerList();
+        WMSMapLayer[] wmslayers = new WMSMapLayer[layers.size()];
+
+        for (int i = 0, L = layers.size(); i < L; i++) {
+            Layer l = layers.get(i);
+
+            System.out.println("   -> add layer: " + l);
+            wmslayers[i] = new WMSMapLayer(server, l);
+        }
+
+        return wmslayers;
+    }
+}
+// vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :
--- a/flys-artifacts/src/main/java/de/intevation/flys/wsplgen/FacetCreator.java	Thu Mar 21 10:49:38 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/wsplgen/FacetCreator.java	Fri Mar 22 11:25:54 2013 +0100
@@ -1,25 +1,25 @@
 package de.intevation.flys.wsplgen;
 
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.log4j.Logger;
-
 import com.vividsolutions.jts.geom.Envelope;
 
 import de.intevation.artifactdatabase.state.Facet;
 import de.intevation.artifacts.CallContext;
+import de.intevation.flys.artifacts.FLYSArtifact;
 import de.intevation.flys.artifacts.access.RangeAccess;
-import de.intevation.flys.artifacts.FLYSArtifact;
 import de.intevation.flys.artifacts.model.FacetTypes;
 import de.intevation.flys.artifacts.model.map.WMSLayerFacet;
 import de.intevation.flys.artifacts.model.map.WSPLGENLayerFacet;
 import de.intevation.flys.artifacts.resources.Resources;
 import de.intevation.flys.artifacts.states.DefaultState.ComputeType;
+import de.intevation.flys.mapserver.MapfileGenerator;
 import de.intevation.flys.model.CrossSectionTrack;
 import de.intevation.flys.utils.FLYSUtils;
 import de.intevation.flys.utils.GeometryUtils;
-import de.intevation.flys.utils.MapfileGenerator;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.log4j.Logger;
 
 
 public class FacetCreator implements FacetTypes {
@@ -138,7 +138,7 @@
         }
 
         wsplgen.addLayer(
-            MapfileGenerator.MS_WSPLGEN_PREFIX + artifact.identifier());
+            MapfileGenerator.MS_PREFIX_WSPLGEN + artifact.identifier());
         wsplgen.setSrid(getSrid());
         wsplgen.setOriginalExtent(bounds);
         wsplgen.setExtent(bounds);
@@ -160,10 +160,9 @@
             getUrl());
 
         barriers.addLayer(MapfileGenerator.MS_LAYER_PREFIX +
-            MapfileGenerator.MS_BARRIERS_PREFIX + "lines" + artifact.identifier());
+                MapfileGenerator.MS_PREFIX_WSPLGEN + "lines" + artifact.identifier());
         barriers.addLayer( MapfileGenerator.MS_LAYER_PREFIX +
-            MapfileGenerator.MS_BARRIERS_PREFIX + "poly" + artifact.identifier());
-
+                MapfileGenerator.MS_PREFIX_WSPLGEN + "poly" + artifact.identifier());
         barriers.setSrid(getSrid());
         barriers.setExtent(getBounds());
 
@@ -189,7 +188,7 @@
             getUrl());
 
         shape.addLayer(
-            layer + artifact.identifier());
+            MapfileGenerator.MS_PREFIX_USER + artifact.identifier());
         shape.setSrid(getSrid());
         shape.setExtent(getBounds());
 

http://dive4elements.wald.intevation.org