changeset 5088:2b24073e80d9 mapgenfix

Merge with default branch
author Christian Lins <christian.lins@intevation.de>
date Mon, 25 Feb 2013 11:55:34 +0100
parents cbfdd7376009 (diff) b87e504f916e (current diff)
children cfc5540a4eec
files flys-artifacts/src/main/java/de/intevation/flys/artifacts/states/FloodMapState.java
diffstat 16 files changed, 1193 insertions(+), 1129 deletions(-) [+]
line wrap: on
line diff
--- a/flys-artifacts/doc/conf/conf.xml	Fri Feb 22 15:50:06 2013 +0100
+++ b/flys-artifacts/doc/conf/conf.xml	Mon Feb 25 11:55:34 2013 +0100
@@ -225,7 +225,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/src/main/java/de/intevation/flys/artifacts/map/PrintMap.java	Fri Feb 22 15:50:06 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	Fri Feb 22 15:50:06 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	Fri Feb 22 15:50:06 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/artifacts/services/FileUploadService.java	Mon Feb 25 11:55:34 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	Fri Feb 22 15:50:06 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/artifacts/states/FloodMapState.java	Mon Feb 25 11:55:34 2013 +0100
@@ -11,8 +11,8 @@
 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.FLYSArtifact;
 import de.intevation.flys.artifacts.context.FLYSContext;
 import de.intevation.flys.artifacts.model.CalculationMessage;
 import de.intevation.flys.artifacts.model.CalculationResult;
@@ -24,14 +24,15 @@
 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;
@@ -56,7 +57,7 @@
 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 =
@@ -142,10 +143,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);
@@ -490,15 +491,7 @@
         boolean exists = archive.exists();
         logger.debug("Zip file exists: " + exists);
         if (exists) {
-            try {
-                File tmpDir = new File(dir, "usr_tmp");
-                FileTools.extractArchive(archive, tmpDir);
-                moveFiles(tmpDir, dir);
-            }
-            catch (IOException ioe) {
-                logger.warn("Zip archive " + dir + "/" + WSPLGEN_USER_ZIP + " could not be extracted.");
-                return;
-            }
+            FileUtils.extractZipfile(archive, dir);
 
             job.addLin(dir + "/" + WSPLGEN_USER_SHAPE);
             facetCreator.createUserShapeFacet();
@@ -845,43 +838,5 @@
             }
         }
     }
-
-
-    protected 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, WSPLGEN_USER_FILENAME + "." + suffix));
-                    }
-                    catch (IOException ioe) {
-                        logger.warn ("Error while copying file " + file.getName());
-                        return true;
-                    }
-                }
-                return true;
-            }
-        });
-
-        FileTools.deleteRecursive(source);
-    }
 }
 // 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	Fri Feb 22 15:50:06 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/exports/MapGenerator.java	Mon Feb 25 11:55:34 2013 +0100
@@ -12,13 +12,11 @@
 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;
 
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -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");
@@ -132,29 +121,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);*/ // FIXME
             }
             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 +152,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 +167,7 @@
         }
         catch (IOException ioe) {
             logger.error(ioe, ioe);
-        }
+        }*/ // FIXME
     }
 
 
@@ -200,7 +189,7 @@
                 artDir.mkdir();
             }
 
