-
Notifications
You must be signed in to change notification settings - Fork 60
/
RequestExecutor.cs
240 lines (206 loc) · 9.37 KB
/
RequestExecutor.cs
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using RestSharp;
using RestSharp.Serialization.Json;
namespace SharpBucket.Authentication
{
internal abstract class RequestExecutor
{
private readonly JsonDeserializer jsonDeserializer = new JsonDeserializer();
/// <summary>
/// Configure a <see cref="IRestClient"/> instance to be compatible with the style of requests done by the <see cref="RequestExecutor"/>.
/// </summary>
/// <param name="client">The client to configure.</param>
public virtual void ConfigureRestClient(IRestClient client)
{
//Fixed bug that prevents RestClient for adding custom headers to the request
//https://stackoverflow.com/questions/22229393/why-is-restsharp-addheaderaccept-application-json-to-a-list-of-item
client.ClearHandlers();
client.AddHandler("application/json", () => new JsonDeserializer());
client.FollowRedirects = false;
}
public string ExecuteRequest(string url, Method method, object body, IRestClient client, IDictionary<string, object> requestParameters)
{
var result = Execute(url, method, body, client, requestParameters);
return result.Content;
}
public async Task<string> ExecuteRequestAsync(string url, Method method, object body, IRestClient client, IDictionary<string, object> requestParameters, CancellationToken token)
{
var result = await ExecuteAsync(url, method, body, client, requestParameters, token);
return result.Content;
}
public T ExecuteRequest<T>(string url, Method method, object body, IRestClient client, IDictionary<string, object> requestParameters)
where T : new()
{
var result = Execute(url, method, body, client, requestParameters);
return jsonDeserializer.Deserialize<T>(result);
}
public async Task<T> ExecuteRequestAsync<T>(string url, Method method, object body, IRestClient client, IDictionary<string, object> requestParameters, CancellationToken token)
where T : new()
{
var result = await ExecuteAsync(url, method, body, client, requestParameters, token);
return jsonDeserializer.Deserialize<T>(result);
}
public IRestResponse ExecuteRequestNoRedirect(string url, Method method, object body, IRestClient client, IDictionary<string, object> requestParameters)
{
return ExecuteNoRedirect(url, method, body, client, requestParameters);
}
public Task<IRestResponse> ExecuteRequestNoRedirectAsync(string url, Method method, object body, IRestClient client, IDictionary<string, object> requestParameters, CancellationToken token)
{
return ExecuteNoRedirectAsync(url, method, body, client, requestParameters, token);
}
private IRestResponse Execute(
string url,
Method method,
object body,
IRestClient client,
IDictionary<string, object> requestParameters)
{
var request = BuildRestRequest(url, method, body, requestParameters);
var result = ExecuteRequestWithManualFollowRedirect(request, client);
ThrowExceptionIfResponseIsInvalid(result);
return result;
}
private async Task<IRestResponse> ExecuteAsync(
string url,
Method method,
object body,
IRestClient client,
IDictionary<string, object> requestParameters,
CancellationToken token)
{
var request = BuildRestRequest(url, method, body, requestParameters);
var result = await ExecuteRequestWithManualFollowRedirectAsync(request, client, token);
ThrowExceptionIfResponseIsInvalid(result);
return result;
}
private IRestResponse ExecuteNoRedirect(
string url,
Method method,
object body,
IRestClient client,
IDictionary<string, object> requestParameters)
{
var request = BuildRestRequest(url, method, body, requestParameters);
var result = client.Execute(request);
ThrowExceptionIfResponseIsInvalid(result);
return result;
}
private async Task<IRestResponse> ExecuteNoRedirectAsync(
string url,
Method method,
object body,
IRestClient client,
IDictionary<string, object> requestParameters,
CancellationToken token)
{
var request = BuildRestRequest(url, method, body, requestParameters);
var result = await client.ExecuteAsync(request, token);
ThrowExceptionIfResponseIsInvalid(result);
return result;
}
private void ThrowExceptionIfResponseIsInvalid(IRestResponse response)
{
if (response.ResponseStatus != ResponseStatus.Completed)
{
// There is an issue that prevents the request to complete (timeout, request aborted, ...).
// Throw the exception prepared by RestSharp
throw new Exception(response.ErrorMessage, response.ErrorException);
}
if ((int)response.StatusCode >= 400)
{
// There is an issue which is described in the HTTP response.
// Build an throw a BitbucketException, since the message should be provided by Bitbucket.
throw BuildBitbucketException(response);
}
}
protected virtual BitbucketException BuildBitbucketException(IRestResponse response)
{
// response.ErrorException is not useful for caller in that case, so it's useless to transmit it as an inner exception
throw new BitbucketException(response.StatusCode, response.Content);
}
private IRestRequest BuildRestRequest(string url, Method method, object body, IDictionary<string, object> requestParameters)
{
var request = new RestRequest(url, method);
if (requestParameters != null)
{
foreach (var requestParameter in requestParameters)
{
var key = requestParameter.Key;
var val = requestParameter.Value;
if (val is IEnumerable enumerable && !(enumerable is string))
{
foreach (var item in enumerable)
request.AddParameter(key, item);
}
else
request.AddParameter(key, val);
}
}
if (method == Method.PUT || method == Method.POST)
{
AddBody(request, body);
}
return request;
}
protected abstract void AddBody(IRestRequest request, object body);
private static IRestResponse ExecuteRequestWithManualFollowRedirect(IRestRequest request, IRestClient client)
{
var result = client.Execute(request);
if (result.StatusCode == HttpStatusCode.Redirect)
{
request = BuildRedirectedRestRequest(request, client, result);
result = client.Execute(request);
}
return result;
}
private static async Task<IRestResponse>ExecuteRequestWithManualFollowRedirectAsync(IRestRequest request, IRestClient client, CancellationToken token)
{
var result = await client.ExecuteAsync(request, token);
if (result.StatusCode == HttpStatusCode.Redirect)
{
request = BuildRedirectedRestRequest(request, client, result);
result = await client.ExecuteAsync(request, token);
}
return result;
}
private static IRestRequest BuildRedirectedRestRequest<TRestResponse>(IRestRequest request, IRestClient client,
TRestResponse result) where TRestResponse : IRestResponse
{
var redirectUrl = GetRedirectUrl(result, client.BaseUrl.ToString());
NameValueCollection queryValues;
if (redirectUrl.Contains("?"))
{
var urlAndQuery = redirectUrl.Split('?');
redirectUrl = urlAndQuery[0];
queryValues = HttpUtility.ParseQueryString(urlAndQuery[1]);
}
else
{
queryValues = new NameValueCollection();
}
request = new RestRequest(redirectUrl, request.Method);
foreach (var queryKey in queryValues.AllKeys)
{
request.AddQueryParameter(queryKey, queryValues[queryKey]);
}
return request;
}
private static string GetRedirectUrl(IRestResponse result, string requestBaseUrl)
{
var redirectUrl = result.Headers.Where(header => header.Name == "Location").Select(header => header.Value).First().ToString();
if (redirectUrl.StartsWith(requestBaseUrl))
{
redirectUrl = redirectUrl.Remove(0, requestBaseUrl.Length);
}
return redirectUrl;
}
}
}