diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..e0f15db2e --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "java.configuration.updateBuildConfiguration": "automatic" +} \ No newline at end of file diff --git a/build.gradle b/build.gradle index 2cf14edd2..b709aabe7 100644 --- a/build.gradle +++ b/build.gradle @@ -30,8 +30,7 @@ dependencies { api 'com.squareup.okhttp3:okhttp:3.12.1' - // https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple - implementation group: 'com.googlecode.json-simple', name: 'json-simple', version: '1.1.1' + implementation 'com.google.code.gson:gson:2.8.6' } def pomConfig = { diff --git a/src/main/java/com/microsoft/graph/content/MSBatchRequestContent.java b/src/main/java/com/microsoft/graph/content/MSBatchRequestContent.java index 5ffa80179..94ee638d0 100644 --- a/src/main/java/com/microsoft/graph/content/MSBatchRequestContent.java +++ b/src/main/java/com/microsoft/graph/content/MSBatchRequestContent.java @@ -5,10 +5,11 @@ import java.util.List; import java.util.Map; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; -import org.json.simple.parser.JSONParser; -import org.json.simple.parser.ParseException; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonParseException; import okhttp3.Headers; import okhttp3.Request; @@ -16,134 +17,140 @@ import okio.Buffer; public class MSBatchRequestContent { - private Map batchRequestStepsHashMap; - + private final Map batchRequestStepsHashMap; + // Maximum number of requests that can be sent in a batch public static final int MAX_NUMBER_OF_REQUESTS = 20; - + /* * Creates Batch request content using list provided * * @param batchRequestStepsArray List of batch steps for batching */ - public MSBatchRequestContent(List batchRequestStepsArray) { - if(batchRequestStepsArray.size() > MAX_NUMBER_OF_REQUESTS) + public MSBatchRequestContent(final List batchRequestStepsArray) { + if (batchRequestStepsArray.size() > MAX_NUMBER_OF_REQUESTS) throw new IllegalArgumentException("Number of batch request steps cannot exceed " + MAX_NUMBER_OF_REQUESTS); - + this.batchRequestStepsHashMap = new HashMap<>(); - for(MSBatchRequestStep requestStep: batchRequestStepsArray) + for (final MSBatchRequestStep requestStep : batchRequestStepsArray) addBatchRequestStep(requestStep); } - + /* * Creates empty batch request content */ public MSBatchRequestContent() { batchRequestStepsHashMap = new HashMap(); } - + /* * @param batchRequestStep Batch request step adding to batch content - * @return true or false based on addition or no addition of batch request step given + * + * @return true or false based on addition or no addition of batch request step + * given */ - public boolean addBatchRequestStep(MSBatchRequestStep batchRequestStep) { - if(batchRequestStepsHashMap.containsKey(batchRequestStep.getRequestId())) + public boolean addBatchRequestStep(final MSBatchRequestStep batchRequestStep) { + if (batchRequestStepsHashMap.containsKey(batchRequestStep.getRequestId())) return false; batchRequestStepsHashMap.put(batchRequestStep.getRequestId(), batchRequestStep); return true; } - + /* * @param requestId Id of Batch request step to be removed - * @return true or false based on removal or no removal of batch request step with given id + * + * @return true or false based on removal or no removal of batch request step + * with given id */ - public boolean removeBatchRequestStepWithId(String requestId) { + public boolean removeBatchRequestStepWithId(final String requestId) { boolean removed = false; - if(batchRequestStepsHashMap.containsKey(requestId)) { + if (batchRequestStepsHashMap.containsKey(requestId)) { batchRequestStepsHashMap.remove(requestId); removed = true; - for(Map.Entry steps : batchRequestStepsHashMap.entrySet()) { - if(steps.getValue() != null && steps.getValue().getArrayOfDependsOnIds() != null) { - while(steps.getValue().getArrayOfDependsOnIds().remove(requestId)); + for (final Map.Entry steps : batchRequestStepsHashMap.entrySet()) { + if (steps.getValue() != null && steps.getValue().getArrayOfDependsOnIds() != null) { + while (steps.getValue().getArrayOfDependsOnIds().remove(requestId)) + ; } } } return removed; } - + /* * @return Batch request content's json as String */ public String getBatchRequestContent() { - JSONObject batchRequestContentMap = new JSONObject(); - JSONArray batchContentArray = new JSONArray(); - for(Map.Entry requestStep : batchRequestStepsHashMap.entrySet()) { + final JsonObject batchRequestContentMap = new JsonObject(); + final JsonArray batchContentArray = new JsonArray(); + for (final Map.Entry requestStep : batchRequestStepsHashMap.entrySet()) { batchContentArray.add(getBatchRequestObjectFromRequestStep(requestStep.getValue())); } - batchRequestContentMap.put("requests", batchContentArray); - - String content = batchRequestContentMap.toString(); + batchRequestContentMap.add("requests", batchContentArray); + + final String content = batchRequestContentMap.toString(); return content; } - - private JSONObject getBatchRequestObjectFromRequestStep(final MSBatchRequestStep batchRequestStep){ - JSONObject contentmap = new JSONObject(); - contentmap.put("id", batchRequestStep.getRequestId()); - - String url = batchRequestStep.getRequest().url().toString(); - url = url.replaceAll("https://graph.microsoft.com/v1.0/", ""); - url = url.replaceAll("http://graph.microsoft.com/v1.0/", ""); - url = url.replaceAll("https://graph.microsoft.com/beta/", ""); - url = url.replaceAll("http://graph.microsoft.com/beta/", ""); - contentmap.put("url", url); - - contentmap.put("method", batchRequestStep.getRequest().method().toString()); - - Headers headers = batchRequestStep.getRequest().headers(); - if(headers != null && headers.size() != 0) { - JSONObject headerMap = new JSONObject(); - for(Map.Entry> entry : headers.toMultimap().entrySet()) { - headerMap.put(entry.getKey(), getHeaderValuesAsString(entry.getValue())); + + private JsonObject getBatchRequestObjectFromRequestStep(final MSBatchRequestStep batchRequestStep) { + final JsonObject contentmap = new JsonObject(); + contentmap.add("id", new JsonPrimitive(batchRequestStep.getRequestId())); + + final String url = batchRequestStep.getRequest().url().toString() + .replaceAll("https://graph.microsoft.com/v1.0/", "").replaceAll("http://graph.microsoft.com/v1.0/", "") + .replaceAll("https://graph.microsoft.com/beta/", "").replaceAll("http://graph.microsoft.com/beta/", ""); + contentmap.add("url", new JsonPrimitive(url)); + + contentmap.add("method", new JsonPrimitive(batchRequestStep.getRequest().method().toString())); + + final Headers headers = batchRequestStep.getRequest().headers(); + if (headers != null && headers.size() != 0) { + final JsonObject headerMap = new JsonObject(); + for (final Map.Entry> entry : headers.toMultimap().entrySet()) { + headerMap.add(entry.getKey(), new JsonPrimitive(getHeaderValuesAsString(entry.getValue()))); } - contentmap.put("headers", headerMap); + contentmap.add("headers", headerMap); } - - List arrayOfDependsOnIds = batchRequestStep.getArrayOfDependsOnIds(); - if(arrayOfDependsOnIds != null) { - JSONArray array = new JSONArray(); - for(String dependsOnId : arrayOfDependsOnIds) array.add(dependsOnId); - contentmap.put("dependsOn", array); + + final List arrayOfDependsOnIds = batchRequestStep.getArrayOfDependsOnIds(); + if (arrayOfDependsOnIds != null) { + final JsonArray array = new JsonArray(); + for (final String dependsOnId : arrayOfDependsOnIds) + array.add(dependsOnId); + contentmap.add("dependsOn", array); } - - RequestBody body = batchRequestStep.getRequest().body(); - if(body != null) { + + final RequestBody body = batchRequestStep.getRequest().body(); + if (body != null) { try { - contentmap.put("body", requestBodyToJSONObject(batchRequestStep.getRequest())); - }catch(IOException | ParseException e) { + contentmap.add("body", requestBodyToJSONObject(batchRequestStep.getRequest())); + } catch (IOException | JsonParseException e) { e.printStackTrace(); - } + } } return contentmap; } - + private String getHeaderValuesAsString(final List list) { - if(list == null || list.size() == 0)return ""; - StringBuilder builder = new StringBuilder(list.get(0)); - for(int i=1;i batchRequestsHashMap; - private JSONArray batchResponseArray; + private JsonArray batchResponseArray; private String nextLink; - + /* * @param batchResponse OkHttp batch response on execution of batch requests */ - public MSBatchResponseContent(Response batchResponse) { + public MSBatchResponseContent(final Response batchResponse) { this.batchResponse = batchResponse; update(batchResponse); } - + /* * Returns OkHttp Response of given request Id * * @param requestId Request Id of batch step + * * @return OkHttp Response corresponding to requestId */ - public Response getResponseById(String requestId) { - if(batchResponseArray == null) return null; - - JSONArray responses = batchResponseArray; - - for(Object response : responses) { - JSONObject jsonresponse = (JSONObject)response; - String id = (String)jsonresponse.get("id"); - if(id.compareTo(requestId) == 0) { - Response.Builder builder = new Response.Builder(); - - // Put corresponding request into the constructed response - builder.request(batchRequestsHashMap.get(requestId)); - // copy protocol and message same as of batch response - builder.protocol(batchResponse.protocol()); - builder.message(batchResponse.message()); - - // Put status code of the corresponding request in JSONArray - if(jsonresponse.get("status") != null) { - Long status = (Long)jsonresponse.get("status"); - builder.code(status.intValue()); - } - - // Put body from response array for corresponding id into constructing response - if(jsonresponse.get("body") != null) { - JSONObject jsonObject = (JSONObject)jsonresponse.get("body"); - String bodyAsString = jsonObject.toJSONString(); - ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json; charset=utf-8"), bodyAsString); - builder.body(responseBody); - } - - // Put headers from response array for corresponding id into constructing response - if(jsonresponse.get("headers") != null){ - JSONObject jsonheaders = (JSONObject)jsonresponse.get("headers"); - for(Object key: jsonheaders.keySet()) { - String strkey = (String)key; - String strvalue = (String)jsonheaders.get(strkey); - for(String value : strvalue.split(";")) { - builder.header(strkey, value); + public Response getResponseById(final String requestId) { + if (batchResponseArray == null) + return null; + + final JsonArray responses = batchResponseArray; + + for (final JsonElement response : responses) { + final JsonObject jsonresponse = response.getAsJsonObject(); + final JsonElement idElement = jsonresponse.get("id"); + if (idElement != null) { + final String id = idElement.getAsString(); + if (id.compareTo(requestId) == 0) { + final Response.Builder builder = new Response.Builder(); + + // Put corresponding request into the constructed response + builder.request(batchRequestsHashMap.get(requestId)); + // copy protocol and message same as of batch response + builder.protocol(batchResponse.protocol()); + builder.message(batchResponse.message()); + + // Put status code of the corresponding request in JsonArray + final JsonElement statusElement = jsonresponse.get("status"); + if (statusElement != null) { + final Long status = statusElement.getAsLong(); + builder.code(status.intValue()); + } + + // Put body from response array for corresponding id into constructing response + final JsonElement jsonBodyElement = jsonresponse.get("body"); + if (jsonBodyElement != null) { + final JsonObject JsonObject = jsonBodyElement.getAsJsonObject(); + final String bodyAsString = JsonObject.toString(); + final ResponseBody responseBody = ResponseBody + .create(MediaType.parse("application/json; charset=utf-8"), bodyAsString); + builder.body(responseBody); + } + + // Put headers from response array for corresponding id into constructing + // response + final JsonElement jsonheadersElement = jsonresponse.get("headers"); + if (jsonheadersElement != null) { + final JsonObject jsonheaders = jsonheadersElement.getAsJsonObject(); + for (final String key : jsonheaders.keySet()) { + final JsonElement strValueElement = jsonheaders.get(key); + if (strValueElement != null) { + final String strvalue = strValueElement.getAsString(); + for (final String value : strvalue.split(";")) { + builder.header(key, value); + } + } } - } + } + return builder.build(); } - return builder.build(); } } return null; } - + /** * Get map of id and responses * * @return responses in Map of id and response */ public Map getResponses() { - if(batchResponseArray == null) + if (batchResponseArray == null) return null; - Map responsesMap = new HashMap<>(); - for(String id : batchRequestsHashMap.keySet()) { + final Map responsesMap = new HashMap<>(); + for (final String id : batchRequestsHashMap.keySet()) { responsesMap.put(id, getResponseById(id)); } return responsesMap; } - + /** * Get iterator over the responses * * @return iterator for responses */ public Iterator> getResponsesIterator() { - Map responsesMap = getResponses(); + final Map responsesMap = getResponses(); return responsesMap != null ? responsesMap.entrySet().iterator() : null; } - - public void update(Response batchResponse) { - if(batchResponse == null) + + public void update(final Response batchResponse) { + if (batchResponse == null) throw new IllegalArgumentException("Batch Response cannot be null"); - - Map requestMap = createBatchRequestsHashMap(batchResponse); - if(batchRequestsHashMap == null) + + final Map requestMap = createBatchRequestsHashMap(batchResponse); + if (batchRequestsHashMap == null) batchRequestsHashMap = new HashMap<>(); - if(requestMap != null) + if (requestMap != null) batchRequestsHashMap.putAll(requestMap); - - if(batchResponse.body() != null) { + + if (batchResponse.body() != null) { try { - String batchResponseData = batchResponse.body().string(); - if(batchResponseData != null) { - JSONObject batchResponseObj = stringToJSONObject(batchResponseData); - if(batchResponseObj != null) { - - JSONObject nextLinkObject = (JSONObject) batchResponseObj.get("@odata.nextLink"); - if(nextLinkObject!=null) - nextLink = nextLinkObject.toString(); - - if(batchResponseArray == null) - batchResponseArray = new JSONArray(); - - JSONArray responseArray = (JSONArray)batchResponseObj.get("responses"); - if(responseArray!=null) + final String batchResponseData = batchResponse.body().string(); + if (batchResponseData != null) { + final JsonObject batchResponseObj = stringToJSONObject(batchResponseData); + if (batchResponseObj != null) { + + final JsonElement nextLinkElement = batchResponseObj.get("@odata.nextLink"); + if (nextLinkElement != null) + nextLink = nextLinkElement.getAsString(); + + if (batchResponseArray == null) + batchResponseArray = new JsonArray(); + + final JsonElement responseArrayElement = batchResponseObj.get("responses"); + if (responseArrayElement != null) { + final JsonArray responseArray = responseArrayElement.getAsJsonArray(); batchResponseArray.addAll(responseArray); + } } } - } catch (IOException e) { + } catch (final IOException e) { e.printStackTrace(); } } } - + /* * @return nextLink of batch response */ public String nextLink() { return nextLink; } - - private Map createBatchRequestsHashMap(Response batchResponse) { - if(batchResponse == null)return null; + + private Map createBatchRequestsHashMap(final Response batchResponse) { + if (batchResponse == null) + return null; try { - Map batchRequestsHashMap = new HashMap<>(); - JSONObject requestJSONObject = requestBodyToJSONObject(batchResponse.request()); - JSONArray requestArray = (JSONArray)requestJSONObject.get("requests"); - for(Object item : requestArray) { - JSONObject requestObject = (JSONObject)item; - - Request.Builder builder = new Request.Builder(); - - if(requestObject.get("url") != null) { - StringBuilder fullUrl = new StringBuilder(batchResponse.request().url().toString().replace("$batch","")); - fullUrl.append(requestObject.get("url").toString()); - builder.url(fullUrl.toString()); - } - if(requestObject.get("headers") != null) { - JSONObject jsonheaders = (JSONObject)requestObject.get("headers"); - for(Object key: jsonheaders.keySet()) { - String strkey = (String)key; - String strvalue = (String)jsonheaders.get(strkey); - for(String value : strvalue.split("; ")) { - builder.header(strkey, value); + final Map batchRequestsHashMap = new HashMap<>(); + final JsonObject requestJSONObject = requestBodyToJSONObject(batchResponse.request()); + final JsonElement requestArrayElement = requestJSONObject.get("requests"); + if (requestArrayElement != null) { + final JsonArray requestArray = requestArrayElement.getAsJsonArray(); + for (final JsonElement item : requestArray) { + final JsonObject requestObject = item.getAsJsonObject(); + + final Request.Builder builder = new Request.Builder(); + + final JsonElement urlElement = requestObject.get("url"); + if (urlElement != null) { + final StringBuilder fullUrl = new StringBuilder( + batchResponse.request().url().toString().replace("$batch", "")); + fullUrl.append(urlElement.getAsString()); + builder.url(fullUrl.toString()); + } + final JsonElement jsonHeadersElement = requestObject.get("headers"); + if (jsonHeadersElement != null) { + final JsonObject jsonheaders = jsonHeadersElement.getAsJsonObject(); + for (final String key : jsonheaders.keySet()) { + final JsonElement strvalueElement = jsonheaders.get(key); + if (strvalueElement != null) { + final String strvalue = strvalueElement.getAsString(); + for (final String value : strvalue.split("; ")) { + builder.header(key, value); + } + } } - } - } - if(requestObject.get("body") != null) { - JSONObject jsonObject = (JSONObject)requestObject.get("body"); - String bodyAsString = jsonObject.toJSONString(); - RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), bodyAsString); - builder.method(requestObject.get("method").toString(), requestBody); - } else { - builder.method(requestObject.get("method").toString(), null); + } + final JsonElement jsonBodyElement = requestObject.get("body"); + final JsonElement jsonMethodElement = requestObject.get("method"); + if (jsonBodyElement != null && jsonMethodElement != null) { + final JsonObject JsonObject = jsonBodyElement.getAsJsonObject(); + final String bodyAsString = JsonObject.toString(); + final RequestBody requestBody = RequestBody + .create(MediaType.parse("application/json; charset=utf-8"), bodyAsString); + builder.method(jsonMethodElement.getAsString(), requestBody); + } else if (jsonMethodElement != null) { + builder.method(jsonMethodElement.getAsString(), null); + } + final JsonElement jsonIdElement = requestObject.get("id"); + if (jsonIdElement != null) { + batchRequestsHashMap.put(jsonIdElement.getAsString(), builder.build()); + } } - batchRequestsHashMap.put(requestObject.get("id").toString(), builder.build()); } return batchRequestsHashMap; - - } catch (IOException | ParseException e) { e.printStackTrace(); } + + } catch (IOException | JsonParseException e) { + e.printStackTrace(); + } return null; } - - private JSONObject stringToJSONObject(String input) { - JSONParser parser = new JSONParser(); - JSONObject jsonObject = null; + + private JsonObject stringToJSONObject(final String input) { + JsonObject JsonObject = null; try { - if(input != null) { - jsonObject = (JSONObject) parser.parse(input); + if (input != null) { + JsonObject = JsonParser.parseString(input).getAsJsonObject(); } - } - catch(Exception e) { + } catch (final Exception e) { e.printStackTrace(); } - return jsonObject; + return JsonObject; } - - private JSONObject requestBodyToJSONObject(final Request request) throws IOException, ParseException{ - if(request == null || request.body() == null)return null; - Request copy = request.newBuilder().build(); - Buffer buffer = new Buffer(); + + private JsonObject requestBodyToJSONObject(final Request request) throws IOException, JsonParseException { + if (request == null || request.body() == null) + return null; + final Request copy = request.newBuilder().build(); + final Buffer buffer = new Buffer(); copy.body().writeTo(buffer); - String requestBody = buffer.readUtf8(); - JSONObject jsonObject = (JSONObject)new JSONParser().parse(requestBody); - return jsonObject; + final String requestBody = buffer.readUtf8(); + final JsonObject JsonObject = JsonParser.parseString(requestBody).getAsJsonObject(); + return JsonObject; } } diff --git a/src/test/java/com/microsoft/graph/content/MSBatchRequestContentTest.java b/src/test/java/com/microsoft/graph/content/MSBatchRequestContentTest.java index ef5835654..924dc6c68 100644 --- a/src/test/java/com/microsoft/graph/content/MSBatchRequestContentTest.java +++ b/src/test/java/com/microsoft/graph/content/MSBatchRequestContentTest.java @@ -34,7 +34,7 @@ public void testGetBatchRequestContent() { MSBatchRequestContent requestContent = new MSBatchRequestContent(); requestContent.addBatchRequestStep(requestStep); String content = requestContent.getBatchRequestContent(); - String expectedContent = "{\"requests\":[{\"method\":\"GET\",\"dependsOn\":[],\"id\":\"1\",\"url\":\"http:\\/\\/graph.microsoft.com\\/me\"}]}"; + String expectedContent = "{\"requests\":[{\"id\":\"1\",\"url\":\"http://graph.microsoft.com/me\",\"method\":\"GET\",\"dependsOn\":[]}]}"; assertTrue(content.compareTo(expectedContent) == 0); } @@ -47,7 +47,7 @@ public void testGetBatchRequestContentWithHeader() { requestContent.addBatchRequestStep(requestStep); String content = requestContent.getBatchRequestContent(); System.out.println(content); - String expectedContent = "{\"requests\":[{\"headers\":{\"testkey\":\"testvalue\"},\"method\":\"GET\",\"dependsOn\":[],\"id\":\"1\",\"url\":\"http:\\/\\/graph.microsoft.com\\/me\"}]}"; + String expectedContent = "{\"requests\":[{\"id\":\"1\",\"url\":\"http://graph.microsoft.com/me\",\"method\":\"GET\",\"headers\":{\"testkey\":\"testvalue\"},\"dependsOn\":[]}]}"; assertTrue(content.compareTo(expectedContent) == 0); } @@ -81,7 +81,7 @@ public void testRemoveBatchRequesStepWithIdByAddingMultipleBatchSteps() { requestContent.removeBatchRequestStepWithId("1"); String content = requestContent.getBatchRequestContent(); - String expectedContent = "{\"requests\":[{\"method\":\"GET\",\"dependsOn\":[],\"id\":\"2\",\"url\":\"http:\\/\\/graph.microsoft.com\\/me\"}]}"; + String expectedContent = "{\"requests\":[{\"id\":\"2\",\"url\":\"http://graph.microsoft.com/me\",\"method\":\"GET\",\"dependsOn\":[]}]}"; assertTrue(content.compareTo(expectedContent) == 0); } diff --git a/src/test/java/com/microsoft/graph/content/MSBatchResponseContentTest.java b/src/test/java/com/microsoft/graph/content/MSBatchResponseContentTest.java index a7772aab9..56095531e 100644 --- a/src/test/java/com/microsoft/graph/content/MSBatchResponseContentTest.java +++ b/src/test/java/com/microsoft/graph/content/MSBatchResponseContentTest.java @@ -62,7 +62,7 @@ public void testInvalidMSBatchResponseContentWithMalformedResponse() { String requestbody = "{requests:[]}"; Response invalidResponsedata = TestResponse(invalidResponsebody, requestbody); MSBatchResponseContent batchresponse = new MSBatchResponseContent(invalidResponsedata); - assertTrue(batchresponse.getResponses() == null); + assertTrue(batchresponse.getResponses().keySet().isEmpty()); } @Test