comparison artifacts/src/main/java/org/dive4elements/river/utils/MapfileGenerator.java @ 5838:5aa05a7a34b7

Rename modules to more fitting names.
author Sascha L. Teichmann <teichmann@intevation.de>
date Thu, 25 Apr 2013 15:23:37 +0200
parents flys-artifacts/src/main/java/org/dive4elements/river/utils/MapfileGenerator.java@bd047b71ab37
children 4897a58c8746
comparison
equal deleted inserted replaced
5837:d9901a08d0a6 5838:5aa05a7a34b7
1 package org.dive4elements.river.utils;
2
3 import org.dive4elements.artifacts.common.utils.Config;
4 import org.dive4elements.river.artifacts.model.LayerInfo;
5
6 import java.io.File;
7 import java.io.FileNotFoundException;
8 import java.io.FileWriter;
9 import java.io.FilenameFilter;
10 import java.io.IOException;
11 import java.io.Writer;
12 import java.util.ArrayList;
13 import java.util.Date;
14 import java.util.List;
15
16 import org.apache.log4j.Logger;
17 import org.apache.velocity.Template;
18 import org.apache.velocity.VelocityContext;
19 import org.apache.velocity.app.VelocityEngine;
20 import org.apache.velocity.runtime.RuntimeConstants;
21
22 /**
23 * This class iterates over a bunch of directories, searches for meta
24 * information coresponding to shapefiles and creates a mapfile which is used by
25 * a <i>MapServer</i>.
26 *
27 * @author <a href="mailto:ingo.weinzierl@intevation.de">Ingo Weinzierl</a>
28 */
29 public abstract class MapfileGenerator
30 {
31 public static final String WSPLGEN_RESULT_SHAPE = "wsplgen.shp";
32 public static final String WSPLGEN_LINES_SHAPE = "barrier_lines.shp";
33 public static final String WSPLGEN_POLYGONS_SHAPE = "barrier_polygons.shp";
34 public static final String WSPLGEN_USER_SHAPE = "user-rgd.shp";
35
36 public static final String WSPLGEN_LAYER_TEMPLATE = "wsplgen_layer.vm";
37 public static final String SHP_LAYER_TEMPLATE = "shapefile_layer.vm";
38 public static final String DB_LAYER_TEMPLATE = "db_layer.vm";
39 public static final String RIVERAXIS_LAYER_TEMPLATE = "riveraxis-layer.vm";
40
41 public static final String MS_WSPLGEN_PREFIX = "wsplgen-";
42 public static final String MS_BARRIERS_PREFIX = "barriers-";
43 public static final String MS_LINE_PREFIX = "lines-";
44 public static final String MS_POLYGONS_PREFIX = "polygons-";
45 public static final String MS_LAYER_PREFIX = "ms_layer-";
46 public static final String MS_USERSHAPE_PREFIX = "user-";
47
48 private static Logger logger = Logger.getLogger(MapfileGenerator.class);
49
50 private File shapefileDirectory;
51
52 private VelocityEngine velocityEngine;
53
54
55 protected MapfileGenerator() {
56 }
57
58
59 /**
60 * Method to check the existance of a template file.
61 *
62 * @param templateID The name of a template.
63 * @return true, of the template exists - otherwise false.
64 */
65 public boolean templateExists(String templateID){
66 Template template = getTemplateByName(templateID);
67 return template != null;
68 }
69
70
71 public abstract void generate() throws Exception;
72
73
74 /**
75 * Returns the VelocityEngine used for the template mechanism.
76 *
77 * @return the velocity engine.
78 */
79 protected VelocityEngine getVelocityEngine() {
80 if (velocityEngine == null) {
81 velocityEngine = new VelocityEngine();
82 try {
83 setupVelocity(velocityEngine);
84 }
85 catch (Exception e) {
86 logger.error(e, e);
87 return null;
88 }
89 }
90 return velocityEngine;
91 }
92
93
94 /**
95 * Initialize velocity.
96 *
97 * @param engine Velocity engine.
98 * @throws Exception if an error occured while initializing velocity.
99 */
100 protected void setupVelocity(VelocityEngine engine)
101 throws Exception
102 {
103 engine.setProperty(
104 "input.encoding",
105 "UTF-8");
106
107 engine.setProperty(
108 RuntimeConstants.RUNTIME_LOG,
109 getVelocityLogfile());
110
111 engine.setProperty(
112 "resource.loader",
113 "file");
114
115 engine.setProperty(
116 "file.resource.loader.path",
117 getMapserverTemplatePath());
118
119 engine.init();
120 }
121
122 protected abstract String getVelocityLogfile();
123
124 protected abstract String getMapserverTemplatePath();
125
126 public abstract String getMapserverUrl();
127
128 protected VelocityContext getVelocityContext() {
129 VelocityContext context = new VelocityContext();
130
131 try {
132 context.put("MAPSERVERURL",
133 getMapserverUrl());
134 context.put("SHAPEFILEPATH",
135 getShapefileBaseDir().getCanonicalPath());
136 context.put("CONFIGDIR",
137 Config.getConfigDirectory().getCanonicalPath());
138 }
139 catch (FileNotFoundException fnfe) {
140 // this is bad
141 logger.warn(fnfe, fnfe);
142 }
143 catch (IOException ioe) {
144 // this is also bad
145 logger.warn(ioe, ioe);
146 }
147
148 return context;
149 }
150
151
152 /**
153 * Returns a template specified by <i>model</i>.
154 *
155 * @param model The name of the template.
156 * @return a template.
157 */
158 public Template getTemplateByName(String model) {
159 if (model.indexOf(".vm") < 0) {
160 model = model.concat(".vm");
161 }
162
163 try {
164 VelocityEngine engine = getVelocityEngine();
165 if (engine == null) {
166 logger.error("Error while fetching VelocityEngine.");
167 return null;
168 }
169
170 return engine.getTemplate(model);
171 }
172 catch (Exception e) {
173 logger.warn(e, e);
174 }
175
176 return null;
177 }
178
179
180 /**
181 * Returns the mapfile template.
182 *
183 * @return the mapfile template.
184 * @throws Exception if an error occured while reading the configuration.
185 */
186 protected Template getMapfileTemplateObj()
187 throws Exception
188 {
189 String mapfileName = getMapfileTemplate();
190 return getTemplateByName(mapfileName);
191 }
192
193 protected abstract String getMapfilePath();
194
195 protected abstract String getMapfileTemplate();
196
197
198 /**
199 * Returns the base directory storing the shapefiles.
200 *
201 * @return the shapefile base directory.
202 *
203 * @throws FileNotFoundException if no shapefile path is found or
204 * configured.
205 */
206 public File getShapefileBaseDir()
207 throws FileNotFoundException, IOException
208 {
209 if (shapefileDirectory == null) {
210 String path = FLYSUtils.getXPathString(
211 FLYSUtils.XPATH_FLOODMAP_SHAPEFILE_DIR);
212
213 if (path != null) {
214 shapefileDirectory = new File(path);
215 }
216
217 if (shapefileDirectory == null) {
218 throw new FileNotFoundException("No shapefile directory given");
219 }
220
221 if (!shapefileDirectory.exists()) {
222 shapefileDirectory.mkdirs();
223 }
224 }
225
226 return shapefileDirectory;
227 }
228
229
230 protected File[] getUserDirs()
231 throws FileNotFoundException, IOException
232 {
233 File baseDir = getShapefileBaseDir();
234 File[] artifactDirs = baseDir.listFiles();
235
236 // TODO ONLY RETURN DIRECTORIES OF THE SPECIFIED USER
237
238 return artifactDirs;
239 }
240
241
242
243 protected List<String> parseLayers(File[] dirs) {
244 List<String> layers = new ArrayList<String>();
245
246 for (File dir: dirs) {
247 File[] layerFiles = dir.listFiles(new FilenameFilter() {
248 @Override
249 public boolean accept(File directory, String name) {
250 return name.startsWith(MS_LAYER_PREFIX);
251 }
252 });
253
254 for (File layer: layerFiles) {
255 try {
256 layers.add(layer.getCanonicalPath());
257 }
258 catch (IOException ioe) {
259 logger.warn(ioe, ioe);
260 }
261 }
262 }
263
264 return layers;
265 }
266
267
268
269
270 /**
271 * Creates a layer snippet which might be included in the mapfile.
272 *
273 * @param layerinfo A LayerInfo object that contains all necessary
274 * information to build a Mapserver LAYER section.
275 * @param dir The base dir for the LAYER snippet.
276 * @param filename The name of the file that is written.
277 * @param tpl The Velocity template which is used to create the LAYER
278 * section.
279 */
280 public void writeLayer(
281 LayerInfo layerInfo,
282 File layerFile,
283 Template tpl
284 )
285 throws FileNotFoundException
286 {
287 if (logger.isDebugEnabled()) {
288 logger.debug("Write layer for:");
289 logger.debug(" directory/file: " + layerFile.getName());
290 }
291
292 Writer writer = null;
293
294 try {
295 writer = new FileWriter(layerFile);
296
297 VelocityContext context = getVelocityContext();
298 context.put("LAYER", layerInfo);
299
300 tpl.merge(context, writer);
301 }
302 catch (FileNotFoundException fnfe) {
303 logger.error(fnfe, fnfe);
304 }
305 catch (IOException ioe) {
306 logger.error(ioe, ioe);
307 }
308 catch (Exception e) {
309 logger.error(e, e);
310 }
311 finally {
312 try {
313 if (writer != null) {
314 writer.close();
315 }
316 }
317 catch (IOException ioe) {
318 logger.debug(ioe, ioe);
319 }
320 }
321 }
322
323
324 /**
325 * Creates a mapfile with the layer information stored in <i>layers</i>.
326 *
327 * @param layers Layer information.
328 */
329 public void writeMapfile(List<String> layers) {
330 String tmpMapName = "mapfile" + new Date().getTime();
331
332 File mapfile = new File(getMapfilePath());
333
334 File tmp = null;
335 Writer writer = null;
336
337 try {
338 tmp = new File(mapfile.getParent(), tmpMapName);
339 tmp.createNewFile();
340
341 writer = new FileWriter(tmp);
342
343 VelocityContext context = getVelocityContext();
344 context.put("LAYERS", layers);
345
346 Template mapTemplate = getMapfileTemplateObj();
347 if (mapTemplate == null) {
348 logger.warn("No mapfile template found.");
349 return;
350 }
351
352 mapTemplate.merge(context, writer);
353
354 // we need to create a temporary mapfile first und rename it into
355 // real mapfile because we don't run into race conditions on this
356 // way. (iw)
357 tmp.renameTo(mapfile);
358 }
359 catch (FileNotFoundException fnfe) {
360 logger.error(fnfe, fnfe);
361 }
362 catch (IOException ioe) {
363 logger.error(ioe, ioe);
364 }
365 catch (Exception e) {
366 logger.error(e, e);
367 }
368 finally {
369 try {
370 if (writer != null) {
371 writer.close();
372 }
373
374 if (tmp.exists()) {
375 tmp.delete();
376 }
377 }
378 catch (IOException ioe) {
379 logger.debug(ioe, ioe);
380 }
381 }
382 }
383 }
384 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf8 :

http://dive4elements.wald.intevation.org