Line data Source code
1 : // Copyright (C) 2009 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 com.google.gerrit.server.config.CanonicalWebUrlProvider; 18 : import com.google.gerrit.server.config.GerritServerConfig; 19 : import com.google.inject.Inject; 20 : import com.google.inject.OutOfScopeException; 21 : import com.google.inject.Provider; 22 : import com.google.inject.ProvisionException; 23 : import java.util.Optional; 24 : import javax.servlet.http.HttpServletRequest; 25 : import org.eclipse.jgit.lib.Config; 26 : import org.eclipse.jgit.util.SystemReader; 27 : 28 : /** Sets {@code CanonicalWebUrl} to current HTTP request if not configured. */ 29 : public class HttpCanonicalWebUrlProvider extends CanonicalWebUrlProvider { 30 : private Provider<HttpServletRequest> requestProvider; 31 : 32 : @Inject 33 : HttpCanonicalWebUrlProvider(@GerritServerConfig Config config) { 34 99 : super(config); 35 99 : } 36 : 37 : @Inject(optional = true) 38 : public void setHttpServletRequest(Provider<HttpServletRequest> hsr) { 39 99 : requestProvider = hsr; 40 99 : } 41 : 42 : @Override 43 : public String get() { 44 99 : String canonicalUrl = super.get(); 45 99 : if (canonicalUrl != null) { 46 99 : return canonicalUrl; 47 : } 48 : 49 0 : return guessUrlFromHttpRequest() 50 0 : .orElseGet(() -> "http://" + SystemReader.getInstance().getHostname() + '/'); 51 : } 52 : 53 : private Optional<String> guessUrlFromHttpRequest() { 54 0 : if (requestProvider == null) { 55 : // We have no way of guessing our HTTP url. 56 0 : return Optional.empty(); 57 : } 58 : 59 : // No canonical URL configured? Maybe we can get a reasonable 60 : // guess from the incoming HTTP request, if we are currently 61 : // inside of an HTTP request scope. 62 : // 63 : final HttpServletRequest req; 64 : try { 65 0 : req = requestProvider.get(); 66 0 : } catch (ProvisionException noWeb) { 67 0 : if (noWeb.getCause() instanceof OutOfScopeException) { 68 : // We can't obtain the request as we are not inside of 69 : // an HTTP request scope. Callers must handle null. 70 0 : return Optional.empty(); 71 : } 72 0 : throw noWeb; 73 0 : } 74 0 : return Optional.of(CanonicalWebUrl.computeFromRequest(req)); 75 : } 76 : }