Added getBaseUrl to Utils

This commit is contained in:
Giuseppe Digilio
2020-02-24 10:02:49 +01:00
parent a28cb7551c
commit 8cbe3e1f30
2 changed files with 37 additions and 0 deletions

View File

@@ -13,8 +13,10 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.rmi.dgc.VMID;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
@@ -414,6 +416,20 @@ public final class Utils {
}
}
/**
* Retrieve the baseurl from a given URL string
* @param urlString URL string
* @return baseurl (without any context path) or null (if URL was invalid)
*/
public static String getBaseUrl(String urlString) {
try {
URL url = new URL(urlString);
String baseUrl = url.getProtocol() + "://" + url.getHost();
return baseUrl;
} catch (MalformedURLException e) {
return null;
}
}
/**
* Retrieve the hostname from a given URI string

View File

@@ -22,6 +22,27 @@ import org.junit.Test;
*/
public class UtilsTest extends AbstractUnitTest {
/**
* Test of getBaseUrl method, of class Utils
*/
@Test
public void testGetBaseUrl() {
assertEquals("Test remove /server", "http://dspace.org",
Utils.getBaseUrl("http://dspace.org/server"));
assertEquals("Test remove /server/api/core/items", "https://dspace.org",
Utils.getBaseUrl("https://dspace.org/server/api/core/items"));
assertEquals("Test remove trailing slash", "https://dspace.org",
Utils.getBaseUrl("https://dspace.org/"));
assertEquals("Test keep url", "https://demo.dspace.org",
Utils.getBaseUrl("https://demo.dspace.org"));
// This uses a bunch of reserved URI characters
assertNull("Test invalid URI returns null", Utils.getBaseUrl("&+,?/@="));
}
/**
* Test of getHostName method, of class Utils
*/