summaryrefslogtreecommitdiffstats
path: root/java/com/google/gerrit/util/http/RequestUtil.java
blob: 51ffe0cf397c7f69f77bffdf7acbdf59f5094a8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.gerrit.util.http;

import com.google.common.base.Splitter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

/** Utilities for manipulating HTTP request objects. */
public class RequestUtil {
  private static final Splitter SPLITTER = Splitter.on("/");

  /** HTTP request attribute for storing the Throwable that caused an error condition. */
  private static final String ATTRIBUTE_ERROR_TRACE =
      RequestUtil.class.getName() + "/ErrorTraceThrowable";

  public static void setErrorTraceAttribute(HttpServletRequest req, Throwable t) {
    req.setAttribute(ATTRIBUTE_ERROR_TRACE, t);
  }

  public static Throwable getErrorTraceAttribute(HttpServletRequest req) {
    return (Throwable) req.getAttribute(ATTRIBUTE_ERROR_TRACE);
  }

  /**
   * Returns the same value as {@link HttpServletRequest#getPathInfo()}, but without decoding
   * URL-encoded characters.
   */
  public static String getEncodedPathInfo(HttpServletRequest req) {
    // CS IGNORE LineLength FOR NEXT 3 LINES. REASON: URL.
    // Based on com.google.guice.ServletDefinition$1#getPathInfo() from:
    // https://github.com/google/guice/blob/41c126f99d6309886a0ded2ac729033d755e1593/extensions/servlet/src/com/google/inject/servlet/ServletDefinition.java
    String servletPath = req.getServletPath();
    int servletPathLength = servletPath.length();
    String requestUri = req.getRequestURI();
    String pathInfo =
        requestUri.substring(req.getContextPath().length()).replaceAll("[/]{2,}", "/");
    if (pathInfo.startsWith(servletPath)) {
      pathInfo = pathInfo.substring(servletPathLength);
      // Corner case: when servlet path & request path match exactly (without
      // trailing '/'), then pathinfo is null.
      if (pathInfo.isEmpty() && servletPathLength > 0) {
        pathInfo = null;
      }
    } else {
      pathInfo = null;
    }
    return pathInfo;
  }

  /**
   * Trims leading '/' and 'a/'. Removes the context path, but keeps the servlet path. Removes all
   * IDs from the rest of the URI.
   *
   * <p>The returned string is a good fit for cases where one wants the full context of the request
   * without any identifiable data. For example: Logging or quota checks.
   *
   * <p>Examples:
   *
   * <ul>
   *   <li>/a/accounts/self/detail => /accounts/detail
   *   <li>/changes/123/revisions/current/detail => /changes/revisions/detail
   *   <li>/changes/ => /changes
   * </ul>
   */
  public static String getRestPathWithoutIds(HttpServletRequest req) {
    String encodedPathInfo = req.getRequestURI().substring(req.getContextPath().length());
    if (encodedPathInfo.startsWith("/")) {
      encodedPathInfo = encodedPathInfo.substring(1);
    }
    if (encodedPathInfo.startsWith("a/")) {
      encodedPathInfo = encodedPathInfo.substring(2);
    }

    List<String> parts = SPLITTER.splitToList(encodedPathInfo);
    StringBuilder result = new StringBuilder(parts.size());
    for (int i = 0; i < parts.size(); i = i + 2) {
      result.append("/");
      result.append(parts.get(i));
    }
    return result.toString();
  }

  public static boolean acceptsGzipEncoding(HttpServletRequest request) {
    String accepts = request.getHeader("Accept-Encoding");
    return accepts != null && accepts.indexOf("gzip") != -1;
  }

  private RequestUtil() {}
}