Skip to content

Commit ba6cf34

Browse files
authored
Merge pull request #125 from microsoftgraph/bugfix/collection-responses
- fixes a bug where collection responses would not respect odata inheritance
2 parents 391187d + 08e1293 commit ba6cf34

6 files changed

Lines changed: 190 additions & 95 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
*
1818
* @param <T> the entity or complex type
1919
*/
20-
public abstract class BaseCollectionResponse<T> implements ICollectionResponse<T> {
20+
public abstract class BaseCollectionResponse<T> implements ICollectionResponse<T> {
2121

2222
/**
2323
* The list of items within this collection page

‎src/main/java/com/microsoft/graph/httpcore/ChaosHttpHandler.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ public class ChaosHttpHandler implements Interceptor {
3232
/**
3333
* Denominator for the failure rate (i.e. 1/X)
3434
*/
35-
private final Integer failureRate = 3;
35+
private final int failureRate = 3;
3636
/**
3737
* default value to return on retry after
3838
*/
@@ -55,7 +55,7 @@ public Response intercept(@Nonnull final Chain chain) throws IOException {
5555
request = request.newBuilder().tag(TelemetryOptions.class, new TelemetryOptions()).build();
5656
request.tag(TelemetryOptions.class).setFeatureUsage(TelemetryOptions.RETRY_HANDLER_ENABLED_FLAG);
5757

58-
final Integer dice = ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE);
58+
final int dice = ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE);
5959

6060
if(dice % failureRate == 0) {
6161
return new Response

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

Lines changed: 68 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,6 @@
2424

2525
import java.lang.reflect.InvocationTargetException;
2626
import java.lang.reflect.Type;
27-
import java.util.ArrayList;
28-
import java.util.Arrays;
2927
import java.util.List;
3028

3129
import javax.annotation.Nullable;
@@ -36,115 +34,95 @@
3634
import com.google.gson.JsonObject;
3735
import com.google.gson.JsonParseException;
3836
import com.google.gson.JsonParser;
39-
import com.google.common.reflect.TypeToken;
4037
import com.microsoft.graph.http.BaseCollectionPage;
38+
import com.microsoft.graph.http.BaseCollectionResponse;
4139
import com.microsoft.graph.http.BaseRequestBuilder;
42-
import com.microsoft.graph.http.IRequestBuilder;
4340
import com.microsoft.graph.logger.ILogger;
4441

4542
/** Specialized serializer to handle collection pages */
4643
public class CollectionPageSerializer {
4744

48-
private static DefaultSerializer serializer;
49-
/** length of the word "page" */
50-
private final static Integer pageLength = 4;
51-
/** length of the word "collection" */
52-
private final static Integer collectionLength = 10;
53-
/** length of the work "response" */
54-
private final static Integer responseLength = 8;
45+
private static DefaultSerializer serializer;
46+
/** length of the work "response" */
47+
private final static int responseLength = 8;
48+
/** length of the work "page" */
49+
private final static int pageLength = 4;
5550

56-
/**
57-
* Not available for instantiation
58-
*/
59-
private CollectionPageSerializer() {
60-
}
51+
/**
52+
* Not available for instantiation
53+
*/
54+
private CollectionPageSerializer() {
55+
}
6156

62-
/**
57+
/**
6358
* Serializes an CollectionPage
6459
*
6560
* @param src the CollectionPage variable for serialization
6661
* @param logger the logger
67-
* @param <T1> the entity type for the collection
68-
* @param <T2> the collection request builder interface type
62+
* @param <T1> the entity type for the collection
63+
* @param <T2> the collection request builder interface type
6964
* @return JsonElement of CollectionPage
7065
*/
71-
@Nullable
72-
public static <T1, T2 extends BaseRequestBuilder<T1>> JsonElement serialize(@Nonnull final BaseCollectionPage<T1, T2> src, @Nonnull final ILogger logger) {
73-
if(src == null) {
74-
return null;
75-
}
76-
JsonArray jsonArray = new JsonArray();
77-
List<T1> items = src.getCurrentPage();
78-
serializer = new DefaultSerializer(logger);
79-
for(T1 item : items) {
80-
final String json = serializer.serializeObject(item);
81-
final JsonElement element = JsonParser.parseString(json);
82-
if(element != null && element.isJsonObject()) {
83-
final JsonObject jsonObject = element.getAsJsonObject();
84-
jsonArray.add(jsonObject);
85-
}
86-
}
87-
return jsonArray;
88-
}
66+
@Nullable
67+
public static <T1, T2 extends BaseRequestBuilder<T1>> JsonElement serialize(@Nonnull final BaseCollectionPage<T1, T2> src, @Nonnull final ILogger logger) {
68+
if(src == null) {
69+
return null;
70+
}
71+
JsonArray jsonArray = new JsonArray();
72+
List<T1> items = src.getCurrentPage();
73+
serializer = new DefaultSerializer(logger);
74+
for(T1 item : items) {
75+
final String json = serializer.serializeObject(item);
76+
final JsonElement element = JsonParser.parseString(json);
77+
if(element != null && element.isJsonObject()) {
78+
final JsonObject jsonObject = element.getAsJsonObject();
79+
jsonArray.add(jsonObject);
80+
}
81+
}
82+
return jsonArray;
83+
}
8984

90-
/**
85+
/**
9186
* Deserializes the JsonElement
9287
*
9388
* @param json the source CollectionPage's Json
94-
* @param typeOfT The type of the CollectionPage to deserialize to
89+
* @param typeOfT The type of the CollectionPage to deserialize to
9590
* @param logger the logger
96-
* @param <T1> the entity type for the collection
97-
* @param <T2> the collection request builder interface type
91+
* @param <T1> the entity type for the collection
92+
* @param <T2> the collection request builder interface type
9893
* @throws JsonParseException the parse exception
9994
* @return the deserialized CollectionPage
10095
*/
101-
@SuppressWarnings("unchecked")
102-
@Nullable
103-
public static <T1, T2 extends BaseRequestBuilder<T1>> BaseCollectionPage<T1, T2> deserialize(@Nonnull final JsonElement json, @Nonnull final Type typeOfT, @Nonnull final ILogger logger) throws JsonParseException {
104-
if (json == null || !json.isJsonArray() || !typeOfT.getClass().equals(Class.class)) {
105-
return null;
106-
}
107-
serializer = new DefaultSerializer(logger);
108-
final JsonArray sourceArray = json.getAsJsonArray();
109-
final ArrayList<T1> list = new ArrayList<>(sourceArray.size());
110-
/** eg: com.microsoft.graph.requests.AttachmentCollectionPage */
111-
final String collectionPageClassCanonicalName = ((Class<?>)typeOfT).getName();
112-
/** eg: com.microsoft.graph.models.Attachment */
113-
final String baseEntityClassCanonicalName = collectionPageClassCanonicalName
114-
.substring(0, collectionPageClassCanonicalName.length() - pageLength - collectionLength)
115-
.replace("requests", "models");
116-
try {
117-
final Class<?> baseEntityClass = Class.forName(baseEntityClassCanonicalName);
118-
for (JsonElement sourceElement : sourceArray) {
119-
if (sourceElement.isJsonObject()) {
120-
final JsonObject sourceObject = sourceElement.getAsJsonObject();
121-
Class<?> entityClass = serializer.getDerivedClass(sourceObject, baseEntityClass);
122-
if (entityClass == null)
123-
entityClass = baseEntityClass;
124-
final T1 targetObject = (T1) serializer.deserializeObject(sourceObject, entityClass, null);
125-
((IJsonBackedObject) targetObject).setRawObject(serializer, sourceObject);
126-
list.add(targetObject);
127-
}
128-
}
129-
/** eg: com.microsoft.graph.requests.AttachmentCollectionResponse */
130-
final String responseClassCanonicalName = collectionPageClassCanonicalName
131-
.substring(0, collectionPageClassCanonicalName.length() - pageLength) + "Response";
132-
final Class<?> responseClass = Class.forName(responseClassCanonicalName);
133-
final Object response = responseClass.getConstructor().newInstance();
134-
responseClass.getField("value").set(response, list);
135-
final Class<?> collectionPageClass = Class.forName(collectionPageClassCanonicalName);
136-
/** eg: com.microsoft.graph.requests.AttachmentCollectionRequestBuilder */
137-
final String responseBuilderCanonicalName = responseClassCanonicalName
138-
.substring(0, responseClassCanonicalName.length() - responseLength) + "RequestBuilder";
139-
final Class<?> responseBuilderClass = Class.forName(responseBuilderCanonicalName);
140-
return (BaseCollectionPage<T1, T2>)collectionPageClass.getConstructor(responseClass, responseBuilderClass).newInstance(response, null);
141-
} catch(ClassNotFoundException ex) {
142-
logger.logError("Could not find class during deserialization", ex);
143-
} catch(NoSuchMethodException | InstantiationException | InvocationTargetException ex) {
144-
logger.logError("Could not instanciate type during deserialization", ex);
145-
} catch(NoSuchFieldException | IllegalAccessException ex) {
146-
logger.logError("Unable to set field value during deserialization", ex);
147-
}
148-
return null;
149-
}
96+
@SuppressWarnings("unchecked")
97+
@Nullable
98+
public static <T1, T2 extends BaseRequestBuilder<T1>> BaseCollectionPage<T1, T2> deserialize(@Nonnull final JsonElement json, @Nonnull final Type typeOfT, @Nonnull final ILogger logger) throws JsonParseException {
99+
if (json == null || !json.isJsonArray() || !typeOfT.getClass().equals(Class.class)) {
100+
return null;
101+
}
102+
serializer = new DefaultSerializer(logger);
103+
/** eg: com.microsoft.graph.requests.AttachmentCollectionPage */
104+
final String collectionPageClassCanonicalName = ((Class<?>)typeOfT).getName();
105+
try {
106+
/** eg: com.microsoft.graph.requests.AttachmentCollectionResponse */
107+
final String responseClassCanonicalName = collectionPageClassCanonicalName
108+
.substring(0, collectionPageClassCanonicalName.length() - pageLength) + "Response";
109+
final Class<?> responseClass = Class.forName(responseClassCanonicalName);
110+
final JsonObject responseJson = new JsonObject();
111+
responseJson.add("value", json);
112+
final BaseCollectionResponse<T1> response = CollectionResponseSerializer.deserialize(responseJson, responseClass, logger);
113+
/** eg: com.microsoft.graph.requests.AttachmentCollectionRequestBuilder */
114+
final String responseBuilderCanonicalName = responseClassCanonicalName
115+
.substring(0, responseClassCanonicalName.length() - responseLength) + "RequestBuilder";
116+
final Class<?> responseBuilderClass = Class.forName(responseBuilderCanonicalName);
117+
final Class<?> collectionPageClass = Class.forName(collectionPageClassCanonicalName);
118+
return (BaseCollectionPage<T1, T2>)collectionPageClass.getConstructor(responseClass, responseBuilderClass).newInstance(response, null);
119+
} catch(ClassNotFoundException ex) {
120+
logger.logError("Could not find class during deserialization", ex);
121+
} catch(NoSuchMethodException | InstantiationException | InvocationTargetException ex) {
122+
logger.logError("Could not instanciate type during deserialization", ex);
123+
} catch(IllegalAccessException ex) {
124+
logger.logError("Unable to set field value during deserialization", ex);
125+
}
126+
return null;
127+
}
150128
}
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// ------------------------------------------------------------------------------
2+
// Copyright (c) 2021 Microsoft Corporation
3+
//
4+
// Permission is hereby granted, free of charge, to any person obtaining a copy
5+
// of this software and associated documentation files (the "Software"), to deal
6+
// in the Software without restriction, including without limitation the rights
7+
// to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
8+
// copies of the Software, and to permit persons to whom the Software is
9+
// furnished to do so, subject to the following conditions:
10+
//
11+
// The above copyright notice and this permission notice shall be included in
12+
// all copies or substantial portions of the Software.
13+
//
14+
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20+
// THE SOFTWARE.
21+
// ------------------------------------------------------------------------------
22+
23+
package com.microsoft.graph.serializer;
24+
25+
import java.lang.reflect.InvocationTargetException;
26+
import java.lang.reflect.Type;
27+
import java.util.ArrayList;
28+
29+
import javax.annotation.Nonnull;
30+
import javax.annotation.Nullable;
31+
32+
import com.google.gson.JsonArray;
33+
import com.google.gson.JsonElement;
34+
import com.google.gson.JsonObject;
35+
import com.google.gson.JsonParseException;
36+
import com.microsoft.graph.http.BaseCollectionResponse;
37+
import com.microsoft.graph.logger.ILogger;
38+
39+
/** Specialized serializer to handle collection responses */
40+
public class CollectionResponseSerializer {
41+
private static DefaultSerializer serializer;
42+
/**
43+
* Not available for instantiation
44+
*/
45+
private CollectionResponseSerializer() {}
46+
/**
47+
* Deserializes the JsonElement
48+
*
49+
* @param json the source CollectionResponse's Json
50+
* @param typeOfT The type of the CollectionResponse to deserialize to
51+
* @param logger the logger
52+
* @param <T1> the entity type for the collection
53+
* @throws JsonParseException the parse exception
54+
* @return the deserialized CollectionResponse
55+
*/
56+
@SuppressWarnings("unchecked")
57+
@Nullable
58+
public static <T1> BaseCollectionResponse<T1> deserialize(@Nonnull final JsonElement json, @Nonnull final Type typeOfT, @Nonnull final ILogger logger) throws JsonParseException {
59+
if (json == null || !json.isJsonObject()| !typeOfT.getClass().equals(Class.class)) {
60+
return null;
61+
}
62+
serializer = new DefaultSerializer(logger);
63+
final JsonObject jsonAsObject = json.getAsJsonObject();
64+
final JsonArray sourceArray = jsonAsObject.get("value").getAsJsonArray();
65+
final ArrayList<T1> list = new ArrayList<>(sourceArray.size());
66+
/** eg: com.microsoft.graph.requests.AttachmentCollectionResponse */
67+
/** eg: com.microsoft.graph.requests.DriveItemDeltaCollectionResponse */
68+
/** eg: com.microsoft.graph.requests.DriveItemGetActivitiesByIntervalCollectionResponse */
69+
final Class<?> responseClass = ((Class<?>)typeOfT);
70+
/** eg: com.microsoft.graph.http.BaseCollectionResponse<com.microsoft.graph.models.DriveItem> */
71+
final String genericResponseName = responseClass.getGenericSuperclass().toString();
72+
final int indexOfGenericMarker = genericResponseName.indexOf('<');
73+
/** eg: com.microsoft.graph.models.Attachment */
74+
final String baseEntityClassCanonicalName = genericResponseName
75+
.substring(indexOfGenericMarker + 1, genericResponseName.length() - 1);
76+
Class<?> baseEntityClass;
77+
try {
78+
baseEntityClass = Class.forName(baseEntityClassCanonicalName);
79+
} catch (ClassNotFoundException ex) {
80+
//it is possible we can't find the parent base class depending on the response class name, see examples
81+
baseEntityClass = null;
82+
logger.logDebug("could not find class" + baseEntityClassCanonicalName);
83+
}
84+
try {
85+
for(JsonElement sourceElement : sourceArray) {
86+
if(sourceElement.isJsonObject()) {
87+
final JsonObject sourceObject = sourceElement.getAsJsonObject();
88+
Class<?> entityClass = serializer.getDerivedClass(sourceObject, baseEntityClass);
89+
if(entityClass == null && baseEntityClass != null)
90+
entityClass = baseEntityClass; // it is possible the odata type is absent or we can't find the derived type (not in SDK yet)
91+
final T1 targetObject = (T1)serializer.deserializeObject(sourceObject, entityClass);
92+
((IJsonBackedObject)targetObject).setRawObject(serializer, sourceObject);
93+
list.add(targetObject);
94+
}
95+
}
96+
final BaseCollectionResponse<T1> response = (BaseCollectionResponse<T1>)responseClass.getConstructor().newInstance();
97+
response.value = list;
98+
response.setRawObject(serializer, jsonAsObject);
99+
return response;
100+
} catch(NoSuchMethodException | InstantiationException | InvocationTargetException ex) {
101+
logger.logError("Could not instanciate type during deserialization", ex);
102+
} catch(IllegalAccessException ex) {
103+
logger.logError("Unable to set field value during deserialization", ex);
104+
}
105+
return null;
106+
}
107+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -360,7 +360,7 @@ public Class<?> getDerivedClass(@Nonnull final JsonObject jsonObject, @Nonnull f
360360
if (jsonObject.get(ODATA_TYPE_KEY) != null) {
361361
/** #microsoft.graph.user or #microsoft.graph.callrecords.callrecord */
362362
final String odataType = jsonObject.get(ODATA_TYPE_KEY).getAsString();
363-
final Integer lastDotIndex = odataType.lastIndexOf(".");
363+
final int lastDotIndex = odataType.lastIndexOf(".");
364364
final String derivedType = (odataType.substring(0, lastDotIndex) +
365365
".models." +
366366
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
@@ -369,7 +369,7 @@ public Class<?> getDerivedClass(@Nonnull final JsonObject jsonObject, @Nonnull f
369369
try {
370370
Class<?> derivedClass = Class.forName(derivedType);
371371
//Check that the derived class inherits from the given parent class
372-
if (parentClass.isAssignableFrom(derivedClass)) {
372+
if (parentClass == null || parentClass.isAssignableFrom(derivedClass)) {
373373
return derivedClass;
374374
}
375375
return null;

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

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import com.google.gson.JsonSerializationContext;
3333
import com.google.gson.JsonSerializer;
3434
import com.microsoft.graph.http.BaseCollectionPage;
35+
import com.microsoft.graph.http.BaseCollectionResponse;
3536
import com.microsoft.graph.logger.ILogger;
3637
import com.microsoft.graph.core.DateOnly;
3738

@@ -230,6 +231,14 @@ public JsonElement serialize(final BaseCollectionPage<?, ?> src,
230231
return CollectionPageSerializer.deserialize(json, typeOfT, logger);
231232
}
232233
};
234+
final JsonDeserializer<BaseCollectionResponse<?>> collectionResponseDeserializer = new JsonDeserializer<BaseCollectionResponse<?>>() {
235+
@Override
236+
public BaseCollectionResponse<?> deserialize(final JsonElement json,
237+
final Type typeOfT,
238+
final JsonDeserializationContext context) throws JsonParseException {
239+
return CollectionResponseSerializer.deserialize(json, typeOfT, logger);
240+
}
241+
};
233242

234243
final JsonDeserializer<TimeOfDay> timeOfDayJsonDeserializer = new JsonDeserializer<TimeOfDay>() {
235244
@Override
@@ -260,6 +269,7 @@ public TimeOfDay deserialize(final JsonElement json,
260269
.registerTypeAdapter(Duration.class, durationJsonDeserializer)
261270
.registerTypeHierarchyAdapter(BaseCollectionPage.class, collectionPageSerializer)
262271
.registerTypeHierarchyAdapter(BaseCollectionPage.class, collectionPageDeserializer)
272+
.registerTypeHierarchyAdapter(BaseCollectionResponse.class, collectionResponseDeserializer)
263273
.registerTypeAdapter(TimeOfDay.class, timeOfDayJsonDeserializer)
264274
.registerTypeAdapterFactory(new FallbackTypeAdapterFactory(logger))
265275
.create();

0 commit comments

Comments
 (0)