- Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathBatchResponseContent.cs
236 lines (212 loc) · 12.1 KB
/
BatchResponseContent.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
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
namespaceMicrosoft.Graph
{
usingSystem;
usingSystem.Collections.Generic;
usingSystem.IO;
usingSystem.Net;
usingSystem.Net.Http;
usingSystem.Net.Http.Headers;
usingSystem.Text;
usingSystem.Text.Json;
usingSystem.Threading.Tasks;
usingMicrosoft.Kiota.Abstractions;
usingMicrosoft.Kiota.Abstractions.Serialization;
/// <summary>
/// Handles batch request responses.
/// </summary>
publicclassBatchResponseContent
{
privateJsonDocumentjBatchResponseObject;
privatereadonlyHttpResponseMessagebatchResponseMessage;
privatereadonlyDictionary<string,ParsableFactory<IParsable>>apiErrorMappings;
/// <summary>
/// Constructs a new <see cref="BatchResponseContent"/>
/// </summary>
/// <param name="httpResponseMessage">A <see cref="HttpResponseMessage"/> of a batch request execution.</param>
/// <param name="errorMappings">A dictionary of error mappings to handle failed responses.</param>
publicBatchResponseContent(HttpResponseMessagehttpResponseMessage,Dictionary<string,ParsableFactory<IParsable>>errorMappings=null)
{
this.batchResponseMessage=httpResponseMessage??thrownewArgumentNullException(nameof(httpResponseMessage));
this.apiErrorMappings=errorMappings??newDictionary<string,ParsableFactory<IParsable>>(StringComparer.OrdinalIgnoreCase){
{"XXX",(parsable)=>newServiceException(ErrorConstants.Messages.BatchRequestError,newException(parsable.GetErrorMessage()))}
};
}
/// <summary>
/// Gets all batch responses <see cref="Dictionary{String, HttpResponseMessage}"/>.
/// All <see cref="HttpResponseMessage"/> in the dictionary MUST be disposed since they implement <see cref="IDisposable"/>.
/// </summary>
/// <returns>A Dictionary of id and <see cref="HttpResponseMessage"/> representing batch responses.</returns>
publicasyncTask<Dictionary<string,HttpResponseMessage>>GetResponsesAsync()
{
Dictionary<string,HttpResponseMessage>responseMessages=newDictionary<string,HttpResponseMessage>();
jBatchResponseObject=jBatchResponseObject??awaitGetBatchResponseContentAsync().ConfigureAwait(false);
if(jBatchResponseObject==null)
returnresponseMessages;
if(jBatchResponseObject.RootElement.TryGetProperty(CoreConstants.BatchRequest.Responses,outJsonElementjResponses)&&jResponses.ValueKind==JsonValueKind.Array)
{
foreach(JsonElementjResponseIteminjResponses.EnumerateArray())
responseMessages.Add(jResponseItem.GetProperty(CoreConstants.BatchRequest.Id).ToString(),GetResponseMessageFromJObject(jResponseItem));
}
returnresponseMessages;
}
/// <summary>
/// Gets all batch responses statuscodes <see cref="Dictionary{String, HttpStatusCode}"/>.
/// </summary>
/// <returns>A Dictionary of id and <see cref="HttpStatusCode"/> representing batch responses.</returns>
publicasyncTask<Dictionary<string,HttpStatusCode>>GetResponsesStatusCodesAsync()
{
Dictionary<string,HttpStatusCode>statuscodes=newDictionary<string,HttpStatusCode>();
jBatchResponseObject=jBatchResponseObject??awaitGetBatchResponseContentAsync().ConfigureAwait(false);
if(jBatchResponseObject==null)
returnstatuscodes;
if(jBatchResponseObject.RootElement.TryGetProperty(CoreConstants.BatchRequest.Responses,outJsonElementjResponses)&&jResponses.ValueKind==JsonValueKind.Array)
{
foreach(JsonElementjResponseIteminjResponses.EnumerateArray())
statuscodes.Add(jResponseItem.GetProperty(CoreConstants.BatchRequest.Id).ToString(),GetStatusCodeFromJObject(jResponseItem));
}
returnstatuscodes;
}
/// <summary>
/// Gets a batch response as <see cref="HttpResponseMessage"/> for the specified batch request id.
/// The returned <see cref="HttpResponseMessage"/> MUST be disposed since it implements an <see cref="IDisposable"/>.
/// </summary>
/// <param name="requestId">A batch request id.</param>
/// <returns>A <see cref="HttpResponseMessage"/> response object for a batch request.</returns>
publicasyncTask<HttpResponseMessage>GetResponseByIdAsync(stringrequestId)
{
jBatchResponseObject=jBatchResponseObject??awaitGetBatchResponseContentAsync().ConfigureAwait(false);
if(jBatchResponseObject==null)
returnnull;
if(jBatchResponseObject.RootElement.TryGetProperty(CoreConstants.BatchRequest.Responses,outJsonElementjResponses)&&jResponses.ValueKind==JsonValueKind.Array)
{
foreach(varelementinjResponses.EnumerateArray())
{
if(element.GetProperty(CoreConstants.BatchRequest.Id).GetString().Equals(requestId))
{
returnGetResponseMessageFromJObject(element);
}
}
}
returnnull;
}
/// <summary>
/// Gets a batch response as a requested type for the specified batch request id.
/// </summary>
/// <param name="requestId">A batch request id.</param>
/// <param name="responseHandler">ResponseHandler to use for the response</param>
/// <returns>A deserialized object of type T<see cref="HttpResponseMessage"/>.</returns>
publicasyncTask<T>GetResponseByIdAsync<T>(stringrequestId,IResponseHandlerresponseHandler=null)whereT:IParsable,new()
{
usingvarhttpResponseMessage=awaitGetResponseByIdAsync(requestId).ConfigureAwait(false);
if(httpResponseMessage==null)
returndefault;
// return the deserialized object
responseHandler??=newResponseHandler<T>();
returnawaitresponseHandler.HandleResponseAsync<HttpResponseMessage,T>(httpResponseMessage,apiErrorMappings).ConfigureAwait(false);
}
/// <summary>
/// Gets a batch response content as a stream
/// </summary>
/// <param name="requestId">A batch request id.</param>
/// <returns>The response stream of the batch response object</returns>
/// <remarks> Stream should be dispose once done with.</remarks>
publicasyncTask<Stream>GetResponseStreamByIdAsync(stringrequestId)
{
usingvarhttpResponseMessage=awaitGetResponseByIdAsync(requestId).ConfigureAwait(false);
if(httpResponseMessage==null)
returndefault;
usingvarstream=awaithttpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
varmemoryStream=newMemoryStream();
awaitstream.CopyToAsync(memoryStream).ConfigureAwait(false);
returnmemoryStream;
}
/// <summary>
/// Gets the @NextLink of a batch response.
/// </summary>
/// <returns></returns>
[Obsolete("This method is deprecated as a batch response does not contain a next link",true)]
publicasyncTask<string>GetNextLinkAsync()
{
jBatchResponseObject=jBatchResponseObject??awaitGetBatchResponseContentAsync().ConfigureAwait(false);
if(jBatchResponseObject==null)
returnnull;
if(jBatchResponseObject.RootElement.TryGetProperty(CoreConstants.Serialization.ODataNextLink,outJsonElementnextLink))
{
returnnextLink.GetString();
}
returnnull;
}
/// <summary>
/// Checks is a <see cref="HttpStatusCode"/> can be marked as successful
/// </summary>
/// <param name="statusCode">A single <see cref="HttpStatusCode"/>.</param>
/// <returns>Returns true if status code is between 200 and 300.</returns>
publicstaticboolIsSuccessStatusCode(HttpStatusCodestatusCode)
{
return((int)statusCode>=200)&&((int)statusCode<=299);
}
/// <summary>
/// Gets a <see cref="HttpResponseMessage"/> from <see cref="JsonElement"/> representing a batch response item.
/// </summary>
/// <param name="jResponseItem">A single batch response item of type <see cref="JsonElement"/>.</param>
/// <returns>A single batch response as a <see cref="HttpResponseMessage"/>.</returns>
privateHttpResponseMessageGetResponseMessageFromJObject(JsonElementjResponseItem)
{
HttpResponseMessageresponseMessage=newHttpResponseMessage();
if(jResponseItem.TryGetProperty(CoreConstants.BatchRequest.Status,outJsonElementstatus))
{
responseMessage.StatusCode=(HttpStatusCode)int.Parse(status.ToString());
}
if(jResponseItem.TryGetProperty(CoreConstants.BatchRequest.Body,outJsonElementbody))
{
responseMessage.Content=newStringContent(body.ToString(),Encoding.UTF8,CoreConstants.MimeTypeNames.Application.Json);
}
if(jResponseItem.TryGetProperty(CoreConstants.BatchRequest.Headers,outJsonElementheaders))
{
foreach(varheaderKeyValueinheaders.EnumerateObject())
{
// try to add the header to the request message otherwise add it to the content message if the content is set
if(!responseMessage.Headers.TryAddWithoutValidation(headerKeyValue.Name,headerKeyValue.Value.ToString())&&responseMessage.Content!=null)
{
if(headerKeyValue.Name.Equals("Content-Type",StringComparison.OrdinalIgnoreCase))
responseMessage.Content.Headers.ContentType=MediaTypeHeaderValue.Parse(headerKeyValue.Value.ToString());// we do this to override the default and to allow content types with parameters e.g. Content-Type: application/json; odata=verbose
else
responseMessage.Content.Headers.TryAddWithoutValidation(headerKeyValue.Name,headerKeyValue.Value.ToString());// Try to add the headers we couldn't add to the HttpResponseMessage to the HttpContent
}
}
}
returnresponseMessage;
}
privateHttpStatusCodeGetStatusCodeFromJObject(JsonElementjResponseItem)
{
if(jResponseItem.TryGetProperty(CoreConstants.BatchRequest.Status,outJsonElementstatus))
{
return(HttpStatusCode)int.Parse(status.ToString());
}
thrownewArgumentException("Response does not contain statuscode");
}
/// <summary>
/// Gets the <see cref="HttpContent"/> of a batch response as a <see cref="JsonDocument"/>.
/// </summary>
/// <returns>A batch response content as <see cref="JsonDocument"/>.</returns>
privateasyncTask<JsonDocument>GetBatchResponseContentAsync()
{
if(this.batchResponseMessage.Content==null||this.batchResponseMessage.Content.Headers.ContentLength==0)
returnnull;
try
{
using(StreamstreamContent=awaitthis.batchResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false))
{
returnawaitJsonDocument.ParseAsync(streamContent).ConfigureAwait(false);
}
}
catch(Exceptionex)
{
thrownewClientException(ErrorConstants.Messages.UnableToDeserializeContent,ex);
}
}
}
}