Repository navigation
Expand file tree
/
Copy pathRestSharpCommandProcessor.cs
More file actions
219 lines (189 loc) · 6.88 KB
/
Copy pathRestSharpCommandProcessor.cs
File metadata and controls
219 lines (189 loc) · 6.88 KB
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
//------------------------------------------------------------------------------
// <copyright company="LeanKit Inc.">
// Copyright (c) LeanKit Inc. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
using System.Text;
using System.Threading;
using LeanKit.API.Client.Library.Exceptions;
using LeanKit.API.Client.Library.TransferObjects;
using LeanKit.API.Client.Library.Validation;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using RestSharp;
using UnauthorizedAccessException = LeanKit.API.Client.Library.Exceptions.UnauthorizedAccessException;
namespace LeanKit.API.Client.Library
{
public class RestSharpCommandProcessor : IRestCommandProcessor
{
private readonly IntegrationSettings _settings;
private readonly IValidationService _validationService;
public RestSharpCommandProcessor(IValidationService validationService, IntegrationSettings settings)
{
_validationService = validationService;
_settings = settings;
}
public T Get<T>(LeanKitAccountAuth accountAuth, string resource) where T : new()
{
return Process<T>(accountAuth,
new RestRequest(Method.GET) {Resource = resource, RequestFormat = DataFormat.Json});
}
public T Get<T>(LeanKitAccountAuth accountAuth, string resource, object body) where T : new()
{
var restRequest = new RestRequest(Method.GET) {Resource = resource, RequestFormat = DataFormat.Json};
restRequest.AddBody(body);
return Process<T>(accountAuth, restRequest);
}
public T Post<T>(LeanKitAccountAuth accountAuth, string resource, object body) where T : new()
{
var restRequest = new RestRequest(Method.POST)
{
Resource = resource,
RequestFormat = DataFormat.Json,
JsonSerializer = new JsonSerializer()
};
restRequest.AddBody(body);
return Process<T>(accountAuth, restRequest);
}
public T Post<T>(LeanKitAccountAuth accountAuth, string resource) where T : new()
{
return Process<T>(accountAuth,
new RestRequest(Method.POST) {Resource = resource, RequestFormat = DataFormat.Json});
}
private T Process<T>(LeanKitAccountAuth accountAuth, IRestRequest request) where T : new()
{
var errorMessages = _validationService.ValidateRequest((RestRequest) request);
if (errorMessages.Count > 0)
{
var ex = new ValidationException("Provided request parameters are invalid.");
ex.Data["ErrorMessages"] = errorMessages;
throw ex;
}
var client = new RestClient
{
BaseUrl = accountAuth.GetAccountUrl(),
Authenticator = new HttpBasicAuthenticator(accountAuth.Username, accountAuth.Password)
};
var response = RetryRequest(request, accountAuth, client);
var asyncResponse = response.Data;
if (string.IsNullOrEmpty(asyncResponse.ReplyData))
{
return new T();
}
var rawJson = asyncResponse.ReplyData;
var authUserDateFormat = _settings.DateFormat;
var isoDateTimeConverter = new IsoDateTimeConverter { DateTimeFormat = authUserDateFormat };
rawJson = rawJson.Substring(1, rawJson.Length - 2);
var retVal = JsonConvert.DeserializeObject<T>(rawJson, new JsonSerializerSettings
{
Error = HandleError,
Converters = {isoDateTimeConverter}
});
return retVal;
}
private static IRestResponse<AsyncResponse> RetryRequest(IRestRequest request, LeanKitAccountAuth accountAuth,
RestClient client)
{
IRestResponse<AsyncResponse> response = new RestResponse<AsyncResponse>();
for (var tryCount = 0; tryCount <= 10; tryCount++)
{
try
{
response = client.Execute<AsyncResponse>(request);
ValidateResponse(response, accountAuth, request);
break;
}
catch (NoDataException)
{
return response;
}
catch (Exception)
{
if (tryCount == 10) throw;
Thread.Sleep(1000);
}
}
return response;
}
private static void HandleError(object sender, ErrorEventArgs e)
{
e.ErrorContext.Handled = true;
}
private static Uri GetRequestUri(string fullUrl)
{
return new Uri(fullUrl);
}
private static void ValidateResponse(IRestResponse<AsyncResponse> response,
LeanKitAccountAuth leanKitAccountAuth,
IRestRequest request)
{
var requestedResource = GetRequestUri(leanKitAccountAuth.GetAccountUrl());
var logAuthString = FormatApiRequestInfo(leanKitAccountAuth, request, true);
if (response == null)
{
throw new LeanKitAPIException("A failure occurred retrieving the response from the API.");
}
if (response.ResponseUri.Host != requestedResource.Host)
{
throw new InvalidAPIResourceException();
}
if (response.ResponseStatus == ResponseStatus.Error)
{
throw new LeanKitAPIException(response.ErrorException);
}
switch (response.StatusCode)
{
case HttpStatusCode.Unauthorized:
throw new UnauthorizedAccessException(response.StatusDescription + ": " + logAuthString);
}
AsyncResponse responseData = response.Data;
if (responseData == null)
{
throw new LeanKitAPIException("Unable to process the response from the API.");
}
switch ((ResponseCode) responseData.ReplyCode)
{
case ResponseCode.UnauthorizedAccess:
throw new UnauthorizedAccessException(responseData.ReplyText + ": " + logAuthString);
case ResponseCode.NoData:
throw new NoDataException(responseData.ReplyText);
case ResponseCode.FatalException:
case ResponseCode.MinorException:
case ResponseCode.UserException:
throw new LeanKitAPIException(responseData.ReplyText, (ResponseCode) responseData.ReplyCode);
}
//check to make sure there is data
if (string.IsNullOrEmpty(responseData.ReplyData))
{
throw new LeanKitAPIException(responseData.ReplyText + ": " + logAuthString, (ResponseCode) responseData.ReplyCode);
}
}
private static string FormatApiRequestInfo(LeanKitAccountAuth leanKitAccountAuth, IRestRequest request, bool hidePassword = false)
{
var accountAuthStringStringBuilder = new StringBuilder();
accountAuthStringStringBuilder.Append("Attempted Authentication Information: ");
accountAuthStringStringBuilder.Append("Hostname: ");
accountAuthStringStringBuilder.Append(leanKitAccountAuth.Hostname != null
? leanKitAccountAuth.Hostname + ", "
: "Unknown, ");
accountAuthStringStringBuilder.Append("Username: ");
accountAuthStringStringBuilder.Append(leanKitAccountAuth.Username != null
? leanKitAccountAuth.Username + ", "
: "Unknown, ");
if (!hidePassword)
{
accountAuthStringStringBuilder.Append("Password: ");
accountAuthStringStringBuilder.Append(leanKitAccountAuth.Password != null
? leanKitAccountAuth.Password + ", "
: "Unknown, ");
}
accountAuthStringStringBuilder.Append("Resource: ");
accountAuthStringStringBuilder.Append(request.Resource != null ? request.Resource + ", " : "Unknown, ");
return accountAuthStringStringBuilder.ToString();
}
}
}