View Javadoc
1   package com.atlassian.refapp.sal;
2   
3   import javax.servlet.http.HttpServletRequest;
4   
5   /**
6    * Utility class for extracting the base URL (scheme, hostname, port, and context path) from an {@link
7    * HttpServletRequest}.
8    *
9    * @since 2.0.8
10   */
11  final class HttpServletRequestBaseUrlExtractor {
12      private HttpServletRequestBaseUrlExtractor() {
13          throw new AssertionError("may not be constructed");
14      }
15  
16      /**
17       * Extract the base URL from the specified request.
18       *
19       * @param request the current {@code HttpServletRequest}.  Must not be {@code null} or a {@code
20       *                NullPointerException} will be thrown.
21       * @return a string representation of the base URL of the current request
22       * @throws NullPointerException if {@code request} is {@code null}
23       */
24      static String extractBaseUrl(HttpServletRequest request) {
25          if (request == null) {
26              throw new NullPointerException("request parameter must not be null");
27          }
28          StringBuilder baseUrl = new StringBuilder(request.getScheme());
29          baseUrl.append("://").append(request.getServerName());
30          if (!isDefaultPort(request.getScheme(), request.getServerPort())) {
31              baseUrl.append(":").append(request.getServerPort());
32          }
33          baseUrl.append(request.getContextPath());
34          return baseUrl.toString();
35      }
36  
37      private static boolean isDefaultPort(String scheme, int serverPort) {
38          return (scheme.equals("http") && serverPort == 80) || (scheme.equals("https") && serverPort == 443);
39      }
40  }