// Copyright (C) 2013 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.httpd;

import com.google.gerrit.common.Nullable;
import com.google.inject.Inject;
import com.google.inject.Provider;
import javax.servlet.http.HttpServletRequest;

public class CanonicalWebUrl {
  private final Provider<String> configured;

  @Inject
  CanonicalWebUrl(
      @com.google.gerrit.server.config.CanonicalWebUrl @Nullable Provider<String> provider) {
    configured = provider;
  }

  public String get(HttpServletRequest req) {
    String url = configured.get();
    return url != null ? url : computeFromRequest(req);
  }

  static String computeFromRequest(HttpServletRequest req) {
    StringBuffer url = req.getRequestURL();
    url.setLength(url.length() - req.getServletPath().length());
    if (url.charAt(url.length() - 1) != '/') {
      url.append('/');
    }
    return url.toString();
  }
}

@@ -636,16 +636,72 @@
 httpd;%0A%0A
+import static java.nio.charset.StandardCharsets.UTF_8;%0A%0A
 import c
@@ -802,16 +802,89 @@
 ovider;%0A
+import java.io.UnsupportedEncodingException;%0Aimport java.net.URLDecoder;%0A
 import j
@@ -1397,24 +1397,115 @@
 questURL();%0A
+    try %7B%0A      url = new StringBuffer(URLDecoder.decode(url.toString(), UTF_8.name()));%0A  
     url.setL
@@ -1561,16 +1561,18 @@
 ));%0A    
+  
 if (url.
@@ -1608,24 +1608,26 @@
 /') %7B%0A      
+  
 url.append('
@@ -1635,18 +1635,22 @@
 ');%0A    
-%7D%0A
+  %7D%0A  
     retu
@@ -1668,14 +1668,156 @@
 ring();%0A
+    %7D catch (UnsupportedEncodingException e) %7B%0A      throw new IllegalStateException(%22Unsupported encoding for request URL %22 + url, e);%0A    %7D%0A
   %7D%0A%7D%0A

Fix canonical URL detection with URL encoded parts