1 package tim.prune.function.srtm;
4 import java.io.FileOutputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
8 import java.net.URLConnection;
10 import tim.prune.GpsPrune;
11 import tim.prune.config.Config;
14 * Class to provide a download function for the Space Shuttle's SRTM data files.
15 * HGT files are downloaded into memory via HTTP and stored in the map cache.
17 public class TileDownloader
19 /** Possible results of the download */
20 public enum Result {DOWNLOADED, NOTHING_TO_DO, DOWNLOAD_FAILED, CACHE_FAILED};
23 * Download a single tile of SRTM data
24 * @param inUrl remote URL to get
26 public Result downloadTile(URL inUrl)
29 return Result.NOTHING_TO_DO;
32 // Check the cache is ok
33 final String diskCachePath = Config.getConfigString(Config.KEY_DISK_CACHE);
34 if (diskCachePath != null)
36 File srtmDir = new File(diskCachePath, "srtm");
37 if (srtmDir.exists() && !srtmDir.isDirectory()) {
38 // exists but isn't a directory - can't be used
39 return Result.CACHE_FAILED;
41 if (!srtmDir.exists() && !srtmDir.mkdir()) {
42 // can't create the srtm directory
43 return Result.CACHE_FAILED;
48 return Result.CACHE_FAILED;
52 FileOutputStream outStream = null;
53 InputStream inStream = null;
54 Result result = Result.NOTHING_TO_DO;
57 // See if we've already got this tile or not
58 File outputFile = getFileToWrite(inUrl);
59 if (outputFile != null)
61 System.out.println("Download: Need to download: " + inUrl);
62 outStream = new FileOutputStream(outputFile);
63 URLConnection conn = inUrl.openConnection();
64 conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
65 inStream = conn.getInputStream();
66 // Copy all the bytes to the file
68 while ((c = inStream.read()) != -1)
72 result = Result.DOWNLOADED;
75 catch (IOException ioe) {
76 System.err.println(ioe.getClass().getName() + " - " + ioe.getMessage());
77 result = Result.DOWNLOAD_FAILED;
79 // Make sure streams are closed
80 try {inStream.close();} catch (Exception e) {}
81 try {outStream.close();} catch (Exception e) {}
87 * See whether the SRTM file is already available locally
88 * @param inUrl URL for online resource
89 * @return file object to write to, or null if already there
91 private static File getFileToWrite(URL inUrl)
93 String diskCachePath = Config.getConfigString(Config.KEY_DISK_CACHE);
94 if (diskCachePath != null)
96 File srtmDir = new File(diskCachePath, "srtm");
97 if (srtmDir.exists() && srtmDir.isDirectory() && srtmDir.canRead())
99 File srtmFile = new File(srtmDir, new File(inUrl.getFile()).getName());
100 if (!srtmFile.exists() || !srtmFile.canRead() || srtmFile.length() <= 400) {