Line data Source code
1 : // Copyright (C) 2013 The Android Open Source Project 2 : // 3 : // Licensed under the Apache License, Version 2.0 (the "License"); 4 : // you may not use this file except in compliance with the License. 5 : // You may obtain a copy of the License at 6 : // 7 : // http://www.apache.org/licenses/LICENSE-2.0 8 : // 9 : // Unless required by applicable law or agreed to in writing, software 10 : // distributed under the License is distributed on an "AS IS" BASIS, 11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 : // See the License for the specific language governing permissions and 13 : // limitations under the License. 14 : 15 : package com.google.gerrit.httpd; 16 : 17 : import static java.nio.charset.StandardCharsets.UTF_8; 18 : 19 : import com.google.gerrit.common.Nullable; 20 : import com.google.inject.Inject; 21 : import com.google.inject.Provider; 22 : import java.io.UnsupportedEncodingException; 23 : import java.net.URLDecoder; 24 : import javax.servlet.http.HttpServletRequest; 25 : 26 : public class CanonicalWebUrl { 27 : private final Provider<String> configured; 28 : 29 : @Inject 30 : CanonicalWebUrl( 31 99 : @com.google.gerrit.server.config.CanonicalWebUrl @Nullable Provider<String> provider) { 32 99 : configured = provider; 33 99 : } 34 : 35 : public String get(HttpServletRequest req) { 36 0 : String url = configured.get(); 37 0 : return url != null ? url : computeFromRequest(req); 38 : } 39 : 40 : @SuppressWarnings("JdkObsolete") 41 : static String computeFromRequest(HttpServletRequest req) { 42 0 : StringBuffer url = req.getRequestURL(); 43 : try { 44 0 : url = new StringBuffer(URLDecoder.decode(url.toString(), UTF_8.name())); 45 0 : url.setLength(url.length() - req.getServletPath().length()); 46 0 : if (url.charAt(url.length() - 1) != '/') { 47 0 : url.append('/'); 48 : } 49 0 : return url.toString(); 50 0 : } catch (UnsupportedEncodingException e) { 51 0 : throw new IllegalStateException("Unsupported encoding for request URL " + url, e); 52 : } 53 : } 54 : }