-            if (wms instanceof WMSDBLayerFacet) {
+            /*if (wms instanceof WMSDBLayerFacet) {
                 mfg.createDatabaseLayer(
                     flys,
                     (WMSDBLayerFacet) wms,
@@ -208,7 +197,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	Mon Feb 25 11:55:34 2013 +0100
@@ -0,0 +1,380 @@
+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.model.map.WSPLGENLayerFacet;
+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).
+     */
+    @Override
+    public void generate() 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();
+            if (fileName.startsWith(MS_PREFIX_BARRIERS)) {
+
+            }
+            else if (fileName.startsWith(MS_PREFIX_USER)) {
+                File userLayer = createUserShapeLayer(layerShape);
+                if (userLayer != null) {
+                    layerSnippets.add(userLayer.getCanonicalPath());
+                }
+            }
+            else if (fileName.startsWith(MS_PREFIX_WSPLGEN)) {
+
+            }
+        }
+
+        writeMapfile(layerSnippets);
+    }
+
+    /**
+     * Creates a layer file used for Mapserver's mapfile which represents the
+     * floodmap.
+     *
+     * @param flys The FLYSArtifact that owns <i>wms</i>.
+     * @param wms The WMSLayerFacet that contains information for the layer.
+     */
+    protected void createUeskLayer(
+        FLYSArtifact  flys,
+        WSPLGENLayerFacet wms,
+        String        style,
+        CallContext context
+    ) throws FileNotFoundException, IOException
+    {
+        logger.debug("createUeskLayer");
+
+        LayerInfo layerinfo = new LayerInfo();
+        layerinfo.setName(MS_PREFIX_WSPLGEN + flys.identifier());
+        layerinfo.setType("POLYGON");
+        layerinfo.setDirectory(flys.identifier());
+        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 = MS_LAYER_PREFIX + wms.getName();
+
+        Template template = getTemplateByName(WSPLGEN_LAYER_TEMPLATE);
+        if (template == null) {
+            logger.warn("Template '" + WSPLGEN_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);
+        }
+    }
+
+
+    /**
+     * 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	Mon Feb 25 11:55:34 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	Mon Feb 25 11:55:34 2013 +0100
@@ -0,0 +1,144 @@
+package de.intevation.flys.mapserver;
+
+import com.vividsolutions.jts.geom.Envelope;
+import com.vividsolutions.jts.geom.LineString;
+
+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;
+            }
+            LineString 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	Mon Feb 25 11:55:34 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
+    }
+
+}
--- a/flys-artifacts/src/main/java/de/intevation/flys/utils/ArtifactMapfileGenerator.java	Fri Feb 22 15:50:06 2013 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,340 +0,0 @@
-package de.intevation.flys.utils;
-
-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.model.map.WSPLGENLayerFacet;
-import de.intevation.flys.artifacts.resources.Resources;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-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);
-    }
-
-    /**
-     * Method which starts searching for meta information file and mapfile
-     * generation.
-     */
-    @Override
-    public void generate() throws IOException
-    {
-        File[] userDirs = getUserDirs();
-        List<String> layers = parseLayers(userDirs);
-        logger.info("Found " + layers.size() + " layers for user mapfile.");
-
-        writeMapfile(layers);
-    }
-
-    /**
-     * Creates a layer file used for Mapserver's mapfile which represents the
-     * floodmap.
-     *
-     * @param flys The FLYSArtifact that owns <i>wms</i>.
-     * @param wms The WMSLayerFacet that contains information for the layer.
-     */
-    public void createUeskLayer(
-        FLYSArtifact  flys,
-        WSPLGENLayerFacet wms,
-        String        style,
-        CallContext context
-    ) throws FileNotFoundException, IOException
-    {
-        logger.debug("createUeskLayer");
-
-        LayerInfo layerinfo = new LayerInfo();
-        layerinfo.setName(MS_WSPLGEN_PREFIX + flys.identifier());
-        layerinfo.setType("POLYGON");
-        layerinfo.setDirectory(flys.identifier());
-        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 = MS_LAYER_PREFIX + wms.getName();
-
-        Template template = getTemplateByName(WSPLGEN_LAYER_TEMPLATE);
-        if (template == null) {
-            logger.warn("Template '" + WSPLGEN_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);
-        }
-    }
-
-
-    /**
-     * 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.
-     */
-    public 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_BARRIERS_PREFIX + 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_BARRIERS_PREFIX;
-            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);
-            }
-        }
-
-
-        /**
-         * Creates a layer file used for Mapserver's mapfile which represents the
-         * shape files uploaded by the user.
-         *
-         * @param flys The FLYSArtifact that owns <i>wms</i>.
-         * @param wms The WMSLayerFacet that contains information for the layer.
-         */
-        public void createUserShapeLayer(FLYSArtifact flys, WMSLayerFacet wms)
-        throws FileNotFoundException, IOException
-        {
-            logger.debug("createUserShapeLayer");
-
-            String uuid = flys.identifier();
-            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;
-            }
-
-            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_USERSHAPE_PREFIX;
-            String groupTitle = "I18N_USER_SHAPE_TITLE";
-
-            LayerInfo info = new LayerInfo();
-            info.setName(MS_USERSHAPE_PREFIX + uuid);
-            if (sfh.getShapeType().isLineType()) {
-                info.setType("LINE");
-            }
-            else if (sfh.getShapeType().isPolygonType()) {
-                info.setType("POLYGON");
-            }
-            else {
-                return;
-            }
-            info.setDirectory(uuid);
-            info.setData(WSPLGEN_USER_SHAPE);
-            info.setTitle("I18N_USER_SHAPE");
-            info.setGroup(group);
-            info.setGroupTitle(groupTitle);
-            info.setSrid(wms.getSrid());
-
-            String nameUser = MS_LAYER_PREFIX + wms.getName();
-
-            Template tpl = getTemplateByName(SHP_LAYER_TEMPLATE);
-            if (tpl == null) {
-                logger.warn("Template '" + SHP_LAYER_TEMPLATE + "' found.");
-                return;
-            }
-
-            try {
-                writeLayer(info, new File(dir, nameUser), tpl);
-            }
-            catch (FileNotFoundException fnfe) {
-                logger.error(fnfe, fnfe);
-                logger.warn("Unable to write layer: " + nameUser);
-            }
-
-        }
-
-
-        /**
-         * 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.
-         */
-        public 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/utils/FileUtils.java	Mon Feb 25 11:55:34 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);
+    }
+
+}
--- a/flys-artifacts/src/main/java/de/intevation/flys/utils/MapfileGenerator.java	Fri Feb 22 15:50:06 2013 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,384 +0,0 @@
-package de.intevation.flys.utils;
-
-import de.intevation.artifacts.common.utils.Config;
-import de.intevation.flys.artifacts.model.LayerInfo;
-
-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_WSPLGEN_PREFIX   = "wsplgen-";
-    public static final String MS_BARRIERS_PREFIX  = "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_USERSHAPE_PREFIX = "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.
-     */
-    public boolean templateExists(String templateID){
-        Template template = getTemplateByName(templateID);
-        return template != null;
-    }
-
-
-    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[] getUserDirs()
-            throws FileNotFoundException, IOException
-    {
-        File   baseDir      = getShapefileBaseDir();
-        File[] artifactDirs = baseDir.listFiles();
-
-        // TODO ONLY RETURN DIRECTORIES OF THE SPECIFIED USER
-
-        return artifactDirs;
-    }
-
-
-
-    protected List<String> parseLayers(File[] dirs) {
-        List<String> layers = new ArrayList<String>();
-
-        for (File dir: dirs) {
-            File[] layerFiles = dir.listFiles(new FilenameFilter() {
-                @Override
-                public boolean accept(File directory, String name) {
-                    return name.startsWith(MS_LAYER_PREFIX);
-                }
-            });
-
-            for (File layer: layerFiles) {
-                try {
-                    layers.add(layer.getCanonicalPath());
-                }
-                catch (IOException ioe) {
-                    logger.warn(ioe, ioe);
-                }
-            }
-        }
-
-        return layers;
-    }
-
-
-
-
-    /**
-     * 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/utils/PrintMap.java	Mon Feb 25 11:55:34 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/utils/RiverMapfileGenerator.java	Fri Feb 22 15:50:06 2013 +0100
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,142 +0,0 @@
-package de.intevation.flys.utils;
-
-import com.vividsolutions.jts.geom.Envelope;
-import com.vividsolutions.jts.geom.LineString;
-
-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 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;
-            }
-            LineString 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);
-    }
-}
--- a/flys-artifacts/src/main/java/de/intevation/flys/wsplgen/FacetCreator.java	Fri Feb 22 15:50:06 2013 +0100
+++ b/flys-artifacts/src/main/java/de/intevation/flys/wsplgen/FacetCreator.java	Mon Feb 25 11:55:34 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,7 +160,7 @@
             getUrl());
 
         barriers.addLayer(
-            MapfileGenerator.MS_BARRIERS_PREFIX + artifact.identifier());
+            MapfileGenerator.MS_PREFIX_WSPLGEN + artifact.identifier());
         barriers.setSrid(getSrid());
         barriers.setExtent(getBounds());
 
@@ -182,7 +182,7 @@
             getUrl());
 
         shape.addLayer(
-            MapfileGenerator.MS_USERSHAPE_PREFIX + artifact.identifier());
+            MapfileGenerator.MS_PREFIX_USER + artifact.identifier());
         shape.setSrid(getSrid());
         shape.setExtent(getBounds());
 

http://dive4elements.wald.intevation.org