1 package tim.prune.function.srtm;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.InputStream;
7 import java.io.IOException;
8 import java.util.zip.ZipEntry;
9 import java.util.zip.ZipInputStream;
11 public abstract class SrtmSource {
12 // methods implemented by each source
13 public abstract String getName();
14 public abstract boolean isReadyToUse();
15 public abstract boolean downloadTile(SrtmTile inTile)
16 throws SrtmSourceException;
17 public abstract int getRowSize(SrtmTile inTile);
18 protected abstract String getSourceExtension();
20 protected boolean downloadToFile(InputStream inStream, File outputFile)
23 FileOutputStream outStream = new FileOutputStream(outputFile);
25 byte[] buffer = new byte[4096];
27 while ((read = inStream.read(buffer)) != -1)
29 outStream.write(buffer, 0, read);
31 // Make sure streams are closed
32 try {inStream.close();} catch (Exception e) {}
33 try {outStream.close();} catch (Exception e) {}
38 protected int[] slurpTileHeigths(ZipInputStream inStream, int tileSize)
41 int[] heights = new int[tileSize];
42 int dataSize = 2 * tileSize;
43 byte[] buffer = new byte[dataSize];
44 // Read entire file contents into one byte array
46 while (alreadyRead < dataSize)
48 alreadyRead += inStream.read(buffer, alreadyRead, dataSize - alreadyRead);
50 for (int i = 0; i < tileSize; i++)
52 // Bytes are signed. Cast high-order to int with sign
53 // extension, and clamp low-order to its unsigned range
54 heights[i] = buffer[2 * i] * 256 + (0xff & buffer[2 * i + 1]);
61 public int[] getTileHeights(SrtmTile inTile)
62 throws SrtmSourceException
64 File cacheFileName = getCacheFileName(inTile);
65 if (cacheFileName == null)
67 throw new SrtmSourceException("Tile "+inTile.getTileName()+" not in cache");
71 ZipInputStream inStream = new ZipInputStream(new FileInputStream(cacheFileName));
72 ZipEntry entry = inStream.getNextEntry();
73 int rowSize = getRowSize(inTile);
74 int tileSize = rowSize * rowSize;
75 if (entry.getSize() != 2 * tileSize)
77 throw new SrtmSourceException("Tile file "+cacheFileName+" does not have the expected size");
79 return slurpTileHeigths(inStream, tileSize);
83 throw new SrtmSourceException("Failure opening "+cacheFileName+" for reading:"+e.getMessage());
88 protected File getCacheDir()
90 return SrtmDiskCache.getCacheDir(getName());
93 protected File getCacheFileName(SrtmTile inTile)
95 String fileName = inTile.getTileName() + getSourceExtension();
96 return new File(getCacheDir(), fileName);
99 public boolean isCached(SrtmTile inTile)
101 File cachedFileName = getCacheFileName(inTile);
102 return cachedFileName != null &&
103 getCacheFileName(inTile).exists();