1 package tim.prune.function.srtm;
4 import java.io.FileInputStream;
5 import java.io.FileOutputStream;
6 import java.io.IOException;
7 import java.util.zip.ZipEntry;
8 import java.util.zip.ZipInputStream;
10 public abstract class SrtmSource {
11 public abstract String getName();
12 public abstract boolean isReadyToUse();
13 public abstract boolean downloadTile(SrtmTile inTile)
14 throws SrtmSourceException;
15 public abstract int getRowSize(SrtmTile inTile);
16 protected abstract String getSourceExtension();
18 protected int[] slurpTileHeigths(ZipInputStream inStream, int tileSize)
21 int[] heights = new int[tileSize];
22 int dataSize = 2 * tileSize;
23 byte[] buffer = new byte[dataSize];
24 // Read entire file contents into one byte array
26 while (alreadyRead < dataSize)
28 alreadyRead += inStream.read(buffer, alreadyRead, dataSize - alreadyRead);
30 for (int i = 0; i < tileSize; i++)
32 // Bytes are signed. Cast high-order to int with sign
33 // extension, and clamp low-order to its unsigned range
34 heights[i] = buffer[2 * i] * 256 + (0xff & buffer[2 * i + 1]);
41 public int[] getTileHeights(SrtmTile inTile)
42 throws SrtmSourceException
44 File cacheFileName = getCacheFileName(inTile);
45 if (cacheFileName == null)
47 throw new SrtmSourceException("Tile "+inTile.getTileName()+" not in cache");
51 ZipInputStream inStream = new ZipInputStream(new FileInputStream(cacheFileName));
52 ZipEntry entry = inStream.getNextEntry();
53 int rowSize = getRowSize(inTile);
54 int tileSize = rowSize * rowSize;
55 if (entry.getSize() != 2 * tileSize)
57 throw new SrtmSourceException("Tile file "+cacheFileName+" does not have the expected size");
59 return slurpTileHeigths(inStream, tileSize);
63 throw new SrtmSourceException("Failure opening "+cacheFileName+" for reading:"+e.getMessage());
68 protected File getCacheDir()
70 return SrtmDiskCache.getCacheDir(getName());
73 protected File getCacheFileName(SrtmTile inTile)
75 String fileName = inTile.getTileName() + getSourceExtension();
76 return new File(getCacheDir(), fileName);
79 public boolean isCached(SrtmTile inTile)
81 File cachedFileName = getCacheFileName(inTile);
82 return cachedFileName != null &&
83 getCacheFileName(inTile).exists();