package eu.openaire.urls_controller.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.env.Environment; import java.net.InetAddress; public class UriBuilder { private static final Logger logger = LoggerFactory.getLogger(UriBuilder.class); public static String baseUrl = null; public UriBuilder(Environment environment) { 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 += "://"; String hostName = InetAddress.getLoopbackAddress().getHostName(); // Non-null. baseUrl += hostName; String serverPort = environment.getProperty("server.port"); if (serverPort == null) { // This is unacceptable! logger.error("No property \"server.port\" was found in \"application.properties\"!"); System.exit(-1); // Well, I guess the Spring Boot would not start in this case anyway. } baseUrl += ":" + serverPort; 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); } public static String getBaseUrl() { return baseUrl; } public static void setBaseUrl(String baseUrl) { UriBuilder.baseUrl = baseUrl; } }