83 lines
2.7 KiB
Java
83 lines
2.7 KiB
Java
package eu.openaire.urls_worker.util;
|
|
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
|
|
import org.springframework.core.env.Environment;
|
|
|
|
import java.io.BufferedReader;
|
|
import java.io.InputStreamReader;
|
|
import java.net.InetAddress;
|
|
import java.net.MalformedURLException;
|
|
import java.net.URL;
|
|
|
|
public class UriBuilder {
|
|
|
|
private static final Logger logger = LoggerFactory.getLogger(UriBuilder.class);
|
|
|
|
|
|
public static String ip = null;
|
|
public static String baseUrl = null;
|
|
|
|
public UriBuilder(Environment environment, ServletWebServerApplicationContext webServerAppCtxt) {
|
|
baseUrl = "http";
|
|
|
|
String sslEnabled = environment.getProperty("server.ssl.enabled");
|
|
if (sslEnabled == null) { // It's expected to not exist if there is no SSL-configuration.
|
|
logger.warn("No property \"server.ssl.enabled\" was found in \"application.properties\". Continuing with plain HTTP..");
|
|
sslEnabled = "false";
|
|
}
|
|
baseUrl += sslEnabled.equals("true") ? "s" : "";
|
|
baseUrl += "://";
|
|
|
|
ip = getPublicIP();
|
|
if ( ip == null )
|
|
ip = InetAddress.getLoopbackAddress().getHostAddress(); // Non-null.
|
|
|
|
baseUrl += ip + ":" + webServerAppCtxt.getWebServer().getPort();
|
|
|
|
String baseInternalPath = environment.getProperty("server.servlet.context-path");
|
|
if ( baseInternalPath != null ) {
|
|
if ( !baseInternalPath.startsWith("/") )
|
|
baseUrl += "/";
|
|
baseUrl += baseInternalPath;
|
|
if ( !baseInternalPath.endsWith("/") )
|
|
baseUrl += "/";
|
|
} else {
|
|
logger.warn("No property \"server.servlet.context-path\" was found in \"application.properties\"!"); // Yes it's expected.
|
|
baseUrl += "/";
|
|
}
|
|
|
|
logger.debug("ServerBaseURL: " + baseUrl);
|
|
}
|
|
|
|
private static String getPublicIP()
|
|
{
|
|
String publicIpAddress = "";
|
|
URL url_name;
|
|
try {
|
|
url_name = new URL("https://api.ipify.org/");
|
|
} catch (MalformedURLException mue) {
|
|
logger.warn(mue.getMessage());
|
|
return null;
|
|
}
|
|
try ( BufferedReader bf = new BufferedReader(new InputStreamReader(url_name.openStream()))) {
|
|
publicIpAddress = bf.readLine().trim();
|
|
} catch (Exception e) {
|
|
logger.warn("Cannot get the publicIP address for this machine!", e);
|
|
return null;
|
|
}
|
|
return publicIpAddress;
|
|
}
|
|
|
|
public static String getBaseUrl() {
|
|
return baseUrl;
|
|
}
|
|
|
|
public static void setBaseUrl(String baseUrl) {
|
|
UriBuilder.baseUrl = baseUrl;
|
|
}
|
|
|
|
}
|