]> gitweb.fperrin.net Git - GpsPrune.git/blobdiff - src/tim/prune/function/srtm/SrtmSource.java
Download tiles in chunks
[GpsPrune.git] / src / tim / prune / function / srtm / SrtmSource.java
index 0791cd833c28fc7a2acd14cb4901a1a675d3cae2..6e49ad18383060541e8378c854df365db86c0144 100644 (file)
@@ -3,11 +3,13 @@ package tim.prune.function.srtm;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
+import java.io.InputStream;
 import java.io.IOException;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipInputStream;
 
 public abstract class SrtmSource {
+       // methods implemented by each source
        public abstract String getName();
        public abstract boolean isReadyToUse();
        public abstract boolean downloadTile(SrtmTile inTile)
@@ -15,15 +17,41 @@ public abstract class SrtmSource {
        public abstract int getRowSize(SrtmTile inTile);
        protected abstract String getSourceExtension();
 
+       protected boolean downloadToFile(InputStream inStream, File outputFile)
+               throws IOException
+       {
+               FileOutputStream outStream = new FileOutputStream(outputFile);
+
+               byte[] buffer = new byte[4096];
+               int read = 0;
+               while ((read = inStream.read(buffer)) != -1)
+               {
+                       outStream.write(buffer, 0, read);
+               }
+               // Make sure streams are closed
+               try {inStream.close();} catch (Exception e) {}
+               try {outStream.close();} catch (Exception e) {}
+               return true;
+
+       }
+
        protected int[] slurpTileHeigths(ZipInputStream inStream, int tileSize)
                throws IOException
        {
                int[] heights = new int[tileSize];
+               int dataSize = 2 * tileSize;
+               byte[] buffer = new byte[dataSize];
                // Read entire file contents into one byte array
-               for (int i = 0; i < heights.length; i++)
+               int alreadyRead = 0;
+               while (alreadyRead < dataSize)
+               {
+                       alreadyRead += inStream.read(buffer, alreadyRead, dataSize - alreadyRead);
+               }
+               for (int i = 0; i < tileSize; i++)
                {
-                       heights[i] = inStream.read() * 256 + inStream.read();
-                       if (heights[i] >= 32768) {heights[i] -= 65536;}
+                       // Bytes are signed. Cast high-order to int with sign
+                       // extension, and clamp low-order to its unsigned range
+                       heights[i] = buffer[2 * i] * 256 + (0xff & buffer[2 * i + 1]);
                }
                // Close stream
                inStream.close();