Skip to content

Commit d644fda

Browse files
author
Nakul Sabharwal
committed
Added okhttp to batch request, redirect
1 parent 1ec6286 commit d644fda

File tree

12 files changed

+215
-198
lines changed

12 files changed

+215
-198
lines changed
Lines changed: 87 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -1,112 +1,127 @@
11
package com.microsoft.graph.content;
22

3-
import java.util.ArrayList;
3+
import java.io.IOException;
44
import java.util.HashMap;
55
import java.util.List;
66
import java.util.Map;
77

8-
import org.apache.http.Header;
9-
import org.apache.http.HttpEntity;
10-
import org.apache.http.HttpRequest;
11-
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
12-
import org.apache.http.util.EntityUtils;
8+
import org.json.simple.JSONArray;
139
import org.json.simple.JSONObject;
14-
import org.json.simple.JSONValue;
10+
import org.json.simple.parser.JSONParser;
11+
import org.json.simple.parser.ParseException;
12+
13+
import okhttp3.Headers;
14+
import okhttp3.Request;
15+
import okhttp3.RequestBody;
16+
import okio.Buffer;
1517

1618
public class MSBatchRequestContent {
17-
private List<MSBatchRequestStep> batchRequestStepsArray;
19+
private Map<String, MSBatchRequestStep> batchRequestStepsHashMap;
1820
private final int maxNumberOfRequests = 20;
1921

2022
public MSBatchRequestContent(List<MSBatchRequestStep> batchRequestStepsArray) {
21-
this.batchRequestStepsArray = new ArrayList<>();
22-
if(batchRequestStepsArray.size() <= maxNumberOfRequests) {
23-
for(MSBatchRequestStep requestStep: batchRequestStepsArray)
24-
addBatchRequestStep(requestStep);
25-
}
23+
if(batchRequestStepsArray.size() > maxNumberOfRequests)
24+
throw new IllegalArgumentException("Number of batch request steps cannot exceed 20.");
25+
26+
this.batchRequestStepsHashMap = new HashMap<>();
27+
for(MSBatchRequestStep requestStep: batchRequestStepsArray)
28+
addBatchRequestStep(requestStep);
2629
}
2730

2831
public MSBatchRequestContent() {
29-
batchRequestStepsArray = new ArrayList<>();
32+
batchRequestStepsHashMap = new HashMap<String, MSBatchRequestStep>();
3033
}
3134

3235
public boolean addBatchRequestStep(MSBatchRequestStep batchRequestStep) {
33-
if(batchRequestStep.getRequestId().compareTo("") == 0)
34-
return false;
35-
if(batchRequestStepsArray.size() == maxNumberOfRequests)
36+
if(batchRequestStepsHashMap.containsKey(batchRequestStep.getRequestId()))
3637
return false;
37-
for(MSBatchRequestStep requestStep: batchRequestStepsArray) {
38-
if(batchRequestStep.getRequestId().compareTo(requestStep.getRequestId()) == 0)
39-
return false;
40-
}
41-
return batchRequestStepsArray.add(batchRequestStep);
38+
batchRequestStepsHashMap.put(batchRequestStep.getRequestId(), batchRequestStep);
39+
return true;
4240
}
4341

44-
public boolean removeBatchRequesStepWithId(String requestId) {
45-
boolean ret = false;
46-
for (int i = batchRequestStepsArray.size()-1; i >= 0; i--)
47-
{
48-
MSBatchRequestStep requestStep = batchRequestStepsArray.get(i);
49-
for (int j = requestStep.getArrayOfDependsOnIds().size() - 1; j >= 0; j--)
50-
{
51-
String dependsOnId = requestStep.getArrayOfDependsOnIds().get(j);
52-
if(dependsOnId.compareTo(requestId) == 0)
53-
{
54-
requestStep.getArrayOfDependsOnIds().remove(j);
55-
ret = true;
56-
}
57-
}
58-
if(requestId.compareTo(requestStep.getRequestId()) == 0) {
59-
batchRequestStepsArray.remove(i);
60-
ret = true;
61-
}
62-
}
63-
return ret;
42+
public boolean removeBatchRequestStepWithId(String requestId) {
43+
boolean removed = false;
44+
if(batchRequestStepsHashMap.containsKey(requestId)) {
45+
batchRequestStepsHashMap.remove(requestId);
46+
removed = true;
47+
}
48+
for(Map.Entry<String, MSBatchRequestStep> steps : batchRequestStepsHashMap.entrySet()) {
49+
while(steps.getValue().getArrayOfDependsOnIds().remove(requestId))
50+
removed = true;
51+
}
52+
return removed;
6453
}
6554

55+
@SuppressWarnings("unchecked")
6656
public String getBatchRequestContent() {
67-
Map<String, List<Map<String, String>>> batchRequestContentMap = new HashMap<>();
68-
List<Map<String, String>> batchContentArray = new ArrayList<>();
69-
for(MSBatchRequestStep requestStep : batchRequestStepsArray) {
70-
batchContentArray.add(getBatchRequestMapFromRequestStep(requestStep));
57+
JSONObject batchRequestContentMap = new JSONObject();
58+
JSONArray batchContentArray = new JSONArray();
59+
for(Map.Entry<String, MSBatchRequestStep> requestStep : batchRequestStepsHashMap.entrySet()) {
60+
batchContentArray.add(getBatchRequestMapFromRequestStep(requestStep.getValue()));
7161
}
7262
batchRequestContentMap.put("requests", batchContentArray);
73-
return JSONValue.toJSONString(batchRequestContentMap);
63+
return batchRequestContentMap.toJSONString();
7464
}
7565

76-
private Map<String, String> getBatchRequestMapFromRequestStep(MSBatchRequestStep batchRequestStep){
77-
Map<String, String> contentmap = new HashMap<>();
66+
@SuppressWarnings("unchecked")
67+
private JSONObject getBatchRequestMapFromRequestStep(final MSBatchRequestStep batchRequestStep){
68+
JSONObject contentmap = new JSONObject();
7869
contentmap.put("id", batchRequestStep.getRequestId());
79-
contentmap.put("url", batchRequestStep.getRequest().getRequestLine().getUri());
80-
contentmap.put("method", batchRequestStep.getRequest().getRequestLine().getMethod());
81-
Header[] headers = batchRequestStep.getRequest().getAllHeaders();
82-
if(headers != null && headers.length != 0) {
83-
JSONObject obj = new JSONObject();
84-
for(Header header: headers) {
85-
obj.put(header.getName(), header.getValue());
70+
71+
String url = batchRequestStep.getRequest().url().toString();
72+
url = url.replaceAll("https://graph.microsoft.com/v1.0", "");
73+
url = url.replace("https://graph.microsoft.com/beta", "");
74+
contentmap.put("url", url);
75+
76+
contentmap.put("method", batchRequestStep.getRequest().method().toString());
77+
78+
Headers headers = batchRequestStep.getRequest().headers();
79+
if(headers != null && headers.size() != 0) {
80+
JSONObject headerMap = new JSONObject();
81+
for(Map.Entry<String, List<String>> entry : headers.toMultimap().entrySet()) {
82+
headerMap.put(entry.getKey(), getHeaderValuesAsString(entry.getValue()));
8683
}
87-
contentmap.put("headers", obj.toJSONString());
84+
contentmap.put("headers", headerMap);
8885
}
89-
HttpEntity entity = null;
90-
HttpRequest request = batchRequestStep.getRequest();
91-
if(request instanceof HttpEntityEnclosingRequestBase) {
92-
HttpEntityEnclosingRequestBase httprequest = (HttpEntityEnclosingRequestBase)request;
93-
entity = httprequest.getEntity();
86+
87+
List<String> arrayOfDependsOnIds = batchRequestStep.getArrayOfDependsOnIds();
88+
if(arrayOfDependsOnIds != null) {
89+
JSONArray array = new JSONArray();
90+
for(String dependsOnId : arrayOfDependsOnIds) array.add(dependsOnId);
91+
contentmap.put("dependsOn", array);
9492
}
95-
if(entity != null) {
93+
94+
RequestBody body = batchRequestStep.getRequest().body();
95+
if(body != null) {
9696
try {
97-
String body = EntityUtils.toString(entity);
98-
contentmap.put("body", body);
99-
}
100-
catch(Exception e) {
97+
contentmap.put("body", requestBodyToJSONObject(batchRequestStep.getRequest()));
98+
}catch(IOException | ParseException e) {
10199
e.printStackTrace();
102-
}
103-
}
104-
List<String> arrayOfDependsOnIds = batchRequestStep.getArrayOfDependsOnIds();
105-
if(arrayOfDependsOnIds != null) {
106-
contentmap.put("dependsOn", JSONValue.toJSONString(arrayOfDependsOnIds));
100+
}
107101
}
108102

109103
return contentmap;
110104
}
105+
106+
private String getHeaderValuesAsString(final List<String> list) {
107+
StringBuilder builder = new StringBuilder("");
108+
if(list.size() != 0) {
109+
builder.append(list.get(0));
110+
for(int i=1;i<list.size();i++) {
111+
builder.append("; ");
112+
builder.append(list.get(i));
113+
}
114+
}
115+
return builder.toString();
116+
}
117+
118+
private JSONObject requestBodyToJSONObject(final Request request) throws IOException, ParseException{
119+
Request copy = request.newBuilder().build();
120+
Buffer buffer = new Buffer();
121+
copy.body().writeTo(buffer);
122+
String body = buffer.readUtf8();
123+
JSONObject json = (JSONObject)new JSONParser().parse(body);
124+
return json;
125+
}
111126

112127
}

src/main/java/com/microsoft/graph/content/MSBatchRequestStep.java

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,23 @@
22

33
import java.util.List;
44

5-
import org.apache.http.HttpRequest;
5+
import okhttp3.Request;
66

77
public class MSBatchRequestStep {
88
private String requestId;
9-
private HttpRequest request;
9+
private Request request;
1010
private List<String> arrayOfDependsOnIds;
1111

12-
public MSBatchRequestStep(String requestId, HttpRequest request, List<String> arrayOfDependsOnIds) {
12+
public MSBatchRequestStep(String requestId, Request request, List<String> arrayOfDependsOnIds) {
13+
if(requestId == null)
14+
throw new IllegalArgumentException("Request Id cannot be null.");
15+
if(request == null)
16+
new IllegalArgumentException("Request cannot be null.");
17+
if(request.url() == null)
18+
throw new IllegalArgumentException("Request url cannot be null.");
19+
if(request.method() == null)
20+
throw new IllegalArgumentException("Request method cannot be null.");
21+
1322
this.requestId = requestId;
1423
this.request = request;
1524
this.arrayOfDependsOnIds = arrayOfDependsOnIds;
@@ -19,7 +28,7 @@ public String getRequestId() {
1928
return requestId;
2029
}
2130

22-
public HttpRequest getRequest() {
31+
public Request getRequest() {
2332
return request;
2433
}
2534

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

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
package com.microsoft.graph.content;
22

3-
import org.apache.http.HttpEntity;
4-
import org.apache.http.HttpResponse;
5-
import org.apache.http.entity.ContentType;
6-
import org.apache.http.entity.StringEntity;
7-
import org.apache.http.message.BasicHttpResponse;
83
import org.json.simple.JSONArray;
94
import org.json.simple.JSONObject;
105
import org.json.simple.parser.JSONParser;
116
import org.json.simple.parser.ParseException;
127

8+
import okhttp3.MediaType;
9+
import okhttp3.Response;
10+
import okhttp3.ResponseBody;
11+
1312
public class MSBatchResponseContent {
1413

1514
private JSONObject batchResponseObj;
1615

17-
public MSBatchResponseContent(String batchResponseData ) {
16+
public MSBatchResponseContent(String batchResponseData) {
1817
JSONParser parser = new JSONParser();
1918
try {
2019
if(batchResponseData != null)
@@ -25,7 +24,7 @@ public MSBatchResponseContent(String batchResponseData ) {
2524
}
2625
}
2726

28-
public HttpResponse getResponseById(String requestId) {
27+
public Response getResponseById(String requestId) {
2928
if(batchResponseObj == null)
3029
return null;
3130

@@ -37,21 +36,29 @@ public HttpResponse getResponseById(String requestId) {
3736
JSONObject jsonresponse = (JSONObject)response;
3837
String id = (String)jsonresponse.get("id");
3938
if(id.compareTo(requestId) == 0) {
40-
HttpResponse httpresponse = new BasicHttpResponse(null, ((Long)jsonresponse.get("status")).intValue(), null);
39+
Response.Builder builder = new Response.Builder();
40+
41+
if(jsonresponse.get("status") != null) {
42+
String status = (String)jsonresponse.get("status");
43+
builder.code(Integer.parseInt(status));
44+
}
45+
4146
if(jsonresponse.get("body") != null) {
42-
HttpEntity entity = new StringEntity(jsonresponse.get("body").toString(), ContentType.APPLICATION_JSON);
43-
httpresponse.setEntity(entity);
47+
String bodyAsString = (String)jsonresponse.get("body");
48+
ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), bodyAsString);
49+
builder.body(responseBody);
4450
}
4551
if(jsonresponse.get("headers") != null){
4652
JSONObject jsonheaders = (JSONObject)jsonresponse.get("headers");
4753
for(Object key: jsonheaders.keySet()) {
4854
String strkey = (String)key;
4955
String strvalue = (String)jsonheaders.get(strkey);
50-
httpresponse.setHeader(strkey, strvalue);
56+
for(String value : strvalue.split("; ")) {
57+
builder.header(strkey, value);
58+
}
5159
}
5260
}
53-
return httpresponse;
54-
61+
return builder.build();
5562
}
5663
}
5764
return null;

src/main/java/com/microsoft/graph/httpcore/HttpClients.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ public static Builder custom() {
2121
* configuration and provided authProvider
2222
*/
2323
public static OkHttpClient createDefault(IAuthenticationProvider auth) {
24-
2524
return new OkHttpClient.Builder().addInterceptor(new AuthenticationHandler(auth))
2625
.addInterceptor(new RetryHandler())
2726
.addInterceptor(new RedirectHandler())

src/main/java/com/microsoft/graph/httpcore/RedirectHandler.java

Lines changed: 13 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,11 @@ public boolean isRedirected(Request request, Response response, int redirectCoun
3030
return false;
3131

3232
final int statusCode = response.code();
33-
if(statusCode == HTTP_PERM_REDIRECT ||
34-
statusCode == HTTP_MOVED_PERM ||
35-
statusCode == HTTP_TEMP_REDIRECT ||
36-
statusCode == HTTP_SEE_OTHER ||
37-
statusCode == HTTP_MOVED_TEMP)
33+
if(statusCode == HTTP_PERM_REDIRECT || //308
34+
statusCode == HTTP_MOVED_PERM || //301
35+
statusCode == HTTP_TEMP_REDIRECT || //307
36+
statusCode == HTTP_SEE_OTHER || //303
37+
statusCode == HTTP_MOVED_TEMP) //302
3838
return true;
3939

4040
return false;
@@ -45,39 +45,26 @@ public Request getRedirect(
4545
final Response userResponse) throws ProtocolException {
4646
String location = userResponse.header("Location");
4747
if (location == null) return null;
48-
HttpUrl url = userResponse.request().url().resolve(location);
48+
49+
HttpUrl requestUrl = userResponse.request().url();
50+
51+
HttpUrl locationUrl = userResponse.request().url().resolve(location);
4952
// Don't follow redirects to unsupported protocols.
50-
if (url == null) return null;
53+
if (locationUrl == null) return null;
5154

5255
// Most redirects don't include a request body.
5356
Request.Builder requestBuilder = userResponse.request().newBuilder();
54-
final String method = userResponse.request().method();
55-
56-
if (HttpMethod.permitsRequestBody(method)) {
57-
final boolean maintainBody = HttpMethod.redirectsWithBody(method);
58-
if (HttpMethod.redirectsToGet(method)) {
59-
requestBuilder.method("GET", null);
60-
} else {
61-
RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
62-
requestBuilder.method(method, requestBody);
63-
}
64-
if (!maintainBody) {
65-
requestBuilder.removeHeader("Transfer-Encoding");
66-
requestBuilder.removeHeader("Content-Length");
67-
requestBuilder.removeHeader("Content-Type");
68-
}
69-
}
7057

7158
// When redirecting across hosts, drop all authentication headers. This
7259
// is potentially annoying to the application layer since they have no
7360
// way to retain them.
74-
boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
75-
boolean sameHost = url.host().equals(userResponse.request().url().host());
61+
boolean sameScheme = locationUrl.scheme().equalsIgnoreCase(requestUrl.scheme());
62+
boolean sameHost = locationUrl.host().toString().equalsIgnoreCase(requestUrl.host().toString());
7663
if (!sameScheme || !sameHost) {
7764
requestBuilder.removeHeader("Authorization");
7865
}
7966

80-
return requestBuilder.url(url).build();
67+
return requestBuilder.url(locationUrl).build();
8168
}
8269

8370
@Override

0 commit comments

Comments
 (0)