Skip to content

Commit 36e4b6b

Browse files
committed
- fixes a bug where collection responses would not respect odata inheritance
1 parent 3cd16f0 commit 36e4b6b

6 files changed

Lines changed: 174 additions & 102 deletions

File tree

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

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,23 +11,22 @@
1111
import com.microsoft.graph.serializer.IJsonBackedObject;
1212
import com.microsoft.graph.serializer.ISerializer;
1313
import com.microsoft.graph.serializer.AdditionalDataManager;
14-
import com.microsoft.graph.http.ICollectionResponse;
1514

1615
/**
1716
* The basic collection response implementation
18-
*
17+
*
1918
* @param <T> the entity or complex type
2019
*/
21-
public abstract class BaseCollectionResponse<T> implements ICollectionResponse<T>, IJsonBackedObject {
22-
20+
public abstract class BaseCollectionResponse<T> implements ICollectionResponse<T> {
21+
2322
/**
2423
* The list of items within this collection page
2524
*/
2625
@SerializedName("value")
2726
@Expose
2827
@Nullable
2928
public java.util.List<T> value;
30-
29+
3130

3231
/**
3332
* The list of items within this collection page
@@ -43,7 +42,7 @@ public java.util.List<T> values() {
4342
@Expose(serialize = false)
4443
@Nullable
4544
public String nextLink;
46-
45+
4746
@Override
4847
@Nullable
4948
public String nextLink() {
@@ -69,7 +68,7 @@ public final AdditionalDataManager additionalDataManager() {
6968
*/
7069
@Nullable
7170
protected ISerializer serializer;
72-
71+
7372
/**
7473
* Gets the raw representation of this class
7574
*
@@ -110,4 +109,4 @@ public void setRawObject(@Nonnull final ISerializer serializer, @Nonnull final J
110109
}
111110
}
112111
}
113-
}
112+
}

‎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<T1>(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.toString(), entityClass);
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: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package com.microsoft.graph.serializer;
2+
3+
import java.lang.reflect.InvocationTargetException;
4+
import java.lang.reflect.Type;
5+
import java.util.ArrayList;
6+
7+
import javax.annotation.Nonnull;
8+
import javax.annotation.Nullable;
9+
10+
import com.google.gson.JsonArray;
11+
import com.google.gson.JsonElement;
12+
import com.google.gson.JsonObject;
13+
import com.google.gson.JsonParseException;
14+
import com.microsoft.graph.http.BaseCollectionResponse;
15+
import com.microsoft.graph.logger.ILogger;
16+
17+
/** Specialized serializer to handle collection responses */
18+
public class CollectionResponseSerializer {
19+
private static DefaultSerializer serializer;
20+
/**
21+
* Not available for instantiation
22+
*/
23+
private CollectionResponseSerializer() {}
24+
/**
25+
* Deserializes the JsonElement
26+
*
27+
* @param json the source CollectionResponse's Json
28+
* @param typeOfT The type of the CollectionResponse to deserialize to
29+
* @param logger the logger
30+
* @param <T1> the entity type for the collection
31+
* @throws JsonParseException the parse exception
32+
* @return the deserialized CollectionResponse
33+
*/
34+
@SuppressWarnings("unchecked")
35+
@Nullable
36+
public static <T1> BaseCollectionResponse<T1> deserialize(@Nonnull final JsonElement json, @Nonnull final Type typeOfT, @Nonnull final ILogger logger) throws JsonParseException {
37+
if (json == null || !json.isJsonObject()| !typeOfT.getClass().equals(Class.class)) {
38+
return null;
39+
}
40+
serializer = new DefaultSerializer(logger);
41+
final JsonObject jsonAsObject = json.getAsJsonObject();
42+
final JsonArray sourceArray = jsonAsObject.get("value").getAsJsonArray();
43+
final ArrayList<T1> list = new ArrayList<T1>(sourceArray.size());
44+
/** eg: com.microsoft.graph.requests.AttachmentCollectionResponse */
45+
/** eg: com.microsoft.graph.requests.DriveItemDeltaCollectionResponse */
46+
/** eg: com.microsoft.graph.requests.DriveItemGetActivitiesByIntervalCollectionResponse */
47+
final Class<?> responseClass = ((Class<?>)typeOfT);
48+
/** eg: com.microsoft.graph.http.BaseCollectionResponse<com.microsoft.graph.models.DriveItem> */
49+
final String genericResponseName = responseClass.getGenericSuperclass().toString();
50+
final int indexOfGenericMarker = genericResponseName.indexOf('<');
51+
/** eg: com.microsoft.graph.models.Attachment */
52+
final String baseEntityClassCanonicalName = genericResponseName
53+
.substring(indexOfGenericMarker + 1, genericResponseName.length() - 1);
54+
Class<?> baseEntityClass;
55+
try {
56+
baseEntityClass = Class.forName(baseEntityClassCanonicalName);
57+
} catch (ClassNotFoundException ex) {
58+
//it is possible we can't find the parent base class depending on the response class name, see examples
59+
baseEntityClass = null;
60+
logger.logDebug("could not find class" + baseEntityClassCanonicalName);
61+
}
62+
try {
63+
for(JsonElement sourceElement : sourceArray) {
64+
if(sourceElement.isJsonObject()) {
65+
final JsonObject sourceObject = sourceElement.getAsJsonObject();
66+
Class<?> entityClass = serializer.getDerivedClass(sourceObject, baseEntityClass);
67+
if(entityClass == null && baseEntityClass != null)
68+
entityClass = baseEntityClass; // it is possible the odata type is absent or we can't find the derived type (not in SDK yet)
69+
final T1 targetObject = (T1)serializer.deserializeObject(sourceObject.toString(), entityClass);
70+
((IJsonBackedObject)targetObject).setRawObject(serializer, sourceObject);
71+
list.add(targetObject);
72+
}
73+
}
74+
final BaseCollectionResponse<T1> response = (BaseCollectionResponse<T1>)responseClass.getConstructor().newInstance();
75+
response.value = list;
76+
response.setRawObject(serializer, jsonAsObject);
77+
return response;
78+
} catch(NoSuchMethodException | InstantiationException | InvocationTargetException ex) {
79+
logger.logError("Could not instanciate type during deserialization", ex);
80+
} catch(IllegalAccessException ex) {
81+
logger.logError("Unable to set field value during deserialization", ex);
82+
}
83+
return null;
84+
}
85+
}

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -347,7 +347,7 @@ public Class<?> getDerivedClass(@Nonnull final JsonObject jsonObject, @Nonnull f
347347
if (jsonObject.get(ODATA_TYPE_KEY) != null) {
348348
/** #microsoft.graph.user or #microsoft.graph.callrecords.callrecord */
349349
final String odataType = jsonObject.get(ODATA_TYPE_KEY).getAsString();
350-
final Integer lastDotIndex = odataType.lastIndexOf(".");
350+
final int lastDotIndex = odataType.lastIndexOf(".");
351351
final String derivedType = (odataType.substring(0, lastDotIndex) +
352352
".models." +
353353
CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL,
@@ -356,7 +356,7 @@ public Class<?> getDerivedClass(@Nonnull final JsonObject jsonObject, @Nonnull f
356356
try {
357357
Class<?> derivedClass = Class.forName(derivedType);
358358
//Check that the derived class inherits from the given parent class
359-
if (parentClass.isAssignableFrom(derivedClass)) {
359+
if (parentClass == null || parentClass.isAssignableFrom(derivedClass)) {
360360
return derivedClass;
361361
}
362362
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)