Skip to content

Commit 6f39a8a

Browse files
committed
- adds an execute method for JSON batches to avoid customers juggling with clients
1 parent 3fe6857 commit 6f39a8a

6 files changed

Lines changed: 140 additions & 41 deletions

File tree

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

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.util.LinkedHashMap;
66
import java.util.List;
77
import java.util.Map;
8+
import java.util.concurrent.CompletableFuture;
89
import java.util.concurrent.ThreadLocalRandom;
910
import java.util.regex.Matcher;
1011
import java.util.regex.Pattern;
@@ -17,6 +18,8 @@
1718
import com.google.gson.JsonObject;
1819
import com.google.gson.JsonParser;
1920
import com.google.gson.JsonPrimitive;
21+
import com.microsoft.graph.core.ClientException;
22+
import com.microsoft.graph.core.IBaseClient;
2023
import com.google.gson.JsonParseException;
2124

2225
import okhttp3.Headers;
@@ -125,6 +128,37 @@ public String getBatchRequestContent() {
125128
return content;
126129
}
127130

131+
/**
132+
* Executes the batch requests and returns the response
133+
* @param client client to use for the request
134+
* @return the batch response
135+
* @throws ClientException when the batch couldn't be executed because of client issues.
136+
*/
137+
@Nonnull
138+
public MSBatchResponseContent execute(@Nonnull final IBaseClient client) throws ClientException {
139+
try {
140+
return executeAsync(client).get();
141+
} catch (Exception ex) {
142+
throw new ClientException("Batch failed to execute", ex);
143+
}
144+
}
145+
/**
146+
* Executes the batch requests asynchronously and returns the response
147+
* @param client client to use for the request
148+
* @return a future with the batch response
149+
*/
150+
@Nonnull
151+
public CompletableFuture<MSBatchResponseContent> executeAsync(@Nonnull final IBaseClient client) {
152+
if(client == null) {
153+
throw new IllegalArgumentException("client parameter cannot be null");
154+
}
155+
final String content = getBatchRequestContent();
156+
return client.customRequest(client.getServiceRoot() + "/$batch", String.class)
157+
.buildRequest()
158+
.postAsync(content)
159+
.thenApply(resp -> new MSBatchResponseContent(client.getServiceRoot() + "/", content, resp));
160+
}
161+
128162
private static final Pattern protocolAndHostReplacementPattern = Pattern.compile("(?i)^http[s]?:\\/\\/graph\\.microsoft\\.com\\/(?>v1\\.0|beta)\\/?"); // (?i) case insensitive
129163
private JsonObject getBatchRequestObjectFromRequestStep(final MSBatchRequestStep batchRequestStep) {
130164
final JsonObject contentmap = new JsonObject();

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

Lines changed: 59 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import com.google.gson.JsonParseException;
1616

1717
import okhttp3.MediaType;
18+
import okhttp3.Protocol;
1819
import okhttp3.Request;
1920
import okhttp3.RequestBody;
2021
import okhttp3.Response;
@@ -26,17 +27,34 @@
2627
*/
2728
public class MSBatchResponseContent {
2829

29-
private final Response batchResponse;
30-
private LinkedHashMap<String, Request> batchRequestsHashMap;
30+
private final Protocol protocol;
31+
private final String message;
32+
private LinkedHashMap<String, Request> batchRequestsHashMap = new LinkedHashMap<>();
3133
private JsonArray batchResponseArray;
3234
private String nextLink;
3335

3436
/**
3537
* @param batchResponse OkHttp batch response on execution of batch requests
3638
*/
3739
public MSBatchResponseContent(@Nullable final Response batchResponse) {
38-
this.batchResponse = batchResponse;
3940
update(batchResponse);
41+
this.message = batchResponse.message();
42+
this.protocol = batchResponse.protocol();
43+
}
44+
/**
45+
* intantiates a new response
46+
* internal only, used when the content executes the requests
47+
* @param baseUrl the base service URL without a trailing slash
48+
* @param batchRequestData the batch request payload data as a JSON string
49+
* @param batchResponseData the batch response body as a JSON string
50+
*/
51+
protected MSBatchResponseContent(@Nonnull final String baseUrl, @Nonnull final String batchRequestData, @Nonnull final String batchResponseData) {
52+
this.protocol = Protocol.HTTP_1_1;
53+
this.message = "OK";
54+
final Map<String, Request> requestMap = createBatchRequestsHashMap(baseUrl, JsonParser.parseString(batchRequestData).getAsJsonObject());
55+
if (requestMap != null)
56+
batchRequestsHashMap.putAll(requestMap);
57+
updateFromResponseBody(batchResponseData);
4058
}
4159

4260
/**
@@ -66,14 +84,13 @@ public Response getResponseById(@Nonnull final String requestId) {
6684
// Put corresponding request into the constructed response
6785
builder.request(batchRequestsHashMap.get(requestId));
6886
// copy protocol and message same as of batch response
69-
builder.protocol(batchResponse.protocol());
70-
builder.message(batchResponse.message());
87+
builder.protocol(protocol);
88+
builder.message(message);
7189

7290
// Put status code of the corresponding request in JsonArray
7391
final JsonElement statusElement = jsonresponse.get("status");
7492
if (statusElement != null && statusElement.isJsonPrimitive()) {
75-
final Long status = statusElement.getAsLong();
76-
builder.code(status.intValue());
93+
builder.code(statusElement.getAsInt());
7794
}
7895

7996
// Put body from response array for corresponding id into constructing response
@@ -144,37 +161,38 @@ public void update(@Nonnull final Response batchResponse) {
144161
throw new IllegalArgumentException("Batch Response cannot be null");
145162

146163
final Map<String, Request> requestMap = createBatchRequestsHashMap(batchResponse);
147-
if (batchRequestsHashMap == null)
148-
batchRequestsHashMap = new LinkedHashMap<>();
149164
if (requestMap != null)
150165
batchRequestsHashMap.putAll(requestMap);
151166

152167
if (batchResponse.body() != null) {
153168
try {
154169
final String batchResponseData = batchResponse.body().string();
155170
if (batchResponseData != null) {
156-
final JsonObject batchResponseObj = stringToJSONObject(batchResponseData);
157-
if (batchResponseObj != null) {
158-
159-
final JsonElement nextLinkElement = batchResponseObj.get("@odata.nextLink");
160-
if (nextLinkElement != null && nextLinkElement.isJsonPrimitive())
161-
nextLink = nextLinkElement.getAsString();
162-
163-
if (batchResponseArray == null)
164-
batchResponseArray = new JsonArray();
165-
166-
final JsonElement responseArrayElement = batchResponseObj.get("responses");
167-
if (responseArrayElement != null && responseArrayElement.isJsonArray()) {
168-
final JsonArray responseArray = responseArrayElement.getAsJsonArray();
169-
batchResponseArray.addAll(responseArray);
170-
}
171-
}
171+
updateFromResponseBody(batchResponseData);
172172
}
173173
} catch (final IOException e) {
174174
e.printStackTrace();
175175
}
176176
}
177177
}
178+
private void updateFromResponseBody(@Nonnull final String batchResponseData) {
179+
final JsonObject batchResponseObj = stringToJSONObject(batchResponseData);
180+
if (batchResponseObj != null) {
181+
182+
final JsonElement nextLinkElement = batchResponseObj.get("@odata.nextLink");
183+
if (nextLinkElement != null && nextLinkElement.isJsonPrimitive())
184+
nextLink = nextLinkElement.getAsString();
185+
186+
if (batchResponseArray == null)
187+
batchResponseArray = new JsonArray();
188+
189+
final JsonElement responseArrayElement = batchResponseObj.get("responses");
190+
if (responseArrayElement != null && responseArrayElement.isJsonArray()) {
191+
final JsonArray responseArray = responseArrayElement.getAsJsonArray();
192+
batchResponseArray.addAll(responseArray);
193+
}
194+
}
195+
}
178196

179197
/**
180198
* @return nextLink of batch response
@@ -188,8 +206,21 @@ private Map<String, Request> createBatchRequestsHashMap(final Response batchResp
188206
if (batchResponse == null)
189207
return null;
190208
try {
191-
final Map<String, Request> batchRequestsHashMap = new LinkedHashMap<>();
192209
final JsonObject requestJSONObject = requestBodyToJSONObject(batchResponse.request());
210+
final String baseUrl = batchResponse.request().url().toString().replace("$batch", "");
211+
return createBatchRequestsHashMap(baseUrl, requestJSONObject);
212+
} catch (IOException ex) {
213+
ex.printStackTrace();
214+
return null;
215+
}
216+
}
217+
@Nullable
218+
protected Map<String, Request> createBatchRequestsHashMap(@Nonnull final String baseUrl, @Nonnull final JsonObject requestJSONObject) {
219+
if(baseUrl == null || baseUrl == "" || requestJSONObject == null) {
220+
return null;
221+
}
222+
try {
223+
final Map<String, Request> batchRequestsHashMap = new LinkedHashMap<>();
193224
final JsonElement requestArrayElement = requestJSONObject.get("requests");
194225
if (requestArrayElement != null && requestArrayElement.isJsonArray()) {
195226
final JsonArray requestArray = requestArrayElement.getAsJsonArray();
@@ -202,8 +233,7 @@ private Map<String, Request> createBatchRequestsHashMap(final Response batchResp
202233

203234
final JsonElement urlElement = requestObject.get("url");
204235
if (urlElement != null && urlElement.isJsonPrimitive()) {
205-
final StringBuilder fullUrl = new StringBuilder(
206-
batchResponse.request().url().toString().replace("$batch", ""));
236+
final StringBuilder fullUrl = new StringBuilder(baseUrl);
207237
fullUrl.append(urlElement.getAsString());
208238
builder.url(fullUrl.toString());
209239
}
@@ -240,7 +270,7 @@ private Map<String, Request> createBatchRequestsHashMap(final Response batchResp
240270
}
241271
return batchRequestsHashMap;
242272

243-
} catch (IOException | JsonParseException e) {
273+
} catch (JsonParseException e) {
244274
e.printStackTrace();
245275
}
246276
return null;

‎src/main/java/com/microsoft/graph/core/BaseClient.java‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222

2323
package com.microsoft.graph.core;
2424

25-
import com.google.gson.JsonObject;
25+
import com.google.gson.JsonElement;
2626
import com.microsoft.graph.http.CoreHttpProvider;
2727
import com.microsoft.graph.http.IHttpProvider;
2828
import com.microsoft.graph.httpcore.HttpClients;
@@ -94,9 +94,9 @@ public <T> CustomRequestBuilder<T> customRequest(@Nonnull final String url, @Non
9494
* @return the instance of this builder
9595
*/
9696
@Nonnull
97-
public CustomRequestBuilder<JsonObject> customRequest(@Nonnull final String url) {
98-
return new CustomRequestBuilder<JsonObject>(getServiceRoot() + url, this, null,
99-
JsonObject.class);
97+
public CustomRequestBuilder<JsonElement> customRequest(@Nonnull final String url) {
98+
return new CustomRequestBuilder<JsonElement>(getServiceRoot() + url, this, null,
99+
JsonElement.class);
100100
}
101101

102102
/**

‎src/main/java/com/microsoft/graph/core/IBaseClient.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
import javax.annotation.Nullable;
2626
import javax.annotation.Nonnull;
2727

28-
import com.google.gson.JsonObject;
28+
import com.google.gson.JsonElement;
2929
import com.microsoft.graph.http.IHttpProvider;
3030
import com.microsoft.graph.logger.ILogger;
3131
import com.microsoft.graph.serializer.ISerializer;
@@ -91,7 +91,7 @@ public interface IBaseClient {
9191
* @param url the url to send the request to
9292
*/
9393
@Nonnull
94-
CustomRequestBuilder<JsonObject> customRequest(@Nonnull final String url);
94+
CustomRequestBuilder<JsonElement> customRequest(@Nonnull final String url);
9595

9696
/**
9797
* Gets the service SDK version if the service SDK is in use, null otherwise

‎src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,10 @@ else if (fieldObject instanceof IJsonBackedObject) {
206206
@Override
207207
@Nullable
208208
public <T> String serializeObject(@Nonnull final T serializableObject) {
209-
logger.logDebug("Serializing type " + serializableObject.getClass().getSimpleName());
209+
logger.logDebug("Serializing type " + serializableObject.getClass().getSimpleName());
210+
if(serializableObject instanceof String) { // we don't want to over serialize if we already have a serialized string
211+
return (String)serializableObject;
212+
}
210213
JsonElement outJsonTree = gson.toJsonTree(serializableObject);
211214

212215
if (serializableObject instanceof IJsonBackedObject) {

‎src/test/java/com/microsoft/graph/core/BaseClientTests.java‎

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
package com.microsoft.graph.core;
22

33
import static org.mockito.Mockito.mock;
4+
import static org.mockito.Mockito.when;
5+
6+
import java.io.ByteArrayInputStream;
7+
import java.io.ByteArrayOutputStream;
8+
import java.io.InputStream;
9+
import java.io.ObjectOutputStream;
10+
import java.io.OutputStream;
411

512
import static org.junit.Assert.assertEquals;
613
import static org.junit.Assert.assertNotNull;
@@ -10,11 +17,17 @@
1017
import org.junit.Test;
1118

1219
import okhttp3.OkHttpClient;
20+
import okhttp3.Request;
21+
import okio.BufferedSink;
22+
import okio.Okio;
1323

1424
import com.microsoft.graph.http.IHttpProvider;
15-
import com.google.gson.JsonObject;
25+
import com.google.gson.JsonElement;
1626
import com.microsoft.graph.http.CoreHttpProvider;
27+
import com.microsoft.graph.http.CustomRequest;
28+
import com.microsoft.graph.http.HttpMethod;
1729
import com.microsoft.graph.logger.ILogger;
30+
import com.microsoft.graph.serializer.DefaultSerializer;
1831
import com.microsoft.graph.serializer.ISerializer;
1932

2033
/**
@@ -74,9 +87,28 @@ public void testSerializer() {
7487
}
7588
@Test
7689
public void testCustomRequest() {
77-
final CustomRequestBuilder<JsonObject> simpleRequest = baseClient.customRequest("");
78-
assertNotNull(simpleRequest);
79-
final CustomRequestBuilder<String> stringRequest = baseClient.customRequest("", String.class);
80-
assertNotNull(stringRequest);
90+
baseClient.setHttpProvider(new CoreHttpProvider(new DefaultSerializer(mLogger), mLogger, new OkHttpClient.Builder().build()));
91+
final CustomRequestBuilder<JsonElement> simpleRequestBuilder = baseClient.customRequest("");
92+
assertNotNull(simpleRequestBuilder);
93+
final CustomRequestBuilder<String> stringRequestBuilder = baseClient.customRequest("", String.class);
94+
assertNotNull(stringRequestBuilder);
95+
final CustomRequest<String> abs = stringRequestBuilder.buildRequest();
96+
abs.setHttpMethod(HttpMethod.POST);
97+
final Request nat = abs.getHttpRequest("somestring");
98+
assertEquals("somestring", getStringFromRequestBody(nat));
99+
assertEquals("application", nat.body().contentType().type());
100+
assertEquals("json", nat.body().contentType().subtype());
101+
}
102+
private String getStringFromRequestBody(Request request) {
103+
try {
104+
ByteArrayOutputStream out = new ByteArrayOutputStream();
105+
final BufferedSink buffer = Okio.buffer(Okio.sink(out));
106+
request.body().writeTo(buffer);
107+
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
108+
return CoreHttpProvider.streamToString(in);
109+
} catch (Exception ex) {
110+
ex.printStackTrace();
111+
return "";
112+
}
81113
}
82114
}

0 commit comments

Comments
 (0)