Skip to content

Commit 5a98e14

Browse files
committed
- fixes a bug where batch response bodies would not be deserialized properly
1 parent 97e8397 commit 5a98e14

4 files changed

Lines changed: 89 additions & 15 deletions

File tree

‎src/main/java/com/microsoft/graph/content/BatchResponseContent.java‎

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
import javax.annotation.Nonnull;
2929
import javax.annotation.Nullable;
3030

31+
import com.google.gson.JsonElement;
3132
import com.google.gson.annotations.Expose;
3233
import com.google.gson.annotations.SerializedName;
3334

@@ -36,23 +37,21 @@ public class BatchResponseContent {
3637
/** Responses to the steps from the request */
3738
@Expose
3839
@SerializedName("responses")
39-
public List<BatchResponseStep<?>> responses;
40+
public List<BatchResponseStep<JsonElement>> responses;
4041

4142
/**
4243
* Gets a response to a request in the batch by its id
43-
* @param <T> Type of the response body
4444
* @param stepId Id of the request step in the batch request
4545
* @return The step response corresponding to the ID or null
4646
*/
4747
@Nullable
48-
@SuppressWarnings("unchecked")
49-
public <T> BatchResponseStep<T> getResponseById(@Nonnull final String stepId) {
48+
public BatchResponseStep<JsonElement> getResponseById(@Nonnull final String stepId) {
5049
Objects.requireNonNull(stepId, "parameter stepId cannot be null");
5150
if(responses == null) return null;
5251

53-
for(final BatchResponseStep<?> step : responses) {
52+
for(final BatchResponseStep<JsonElement> step : responses) {
5453
if(stepId.equals(step.id))
55-
return (BatchResponseStep<T>)step;
54+
return step;
5655
}
5756
return null;
5857
}

‎src/main/java/com/microsoft/graph/content/BatchResponseStep.java‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,45 @@
2121
// ------------------------------------------------------------------------------
2222
package com.microsoft.graph.content;
2323

24+
import java.util.ArrayList;
25+
import java.util.Objects;
26+
27+
import javax.annotation.Nonnull;
28+
import javax.annotation.Nullable;
29+
30+
import com.google.gson.JsonElement;
2431
import com.google.gson.annotations.Expose;
2532
import com.google.gson.annotations.SerializedName;
33+
import com.microsoft.graph.http.GraphErrorResponse;
34+
import com.microsoft.graph.http.GraphFatalServiceException;
35+
import com.microsoft.graph.http.GraphServiceException;
36+
import com.microsoft.graph.serializer.ISerializer;
2637

2738
/** Response for the batch step */
2839
public class BatchResponseStep<T> extends BatchStep<T> {
2940
/** Http status code of the response */
3041
@Expose
3142
@SerializedName("status")
3243
public int status;
44+
45+
/**
46+
* Returned the deserialized response body of the current step
47+
* @param <T2> type of the response body
48+
* @param serializer serializer to use for deserialization. graphClient.getSerializer()
49+
* @param resultClass class of the resulting response body
50+
* @return the deserialized response body
51+
* @throws GraphServiceException when a bad request was sent
52+
* @throws GraphFatalServiceException when the service did not complete the operation as expected because of an internal error
53+
*/
54+
@Nullable
55+
public <T2> T2 getDeserializedBody(@Nonnull final ISerializer serializer, @Nonnull final Class<T2> resultClass) throws GraphServiceException, GraphFatalServiceException {
56+
Objects.requireNonNull(resultClass, "parameter resultClass cannot be null");
57+
if(body == null || !(body instanceof JsonElement)) return null;
58+
59+
final GraphErrorResponse error = serializer.deserializeObject((JsonElement)body, GraphErrorResponse.class);
60+
if(error == null || error.error == null) {
61+
return serializer.deserializeObject((JsonElement)body, resultClass);
62+
} else
63+
throw GraphServiceException.createFromResponse("", "", new ArrayList<>(), "", headers, "", status, error, false);
64+
}
3365
}

‎src/main/java/com/microsoft/graph/http/GraphServiceException.java‎

Lines changed: 30 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
11
// ------------------------------------------------------------------------------
22
// Copyright (c) 2017 Microsoft Corporation
3-
//
3+
//
44
// Permission is hereby granted, free of charge, to any person obtaining a copy
55
// of this software and associated documentation files (the "Software"), to deal
66
// in the Software without restriction, including without limitation the rights
77
// to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
88
// copies of the Software, and to permit persons to whom the Software is
99
// furnished to do so, subject to the following conditions:
10-
//
10+
//
1111
// The above copyright notice and this permission notice shall be included in
1212
// all copies or substantial portions of the Software.
13-
//
13+
//
1414
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1515
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1616
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
@@ -184,7 +184,7 @@ public String getResponseMessage() {
184184
public String getMessage() {
185185
return getMessage(verbose);
186186
}
187-
187+
188188
/**
189189
* Gets the HTTP status code
190190
*
@@ -229,7 +229,7 @@ public String getMethod() {
229229
public String getUrl() {
230230
return url;
231231
}
232-
232+
233233
/**
234234
* Gets the request headers
235235
* @return the request headers
@@ -369,8 +369,32 @@ public static <T> GraphServiceException createFromResponse(@Nonnull final IHttpR
369369
}
370370

371371
final int responseCode = response.code();
372-
final List<String> responseHeaders = new LinkedList<>();
373372
final Map<String, String> headers = responseHeadersHelper.getResponseHeadersAsMapStringString(response);
373+
final String responseMessage = response.message();
374+
GraphErrorResponse error = parseErrorResponse(serializer, response);
375+
376+
return createFromResponse(url, method, requestHeaders, requestBody, headers, responseMessage, responseCode, error, isVerbose);
377+
378+
}
379+
/**
380+
* Creates a Graph service exception.
381+
* @param url url of the original request
382+
* @param method http method of the original request
383+
* @param requestHeaders headers of the original request
384+
* @param requestBody body of the original request
385+
* @param headers response headers
386+
* @param responseMessage reponse status message
387+
* @param responseCode response status code
388+
* @param error graph error response object
389+
* @param isVerbose whether to display a verbose message or not
390+
* @return the Exception to be thrown
391+
*/
392+
@Nonnull
393+
public static GraphServiceException createFromResponse(@Nullable final String url, @Nullable final String method, @Nonnull final List<String> requestHeaders,
394+
@Nullable final String requestBody,
395+
@Nonnull final Map<String,String> headers, @Nonnull final String responseMessage, final int responseCode,
396+
@Nonnull final GraphErrorResponse error, final boolean isVerbose) {
397+
final List<String> responseHeaders = new LinkedList<>();
374398
for (final String key : headers.keySet()) {
375399
final String fieldPrefix;
376400
if (key == null) {
@@ -381,9 +405,7 @@ public static <T> GraphServiceException createFromResponse(@Nonnull final IHttpR
381405
responseHeaders.add(fieldPrefix + headers.get(key));
382406
}
383407

384-
final String responseMessage = response.message();
385408

386-
GraphErrorResponse error = parseErrorResponse(serializer, response);
387409

388410
if (responseCode >= INTERNAL_SERVER_ERROR) {
389411
return new GraphFatalServiceException(method,

‎src/test/java/com/microsoft/graph/content/BatchResponseContentTest.java‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,12 @@
1111
import java.util.Iterator;
1212
import java.util.Map;
1313

14+
import com.google.gson.JsonElement;
15+
import com.microsoft.graph.http.GraphErrorResponse;
16+
import com.microsoft.graph.http.GraphServiceException;
1417
import com.microsoft.graph.logger.ILogger;
1518
import com.microsoft.graph.serializer.DefaultSerializer;
19+
import com.microsoft.graph.serializer.ISerializer;
1620

1721
import org.junit.jupiter.api.Test;
1822

@@ -57,7 +61,7 @@ public void testGetBatchResponseContentByID() throws IOException {
5761
public void testGetBatchResponseContentIteratorOverResponse() throws IOException {
5862
String responsebody = "{\"responses\": [{\"id\": \"1\",\"status\":200,\"headers\" : {\"Cache-Control\":\"no-cache\",\"OData-Version\":\"4.0\",\"Content-Type\":\"application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8\"},\"body\":{\"@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#users/$entity\",\"businessPhones\":[\"8006427676\"],\"displayName\":\"MOD Administrator\",\"givenName\":\"MOD\",\"jobTitle\":null,\"mail\":\"admin@M365x751487.OnMicrosoft.com\",\"mobilePhone\":\"425-882-1032\",\"officeLocation\":null,\"preferredLanguage\":\"en-US\",\"surname\":\"Administrator\",\"userPrincipalName\":\"admin@M365x751487.onmicrosoft.com\",\"id\":\"6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c\"}},{\"id\": \"2\",\"status\":200,\"headers\" : {\"Cache-Control\":\"no-store, no-cache\",\"OData-Version\":\"4.0\",\"Content-Type\":\"application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8\"},\"body\":{\"@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#drives/$entity\",\"createdDateTime\":\"2019-01-12T09:05:38Z\",\"description\":\"\",\"id\":\"b!nlu9o5I9g0y8gsHXfUM_bPTZ0oM_wVNArHM5R4-VkHLlnxx5SpqHRJledwfICP9f\",\"lastModifiedDateTime\":\"2019-03-06T06:59:04Z\",\"name\":\"OneDrive\",\"webUrl\":\"https://m365x751487-my.sharepoint.com/personal/admin_m365x751487_onmicrosoft_com/Documents\",\"driveType\":\"business\",\"createdBy\":{\"user\":{\"displayName\":\"System Account\"}},\"lastModifiedBy\":{\"user\":{\"displayName\":\"System Account\"}},\"owner\":{\"user\":{\"email\":\"admin@M365x751487.OnMicrosoft.com\",\"id\":\"6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c\",\"displayName\":\"MOD Administrator\"}},\"quota\":{\"deleted\":0,\"remaining\":1099509670098,\"state\":\"normal\",\"total\":1099511627776,\"used\":30324}}},{\"id\": \"3\",\"status\":201,\"headers\" : {\"Location\":\"https://graph.microsoft.com/v1.0/users/6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c/onenote/notebooks/1-94e4376a-a1c1-441a-8b41-af5c86ee39d0\",\"Preference-Applied\":\"odata.include-annotations=*\",\"Cache-Control\":\"no-cache\",\"OData-Version\":\"4.0\",\"Content-Type\":\"application/json;odata.metadata=minimal;odata.streaming=true;IEEE754Compatible=false;charset=utf-8\"},\"body\":{\"@odata.context\":\"https://graph.microsoft.com/v1.0/$metadata#users('6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c')/onenote/notebooks/$entity\",\"id\":\"1-94e4376a-a1c1-441a-8b41-af5c86ee39d0\",\"self\":\"https://graph.microsoft.com/v1.0/users/6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c/onenote/notebooks/1-94e4376a-a1c1-441a-8b41-af5c86ee39d0\",\"createdDateTime\":\"2019-03-06T08:08:09Z\",\"displayName\":\"My Notebook -442293399\",\"lastModifiedDateTime\":\"2019-03-06T08:08:09Z\",\"isDefault\":false,\"userRole\":\"Owner\",\"isShared\":false,\"sectionsUrl\":\"https://graph.microsoft.com/v1.0/users/6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c/onenote/notebooks/1-94e4376a-a1c1-441a-8b41-af5c86ee39d0/sections\",\"sectionGroupsUrl\":\"https://graph.microsoft.com/v1.0/users/6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c/onenote/notebooks/1-94e4376a-a1c1-441a-8b41-af5c86ee39d0/sectionGroups\",\"createdBy\":{\"user\":{\"id\":\"6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c\",\"displayName\":\"MOD Administrator\"}},\"lastModifiedBy\":{\"user\":{\"id\":\"6b4fa8ea-7e6e-486e-a8f4-d00a5b23488c\",\"displayName\":\"MOD Administrator\"}},\"links\":{\"oneNoteClientUrl\":{\"href\":\"onenote:https://m365x751487-my.sharepoint.com/personal/admin_m365x751487_onmicrosoft_com/Documents/Notebooks/My%20Notebook%20-442293399\"},\"oneNoteWebUrl\":{\"href\":\"https://m365x751487-my.sharepoint.com/personal/admin_m365x751487_onmicrosoft_com/Documents/Notebooks/My%20Notebook%20-442293399\"}}}}]}";
5963
BatchResponseContent batchresponse = new DefaultSerializer(mock(ILogger.class)).deserializeObject(responsebody, BatchResponseContent.class);
60-
Iterator<BatchResponseStep<?>> it = batchresponse.responses.iterator();
64+
Iterator<BatchResponseStep<JsonElement>> it = batchresponse.responses.iterator();
6165
while(it.hasNext()) {
6266
BatchResponseStep<?> entry = it.next();
6367
assertTrue(entry.id != null && entry.body !=null);
@@ -93,4 +97,21 @@ public void getResponseWithIdReturnsNullOnEmptyResponses()
9397
final BatchResponseContent batchResponse = new BatchResponseContent();
9498
assertNull(batchResponse.getResponseById("id"));
9599
}
100+
@Test
101+
public void deserializesErrorsProperly() {
102+
String responsebody = "{\"responses\":[{\"id\":\"1\",\"status\":400,\"headers\":{\"Cache-Control\":\"no-cache\",\"x-ms-resource-unit\":\"1\",\"Content-Type\":\"application/json\"},\"body\":{\"error\":{\"code\":\"Request_BadRequest\",\"message\":\"Avalueisrequiredforproperty'displayName'ofresource'User'.\",\"innerError\":{\"date\":\"2021-02-02T19:19:38\",\"request-id\":\"408b8e64-4047-4c97-95b6-46e9f212ab48\",\"client-request-id\":\"102910da-260c-3028-0fb3-7d6903a02622\"}}}}]}";
103+
ISerializer serializer = new DefaultSerializer(mock(ILogger.class));
104+
BatchResponseContent batchresponse = serializer.deserializeObject(responsebody, BatchResponseContent.class);
105+
assertThrows(GraphServiceException.class, () -> {
106+
final Object body = batchresponse.getResponseById("1").getDeserializedBody(serializer, BatchRequestContent.class);
107+
});
108+
try {
109+
final Object body = batchresponse.getResponseById("1").getDeserializedBody(serializer, BatchRequestContent.class);
110+
} catch(GraphServiceException ex) {
111+
final GraphErrorResponse response = ex.getError();
112+
assertNotNull(response);
113+
assertNotNull(response.error);
114+
assertNotNull(response.error.message);
115+
}
116+
}
96117
}

0 commit comments

Comments
 (0)