diff --git a/src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java b/src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java index 56e28a443..555dc34b2 100644 --- a/src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java +++ b/src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java @@ -1,16 +1,16 @@ package com.microsoft.graph.authentication; +import com.azure.core.credential.AccessToken; import com.azure.core.credential.TokenCredential; import com.azure.core.credential.TokenRequestContext; +import javax.annotation.Nonnull; import java.net.URL; -import java.util.Arrays; +import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.CompletableFuture; -import javax.annotation.Nonnull; - /** * An implementation of the Authentication Provider with Azure-identity */ @@ -27,7 +27,7 @@ public class TokenCredentialAuthProvider extends BaseAuthenticationProvider { * @param tokenCredential Credential object inheriting the TokenCredential interface used to instantiate the Auth Provider */ public TokenCredentialAuthProvider(@Nonnull final TokenCredential tokenCredential) { - this(Arrays.asList(DEFAULT_GRAPH_SCOPE), tokenCredential); + this(Collections.singletonList(DEFAULT_GRAPH_SCOPE), tokenCredential); } /** @@ -56,7 +56,7 @@ public CompletableFuture getAuthorizationTokenAsync(@Nonnull final URL r return this.tokenCredential .getToken(this.context) .toFuture() - .thenApply(resp -> resp.getToken()); + .thenApply(AccessToken::getToken); else return CompletableFuture.completedFuture((String)null); } diff --git a/src/main/java/com/microsoft/graph/content/BatchRequestContent.java b/src/main/java/com/microsoft/graph/content/BatchRequestContent.java index 935f24c1c..0f0dca716 100644 --- a/src/main/java/com/microsoft/graph/content/BatchRequestContent.java +++ b/src/main/java/com/microsoft/graph/content/BatchRequestContent.java @@ -110,7 +110,7 @@ public String addBatchRequestStep(@Nonnull final IHttpRequest request, @Nonn url = protocolAndHostReplacementMatcher.replaceAll(""); body = serializableBody; method = httpMethod.toString().toUpperCase(Locale.getDefault()); - dependsOn = dependsOnRequestsIds != null && dependsOnRequestsIds.length > 0 ? new HashSet(Arrays.asList(dependsOnRequestsIds)) : null; + dependsOn = dependsOnRequestsIds != null && dependsOnRequestsIds.length > 0 ? new HashSet<>(Arrays.asList(dependsOnRequestsIds)) : null; id = getNextRequestId(); }}; @@ -141,7 +141,7 @@ public void removeBatchRequestStepWithId(@Nonnull final String ...stepIds) { requests.removeIf(x -> stepId.equals(x.id)); for(final BatchRequestStep step : requests) { if(step.dependsOn != null) { - step.dependsOn.removeIf(x -> stepId.equals(x)); + step.dependsOn.removeIf(stepId::equals); if(step.dependsOn.isEmpty()) step.dependsOn = null; // so we don't send dependsOn: [] over the wire } diff --git a/src/main/java/com/microsoft/graph/core/CustomRequestBuilder.java b/src/main/java/com/microsoft/graph/core/CustomRequestBuilder.java index 5915eb32b..468dcdde8 100644 --- a/src/main/java/com/microsoft/graph/core/CustomRequestBuilder.java +++ b/src/main/java/com/microsoft/graph/core/CustomRequestBuilder.java @@ -51,6 +51,6 @@ public CustomRequest buildRequest(@Nullable final com.microsoft.graph.options */ @Nonnull public CustomRequest buildRequest(@Nullable final List requestOptions) { - return new CustomRequest(getRequestUrl(), getClient(), requestOptions, responseType); + return new CustomRequest<>(getRequestUrl(), getClient(), requestOptions, responseType); } } diff --git a/src/main/java/com/microsoft/graph/core/IBaseClient.java b/src/main/java/com/microsoft/graph/core/IBaseClient.java index c260831a8..b3b0e7d32 100644 --- a/src/main/java/com/microsoft/graph/core/IBaseClient.java +++ b/src/main/java/com/microsoft/graph/core/IBaseClient.java @@ -100,7 +100,7 @@ public interface IBaseClient { * @return a request builder to execute a batch. */ @Nonnull - public BatchRequestBuilder batch(); + BatchRequestBuilder batch(); /** * Gets the service SDK version if the service SDK is in use, null otherwise diff --git a/src/main/java/com/microsoft/graph/core/Multipart.java b/src/main/java/com/microsoft/graph/core/Multipart.java index 0600cac80..878f3e84c 100644 --- a/src/main/java/com/microsoft/graph/core/Multipart.java +++ b/src/main/java/com/microsoft/graph/core/Multipart.java @@ -35,7 +35,7 @@ public class Multipart { */ public Multipart() { out = new ByteArrayOutputStream(); - boundary = "part_" + new BigInteger(130, new SecureRandom()).toString(); + boundary = "part_" + new BigInteger(130, new SecureRandom()); } /** @@ -125,7 +125,7 @@ public static String createContentHeaderValue(@Nonnull final String contentValue if(contentDispParameter != null) { for(Map.Entry entry : contentDispParameter.entrySet()) - builder.append(";" + entry.getKey() + "=\"" + entry.getValue() + "\""); + builder.append(";").append(entry.getKey()).append("=\"").append(entry.getValue()).append("\""); } return builder.toString(); } @@ -140,7 +140,7 @@ private String createPartHeader(Map headers) { if(headers != null) { for(Map.Entry entry : headers.entrySet()) - builder.append(entry.getKey() +": "+entry.getValue() + RETURN); + builder.append(entry.getKey()).append(": ").append(entry.getValue()).append(RETURN); builder.append(RETURN); } else builder.append(defaultPartContent); diff --git a/src/main/java/com/microsoft/graph/http/BaseActionCollectionRequest.java b/src/main/java/com/microsoft/graph/http/BaseActionCollectionRequest.java index a9c38b4ec..caff0a918 100644 --- a/src/main/java/com/microsoft/graph/http/BaseActionCollectionRequest.java +++ b/src/main/java/com/microsoft/graph/http/BaseActionCollectionRequest.java @@ -81,7 +81,7 @@ public java.util.concurrent.CompletableFuture postAsync() { .sendAsync(this, responseCollectionClass, bodyToSend) - .thenApply(r -> buildFromResponse(r)); + .thenApply(this::buildFromResponse); } /** * Invokes the method and returns the resulting collection of objects diff --git a/src/main/java/com/microsoft/graph/http/BaseCollectionPage.java b/src/main/java/com/microsoft/graph/http/BaseCollectionPage.java index fce85908a..b7fe35590 100644 --- a/src/main/java/com/microsoft/graph/http/BaseCollectionPage.java +++ b/src/main/java/com/microsoft/graph/http/BaseCollectionPage.java @@ -72,7 +72,7 @@ public BaseCollectionPage(@Nonnull final ICollectionResponse response, @Nulla public BaseCollectionPage(@Nonnull final List pageContents, @Nullable final T2 nextRequestBuilder) { // CollectionPages are never directly modifiable, either 'update'/'delete' the specific child or 'add' the new // object to the 'children' of the collection. - this.pageContents = Collections.unmodifiableList(pageContents == null ? new ArrayList() : pageContents); + this.pageContents = Collections.unmodifiableList(pageContents == null ? new ArrayList<>() : pageContents); requestBuilder = nextRequestBuilder; } diff --git a/src/main/java/com/microsoft/graph/http/BaseEntityCollectionRequest.java b/src/main/java/com/microsoft/graph/http/BaseEntityCollectionRequest.java index dd725b40b..aefb79604 100644 --- a/src/main/java/com/microsoft/graph/http/BaseEntityCollectionRequest.java +++ b/src/main/java/com/microsoft/graph/http/BaseEntityCollectionRequest.java @@ -66,7 +66,7 @@ public BaseEntityCollectionRequest(@Nonnull final String requestUrl, */ @Nonnull public java.util.concurrent.CompletableFuture getAsync() { - return sendAsync().thenApply(r -> buildFromResponse(r)); + return sendAsync().thenApply(this::buildFromResponse); } /** * Gets the collection of items diff --git a/src/main/java/com/microsoft/graph/http/BaseFunctionCollectionRequest.java b/src/main/java/com/microsoft/graph/http/BaseFunctionCollectionRequest.java index 19ca7a08f..8e524316a 100644 --- a/src/main/java/com/microsoft/graph/http/BaseFunctionCollectionRequest.java +++ b/src/main/java/com/microsoft/graph/http/BaseFunctionCollectionRequest.java @@ -66,7 +66,7 @@ public BaseFunctionCollectionRequest(@Nonnull final String requestUrl, */ @Nonnull public java.util.concurrent.CompletableFuture getAsync() { - return sendAsync().thenApply(r -> buildFromResponse(r)); + return sendAsync().thenApply(this::buildFromResponse); } /** diff --git a/src/main/java/com/microsoft/graph/http/BaseRequest.java b/src/main/java/com/microsoft/graph/http/BaseRequest.java index 8bc323005..5e0c537b5 100644 --- a/src/main/java/com/microsoft/graph/http/BaseRequest.java +++ b/src/main/java/com/microsoft/graph/http/BaseRequest.java @@ -193,9 +193,9 @@ public URL getRequestUrl() { return new URL(uriBuilder.build().toString()); } catch (final MalformedURLException e) { if (this instanceof CustomRequest) { - this.getClient().getLogger().logError("Invalid custom URL: " + uriBuilder.toString(), e); + this.getClient().getLogger().logError("Invalid custom URL: " + uriBuilder, e); } else { - throw new ClientException("Invalid URL: " + uriBuilder.toString(), e); + throw new ClientException("Invalid URL: " + uriBuilder, e); } } return null; @@ -228,7 +228,7 @@ private String addFunctionParameters() { requestUrl.append("="); if (option.getValue() != null) { if (option.getValue() instanceof String) { - requestUrl.append("'" + option.getValue() + "'"); + requestUrl.append("'").append(option.getValue()).append("'"); } else { requestUrl.append(option.getValue()); } diff --git a/src/main/java/com/microsoft/graph/http/CustomRequest.java b/src/main/java/com/microsoft/graph/http/CustomRequest.java index 5d2b2f7c5..73f7c1f5a 100644 --- a/src/main/java/com/microsoft/graph/http/CustomRequest.java +++ b/src/main/java/com/microsoft/graph/http/CustomRequest.java @@ -64,7 +64,7 @@ public CustomRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClien */ @Nonnull public static CustomRequest create(@Nonnull final String requestUrl, @Nonnull final IBaseClient client, @Nullable final java.util.List requestOptions) { - return new CustomRequest(requestUrl, client, requestOptions, JsonObject.class); + return new CustomRequest<>(requestUrl, client, requestOptions, JsonObject.class); } /** diff --git a/src/main/java/com/microsoft/graph/http/GraphInnerError.java b/src/main/java/com/microsoft/graph/http/GraphInnerError.java index 9516c1845..b46b1b7f6 100644 --- a/src/main/java/com/microsoft/graph/http/GraphInnerError.java +++ b/src/main/java/com/microsoft/graph/http/GraphInnerError.java @@ -1,16 +1,16 @@ // ------------------------------------------------------------------------------ // Copyright (c) 2017 Microsoft Corporation -// +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sub-license, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -25,7 +25,6 @@ import com.google.gson.annotations.SerializedName; import javax.annotation.Nullable; -import javax.annotation.Nonnull; /** * Represents an inner error returned by the service diff --git a/src/main/java/com/microsoft/graph/httpcore/AuthenticationHandler.java b/src/main/java/com/microsoft/graph/httpcore/AuthenticationHandler.java index daf8fc44c..ce125664b 100644 --- a/src/main/java/com/microsoft/graph/httpcore/AuthenticationHandler.java +++ b/src/main/java/com/microsoft/graph/httpcore/AuthenticationHandler.java @@ -62,6 +62,8 @@ public Response intercept(@Nonnull final Chain chain) throws IOException { .build()); } } catch (InterruptedException | ExecutionException ex) { + if (ex instanceof InterruptedException) + Thread.currentThread().interrupt(); throw new IOException(ex); } } diff --git a/src/main/java/com/microsoft/graph/httpcore/ChaosHttpHandler.java b/src/main/java/com/microsoft/graph/httpcore/ChaosHttpHandler.java index e4eec8304..b1df1b4ee 100644 --- a/src/main/java/com/microsoft/graph/httpcore/ChaosHttpHandler.java +++ b/src/main/java/com/microsoft/graph/httpcore/ChaosHttpHandler.java @@ -3,7 +3,6 @@ import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; -import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.httpcore.middlewareoption.MiddlewareType; diff --git a/src/main/java/com/microsoft/graph/httpcore/HttpClients.java b/src/main/java/com/microsoft/graph/httpcore/HttpClients.java index 34ad32aec..e53586c57 100644 --- a/src/main/java/com/microsoft/graph/httpcore/HttpClients.java +++ b/src/main/java/com/microsoft/graph/httpcore/HttpClients.java @@ -1,17 +1,15 @@ package com.microsoft.graph.httpcore; import com.microsoft.graph.authentication.IAuthenticationProvider; - -import java.util.Arrays; -import java.util.Objects; - -import javax.annotation.Nullable; -import javax.annotation.Nonnull; - import okhttp3.Interceptor; import okhttp3.OkHttpClient; -import okhttp3.Protocol; import okhttp3.OkHttpClient.Builder; +import okhttp3.Protocol; + +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import java.util.Collections; +import java.util.Objects; /** * Builder to get a custom HttpClient to be used for requests against Microsoft Graph @@ -33,7 +31,7 @@ public static Builder custom() { .addInterceptor(new TelemetryHandler()) .followRedirects(false) .followSslRedirects(false) - .protocols(Arrays.asList(Protocol.HTTP_1_1)); //https://stackoverflow.com/questions/62031298/sockettimeout-on-java-11-but-not-on-java-8 + .protocols(Collections.singletonList(Protocol.HTTP_1_1)); //https://stackoverflow.com/questions/62031298/sockettimeout-on-java-11-but-not-on-java-8 } /** diff --git a/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java b/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java index da032a5d4..ed799a7f0 100644 --- a/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java +++ b/src/main/java/com/microsoft/graph/httpcore/RetryHandler.java @@ -111,6 +111,7 @@ && checkStatus(statusCode) && isBuffered(request) try { Thread.sleep(retryInterval); } catch (InterruptedException e) { + Thread.currentThread().interrupt(); logger.logError("error retrying the request", e); } } diff --git a/src/main/java/com/microsoft/graph/httpcore/TelemetryHandler.java b/src/main/java/com/microsoft/graph/httpcore/TelemetryHandler.java index 44632a60c..0c0b924b6 100644 --- a/src/main/java/com/microsoft/graph/httpcore/TelemetryHandler.java +++ b/src/main/java/com/microsoft/graph/httpcore/TelemetryHandler.java @@ -2,6 +2,7 @@ import java.io.IOException; import java.lang.reflect.Field; +import java.util.Objects; import javax.annotation.Nonnull; @@ -57,8 +58,8 @@ public Response intercept(@Nonnull final Chain chain) throws IOException { final String javaVersion = System.getProperty("java.version"); final String androidVersion = getAndroidAPILevel(); final String sdkversion_value = GRAPH_VERSION_PREFIX + "/" + VERSION + " " + featureUsage + - (javaVersion == DEFAULT_VERSION_VALUE ? "" : (", " + JAVA_VERSION_PREFIX + "/" + javaVersion)) + - (androidVersion == DEFAULT_VERSION_VALUE ? "" : (", " + ANDROID_VERSION_PREFIX + "/" + androidVersion)); + (DEFAULT_VERSION_VALUE.equals(javaVersion) ? "" : (", " + JAVA_VERSION_PREFIX + "/" + javaVersion)) + + (DEFAULT_VERSION_VALUE.equals(androidVersion) ? "" : (", " + ANDROID_VERSION_PREFIX + "/" + androidVersion)); telemetryAddedBuilder.addHeader(SDK_VERSION, sdkversion_value); if(request.header(CLIENT_REQUEST_ID) == null) { diff --git a/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RedirectOptions.java b/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RedirectOptions.java index 72c944db1..3016c0a83 100644 --- a/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RedirectOptions.java +++ b/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RedirectOptions.java @@ -23,12 +23,7 @@ public class RedirectOptions implements IMiddlewareControl{ /** * Default redirect evaluation, always follow redirect information. */ - public static final IShouldRedirect DEFAULT_SHOULD_REDIRECT = new IShouldRedirect() { - @Override - public boolean shouldRedirect(Response response) { - return true; - } - }; + public static final IShouldRedirect DEFAULT_SHOULD_REDIRECT = response -> true; /** * Create default instance of redirect options, with default values of max redirects and should redirect diff --git a/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RetryOptions.java b/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RetryOptions.java index ba9418ad8..425a71e13 100644 --- a/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RetryOptions.java +++ b/src/main/java/com/microsoft/graph/httpcore/middlewareoption/RetryOptions.java @@ -14,12 +14,7 @@ public class RetryOptions implements IMiddlewareControl { /** * Default retry evaluation, always retry. */ - public static final IShouldRetry DEFAULT_SHOULD_RETRY = new IShouldRetry() { - @Override - public boolean shouldRetry(long delay, int executionCount, Request request, Response response) { - return true; - } - }; + public static final IShouldRetry DEFAULT_SHOULD_RETRY = (delay, executionCount, request, response) -> true; private int mMaxRetries; /** diff --git a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java index 99c31906e..931a5b5e6 100644 --- a/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/DefaultSerializer.java @@ -32,6 +32,7 @@ import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Field; +import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Iterator; import java.util.List; @@ -98,7 +99,7 @@ public T deserializeObject(@Nonnull final String inputString, @Nonnull final public T deserializeObject(@Nonnull final InputStream inputStream, @Nonnull final Class clazz, @Nullable final Map> responseHeaders) { Objects.requireNonNull(inputStream, "parameter inputStream cannot be null"); T result = null; - try (final InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8")) { + try (final InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { final JsonElement rawElement = gson.fromJson(streamReader, JsonElement.class); result = deserializeObject(rawElement, clazz, responseHeaders); } catch (IOException ex) { @@ -155,24 +156,22 @@ private void setChildAdditionalData(final IJsonBackedObject serializedObject, fi // If the object is a HashMap, iterate through its children @SuppressWarnings("unchecked") final HashMap serializableChildren = (HashMap) fieldObject; - final Iterator> it = serializableChildren.entrySet().iterator(); - while (it.hasNext()) { - final Map.Entry pair = (Map.Entry)it.next(); - final Object child = pair.getValue(); + for (Entry pair : serializableChildren.entrySet()) { + final Object child = pair.getValue(); - // If the item is a valid Graph object, set its additional data - if (child instanceof IJsonBackedObject) { - final AdditionalDataManager childAdditionalDataManager = ((IJsonBackedObject) child).additionalDataManager(); - final JsonElement fieldElement = rawJson.get(field.getName()); - if(fieldElement != null && fieldElement.isJsonObject() - && fieldElement.getAsJsonObject().get(pair.getKey()) != null - && fieldElement.getAsJsonObject().get(pair.getKey()).isJsonObject()) { - childAdditionalDataManager.setAdditionalData(fieldElement.getAsJsonObject().get(pair.getKey()).getAsJsonObject()); - setChildAdditionalData((IJsonBackedObject) child,fieldElement.getAsJsonObject().get(pair.getKey()).getAsJsonObject()); - } - } - } + // If the item is a valid Graph object, set its additional data + if (child instanceof IJsonBackedObject) { + final AdditionalDataManager childAdditionalDataManager = ((IJsonBackedObject) child).additionalDataManager(); + final JsonElement fieldElement = rawJson.get(field.getName()); + if (fieldElement != null && fieldElement.isJsonObject() + && fieldElement.getAsJsonObject().get(pair.getKey()) != null + && fieldElement.getAsJsonObject().get(pair.getKey()).isJsonObject()) { + childAdditionalDataManager.setAdditionalData(fieldElement.getAsJsonObject().get(pair.getKey()).getAsJsonObject()); + setChildAdditionalData((IJsonBackedObject) child, fieldElement.getAsJsonObject().get(pair.getKey()).getAsJsonObject()); + } + } + } } // If the object is a list of Graph objects, iterate through elements else if (fieldObject instanceof List) { diff --git a/src/main/java/com/microsoft/graph/serializer/DerivedClassIdentifier.java b/src/main/java/com/microsoft/graph/serializer/DerivedClassIdentifier.java index e01346a02..563b396c4 100644 --- a/src/main/java/com/microsoft/graph/serializer/DerivedClassIdentifier.java +++ b/src/main/java/com/microsoft/graph/serializer/DerivedClassIdentifier.java @@ -1,9 +1,11 @@ package com.microsoft.graph.serializer; +import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CaseFormat; import com.google.gson.JsonObject; import com.microsoft.graph.logger.ILogger; +import java.util.Locale; import java.util.Objects; import javax.annotation.Nonnull; import javax.annotation.Nullable; @@ -14,12 +16,13 @@ public class DerivedClassIdentifier { private final static String ODATA_TYPE_KEY = "@odata.type"; private final ILogger logger; + /** * Creates a new instance of the dereived class identifier. * @param logger The logger to use. */ public DerivedClassIdentifier(@Nonnull ILogger logger) { - this.logger = Objects.requireNonNull(logger, "logger parameter cannot be null");; + this.logger = Objects.requireNonNull(logger, "logger parameter cannot be null"); } /** @@ -36,14 +39,9 @@ public Class identify(@Nonnull final JsonObject jsonObject, @Nullable final C Objects.requireNonNull(jsonObject, "parameter jsonObject cannot be null"); //Identify the odata.type information if provided if (jsonObject.get(ODATA_TYPE_KEY) != null) { - /** #microsoft.graph.user or #microsoft.graph.callrecords.callrecord */ + // #microsoft.graph.user or #microsoft.graph.callrecords.callrecord final String odataType = jsonObject.get(ODATA_TYPE_KEY).getAsString(); - final int lastDotIndex = odataType.lastIndexOf("."); - final String derivedType = (odataType.substring(0, lastDotIndex) + - ".models." + - CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, - odataType.substring(lastDotIndex + 1))) - .replace("#", "com."); + final String derivedType = oDataTypeToClassName(odataType); try { Class derivedClass = Class.forName(derivedType); //Check that the derived class inherits from the given parent class @@ -61,4 +59,20 @@ public Class identify(@Nonnull final JsonObject jsonObject, @Nullable final C //If there is no defined OData type, return null return null; } + + /** + * Convert {@code @odata.type} to proper java class name + * + * @param odataType to convert + * @return converted class name + */ + @VisibleForTesting + static String oDataTypeToClassName(@Nonnull String odataType) { + Objects.requireNonNull(odataType); + final int lastDotIndex = odataType.lastIndexOf("."); + return (odataType.substring(0, lastDotIndex).toLowerCase(Locale.ROOT) + + ".models." + + CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_CAMEL, odataType.substring(lastDotIndex + 1))) + .replace("#", "com."); + } } diff --git a/src/main/java/com/microsoft/graph/serializer/EdmNativeTypeSerializer.java b/src/main/java/com/microsoft/graph/serializer/EdmNativeTypeSerializer.java index 5871ac4e4..1a7fd1a2f 100644 --- a/src/main/java/com/microsoft/graph/serializer/EdmNativeTypeSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/EdmNativeTypeSerializer.java @@ -1,11 +1,9 @@ package com.microsoft.graph.serializer; -import java.lang.reflect.Type; import java.math.BigDecimal; import java.util.UUID; import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; import com.microsoft.graph.logger.ILogger; import javax.annotation.Nonnull; diff --git a/src/main/java/com/microsoft/graph/serializer/GsonFactory.java b/src/main/java/com/microsoft/graph/serializer/GsonFactory.java index 4b305e5ae..e507ece0c 100644 --- a/src/main/java/com/microsoft/graph/serializer/GsonFactory.java +++ b/src/main/java/com/microsoft/graph/serializer/GsonFactory.java @@ -90,263 +90,129 @@ public static Gson getGsonInstance(@Nonnull final ILogger logger) { @Nonnull public static Gson getGsonInstance(@Nonnull final ILogger logger, final boolean serializeNulls) { Objects.requireNonNull(logger, "parameter logger cannot be null"); - final JsonSerializer calendarJsonSerializer = new JsonSerializer() { - @Override - public JsonElement serialize(final OffsetDateTime src, - final Type typeOfSrc, - final JsonSerializationContext context) { - if (src == null) { - return null; - } - try { - return new JsonPrimitive(OffsetDateTimeSerializer.serialize(src)); - } catch (final Exception e) { - logger.logError(PARSING_MESSAGE + src, e); - return null; - } + final JsonSerializer calendarJsonSerializer = (src, typeOfSrc, context) -> { + if (src == null) { + return null; } - }; - - final JsonDeserializer calendarJsonDeserializer = new JsonDeserializer() { - @Override - public OffsetDateTime deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - if (json == null) { - return null; - } - try { - return OffsetDateTimeSerializer.deserialize(json.getAsString()); - } catch (final ParseException e) { - logger.logError(PARSING_MESSAGE + json.getAsString(), e); - return null; - } + try { + return new JsonPrimitive(OffsetDateTimeSerializer.serialize(src)); + } catch (final Exception e) { + logger.logError(PARSING_MESSAGE + src, e); + return null; } }; - final JsonSerializer byteArrayJsonSerializer = new JsonSerializer() { - @Override - public JsonElement serialize(final byte[] src, - final Type typeOfSrc, - final JsonSerializationContext context) { - if (src == null) { - return null; - } - try { - return new JsonPrimitive(ByteArraySerializer.serialize(src)); - } catch (final Exception e) { - logger.logError(PARSING_MESSAGE + Arrays.toString(src), e); - return null; - } + final JsonDeserializer calendarJsonDeserializer = (json, typeOfT, context) -> { + if (json == null) { + return null; } - }; - - final JsonDeserializer byteArrayJsonDeserializer = new JsonDeserializer() { - @Override - public byte[] deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - if (json == null) { - return null; - } - try { - return ByteArraySerializer.deserialize(json.getAsString()); - } catch (final ParseException e) { - logger.logError(PARSING_MESSAGE + json.getAsString(), e); - return null; - } + try { + return OffsetDateTimeSerializer.deserialize(json.getAsString()); + } catch (final ParseException e) { + logger.logError(PARSING_MESSAGE + json.getAsString(), e); + return null; } }; - final JsonSerializer dateJsonSerializer = new JsonSerializer() { - @Override - public JsonElement serialize(final DateOnly src, - final Type typeOfSrc, - final JsonSerializationContext context) { - if (src == null) { - return null; - } - return new JsonPrimitive(src.toString()); + final JsonSerializer byteArrayJsonSerializer = (src, typeOfSrc, context) -> { + if (src == null) { + return null; } - }; - - final JsonDeserializer dateJsonDeserializer = new JsonDeserializer() { - @Override - public DateOnly deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - if (json == null) { - return null; - } - - try { - return DateOnly.parse(json.getAsString()); - } catch (final ParseException e) { - logger.logError(PARSING_MESSAGE + json.getAsString(), e); - return null; - } + try { + return new JsonPrimitive(ByteArraySerializer.serialize(src)); + } catch (final Exception e) { + logger.logError(PARSING_MESSAGE + Arrays.toString(src), e); + return null; } }; - final EnumSetSerializer eSetSerializer = new EnumSetSerializer(logger); - final JsonSerializer> enumSetJsonSerializer = new JsonSerializer>() { - @Override - public JsonElement serialize(final EnumSet src, - final Type typeOfSrc, - final JsonSerializationContext context) { - if (src == null || src.isEmpty()) { - return null; - } - - return eSetSerializer.serialize(src); + final JsonDeserializer byteArrayJsonDeserializer = (json, typeOfT, context) -> { + if (json == null) { + return null; } - }; - - final JsonDeserializer> enumSetJsonDeserializer = new JsonDeserializer>() { - @Override - public EnumSet deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - if (json == null) { - return null; - } - - return eSetSerializer.deserialize(typeOfT, json.getAsString()); + try { + return ByteArraySerializer.deserialize(json.getAsString()); + } catch (final ParseException e) { + logger.logError(PARSING_MESSAGE + json.getAsString(), e); + return null; } }; - final JsonSerializer durationJsonSerializer = new JsonSerializer() { - @Override - public JsonElement serialize(final Duration src, - final Type typeOfSrc, - final JsonSerializationContext context) { - return new JsonPrimitive(src.toString()); + final JsonSerializer dateJsonSerializer = (src, typeOfSrc, context) -> { + if (src == null) { + return null; } + return new JsonPrimitive(src.toString()); }; - final JsonDeserializer durationJsonDeserializer = new JsonDeserializer() { - @Override - public Duration deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - try { - return DatatypeFactory.newInstance().newDuration(json.getAsString()); - } catch (Exception e) { - return null; - } + final JsonDeserializer dateJsonDeserializer = (json, typeOfT, context) -> { + if (json == null) { + return null; } - }; - final JsonSerializer> collectionPageSerializer = new JsonSerializer>() { - @Override - public JsonElement serialize(final BaseCollectionPage src, - final Type typeOfSrc, - final JsonSerializationContext context) { - return CollectionPageSerializer.serialize(src, logger); + try { + return DateOnly.parse(json.getAsString()); + } catch (final ParseException e) { + logger.logError(PARSING_MESSAGE + json.getAsString(), e); + return null; } }; + final EnumSetSerializer eSetSerializer = new EnumSetSerializer(logger); - final JsonDeserializer> collectionPageDeserializer = new JsonDeserializer>() { - @Override - public BaseCollectionPage deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return CollectionPageSerializer.deserialize(json, typeOfT, logger); + final JsonSerializer> enumSetJsonSerializer = (src, typeOfSrc, context) -> { + if (src == null || src.isEmpty()) { + return null; } - }; - final JsonDeserializer> collectionResponseDeserializer = new JsonDeserializer>() { - @Override - public BaseCollectionResponse deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return CollectionResponseDeserializer.deserialize(json, typeOfT, logger); - } - }; - final JsonDeserializer timeOfDayJsonDeserializer = new JsonDeserializer() { - @Override - public TimeOfDay deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - try { - return TimeOfDay.parse(json.getAsString()); - } catch (Exception e) { - return null; - } - } + return eSetSerializer.serialize(src); }; - final JsonSerializer timeOfDayJsonSerializer = new JsonSerializer() { - @Override - public JsonElement serialize(final TimeOfDay src, - final Type typeOfSrc, - final JsonSerializationContext context) { - return new JsonPrimitive(src.toString()); + final JsonDeserializer> enumSetJsonDeserializer = (json, typeOfT, context) -> { + if (json == null) { + return null; } - }; - final JsonDeserializer booleanJsonDeserializer = new JsonDeserializer() { - @Override - public Boolean deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, Boolean.class, logger); - } + return eSetSerializer.deserialize(typeOfT, json.getAsString()); }; - final JsonDeserializer stringJsonDeserializer = new JsonDeserializer() { - @Override - public String deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, String.class, logger); - } - }; + final JsonSerializer durationJsonSerializer = (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()); - final JsonDeserializer bigDecimalJsonDeserializer = new JsonDeserializer() { - @Override - public BigDecimal deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, BigDecimal.class, logger); + final JsonDeserializer durationJsonDeserializer = (json, typeOfT, context) -> { + try { + return DatatypeFactory.newInstance().newDuration(json.getAsString()); + } catch (Exception e) { + return null; } }; - final JsonDeserializer integerJsonDeserializer = new JsonDeserializer() { - @Override - public Integer deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, Integer.class, logger); - } - }; + final JsonSerializer> collectionPageSerializer = (src, typeOfSrc, context) -> CollectionPageSerializer.serialize(src, logger); - final JsonDeserializer longJsonDeserializer = new JsonDeserializer() { - @Override - public Long deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, Long.class, logger); - } - }; + final JsonDeserializer> collectionPageDeserializer = (json, typeOfT, context) -> CollectionPageSerializer.deserialize(json, typeOfT, logger); + final JsonDeserializer> collectionResponseDeserializer = (json, typeOfT, context) -> CollectionResponseDeserializer.deserialize(json, typeOfT, logger); - final JsonDeserializer uuidJsonDeserializer = new JsonDeserializer() { - @Override - public UUID deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, UUID.class, logger); + final JsonDeserializer timeOfDayJsonDeserializer = (json, typeOfT, context) -> { + try { + return TimeOfDay.parse(json.getAsString()); + } catch (Exception e) { + return null; } }; - final JsonDeserializer floatJsonDeserializer = new JsonDeserializer() { - @Override - public Float deserialize(final JsonElement json, - final Type typeOfT, - final JsonDeserializationContext context) throws JsonParseException { - return EdmNativeTypeSerializer.deserialize(json, Float.class, logger); - } - }; + final JsonSerializer timeOfDayJsonSerializer = (src, typeOfSrc, context) -> new JsonPrimitive(src.toString()); + + final JsonDeserializer booleanJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, Boolean.class, logger); + + final JsonDeserializer stringJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, String.class, logger); + + final JsonDeserializer bigDecimalJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, BigDecimal.class, logger); + + final JsonDeserializer integerJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, Integer.class, logger); + + final JsonDeserializer longJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, Long.class, logger); + + final JsonDeserializer uuidJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, UUID.class, logger); + + final JsonDeserializer floatJsonDeserializer = (json, typeOfT, context) -> EdmNativeTypeSerializer.deserialize(json, Float.class, logger); GsonBuilder builder = new GsonBuilder(); if (serializeNulls) { diff --git a/src/main/java/com/microsoft/graph/serializer/OffsetDateTimeSerializer.java b/src/main/java/com/microsoft/graph/serializer/OffsetDateTimeSerializer.java index 2e8288176..daf22183d 100644 --- a/src/main/java/com/microsoft/graph/serializer/OffsetDateTimeSerializer.java +++ b/src/main/java/com/microsoft/graph/serializer/OffsetDateTimeSerializer.java @@ -23,17 +23,10 @@ package com.microsoft.graph.serializer; import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; import java.util.Objects; -import java.util.TimeZone; import java.util.regex.Pattern; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; -import java.time.format.DateTimeFormatterBuilder; -import java.time.temporal.ChronoField; -import java.time.temporal.TemporalField; import javax.annotation.Nullable; import javax.annotation.Nonnull; diff --git a/src/main/java/com/microsoft/graph/tasks/LargeFileUploadRequest.java b/src/main/java/com/microsoft/graph/tasks/LargeFileUploadRequest.java index a36f94af6..ba2f67785 100644 --- a/src/main/java/com/microsoft/graph/tasks/LargeFileUploadRequest.java +++ b/src/main/java/com/microsoft/graph/tasks/LargeFileUploadRequest.java @@ -103,7 +103,7 @@ public LargeFileUploadResponse upload( if (result != null && (result.chunkCompleted() || result.uploadCompleted())) { return result; } else - return new LargeFileUploadResponse( + return new LargeFileUploadResponse<>( new ClientException("Upload session failed.", result == null ? null : result.getError())); } } diff --git a/src/main/java/com/microsoft/graph/tasks/LargeFileUploadTask.java b/src/main/java/com/microsoft/graph/tasks/LargeFileUploadTask.java index 897cc6d0f..78da111b2 100644 --- a/src/main/java/com/microsoft/graph/tasks/LargeFileUploadTask.java +++ b/src/main/java/com/microsoft/graph/tasks/LargeFileUploadTask.java @@ -115,7 +115,7 @@ public LargeFileUploadTask(@Nonnull final IUploadSession uploadSession, this.inputStream = Objects.requireNonNull(inputStream, "Input stream is null."); this.streamSize = streamSize; this.uploadUrl = uploadSession.getUploadUrl(); - this.responseHandler = new LargeFileUploadResponseHandler(uploadTypeClass, uploadSession.getClass()); + this.responseHandler = new LargeFileUploadResponseHandler<>(uploadTypeClass, uploadSession.getClass()); } /** @@ -169,7 +169,7 @@ public CompletableFuture> uploadAsync(@Nullabl if(progressCallback != null) { progressCallback.progress(this.streamSize, this.streamSize); } - final LargeFileUploadResult result = new LargeFileUploadResult(); + final LargeFileUploadResult result = new LargeFileUploadResult<>(); if (response.getItem() != null) { result.responseBody = response.getItem(); } @@ -190,12 +190,12 @@ public CompletableFuture> uploadAsync(@Nullabl return failedFuture(new ClientException("Upload did not complete", null)); } private CompletableFuture> completedFuture(final LargeFileUploadResult result) { // CompletableFuture.completedFuture(result.getItem()); missing on android - final CompletableFuture> fut = new CompletableFuture>(); + final CompletableFuture> fut = new CompletableFuture<>(); fut.complete(result); return fut; } private CompletableFuture> failedFuture(ClientException ex) { // CompletableFuture.failedFuture not available on android - final CompletableFuture> fut = new CompletableFuture>(); + final CompletableFuture> fut = new CompletableFuture<>(); fut.completeExceptionally(ex); return fut; } @@ -252,6 +252,7 @@ public LargeFileUploadResult upload(@Nullable final int chunkSize, @ try { return uploadAsync(chunkSize, options, progressCallback).get(); } catch (InterruptedException ex) { + Thread.currentThread().interrupt(); throw new ClientException("The request was interrupted", ex); } catch (ExecutionException ex) { throw new ClientException("Error while executing the request", ex); diff --git a/src/test/java/com/microsoft/graph/serializer/DerivedClassIdentifierTest.java b/src/test/java/com/microsoft/graph/serializer/DerivedClassIdentifierTest.java new file mode 100644 index 000000000..b73a29f25 --- /dev/null +++ b/src/test/java/com/microsoft/graph/serializer/DerivedClassIdentifierTest.java @@ -0,0 +1,18 @@ +package com.microsoft.graph.serializer; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Created by Valentin Popov valentin@archiva.ru on 31.08.2021. + */ +class DerivedClassIdentifierTest { + + @Test + void oDataTypeToClassName() { + Assertions.assertEquals("com.microsoft.graph.models.Message", + DerivedClassIdentifier.oDataTypeToClassName("#Microsoft.Graph.Message")); + } +}