import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
+import java.net.CookieHandler;
+import java.net.CookieManager;
+import java.net.CookiePolicy;
import java.net.URL;
-import java.net.URLConnection;
+import java.net.HttpURLConnection;
import java.util.ArrayList;
+import java.util.Base64;
import javax.swing.JOptionPane;
*/
public DownloadSrtmFunction(App inApp) {
super(inApp);
+
+ CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
+
}
/** @return name key */
// Update progress bar
if (_progress != null)
{
- _progress.setMaximum(inTileList.size());
+ // advance by 1 for HTTP connection open, then by 1 for every tenth of the download
+ _progress.setMaximum(inTileList.size() * 11);
_progress.setValue(0);
}
try
{
// Set progress
- _progress.setValue(t);
+ _progress.setValue(t * 10);
// See if we've already got this tile or not
File outputFile = getFileToWrite(urls[t]);
if (outputFile != null)
{
- // System.out.println("Download: Need to download: " + urls[t]);
+ int redirects = 5;
+ System.out.println("Download: Need to download: " + urls[t]);
+ HttpURLConnection conn = (HttpURLConnection) urls[t].openConnection();
+ String auth = "Basic " + Base64.getEncoder().encodeToString(urls[t].getUserInfo().getBytes());
+ long fileLength = 0L;
+
+ while (redirects > 0) {
+ redirects--;
+
+ conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
+ conn.setRequestProperty("Authorization", auth);
+ conn.setInstanceFollowRedirects(false);
+ conn.setUseCaches(false);
+
+ int status = conn.getResponseCode();
+ if (status == 200)
+ {
+ inStream = conn.getInputStream();
+ fileLength = conn.getContentLengthLong();
+ break;
+ }
+ else if (status == 302)
+ {
+ // redirected to SSO server then back to original resource
+ String newUrl = conn.getHeaderField("Location");
+ conn = (HttpURLConnection) (new URL(newUrl)).openConnection();
+ }
+ else
+ {
+ throw new IOException("Invalid response from server: " +status+conn.getContent());
+ }
+ }
+ _progress.setValue(t * 10 + 1);
outStream = new FileOutputStream(outputFile);
- URLConnection conn = urls[t].openConnection();
- conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
- inStream = conn.getInputStream();
+
// Copy all the bytes to the file
int c;
+ long written = 0L;
while ((c = inStream.read()) != -1)
{
outStream.write(c);
+ written++;
+ _progress.setValue(t * 10 + 1 + (int) ((10 * written) / fileLength));
}
numDownloaded++;
}
- // else System.out.println("Don't need to download: " + urls[t].getFile());
+ else System.out.println("Don't need to download: " + urls[t].getFile());
}
catch (IOException ioe) {errorMessage = ioe.getClass().getName() + " - " + ioe.getMessage();
}