View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.rewrite.handler;
20  
21  import javax.servlet.http.HttpServletRequest;
22  
23  import org.eclipse.jetty.util.URIUtil;
24  
25  /**
26   * Utility for managing redirect based rules
27   */
28  public final class RedirectUtil
29  {
30      /**
31       * Common point to generate a proper "Location" header for redirects.
32       * 
33       * @param request
34       *            the request the redirect should be based on (needed when relative locations are provided, so that
35       *            server name, scheme, port can be built out properly)
36       * @param location
37       *            the location URL to redirect to (can be a relative path)
38       * @return the full redirect "Location" URL (including scheme, host, port, path, etc...)
39       */
40      public static String toRedirectURL(final HttpServletRequest request, String location)
41      {
42          if (!URIUtil.hasScheme(location))
43          {
44              StringBuilder url = new StringBuilder(128);
45              URIUtil.appendSchemeHostPort(url,request.getScheme(),request.getServerName(),request.getServerPort());
46  
47              if (location.startsWith("/"))
48              {
49                  // absolute in context
50                  location = URIUtil.canonicalPath(location);
51              }
52              else
53              {
54                  // relative to request
55                  String path = request.getRequestURI();
56                  String parent = (path.endsWith("/")) ? path : URIUtil.parentPath(path);
57                  location = URIUtil.canonicalPath(URIUtil.addPaths(parent,location));
58                  if (!location.startsWith("/"))
59                      url.append('/');
60              }
61  
62              if (location == null)
63                  throw new IllegalStateException("path cannot be above root");
64              url.append(location);
65  
66              location = url.toString();
67          }
68  
69          return location;
70      }
71  }