Skip to content

Commit 3e87c20

Browse files
Use InputStream instead of String in ISerializer
1 parent cffa9d4 commit 3e87c20

10 files changed

Lines changed: 87 additions & 51 deletions

File tree

‎.gitignore‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ hs_err_pid*
2929
.classpath
3030
.settings
3131

32+
# IntelliJ
33+
*.iml
34+
.idea/
35+
3236
# Maven
3337
/target/
3438
local.properties

‎gradlew‎

100644100755
File mode changed.

‎src/main/java/com/microsoft/graph/concurrency/ChunkedUploadResponseHandler.java‎

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -22,26 +22,28 @@
2222

2323
package com.microsoft.graph.concurrency;
2424

25-
import java.io.BufferedInputStream;
26-
import java.io.InputStream;
27-
import java.util.Map;
28-
29-
import javax.annotation.Nullable;
30-
import javax.annotation.Nonnull;
31-
32-
import com.microsoft.graph.http.CoreHttpProvider;
25+
import com.microsoft.graph.core.ClientException;
3326
import com.microsoft.graph.core.Constants;
3427
import com.microsoft.graph.http.GraphServiceException;
35-
import com.microsoft.graph.core.ClientException;
3628
import com.microsoft.graph.http.HttpResponseCode;
3729
import com.microsoft.graph.http.HttpResponseHeadersHelper;
3830
import com.microsoft.graph.http.IHttpRequest;
3931
import com.microsoft.graph.http.IStatefulResponseHandler;
4032
import com.microsoft.graph.logger.ILogger;
4133
import com.microsoft.graph.serializer.ISerializer;
4234

35+
import java.io.BufferedInputStream;
36+
import java.io.InputStream;
37+
import java.util.Map;
38+
39+
import javax.annotation.Nonnull;
40+
import javax.annotation.Nullable;
41+
4342
import okhttp3.Response;
4443

44+
import static com.microsoft.graph.http.HttpResponseCode.HTTP_CREATED;
45+
import static com.microsoft.graph.http.HttpResponseCode.HTTP_OK;
46+
4547
/**
4648
* Handles the stateful response from the OneDrive upload session
4749
*
@@ -98,35 +100,38 @@ public ChunkedUploadResult<UploadType> generateResult(
98100
if (response.code() >= HttpResponseCode.HTTP_CLIENT_ERROR) {
99101
logger.logDebug("Receiving error during upload, see detail on result error");
100102

101-
return new ChunkedUploadResult<UploadType>(
103+
return new ChunkedUploadResult<>(
102104
GraphServiceException.createFromResponse(request, null, serializer,
103-
response, logger));
104-
} else if (response.code() >= HttpResponseCode.HTTP_OK
105+
response, logger));
106+
} else if (response.code() >= HTTP_OK
105107
&& response.code() < HttpResponseCode.HTTP_MULTIPLE_CHOICES) {
106108
final Map<String, String> headers = responseHeadersHelper.getResponseHeadersAsMapStringString(response);
107109
final String contentType = headers.get(Constants.CONTENT_TYPE_HEADER_NAME);
108110
final String location = headers.get("Location");
109-
if(contentType != null
110-
&& contentType.contains(Constants.JSON_CONTENT_TYPE)) {
111+
if (contentType != null
112+
&& contentType.contains(Constants.JSON_CONTENT_TYPE)) {
111113
try (final InputStream in = new BufferedInputStream(response.body().byteStream())) {
112-
final String rawJson = CoreHttpProvider.streamToString(in);
113-
final IUploadSession session = serializer.deserializeObject(rawJson, uploadSessionClass);
114-
if(session == null || session.getNextExpectedRanges() == null) {
114+
if (isUploadSessionCompleted(response)) {
115115
logger.logDebug("Upload session is completed (ODSP), uploaded item returned.");
116-
final UploadType uploadedItem = serializer.deserializeObject(rawJson, this.deserializeTypeClass);
117-
return new ChunkedUploadResult<UploadType>(uploadedItem);
116+
final UploadType uploadedItem = serializer.deserializeObject(in, this.deserializeTypeClass);
117+
return new ChunkedUploadResult<>(uploadedItem);
118118
} else {
119+
final IUploadSession session = serializer.deserializeObject(in, uploadSessionClass);
119120
logger.logDebug("Chunk bytes has been accepted by the server.");
120-
return new ChunkedUploadResult<UploadType>(session);
121+
return new ChunkedUploadResult<>(session);
121122
}
122123
}
123-
} else if(location != null) {
124+
} else if (location != null) {
124125
logger.logDebug("Upload session is completed (Outlook), uploaded item returned.");
125-
return new ChunkedUploadResult<UploadType>(this.deserializeTypeClass.getDeclaredConstructor().newInstance());
126+
return new ChunkedUploadResult<>(this.deserializeTypeClass.getDeclaredConstructor().newInstance());
126127
} else {
127128
logger.logDebug("Upload session returned an unexpected response");
128129
}
129130
}
130-
return new ChunkedUploadResult<UploadType>(new ClientException("Received an unexpected response from the service, response code: " + response.code(), null));
131+
return new ChunkedUploadResult<>(new ClientException("Received an unexpected response from the service, response code: " + response.code(), null));
132+
}
133+
134+
private boolean isUploadSessionCompleted(Response response) {
135+
return response.code() == HTTP_OK || response.code() == HTTP_CREATED;
131136
}
132137
}

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

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,11 @@
6262
import okhttp3.Request;
6363
import okhttp3.RequestBody;
6464
import okhttp3.Response;
65+
import okhttp3.internal.Util;
6566
import okio.BufferedSink;
6667

68+
import static okhttp3.internal.Util.closeQuietly;
69+
6770
/**
6871
* HTTP provider based off of OkHttp and msgraph-sdk-java-core library
6972
*/
@@ -502,8 +505,12 @@ private <Result> Result handleJsonResponse(final InputStream in, Map<String, Lis
502505
return null;
503506
}
504507

