]> gerrit.simantics Code Review - simantics/district.git/blob - org.simantics.maps.elevation.server/src/org/simantics/maps/elevation/server/TiffInterface.java
First version of elevation server based on GeoTIFF files
[simantics/district.git] / org.simantics.maps.elevation.server / src / org / simantics / maps / elevation / server / TiffInterface.java
1 package org.simantics.maps.elevation.server;
2
3 import java.awt.image.DataBuffer;
4 import java.nio.file.Path;
5
6 import org.geotools.coverage.grid.GridCoverage2D;
7 import org.geotools.gce.geotiff.GeoTiffReader;
8 import org.geotools.geometry.Envelope2D;
9 import org.opengis.geometry.DirectPosition;
10 import org.opengis.referencing.crs.CoordinateReferenceSystem;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
13
14 public class TiffInterface {
15
16     private static final Logger LOGGER = LoggerFactory.getLogger(TiffInterface.class);
17
18     private final Path tifPath;
19     private GridCoverage2D coverage;
20     private CoordinateReferenceSystem crs;
21
22     private boolean init = false;
23
24     public TiffInterface(Path tifPath) {
25         this.tifPath = tifPath;
26         loadMetadata();
27     }
28
29     private void loadMetadata() {
30         GeoTiffReader reader = null;
31         try {
32             reader = new GeoTiffReader(this.tifPath.toFile());
33             this.coverage = reader.read(null);
34             this.crs = coverage.getCoordinateReferenceSystem();
35             this.init = true;
36         } catch (Exception e) {
37             LOGGER.error("Could not load {}", tifPath, e);
38         } finally {
39             if (reader != null) {
40                 reader.dispose();
41             }
42         }
43     }
44
45     public Number lookup(DirectPosition pos) {
46         ensureInit();
47         Object r = coverage.evaluate(pos);
48         final int dataType = coverage.getRenderedImage().getSampleModel().getDataType();
49         switch (dataType) {
50             case DataBuffer.TYPE_BYTE:   return new Byte(((byte[]) r)[0]);
51             case DataBuffer.TYPE_SHORT:  // Fall through
52             case DataBuffer.TYPE_USHORT: // Fall through
53             case DataBuffer.TYPE_INT:    return new Integer(((int[]) r)[0]);
54             case DataBuffer.TYPE_FLOAT:  return new Float(((float[]) r)[0]);
55             case DataBuffer.TYPE_DOUBLE: return new Double(((double[]) r)[0]);
56             default: return null;
57         }
58     }
59
60     private void ensureInit() {
61         if (!init) {
62             throw new IllegalStateException("Interface is not initialized for " + this.tifPath);
63         }
64     }
65
66     public void close() {
67         coverage.dispose(true);
68     }
69
70     public Envelope2D getCornerCoords() {
71         return coverage.getEnvelope2D();
72     }
73
74     public CoordinateReferenceSystem getCRS() {
75         return crs;
76     }
77 }