-
Notifications
You must be signed in to change notification settings - Fork 137
/
SyncRestHandler.cs
393 lines (352 loc) · 16.4 KB
/
SyncRestHandler.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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
////********************************************************************
// <copyright file="SyncRestHandler.cs" company="Intuit">
/*******************************************************************************
* Copyright 2016 Intuit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
// <summary>This file contains SdkException.</summary>
// <summary>This file contains logic for REST request handler.</summary>
////********************************************************************
using System.Diagnostics;
namespace Intuit.Ipp.Core.Rest
{
using System;
using System.IO;
using System.Net;
using Intuit.Ipp.Diagnostics;
using Intuit.Ipp.Exception;
using Intuit.Ipp.Utility;
/// <summary>
/// SyncRestHandler contains the logic for preparing the REST request, calls REST services and returns the response.
/// </summary>
public class SyncRestHandler : RestHandler
{
/// <summary>
/// Gets or sets the context.
/// </summary>
/// <value>
/// The context.
/// </value>
private ServiceContext context;
/// <summary>
/// Initializes a new instance of the <see cref="SyncRestHandler"/> class.
/// </summary>
/// <param name="context">The context.</param>
public SyncRestHandler(ServiceContext context)
: base(context)
{
this.context = context;
}
/// <summary>
/// Prevents a default instance of the <see cref="SyncRestHandler"/> class from being created.
/// </summary>
private SyncRestHandler()
{
}
/// <summary>
/// Gets the value which indicates to set the request body of the http web request.
/// </summary>
internal override bool IsSyncRequestStream
{
get
{
return true;
}
}
/// <summary>
/// Prepares the HttpWebRequest along with authentication header added to the request.
/// </summary>
/// <param name="requestParameters">The parameters.</param>
/// <param name="requestBody">The request entity.</param>
/// <param name="oauthRequestUri">The OAuth reqeust uri.</param>
/// <returns>
/// Http web request object.
/// </returns>
public override HttpWebRequest PrepareRequest(RequestParameters requestParameters, object requestBody, string oauthRequestUri = null, bool includeRequestId = true)
{
HttpWebRequest request = base.PrepareRequest(requestParameters, requestBody, oauthRequestUri, includeRequestId);
// set the timeout for the request if it has a value.
Nullable<int> timeout = this.context.Timeout;
if ( timeout.HasValue)
{
request.Timeout = timeout.Value;
}
return request;
}
/// <summary>
/// Returns the response by calling REST service.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Response from REST service.</returns>
public override string GetResponse(HttpWebRequest request)
{
FaultHandler handler = new FaultHandler(this.context);
// Create a variable for storing the response.
string response = string.Empty;
try
{
// Check whether the retryPolicy is null.
if (this.context.IppConfiguration.RetryPolicy == null)
{
// If yes then call the rest service without retry framework enabled.
response = this.CallRestService(request);
}
else
{
// If no then call the rest service using the execute action of retry framework.
this.context.IppConfiguration.RetryPolicy.ExecuteAction(() =>
{
response = this.CallRestService(request);
});
}
if (request != null && request.RequestUri != null && request.RequestUri.Segments != null)
{
if (System.Array.IndexOf(request.RequestUri.Segments, "reports/") >= 0)
{
if (!response.StartsWith("{\"Report\":")) { response = "{\"Report\":" + response + "}"; }
}
}
if (request != null && request.RequestUri != null && request.RequestUri.Segments != null)
{
if (System.Array.IndexOf(request.RequestUri.Segments, "taxservice/") >= 0)
{
//This if condition was added as Json serialization was failing for the FaultResponse bcoz of missing TaxService seriliazation tag on AnyIntuitObject in Fms.cs class
if (!response.Contains("Fault"))
{
if (!response.StartsWith("{\"TaxService\":")) { response = "{\"TaxService\":" + response + "}"; }
}
}
}
}
catch (RetryExceededException retryExceededException)
{
// System.Net.HttpWebRequest.Abort() was previously called.-or- The time-out
// period for the request expired.-or- An error occurred while processing the request.
bool isIps = false;
if (this.context.ServiceType == IntuitServicesType.IPS)
{
isIps = true;
}
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, retryExceededException.ToString());
CoreHelper.AdvancedLogging.Log(retryExceededException.ToString());
throw;
}
catch (WebException webException)
{
// System.Net.HttpWebRequest.Abort() was previously called.-or- The time-out
// period for the request expired.-or- An error occurred while processing the request.
bool isIps = false;
if (this.context.ServiceType == IntuitServicesType.IPS)
{
isIps = true;
}
IdsException idsException = handler.ParseResponseAndThrowException(webException, isIps);
if (idsException != null)
{
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString());
CoreHelper.AdvancedLogging.Log(idsException.ToString());
throw idsException;
}
}
finally
{
this.context.RequestId = null;
}
if (this.context.ServiceType == IntuitServicesType.IPS)
{
// Handle errors here
Utility.IntuitErrorHandler.HandleErrors(response);
}
else
{
// Check the response if there are any fault tags and throw appropriate exceptions.
IdsException exception = handler.ParseErrorResponseAndPrepareException(response);
if (exception != null)
{
throw exception;
}
}
// Return the response.
return response;
}
/// <summary>
/// Returns the response stream by calling REST service.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Response from REST service.</returns>
public override byte[] GetResponseStream(HttpWebRequest request)
{
FaultHandler handler = new FaultHandler(this.context);
byte[] receivedBytes = new byte[0];
try
{
// Check whether the retryPolicy is null.
if (this.context.IppConfiguration.RetryPolicy == null)
{
// If yes then call the rest service without retry framework enabled.
receivedBytes = GetRestServiceCallResponseStream(request);
}
else
{
// If no then call the rest service using the execute action of retry framework.
this.context.IppConfiguration.RetryPolicy.ExecuteAction(() =>
{
receivedBytes = GetRestServiceCallResponseStream(request);
});
}
}
catch (WebException webException)
{
// System.Net.HttpWebRequest.Abort() was previously called.-or- The time-out
// period for the request expired.-or- An error occurred while processing the request.
bool isIps = false;
if (this.context.ServiceType == IntuitServicesType.IPS)
{
isIps = true;
}
IdsException idsException = handler.ParseResponseAndThrowException(webException, isIps);
if (idsException != null)
{
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString());
CoreHelper.AdvancedLogging.Log(idsException.ToString());
throw idsException;
}
}
finally
{
this.context.RequestId = null;
}
return receivedBytes;
}
/// <summary>
/// Calls the rest service.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Returns the response.</returns>
private string CallRestService(HttpWebRequest request)
{
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, "Getting the response from service.");
//if (ServicePointManager.SecurityProtocol != 0)
// ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
// Call the service and get response.
using (HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse)
{
string parsedResponse = this.ParseResponse(httpWebResponse);
TraceSwitch traceSwitch = new TraceSwitch("IPPTraceSwitch", "IPP Trace Switch");
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, (int)traceSwitch.Level > (int)TraceLevel.Info ? "Got the response from service.\n Start dump: \n " + parsedResponse : "Got the response from service.");
CoreHelper.AdvancedLogging.Log("Got the response from service.\n Start dump: \n " + parsedResponse );
// Parse the response from the call and return.
return parsedResponse;
}
}
// <summary>
/// Calls the rest service.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Returns the response.</returns>
private byte[] GetRestServiceCallResponseStream(HttpWebRequest request)
{
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, "Getting the response from service as response stream.");
CoreHelper.AdvancedLogging.Log("Getting the response from service as response stream.");
Stream receiveStream = new MemoryStream();
byte[] receiveBytes = new byte[0];
MemoryStream mem = new MemoryStream();
// Call the service and get response.
using (HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse)
{
if (!string.IsNullOrWhiteSpace(httpWebResponse.ContentEncoding) && this.ResponseCompressor != null)
{
using (var responseStream = httpWebResponse.GetResponseStream())
{
using (var decompressedStream = this.ResponseCompressor.Decompress(responseStream))
{
decompressedStream.CopyTo(mem);
receiveBytes = mem.ToArray();
}
}
}
else
{
using (var responseStream = httpWebResponse.GetResponseStream())
{
responseStream.CopyTo(mem);
receiveBytes = mem.ToArray();
}
}
TraceSwitch traceSwitch = new TraceSwitch("IPPTraceSwitch", "IPP Trace Switch");
this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, "Got the response from service.");
CoreHelper.AdvancedLogging.Log("Got the response from service.");
}
// Return the response stream
return receiveBytes;
}
/// <summary>
/// Parses the response object.
/// </summary>
/// <param name="httpWebResponse">The Http Web Response object.</param>
/// <returns>Returns the response by parsing httpWebResponse object.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Require the method not to be static.")]
private string ParseResponse(HttpWebResponse httpWebResponse)
{
// Create a variable for storing the response.
string response = string.Empty;
// Check whether the Status Code is OK which denotes that successful response.
// TODO: This check might be rhetorical since any response from Ids will be 200OK with error response.
if (httpWebResponse.StatusCode == HttpStatusCode.OK)
{
if (!string.IsNullOrWhiteSpace(httpWebResponse.ContentEncoding) && this.ResponseCompressor != null)
{
using (var responseStream = httpWebResponse.GetResponseStream())
{
using (var decompressedStream = this.ResponseCompressor.Decompress(responseStream))
{
StreamReader reader = new StreamReader(decompressedStream);
// Read the Stream
response = reader.ReadToEnd();
// Close reader
reader.Close();
}
}
}
else
{
using (Stream responseStream = httpWebResponse.GetResponseStream())
{
// Get the response stream.
StreamReader reader = new StreamReader(responseStream);
// Read the Stream
response = reader.ReadToEnd();
// Close reader
reader.Close();
}
}
// Log the response to Disk.
string response_intuit_tid_header = "";
//get intuit_tid header
for (int i = 0; i < httpWebResponse.Headers.Count; ++i)
{
if (httpWebResponse.Headers.Keys[i] == "intuit_tid")
{
response_intuit_tid_header = httpWebResponse.Headers[i];
}
}
this.RequestLogging.LogPlatformRequests(" Response Intuit_Tid header: " + response_intuit_tid_header + ", Response Payload: " + response, false);
//Log to Serilog
CoreHelper.AdvancedLogging.Log(" Response Intuit_Tid header: " + response_intuit_tid_header + ", Response Payload: " + response);
}
// Return the response.
return response;
}
}
}