From 1c8100d3f3f6c684f83565b56431d6153404f3e2 Mon Sep 17 00:00:00 2001
From: carlosuc3m <100329787@alumnos.uc3m.es>
Date: Wed, 5 Jul 2023 19:25:29 +0200
Subject: [PATCH] add redirection of URLs

---
 .../DeepLearningVersionDownloader.java        | 34 ++++++++++++++++++-
 1 file changed, 33 insertions(+), 1 deletion(-)

diff --git a/src/main/java/org/bioimageanalysis/icy/deeplearning/versionmanager/downloading/DeepLearningVersionDownloader.java b/src/main/java/org/bioimageanalysis/icy/deeplearning/versionmanager/downloading/DeepLearningVersionDownloader.java
index e55cfc8..8f4ef74 100644
--- a/src/main/java/org/bioimageanalysis/icy/deeplearning/versionmanager/downloading/DeepLearningVersionDownloader.java
+++ b/src/main/java/org/bioimageanalysis/icy/deeplearning/versionmanager/downloading/DeepLearningVersionDownloader.java
@@ -7,6 +7,7 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.net.HttpURLConnection;
 import java.net.MalformedURLException;
+import java.net.URISyntaxException;
 import java.net.URL;
 import java.nio.channels.Channels;
 import java.nio.channels.ReadableByteChannel;
@@ -261,7 +262,8 @@ public class DeepLearningVersionDownloader
         {
             HttpURLConnection httpConnection = (HttpURLConnection) (url.openConnection());
             while (httpConnection.getResponseCode() == 302) {
-            	url = new URL(httpConnection.getHeaderField("Location"));
+            	// TODO use method from JDLL
+            	url = redirectedURL(url, httpConnection);
             	httpConnection = (HttpURLConnection) (url.openConnection());
             }
             long completeFileSize = httpConnection.getContentLengthLong();
@@ -297,6 +299,36 @@ public class DeepLearningVersionDownloader
         }
         return localFilePath;
     }
+    
+    /**
+     * TODO replae and use method from JDLL
+     * @param url
+     * @param conn
+     * @return
+     */
+	public static URL redirectedURL(URL url, HttpURLConnection conn) {
+		int statusCode;
+		try {
+			statusCode = conn.getResponseCode();
+		} catch (IOException ex) {
+			return url;
+		}
+		if (statusCode != HttpURLConnection.HTTP_MOVED_TEMP
+            && statusCode != HttpURLConnection.HTTP_MOVED_PERM
+            && statusCode != HttpURLConnection.HTTP_SEE_OTHER)
+			return url;
+		String newURL = conn.getHeaderField("Location");
+		try {
+			return new URL(newURL);
+		} catch (MalformedURLException ex) {
+		}
+        try {
+			String mainDomain = url.toURI().getHost();
+			return new URL(mainDomain + newURL);
+		} catch (URISyntaxException | MalformedURLException e) {
+			return null;
+		}
+	}
 
     /**
      * Retrieves the paths of all resources associated to a given version resolved locally.
-- 
GitLab