]> source.dussan.org Git - sonarqube.git/blob
40cb2b128d8dcc1e181aebb0f53b56b92238a2db
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2017 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 3 of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
19  */
20 package org.sonar.server.computation.task.projectanalysis.webhook;
21
22 import java.io.IOException;
23 import okhttp3.HttpUrl;
24 import okhttp3.MediaType;
25 import okhttp3.OkHttpClient;
26 import okhttp3.Request;
27 import okhttp3.RequestBody;
28 import okhttp3.Response;
29 import org.sonar.api.ce.ComputeEngineSide;
30 import org.sonar.api.utils.System2;
31
32 import static java.lang.String.format;
33 import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
34 import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
35 import static okhttp3.internal.http.StatusLine.HTTP_PERM_REDIRECT;
36 import static okhttp3.internal.http.StatusLine.HTTP_TEMP_REDIRECT;
37
38 @ComputeEngineSide
39 public class WebhookCallerImpl implements WebhookCaller {
40
41   private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
42   private static final String PROJECT_KEY_HEADER = "X-SonarQube-Project";
43
44   private final System2 system;
45   private final OkHttpClient okHttpClient;
46
47   public WebhookCallerImpl(System2 system, OkHttpClient okHttpClient) {
48     this.system = system;
49     this.okHttpClient = newClientWithoutRedirect(okHttpClient);
50   }
51
52   @Override
53   public WebhookDelivery call(Webhook webhook, WebhookPayload payload) {
54     WebhookDelivery.Builder builder = new WebhookDelivery.Builder();
55     long startedAt = system.now();
56     builder
57       .setAt(startedAt)
58       .setPayload(payload)
59       .setWebhook(webhook);
60
61     try {
62       Request request = buildHttpRequest(webhook, payload);
63       try (Response response = execute(request)) {
64         builder.setHttpStatus(response.code());
65         builder.setDurationInMs((int) (system.now() - startedAt));
66       }
67     } catch (Exception e) {
68       builder.setError(e);
69     }
70     return builder.build();
71   }
72
73   private static Request buildHttpRequest(Webhook webhook, WebhookPayload payload) {
74     Request.Builder request = new Request.Builder();
75     request.url(webhook.getUrl());
76     request.header(PROJECT_KEY_HEADER, payload.getProjectKey());
77     RequestBody body = RequestBody.create(JSON, payload.getJson());
78     request.post(body);
79     return request.build();
80   }
81
82   private Response execute(Request request) throws IOException {
83     Response response = okHttpClient.newCall(request).execute();
84     switch (response.code()) {
85       case HTTP_MOVED_PERM:
86       case HTTP_MOVED_TEMP:
87       case HTTP_TEMP_REDIRECT:
88       case HTTP_PERM_REDIRECT:
89         // OkHttpClient does not follow the redirect with the same HTTP method. A POST is
90         // redirected to a GET. Because of that the redirect must be manually
91         // implemented.
92         // See:
93         // https://github.com/square/okhttp/blob/07309c1c7d9e296014268ebd155ebf7ef8679f6c/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L316
94         // https://github.com/square/okhttp/issues/936#issuecomment-266430151
95         return followPostRedirect(response);
96       default:
97         return response;
98     }
99   }
100
101   /**
102    * Inspired by https://github.com/square/okhttp/blob/parent-3.6.0/okhttp/src/main/java/okhttp3/internal/http/RetryAndFollowUpInterceptor.java#L286
103    */
104   private Response followPostRedirect(Response response) throws IOException {
105     String location = response.header("Location");
106     if (location == null) {
107       throw new IllegalStateException(format("Missing HTTP header 'Location' in redirect of %s", response.request().url()));
108     }
109     HttpUrl url = response.request().url().resolve(location);
110
111     // Don't follow redirects to unsupported protocols.
112     if (url == null) {
113       throw new IllegalStateException(format("Unsupported protocol in redirect of %s to %s", response.request().url(), location));
114     }
115
116     Request.Builder redirectRequest = response.request().newBuilder();
117     redirectRequest.post(response.request().body());
118     response.body().close();
119     return okHttpClient.newCall(redirectRequest.url(url).build()).execute();
120   }
121
122   private static OkHttpClient newClientWithoutRedirect(OkHttpClient client) {
123     return client.newBuilder()
124       .followRedirects(false)
125       .followSslRedirects(false)
126       .build();
127   }
128 }