package tim.prune.function.srtm; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public abstract class SrtmSource { public abstract String getName(); public abstract boolean isReadyToUse(); public abstract boolean downloadTile(SrtmTile inTile) throws SrtmSourceException; public abstract int getRowSize(SrtmTile inTile); protected abstract String getSourceExtension(); 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 int alreadyRead = 0; while (alreadyRead < dataSize) { alreadyRead += inStream.read(buffer, alreadyRead, dataSize - alreadyRead); } for (int i = 0; i < tileSize; i++) { // 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(); return heights; } public int[] getTileHeights(SrtmTile inTile) throws SrtmSourceException { File cacheFileName = getCacheFileName(inTile); if (cacheFileName == null) { throw new SrtmSourceException("Tile "+inTile.getTileName()+" not in cache"); } try { ZipInputStream inStream = new ZipInputStream(new FileInputStream(cacheFileName)); ZipEntry entry = inStream.getNextEntry(); int rowSize = getRowSize(inTile); int tileSize = rowSize * rowSize; if (entry.getSize() != 2 * tileSize) { throw new SrtmSourceException("Tile file "+cacheFileName+" does not have the expected size"); } return slurpTileHeigths(inStream, tileSize); } catch (IOException e) { throw new SrtmSourceException("Failure opening "+cacheFileName+" for reading:"+e.getMessage()); } } protected File getCacheDir() { return SrtmDiskCache.getCacheDir(getName()); } protected File getCacheFileName(SrtmTile inTile) { String fileName = inTile.getTileName() + getSourceExtension(); return new File(getCacheDir(), fileName); } public boolean isCached(SrtmTile inTile) { File cachedFileName = getCacheFileName(inTile); return cachedFileName != null && getCacheFileName(inTile).exists(); } }