package mil.dds.anet.utils;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.HttpHeaders;

public class HttpsRedirectFilter implements Filter {


  @Override
  public void init(FilterConfig filterConfig) throws ServletException {}

  @Override
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {
    if (req instanceof HttpServletRequest) {
      HttpServletRequest request = (HttpServletRequest) req;
      if ("http".equals(request.getScheme())) {
        StringBuffer url = request.getRequestURL();
        if (request.getQueryString() != null) {
          url.append("?");
          url.append(request.getQueryString());
        }
        String redirectUrl = url.toString().replaceFirst("http", "https");
        HttpServletResponse response = (HttpServletResponse) res;
        response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
        response.setHeader(HttpHeaders.LOCATION, redirectUrl);
        return;
      }
    }
    chain.doFilter(req, res);
  }

  @Override
  public void destroy() {}


}

@@ -391,16 +391,97 @@
 Headers;
+%0Aimport org.eclipse.jetty.http.HttpScheme;%0Aimport org.eclipse.jetty.util.URIUtil;
 %0A%0Apublic
@@ -802,24 +802,30 @@
 st) %7B%0A      
+final 
 HttpServletR
@@ -877,22 +877,42 @@
     if (
-%22http%22
+HttpScheme.HTTP.asString()
 .equals(
@@ -947,51 +947,78 @@
     
-StringBuffer url = request.getRequestURL();
+final String redirectUrl = URIUtil.newURI(HttpScheme.HTTPS.asString(),
 %0A   
@@ -1022,20 +1022,20 @@
         
-if (
+    
 request.
@@ -1041,200 +1041,92 @@
 .get
-QueryString() != null) %7B%0A          url.append(%22?%22);%0A          url.append(request.getQueryString());%0A        %7D%0A        String redirectUrl = url.toString().replaceFirst(%22http%22, %22https%22);%0A       
+ServerName(), 443, request.getRequestURI(), request.getQueryString());%0A        final
  Htt

Make HTTPS redirect safer