505-
final String rawJson = CoreHttpProvider.streamToString(in);
506-
return serializer.deserializeObject(rawJson, clazz, responseHeaders);
508+
try {
509+
return serializer.deserializeObject(in, clazz, responseHeaders);
510+
} finally {
511+
closeQuietly(in);
512+
}
513+
507514
}
508515
/**
509516
* Handles the cause where the response is a Text object

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

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,10 @@
2222

2323
package com.microsoft.graph.http;
2424

25+
import java.io.ByteArrayInputStream;
2526
import java.io.IOException;
2627
import java.io.InputStream;
28+
import java.nio.charset.StandardCharsets;
2729
import java.util.LinkedList;
2830
import java.util.List;
2931
import java.util.Locale;
@@ -42,6 +44,8 @@
4244
import com.microsoft.graph.serializer.ISerializer;
4345

4446
import okhttp3.Response;
47+
48+
import static java.nio.charset.StandardCharsets.UTF_8;
4549
import static okhttp3.internal.Util.closeQuietly;
4650

4751
/**
@@ -377,7 +381,7 @@ public static <T> GraphServiceException createFromResponse(@Nonnull final IHttpR
377381
}
378382

379383
final String responseMessage = response.message();
380-
String rawOutput = "{}";
384+
String rawOutput;
381385

382386
InputStream is = response.body().byteStream();
383387
try {
@@ -387,7 +391,12 @@ public static <T> GraphServiceException createFromResponse(@Nonnull final IHttpR
387391
}
388392
GraphErrorResponse error;
389393
try {
390-
error = serializer.deserializeObject(rawOutput, GraphErrorResponse.class, responseHeadersHelper.getResponseHeadersAsMapOfStringList(response));
394+
// we need a "copy" of the stream, so we can log the raw output if it cannot be parsed
395+
error = serializer.deserializeObject(
396+
new ByteArrayInputStream(rawOutput.getBytes(UTF_8)),
397+
GraphErrorResponse.class,
398+
responseHeadersHelper.getResponseHeadersAsMapOfStringList(response)
399+
);
391400
} catch (final Exception ex) {
392401
error = new GraphErrorResponse();
393402
error.error = new GraphError();

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

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ public static <T1, T2 extends BaseRequestBuilder<T1>> BaseCollectionPage<T1, T2>
106106
}
107107
serializer = new DefaultSerializer(logger);
108108
final JsonArray sourceArray = json.getAsJsonArray();
109-
final ArrayList<T1> list = new ArrayList<T1>(sourceArray.size());
109+
final ArrayList<T1> list = new ArrayList<>(sourceArray.size());
110110
/** eg: com.microsoft.graph.requests.AttachmentCollectionPage */
111111
final String collectionPageClassCanonicalName = ((Class<?>)typeOfT).getName();
112112
/** eg: com.microsoft.graph.models.Attachment */
@@ -115,14 +115,14 @@ public static <T1, T2 extends BaseRequestBuilder<T1>> BaseCollectionPage<T1, T2>
115115
.replace("requests", "models");
116116
try {
117117
final Class<?> baseEntityClass = Class.forName(baseEntityClassCanonicalName);
118-
for(JsonElement sourceElement : sourceArray) {
119-
if(sourceElement.isJsonObject()) {
118+
for (JsonElement sourceElement : sourceArray) {
119+
if (sourceElement.isJsonObject()) {
120120
final JsonObject sourceObject = sourceElement.getAsJsonObject();
121121
Class<?> entityClass = serializer.getDerivedClass(sourceObject, baseEntityClass);
122-
if(entityClass == null)
122+
if (entityClass == null)
123123
entityClass = baseEntityClass;
124-
final T1 targetObject = (T1)serializer.deserializeObject(sourceObject.toString(), entityClass);
125-
((IJsonBackedObject)targetObject).setRawObject(serializer, sourceObject);
124+
final T1 targetObject = (T1) serializer.deserializeObject(sourceObject, entityClass, null);
125+
((IJsonBackedObject) targetObject).setRawObject(serializer, sourceObject);
126126
list.add(targetObject);
127127
}
128128
}

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

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,11 @@
2828
import com.google.gson.JsonArray;
2929
import com.google.gson.JsonElement;
3030
import com.google.gson.JsonObject;
31+
3132
import com.microsoft.graph.logger.ILogger;
3233

34+
import java.io.InputStream;
35+
import java.io.InputStreamReader;
3336
import java.lang.reflect.Field;
3437
import java.lang.reflect.Type;
3538
import java.util.HashMap;
@@ -38,8 +41,8 @@
3841
import java.util.Map;
3942
import java.util.Map.Entry;
4043

41-
import javax.annotation.Nullable;
4244
import javax.annotation.Nonnull;
45+
import javax.annotation.Nullable;
4346

4447
/**
4548
* The default serializer implementation for the SDK
@@ -69,35 +72,41 @@ public DefaultSerializer(@Nonnull final ILogger logger) {
6972
/**
7073
* Deserializes an object from the input string
7174
*
72-
* @param inputString the string that stores the representation of the item
75+
* @param inputStream the string that stores the representation of the item
7376
* @param clazz the class of the item to be deserialized
7477
* @param <T> the type of the item to be deserialized
7578
* @return the deserialized item from the input string
7679
*/
7780
@Override
7881
@Nullable
79-
public <T> T deserializeObject(@Nonnull final String inputString, @Nonnull final Class<T> clazz) {
80-
return deserializeObject(inputString, clazz, null);
82+
public <T> T deserializeObject(@Nonnull final InputStream inputStream, @Nonnull final Class<T> clazz) {
83+
return deserializeObject(inputStream, clazz, null);
8184
}
8285
private static final String graphResponseHeadersKey = "graphResponseHeaders";
8386
@SuppressWarnings("unchecked")
8487
@Override
8588
@Nullable
86-
public <T> T deserializeObject(@Nonnull final String inputString, @Nonnull final Class<T> clazz, @Nonnull final Map<String, java.util.List<String>> responseHeaders) {
87-
final T jsonObject = gson.fromJson(inputString, clazz);
89+
public <T> T deserializeObject(@Nonnull final InputStream inputStream, @Nonnull final Class<T> clazz, @Nonnull final Map<String, List<String>> responseHeaders) {
90+
final JsonElement rawElement = gson.fromJson(new InputStreamReader(inputStream), JsonElement.class);
91+
return deserializeObject(rawElement, clazz, responseHeaders);
92+
}
93+
94+
@SuppressWarnings("unchecked")
95+
@Nullable
96+
public <T> T deserializeObject(@Nonnull final JsonElement rawElement, @Nonnull final Class<T> clazz, @Nonnull final Map<String, List<String>> responseHeaders) {
97+
final T jsonObject = gson.fromJson(rawElement, clazz);
8898

8999
// Populate the JSON-backed fields for any annotations that are not in the object model
90100
if (jsonObject instanceof IJsonBackedObject) {
91101
logger.logDebug("Deserializing type " + clazz.getSimpleName());
92-
final JsonElement rawElement = gson.fromJson(inputString, JsonElement.class);
93102
final JsonObject rawObject = rawElement.isJsonObject() ? rawElement.getAsJsonObject() : null;
94103

95104
// If there is a derived class, try to get it and deserialize to it
96105
T jo = jsonObject;
97106
if (rawElement.isJsonObject()) {
98107
final Class<?> derivedClass = this.getDerivedClass(rawObject, clazz);
99-
if(derivedClass != null)
100-
jo = (T) gson.fromJson(inputString, derivedClass);
108+
if (derivedClass != null)
109+
jo = (T) gson.fromJson(rawElement, derivedClass);
101110
}
102111

103112
final IJsonBackedObject jsonBackedObject = (IJsonBackedObject) jo;

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

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

2323
package com.microsoft.graph.serializer;
2424

25+
import java.io.InputStream;
2526
import java.util.List;
2627
import java.util.Map;
2728

@@ -36,25 +37,25 @@ public interface ISerializer {
3637
/**
3738
* Deserialize an object from the input string
3839
*
39-
* @param inputString the string that stores the representation of the item
40+
* @param inputStream the string that stores the representation of the item
4041
* @param clazz the .class of the item to be deserialized
4142
* @param <T> the type of the item to be deserialized
4243
* @return the deserialized item from the input string
4344
*/
4445
@Nullable
45-
<T> T deserializeObject(@Nonnull final String inputString, @Nonnull final Class<T> clazz);
46+
<T> T deserializeObject(@Nonnull final InputStream inputStream, @Nonnull final Class<T> clazz);
4647

4748
/**
4849
* Deserialize an object from the input string
4950
*
50-
* @param inputString the string that stores the representation of the item
51+
* @param inputStream the string that stores the representation of the item
5152
* @param clazz the .class of the item to be deserialized
5253
* @param responseHeaders the HTTP response headers
5354
* @param <T> the type of the item to be deserialized
5455
* @return the deserialized item from the input string
5556
*/
5657
@Nullable
57-
<T> T deserializeObject(@Nonnull final String inputString, @Nonnull final Class<T> clazz, @Nonnull final Map<String, List<String>> responseHeaders);
58+
<T> T deserializeObject(@Nonnull final InputStream inputStream, @Nonnull final Class<T> clazz, @Nonnull final Map<String, List<String>> responseHeaders);
5859

5960
/**
6061
* Serializes an object into a string

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

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import static org.junit.Assert.assertNotNull;
55
import static org.mockito.Mockito.mock;
66

7+
import java.io.InputStream;
78
import java.util.List;
89
import java.util.Map;
910

@@ -73,13 +74,13 @@ public <T> String serializeObject(T serializableObject) {
7374
}
7475

7576
@Override
76-
public <T> T deserializeObject(String inputString, Class<T> clazz,
77-
Map<String, List<String>> responseHeaders) {
77+
public <T> T deserializeObject(InputStream inputStream, Class<T> clazz,
78+
Map<String, List<String>> responseHeaders) {
7879
return null;
7980
}
8081

8182
@Override
82-
public <T> T deserializeObject(String inputString, Class<T> clazz) {
83+
public <T> T deserializeObject(InputStream inputString, Class<T> clazz) {
8384
return null;
8485
}
8586
};
@@ -90,7 +91,7 @@ public <T> T deserializeObject(String inputString, Class<T> clazz) {
9091
assertEquals(serializer, client.getSerializer());
9192
assertNotNull(client.getHttpProvider());
9293
assertNotNull(client.getLogger());
93-
assertEquals(serializer, ((CoreHttpProvider) client.getHttpProvider()).getSerializer());
94+
assertEquals(serializer, client.getHttpProvider().getSerializer());
9495
}
9596

9697
@Test

‎src/test/java/com/microsoft/graph/http/CoreHttpProviderTests.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ public void testVerboseErrorResponse() throws Exception {
8484
final ILogger logger = mock(ILogger.class);
8585
when(logger.getLoggingLevel()).thenReturn(LoggerLevel.DEBUG);
8686
final ISerializer serializer = mock(ISerializer.class);
87-
when(serializer.deserializeObject(anyString(), any())).thenReturn(toSerialize);
87+
when(serializer.deserializeObject(any(), any())).thenReturn(toSerialize);
8888

8989
mProvider = new CoreHttpProvider(serializer,
9090
logger,

0 commit comments

Comments
 (0)