comparison flys-artifacts/src/main/java/de/intevation/flys/artifacts/states/FloodMapState.java @ 3468:f37e7e8907cb

merged flys-artifacts/2.8.1
author Thomas Arendsen Hein <thomas@intevation.de>
date Fri, 28 Sep 2012 12:14:39 +0200
parents 453d2d0c4258
children b1912514e0f5
comparison
equal deleted inserted replaced
3387:5ffad8bde8ad 3468:f37e7e8907cb
1 package de.intevation.flys.artifacts.states;
2
3 import java.io.File;
4 import java.io.FileNotFoundException;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 import org.apache.log4j.Logger;
11 import org.geotools.feature.FeatureCollection;
12 import org.geotools.feature.FeatureCollections;
13 import org.geotools.feature.simple.SimpleFeatureBuilder;
14 import org.opengis.feature.simple.SimpleFeature;
15 import org.opengis.feature.simple.SimpleFeatureType;
16
17 import com.vividsolutions.jts.geom.Coordinate;
18 import com.vividsolutions.jts.geom.Geometry;
19 import com.vividsolutions.jts.geom.LineString;
20 import com.vividsolutions.jts.geom.Polygon;
21
22 import de.intevation.artifactdatabase.state.Facet;
23 import de.intevation.artifacts.Artifact;
24 import de.intevation.artifacts.CallContext;
25 import de.intevation.artifacts.CallMeta;
26 import de.intevation.artifacts.GlobalContext;
27 import de.intevation.artifacts.common.utils.FileTools;
28 import de.intevation.flys.artifacts.FLYSArtifact;
29 import de.intevation.flys.artifacts.context.FLYSContext;
30 import de.intevation.flys.artifacts.model.CalculationMessage;
31 import de.intevation.flys.artifacts.model.CalculationResult;
32 import de.intevation.flys.artifacts.model.FacetTypes;
33 import de.intevation.flys.artifacts.model.WQKms;
34 import de.intevation.flys.artifacts.model.map.WMSLayerFacet;
35 import de.intevation.flys.artifacts.model.map.WSPLGENCalculation;
36 import de.intevation.flys.artifacts.model.map.WSPLGENJob;
37 import de.intevation.flys.artifacts.model.map.WSPLGENReportFacet;
38 import de.intevation.flys.artifacts.resources.Resources;
39 import de.intevation.flys.exports.WstWriter;
40 import de.intevation.flys.model.CrossSectionTrack;
41 import de.intevation.flys.model.DGM;
42 import de.intevation.flys.model.Floodplain;
43 import de.intevation.flys.model.RiverAxis;
44 import de.intevation.flys.utils.FLYSUtils;
45 import de.intevation.flys.utils.GeometryUtils;
46 import de.intevation.flys.utils.MapfileGenerator;
47 import de.intevation.flys.wsplgen.FacetCreator;
48 import de.intevation.flys.wsplgen.JobObserver;
49 import de.intevation.flys.wsplgen.Scheduler;
50
51
52 public class FloodMapState
53 extends DefaultState
54 implements FacetTypes
55 {
56 /** The logger that is used in this state. */
57 private static Logger logger = Logger.getLogger(FloodMapState.class);
58
59
60 public static final String KEEP_ARTIFACT_DIR =
61 System.getProperty("flys.uesk.keep.artifactsdir", "false");
62
63
64 public static final String OUTPUT_NAME = "floodmap";
65
66 public static final String WSP_ARTIFACT = "wsp";
67
68 public static final String WINFO_WSP_STATE_ID = "state.winfo.waterlevel";
69
70 public static final String WSPLGEN_PARAMETER_FILE = "wsplgen.par";
71 public static final String WSPLGEN_BARRIERS_LINES = "barrier_lines.shp";
72 public static final String WSPLGEN_BARRIERS_POLY = "barrier_polygons.shp";
73 public static final String WSPLGEN_AXIS = "axis.shp";
74 public static final String WSPLGEN_QPS = "qps.shp";
75 public static final String WSPLGEN_FLOODPLAIN = "talaue.shp";
76 public static final String WSPLGEN_WSP_FILE = "waterlevel.wst";
77 public static final String WSPLGEN_OUTPUT_FILE = "wsplgen.shp";
78 public static final String WSPLGEN_USER_SHAPE = "user-rgd.shp";
79 public static final String WSPLGEN_USER_ZIP = "user-rgd.zip";
80 public static final String WSPLGEN_USER_FILENAME = "user-rgd";
81
82 public static final String WSPLGEN_QPS_NAME = "qps";
83
84 public static final int WSPLGEN_DEFAULT_OUTPUT = 0;
85
86
87 /**
88 * @param orig
89 * @param owner
90 * @param context
91 * @param callMeta
92 */
93 @Override
94 public void initialize(
95 Artifact orig,
96 Artifact owner,
97 Object context,
98 CallMeta callMeta
99 ) {
100 logger.info("Initialize State with Artifact: " + orig.identifier());
101
102 copyShapeDir(orig, owner);
103 modifyFacets(orig, owner, context, callMeta);
104
105 MapfileGenerator.getInstance().update();
106 }
107
108
109 protected void copyShapeDir(Artifact orig, Artifact owner) {
110 File origDir = getDirectory((FLYSArtifact) orig);
111 File thisDir = getDirectory((FLYSArtifact) owner);
112
113 FileTools.copyDirectory(origDir, thisDir);
114 }
115
116
117 protected void modifyFacets(
118 Artifact orig,
119 Artifact owner,
120 Object context,
121 CallMeta callMeta
122 ) {
123 FLYSArtifact flys = (FLYSArtifact) owner;
124 List<Facet> facets = flys.getFacets();
125 if (facets == null || facets.size() == 0) {
126 logger.warn("No facets for '" + OUTPUT_NAME + "' given!");
127 return;
128 }
129
130 for (Facet facet: facets) {
131 if (facet instanceof WMSLayerFacet) {
132 WMSLayerFacet wms = (WMSLayerFacet) facet;
133
134 List<String> layers = wms.getLayers();
135
136 for (String layer: layers) {
137 if (layer.startsWith(MapfileGenerator.MS_WSPLGEN_PREFIX)) {
138 wms.removeLayer(layer);
139
140 String newLayer = MapfileGenerator.MS_WSPLGEN_PREFIX +
141 owner.identifier();
142
143 wms.addLayer(newLayer);
144
145 logger.debug(
146 "Replaced layer: " + layer + " with " + newLayer);
147 }
148 }
149 }
150 }
151 }
152
153
154 @Override
155 public Object computeAdvance(
156 FLYSArtifact artifact,
157 String hash,
158 CallContext context,
159 List<Facet> facets,
160 Object old
161 ) {
162 logger.debug("FloodMapState.computeAdvance");
163
164 File artifactDir = getDirectory(artifact);
165
166 if (artifactDir == null) {
167 logger.error("Could not create directory for WSPLGEN results!");
168 return null;
169 }
170
171 WSPLGENCalculation calculation = new WSPLGENCalculation();
172
173 FacetCreator facetCreator = new FacetCreator(
174 artifact, context, hash, getID(), facets);
175
176 WSPLGENJob job = prepareWSPLGENJob(
177 artifact,
178 facetCreator,
179 artifactDir,
180 context,
181 calculation);
182
183 CalculationResult res = new CalculationResult(null, calculation);
184 WSPLGENReportFacet report= new WSPLGENReportFacet(
185 ComputeType.ADVANCE, hash, getID(), res);
186
187 facets.add(report);
188
189 if (job == null) {
190 if (KEEP_ARTIFACT_DIR.equals("false")) {
191 removeDirectory(artifact);
192 }
193
194 calculation.addError(-1, Resources.getMsg(
195 context.getMeta(),
196 "wsplgen.job.error",
197 "wsplgen.job.error"));
198
199 logger.error("No WSPLGEN processing has been started!");
200
201 return null;
202 }
203
204 context.afterCall(CallContext.BACKGROUND);
205 context.addBackgroundMessage(new CalculationMessage(
206 JobObserver.STEPS.length,
207 0,
208 Resources.getMsg(
209 context.getMeta(),
210 "wsplgen.job.queued",
211 "wsplgen.job.queued")
212 ));
213
214 GlobalContext gc = (GlobalContext) context.globalContext();
215 Scheduler scheduler = (Scheduler) gc.get(FLYSContext.SCHEDULER);
216 scheduler.addJob(job);
217
218 return null;
219 }
220
221
222 /**
223 * Returns (and creates if not existing) the directory for storing WSPLEN
224 * data for the owner artifact.
225 *
226 * @param artifact The owner Artifact.
227 *
228 * @return the directory for WSPLEN data.
229 */
230 protected File getDirectory(FLYSArtifact artifact) {
231 String shapePath = FLYSUtils.getXPathString(
232 FLYSUtils.XPATH_SHAPEFILE_DIR);
233
234 File artifactDir = FileTools.getDirectory(
235 shapePath, artifact.identifier());
236
237 return artifactDir;
238 }
239
240
241 /**
242 * Removes the directory and all its content where the required data and the
243 * results of WSPLGEN are stored. Should be called in endOfLife().
244 */
245 protected void removeDirectory(FLYSArtifact artifact) {
246 String shapePath = FLYSUtils.getXPathString(
247 FLYSUtils.XPATH_SHAPEFILE_DIR);
248
249 File artifactDir = new File(shapePath, artifact.identifier());
250
251 if (artifactDir.exists()) {
252 logger.info("Delete directory: " + artifactDir.getAbsolutePath());
253 boolean success = FileTools.deleteRecursive(artifactDir);
254 }
255 else {
256 logger.debug("There is no directory to remove.");
257 }
258 }
259
260
261 @Override
262 public void endOfLife(Artifact artifact, Object callContext) {
263 logger.info("FloodMapState.endOfLife: " + artifact.identifier());
264
265 FLYSArtifact flys = (FLYSArtifact) artifact;
266
267 Scheduler scheduler = Scheduler.getInstance();
268 scheduler.cancelJob(flys.identifier());
269
270 MapfileGenerator.getInstance().update();
271 }
272
273
274 protected WSPLGENJob prepareWSPLGENJob(
275 FLYSArtifact artifact,
276 FacetCreator facetCreator,
277 File artifactDir,
278 CallContext context,
279 WSPLGENCalculation calculation
280 ) {
281 logger.debug("FloodMapState.prepareWSPLGENJob");
282
283 WSPLGENJob job = new WSPLGENJob(
284 artifact,
285 artifactDir,
286 facetCreator,
287 context,
288 calculation);
289
290 File paraFile = new File(artifactDir, WSPLGEN_PARAMETER_FILE);
291
292 setOut(artifact, job);
293 setRange(artifact, job);
294 setDelta(artifact, job);
295 setGel(artifact, job);
296 setDist(artifact, job);
297 setLine(artifact, facetCreator, artifactDir, job);
298 setUserShape(artifact, facetCreator, artifactDir, job);
299 setAxis(artifact, artifactDir, job);
300 setPro(artifact, artifactDir, job);
301 setDgm(artifact, job);
302 setArea(artifact, artifactDir, job);
303 setOutFile(artifact, job);
304 setWsp(artifact, context, artifactDir, job); // WSP
305
306 // TODO
307 // setWspTag(artifact, job);
308
309 try {
310 job.toFile(paraFile);
311
312 return job;
313 }
314 catch (IOException ioe) {
315 logger.warn("Cannot write PAR file: " + ioe.getMessage());
316 }
317 catch (IllegalArgumentException iae) {
318 logger.warn("Cannot write PAR file: " + iae.getMessage());
319 }
320
321 return null;
322 }
323
324
325 protected void setOut(FLYSArtifact artifact, WSPLGENJob job) {
326 job.setOut(WSPLGEN_DEFAULT_OUTPUT);
327 }
328
329
330 protected void setRange(FLYSArtifact artifact, WSPLGENJob job) {
331 double[] range = FLYSUtils.getKmRange(artifact);
332
333 job.setStart(range[0]);
334 job.setEnd(range[1]);
335 }
336
337
338 protected void setDelta(FLYSArtifact artifact, WSPLGENJob job) {
339 String from = artifact.getDataAsString("diff_from");
340 String to = artifact.getDataAsString("diff_to");
341 String diff = artifact.getDataAsString("diff_diff");
342
343 try {
344 job.setFrom(Double.parseDouble(from));
345 }
346 catch (NumberFormatException nfe) {
347 }
348
349 try {
350 job.setTo(Double.parseDouble(to));
351 }
352 catch (NumberFormatException nfe) {
353 }
354
355 try {
356 job.setDiff(Double.parseDouble(diff));
357 }
358 catch (NumberFormatException nfe) {
359 }
360 }
361
362
363 protected void setGel(FLYSArtifact artifact, WSPLGENJob job) {
364 String gel = artifact.getDataAsString("scenario");
365
366 logger.debug("Selected gel = '" + gel + "'");
367
368 if (gel == null || gel.length() == 0) {
369 job.setGel(WSPLGENJob.GEL_NOSPERRE);
370 }
371 else if (gel.equals("scenario.current")) {
372 job.setGel(WSPLGENJob.GEL_SPERRE);
373 }
374 else if (gel.equals("scenario.scenario")) {
375 job.setGel(WSPLGENJob.GEL_SPERRE);
376 }
377 else {
378 job.setGel(WSPLGENJob.GEL_NOSPERRE);
379 }
380 }
381
382
383 protected void setDist(FLYSArtifact artifact, WSPLGENJob job) {
384 String dist = artifact.getDataAsString("profile_distance");
385
386 try {
387 job.setDist(Double.parseDouble(dist));
388 }
389 catch (NumberFormatException nfe) {
390 // nothing to do here
391 }
392 }
393
394
395 protected void setLine(
396 FLYSArtifact artifact,
397 FacetCreator facetCreator,
398 File dir,
399 WSPLGENJob job
400 ) {
401 String geoJSON = artifact.getDataAsString("uesk.barriers");
402 String srid = FLYSUtils.getRiverSrid(artifact);
403 String srs = "EPSG:" + srid;
404
405 if (geoJSON == null || geoJSON.length() == 0) {
406 logger.debug("No barrier features in parameterization existing.");
407 return;
408 }
409
410 SimpleFeatureType ft = getBarriersFeatureType(
411 "barriers", srs, Geometry.class);
412
413 List<SimpleFeature> features = GeometryUtils.parseGeoJSON(geoJSON, ft);
414 if (features == null || features.size() == 0) {
415 logger.debug("No barrier features extracted.");
416 return;
417 }
418
419 FeatureCollection[] fcs = splitLinesAndPolygons(features);
420
421 File shapeLines = new File(dir, WSPLGEN_BARRIERS_LINES);
422 File shapePolys = new File(dir, WSPLGEN_BARRIERS_POLY);
423
424 Object[][] obj = new Object[][] {
425 new Object[] { "typ", String.class }
426 };
427
428 String scenario = job.getGel();
429
430 boolean l = GeometryUtils.writeShapefile(
431 shapeLines,
432 GeometryUtils.buildFeatureType("lines", srs, LineString.class, obj),
433 fcs[0]);
434
435 if (l) {
436 logger.debug(
437 "Successfully created barrier line shapefile. " +
438 "Write shapefile path into WSPLGEN job.");
439
440 if (scenario.equals(WSPLGENJob.GEL_NOSPERRE)) {
441 logger.debug("WSPLGEN will not use barrier features.");
442 }
443 else {
444 job.addLin(shapeLines.getAbsolutePath());
445 }
446 }
447
448 boolean p = GeometryUtils.writeShapefile(
449 shapePolys,
450 GeometryUtils.buildFeatureType("polygons", srs, Polygon.class, obj),
451 fcs[1]);
452
453 if (p) {
454 logger.debug(
455 "Successfully created barrier polygon shapefile. " +
456 "Write shapefile path into WSPLGEN job.");
457
458 if (scenario.equals(WSPLGENJob.GEL_NOSPERRE)) {
459 logger.debug("WSPLGEN will not use barrier features.");
460 }
461 else {
462 job.addLin(shapePolys.getAbsolutePath());
463 }
464 }
465
466 if (p || l) {
467 facetCreator.createBarrierFacet();
468 }
469 }
470
471
472 protected void setUserShape(
473 FLYSArtifact artifact,
474 FacetCreator facetCreator,
475 File dir,
476 WSPLGENJob job
477 ) {
478 File archive = new File(dir, WSPLGEN_USER_ZIP);
479 boolean exists = archive.exists();
480 logger.debug("Zip file exists: " + exists);
481 if (exists) {
482 try {
483 File tmpDir = new File(dir, "usr_tmp");
484 FileTools.extractArchive(archive, tmpDir);
485 moveFiles(tmpDir, dir);
486 }
487 catch (IOException ioe) {
488 logger.warn("Zip archive " + dir + "/" + WSPLGEN_USER_ZIP + " could not be extracted.");
489 return;
490 }
491
492 job.addLin(dir + "/" + WSPLGEN_USER_SHAPE);
493 facetCreator.createUserShapeFacet();
494 }
495 }
496
497 protected SimpleFeatureType getBarriersFeatureType(
498 String name,
499 String srs,
500 Class type
501 ) {
502 Object[][] attrs = new Object[3][];
503 attrs[0] = new Object[] { "typ", String.class };
504 attrs[1] = new Object[] { "elevation", Double.class };
505 attrs[2] = new Object[] { "mark.selected", Integer.class };
506
507 return GeometryUtils.buildFeatureType(name, srs, type, attrs);
508 }
509
510
511 protected FeatureCollection[] splitLinesAndPolygons(List<SimpleFeature> f) {
512 FeatureCollection lines = FeatureCollections.newCollection();
513 FeatureCollection polygons = FeatureCollections.newCollection();
514
515 for (SimpleFeature feature: f) {
516 Geometry geom = (Geometry) feature.getDefaultGeometry();
517
518
519 if (geom instanceof LineString) {
520 geom = applyElevationAttribute(feature, (LineString) geom);
521 lines.add(feature);
522 }
523 else if (geom instanceof Polygon) {
524 geom = applyElevationAttribute(feature, (Polygon) geom);
525 polygons.add(feature);
526 }
527 else {
528 logger.warn("Feature not supported: " + geom.getClass());
529 }
530 }
531
532 logger.debug("Found " + lines.size() + " barrier lines.");
533 logger.debug("Found " + polygons.size() + " barrier polygons.");
534
535 return new FeatureCollection[] { lines, polygons };
536 }
537
538
539 protected static Geometry applyElevationAttribute(
540 SimpleFeature feature,
541 Geometry geom
542 ) {
543 logger.debug("Apply elevations for: " + geom.getClass());
544
545 List<Double> elevations = extractElevations(feature);
546 int numPoints = geom.getNumPoints();
547 int numElevation = elevations.size();
548
549 String typ = (String) feature.getAttribute("typ");
550
551 if (numPoints > numElevation) {
552 logger.warn("More vertices in Geometry than elevations given.");
553 }
554
555 Coordinate[] c = geom.getCoordinates();
556 for (int i = 0; i < numPoints; i++) {
557 if (i < numElevation) {
558 c[i].z = elevations.get(i);
559 }
560 else if (typ != null && typ.equals("Graben")) {
561 c[i].z = -9999d;
562 }
563 else {
564 c[i].z = 9999d;
565 }
566 }
567
568 return geom;
569 }
570
571
572 protected static List<Double> extractElevations(SimpleFeature feature) {
573 String tmp = (String) feature.getAttribute("elevation");
574 String typ = (String) feature.getAttribute("typ");
575
576 String[] elevations = tmp == null ? null : tmp.split(" ");
577
578 int num = elevations != null ? elevations.length : 0;
579
580 List<Double> list = new ArrayList<Double>(num);
581
582 for (int i = 0; i < num; i++) {
583 try {
584 list.add(Double.parseDouble(elevations[i]));
585 }
586 catch (NumberFormatException nfe) {
587 logger.warn("Error while parsing elevation at pos: " + i);
588 if (typ != null && typ.equals("Graben")) {
589 list.add(new Double(-9999.0));
590 }
591 else {
592 list.add(new Double(9999.0));
593 }
594 }
595 }
596
597 return list;
598 }
599
600
601 protected void setAxis(FLYSArtifact artifact, File dir, WSPLGENJob job) {
602 String river = artifact.getDataAsString("river");
603 String srid = FLYSUtils.getRiverSrid(artifact);
604 String srs = "EPSG:" + srid;
605
606 List<RiverAxis> axes = RiverAxis.getRiverAxis(river);
607 if (axes == null || axes.size() == 0) {
608 logger.warn("Could not find river axis for: '" + river + "'");
609 return;
610 }
611
612 SimpleFeatureType ft = GeometryUtils.buildFeatureType(
613 "axis", srs, LineString.class);
614
615 SimpleFeatureBuilder builder = new SimpleFeatureBuilder(ft);
616 FeatureCollection collection = FeatureCollections.newCollection();
617
618 for (int i = 0, n = axes.size(); i < n; i++) {
619 RiverAxis axis = axes.get(i);
620
621 builder.add(axis.getGeom());
622 collection.add(builder.buildFeature(String.valueOf(i)));
623
624 builder.reset();
625 }
626
627 File axisShape = new File(dir, WSPLGEN_AXIS);
628
629 boolean a = GeometryUtils.writeShapefile(
630 axisShape,
631 GeometryUtils.buildFeatureType("axis", srs, LineString.class),
632 collection);
633
634 if (a) {
635 job.setAxis(axisShape.getAbsolutePath());
636 }
637 }
638
639
640 protected void setPro(FLYSArtifact artifact, File dir, WSPLGENJob job) {
641 String river = artifact.getDataAsString("river");
642 String srid = FLYSUtils.getRiverSrid(artifact);
643 String srs = "EPSG:" + srid;
644
645 List<CrossSectionTrack> cst =
646 CrossSectionTrack.getCrossSectionTrack(river, WSPLGEN_QPS_NAME);
647
648 logger.debug("Found " + cst.size() + " CrossSectionTracks.");
649
650 Object[][] attrs = new Object[2][];
651 attrs[0] = new Object[] { "ELEVATION", Double.class };
652 attrs[1] = new Object[] { "KILOMETER", Double.class };
653
654 SimpleFeatureType ft = GeometryUtils.buildFeatureType(
655 "qps", srs, LineString.class, attrs);
656
657 SimpleFeatureBuilder builder = new SimpleFeatureBuilder(ft);
658 FeatureCollection collection = FeatureCollections.newCollection();
659
660 int i = 0;
661 for (CrossSectionTrack track: cst) {
662 builder.reset();
663 builder.add(track.getGeom());
664 builder.add(track.getZ().doubleValue());
665 builder.add(track.getKm().doubleValue());
666
667 collection.add(builder.buildFeature(String.valueOf(i++)));
668 }
669
670 File qpsShape = new File(dir, WSPLGEN_QPS);
671
672 boolean q = GeometryUtils.writeShapefile(
673 qpsShape,
674 GeometryUtils.buildFeatureType("qps", srs, LineString.class, attrs),
675 collection);
676
677 if (q) {
678 job.setPro(qpsShape.getAbsolutePath());
679 }
680 }
681
682
683 protected void setDgm(FLYSArtifact artifact, WSPLGENJob job) {
684 String dgm_id = artifact.getDataAsString("dgm");
685
686 int id = -1;
687 try {
688 id = Integer.parseInt(dgm_id);
689 }
690 catch (NumberFormatException nfe) { /* do nothing */ }
691
692 DGM dgm = DGM.getDGM(id);
693
694 if (dgm == null) {
695 logger.warn("Could not find specified DGM.");
696
697 return;
698 }
699
700 job.setDgm(dgm.getPath());
701 }
702
703
704 protected void setArea(FLYSArtifact artifact, File dir, WSPLGENJob job) {
705 String useFloodplain = artifact.getDataAsString("use_floodplain");
706 if (!Boolean.valueOf(useFloodplain)) {
707 logger.debug("WSPLGEN will not use floodplain.");
708 return;
709 }
710
711 String river = artifact.getDataAsString("river");
712 String srid = FLYSUtils.getRiverSrid(artifact);
713 String srs = "EPSG:" + srid;
714
715 Floodplain plain = Floodplain.getFloodplain(river);
716
717 SimpleFeatureType ft = GeometryUtils.buildFeatureType(
718 "talaue", srs, Polygon.class);
719
720 SimpleFeatureBuilder builder = new SimpleFeatureBuilder(ft);
721 builder.add(plain.getGeom());
722
723 FeatureCollection collection = FeatureCollections.newCollection();
724 collection.add(builder.buildFeature("0"));
725
726 File talaueShape = new File(dir, WSPLGEN_FLOODPLAIN);
727
728 boolean t = GeometryUtils.writeShapefile(
729 talaueShape,
730 GeometryUtils.buildFeatureType("talaue", srs, Polygon.class),
731 collection);
732
733 if (t) {
734 job.setArea(talaueShape.getAbsolutePath());
735 }
736 }
737
738
739 protected void setOutFile(FLYSArtifact artifact, WSPLGENJob job) {
740 job.setOutFile(WSPLGEN_OUTPUT_FILE);
741 }
742
743
744 protected WQKms getWQKms(FLYSArtifact flys, CallContext cc) {
745 String wspString = flys.getDataAsString(WSP_ARTIFACT);
746 String[] parts = wspString.split(";");
747
748 String otherArtifact = parts[0];
749
750 int idx = -1;
751 try {
752 idx = Integer.parseInt(parts[2]);
753 }
754 catch (NumberFormatException nfe) { /* do nothing */ }
755
756 FLYSArtifact src = otherArtifact != null
757 ? FLYSUtils.getArtifact(otherArtifact, cc)
758 : flys;
759
760 logger.debug("Use waterlevel provided by Artifact: " + src.identifier());
761
762 CalculationResult rawData = (CalculationResult) src.compute(
763 cc,
764 null,
765 WINFO_WSP_STATE_ID,
766 ComputeType.ADVANCE,
767 false);
768
769 WQKms[] wqkms = (WQKms[]) rawData.getData();
770
771 return wqkms == null || idx == -1 || idx >= wqkms.length
772 ? null
773 : wqkms[idx];
774 }
775
776
777 protected void setWsp(
778 FLYSArtifact artifact,
779 CallContext context,
780 File dir,
781 WSPLGENJob job)
782 {
783 logger.debug("FloodMapState.setWsp");
784
785 WQKms data = getWQKms(artifact, context);
786
787 if (data == null) {
788 logger.warn("No WST data found!");
789 return;
790 }
791
792 WstWriter writer = new WstWriter(1);
793
794 // TODO REMOVE job.setWspTag(...) This is only used until the user is
795 // able to select the WSP column himself!
796 boolean writeWspTag = true;
797
798 double[] buf = new double[4];
799 logger.debug("Add WST column: " + data.getName());
800 writer.addColumn(data.getName());
801
802 if (writeWspTag) {
803 job.setWspTag(data.getName());
804 writeWspTag = false;
805 }
806
807 for (int i = 0, num = data.size(); i < num; i++) {
808 data.get(i, buf);
809 writer.add(buf);
810 }
811
812 FileOutputStream fout = null;
813
814 try {
815 File wspFile = new File(dir, WSPLGEN_WSP_FILE);
816 fout = new FileOutputStream(wspFile);
817
818 writer.write(fout);
819
820 job.setWsp(wspFile.getAbsolutePath());
821 }
822 catch (FileNotFoundException fnfe) {
823 logger.warn("Error while writing wsp file: " + fnfe.getMessage());
824 }
825 finally {
826 if (fout != null) {
827 try {
828 fout.close();
829 }
830 catch (IOException ioe) { /* do nothing */ }
831 }
832 }
833 }
834
835
836 protected void moveFiles(File source, final File target)
837 throws IOException
838 {
839 if (!source.exists()) {
840 return;
841 }
842 if (!target.exists()) {
843 target.mkdir();
844 }
845 FileTools.walkTree(source, new FileTools.FileVisitor() {
846 public boolean visit(File file) {
847 if (!file.isDirectory()) {
848 String name = file.getName();
849 String suffix = "";
850 int pos = name.lastIndexOf('.');
851 if (pos > 0 && pos < name.length() - 1) {
852 suffix = name.substring(pos + 1);
853 }
854 else {
855 return true;
856 }
857 try {
858 FileTools.copyFile(file, new File(target, WSPLGEN_USER_FILENAME + "." + suffix));
859 }
860 catch (IOException ioe) {
861 logger.warn ("Error while copying file " + file.getName());
862 return true;
863 }
864 }
865 return true;
866 }
867 });
868
869 FileTools.deleteRecursive(source);
870 }
871 }
872 // vim:set ts=4 sw=4 si et sta sts=4 fenc=utf-8 :

http://dive4elements.wald.intevation.org