Skip to content

Commit 8f807b4

Browse files
authored
Merge pull request #121 from microsoftgraph/bugfix/logger-align
- fixes a bug where some higher level classes would write to stdout/stderr instead of using the provided logging infrastructure
2 parents 1151bfe + 3cd16f0 commit 8f807b4

13 files changed

Lines changed: 99 additions & 58 deletions

File tree

‎src/main/java/com/microsoft/graph/authentication/TokenCredentialAuthProvider.java‎

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import java.net.URL;
77
import java.util.Arrays;
88
import java.util.List;
9+
import java.util.Objects;
910
import java.util.concurrent.CompletableFuture;
1011

1112
import javax.annotation.Nonnull;
@@ -36,15 +37,12 @@ public TokenCredentialAuthProvider(@Nonnull final TokenCredential tokenCredentia
3637
* @param scopes Specified desired scopes of the Auth Provider
3738
*/
3839
public TokenCredentialAuthProvider(@Nonnull final List<String> scopes, @Nonnull final TokenCredential tokenCredential) {
39-
if(tokenCredential == null) {
40-
throw new IllegalArgumentException("tokenCredential parameter cannot be null.");
41-
}
4240
if(scopes == null || scopes.isEmpty()) {
4341
throw new IllegalArgumentException("scopes parameter cannot be null or empty");
4442
}
4543
this.context = new TokenRequestContext();
4644
this.context.setScopes(scopes);
47-
this.tokenCredential = tokenCredential;
45+
this.tokenCredential = Objects.requireNonNull(tokenCredential, "tokenCredential parameter cannot be null.");
4846
}
4947

5048
/**
@@ -54,9 +52,7 @@ public TokenCredentialAuthProvider(@Nonnull final List<String> scopes, @Nonnull
5452
*/
5553
@Nonnull
5654
public CompletableFuture<String> getAuthorizationTokenAsync(@Nonnull final URL requestUrl) {
57-
if(requestUrl == null)
58-
throw new IllegalArgumentException("requestUrl parameter cannot be null");
59-
else if(shouldAuthenticateRequestWithUrl(requestUrl))
55+
if(shouldAuthenticateRequestWithUrl(Objects.requireNonNull(requestUrl, "requestUrl parameter cannot be null")))
6056
return this.tokenCredential
6157
.getToken(this.context)
6258
.toFuture()

‎src/main/java/com/microsoft/graph/content/MSBatchRequestContent.java‎

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import java.util.LinkedHashMap;
66
import java.util.List;
77
import java.util.Map;
8+
import java.util.Objects;
89
import java.util.concurrent.CompletableFuture;
910
import java.util.concurrent.ThreadLocalRandom;
1011
import java.util.regex.Matcher;
@@ -20,6 +21,8 @@
2021
import com.google.gson.JsonPrimitive;
2122
import com.microsoft.graph.core.ClientException;
2223
import com.microsoft.graph.core.IBaseClient;
24+
import com.microsoft.graph.logger.DefaultLogger;
25+
import com.microsoft.graph.logger.ILogger;
2326
import com.google.gson.JsonParseException;
2427

2528
import okhttp3.Headers;
@@ -37,16 +40,29 @@ public class MSBatchRequestContent {
3740
* Maximum number of requests that can be sent in a batch
3841
*/
3942
public static final int MAX_NUMBER_OF_REQUESTS = 20;
43+
private final ILogger logger;
4044

4145
/**
4246
* Creates Batch request content using list provided
4347
*
4448
* @param batchRequestStepsArray List of batch steps for batching
4549
*/
4650
public MSBatchRequestContent(@Nonnull final MSBatchRequestStep... batchRequestStepsArray) {
51+
this(new DefaultLogger(), batchRequestStepsArray);
52+
}
53+
54+
/**
55+
* Creates Batch request content using list provided
56+
*
57+
* @param batchRequestStepsArray List of batch steps for batching
58+
* @param logger logger to use for telemetry
59+
*/
60+
public MSBatchRequestContent(@Nonnull final ILogger logger, @Nonnull final MSBatchRequestStep... batchRequestStepsArray) {
4761
if (batchRequestStepsArray.length > MAX_NUMBER_OF_REQUESTS)
4862
throw new IllegalArgumentException("Number of batch request steps cannot exceed " + MAX_NUMBER_OF_REQUESTS);
4963

64+
this.logger = Objects.requireNonNull(logger, "logger cannot be null");
65+
5066
this.batchRequestStepsHashMap = new LinkedHashMap<>();
5167
for (final MSBatchRequestStep requestStep : batchRequestStepsArray)
5268
if(requestStep != null)
@@ -60,8 +76,7 @@ public MSBatchRequestContent(@Nonnull final MSBatchRequestStep... batchRequestSt
6076
* given
6177
*/
6278
public boolean addBatchRequestStep(@Nonnull final MSBatchRequestStep batchRequestStep) {
63-
if(batchRequestStep == null)
64-
throw new IllegalArgumentException("batchRequestStep parameter cannot be null");
79+
Objects.requireNonNull(batchRequestStep, "batchRequestStep parameter cannot be null");
6580
if (batchRequestStepsHashMap.containsKey(batchRequestStep.getRequestId()) ||
6681
batchRequestStepsHashMap.size() >= MAX_NUMBER_OF_REQUESTS)
6782
return false;
@@ -77,8 +92,7 @@ public boolean addBatchRequestStep(@Nonnull final MSBatchRequestStep batchReques
7792
*/
7893
@Nonnull
7994
public String addBatchRequestStep(@Nonnull final Request request, @Nullable final String... arrayOfDependsOnIds) {
80-
if(request == null)
81-
throw new IllegalArgumentException("request parameter cannot be null");
95+
Objects.requireNonNull(request, "request parameter cannot be null");
8296
String requestId;
8397
do {
8498
requestId = Integer.toString(ThreadLocalRandom.current().nextInt(1, Integer.MAX_VALUE));
@@ -136,7 +150,7 @@ public String getBatchRequestContent() {
136150
@Nonnull
137151
public MSBatchResponseContent execute(@Nonnull final IBaseClient client) {
138152
final JsonObject content = getBatchRequestContentAsJson();
139-
return new MSBatchResponseContent(client.getServiceRoot() + "/",
153+
return new MSBatchResponseContent(logger, client.getServiceRoot() + "/",
140154
content,
141155
client.customRequest("/$batch")
142156
.buildRequest()
@@ -150,14 +164,12 @@ public MSBatchResponseContent execute(@Nonnull final IBaseClient client) {
150164
*/
151165
@Nonnull
152166
public CompletableFuture<MSBatchResponseContent> executeAsync(@Nonnull final IBaseClient client) {
153-
if(client == null) {
154-
throw new IllegalArgumentException("client parameter cannot be null");
155-
}
167+
Objects.requireNonNull(client, "client parameter cannot be null");
156168
final JsonObject content = getBatchRequestContentAsJson();
157169
return client.customRequest("/$batch")
158170
.buildRequest()
159171
.postAsync(content)
160-
.thenApply(resp -> new MSBatchResponseContent(client.getServiceRoot() + "/", content, resp.getAsJsonObject()));
172+
.thenApply(resp -> new MSBatchResponseContent(logger, client.getServiceRoot() + "/", content, resp.getAsJsonObject()));
161173
}
162174

163175
private static final Pattern protocolAndHostReplacementPattern = Pattern.compile("(?i)^http[s]?:\\/\\/graph\\.microsoft\\.com\\/(?>v1\\.0|beta)\\/?"); // (?i) case insensitive
@@ -194,7 +206,7 @@ private JsonObject getBatchRequestObjectFromRequestStep(final MSBatchRequestStep
194206
try {
195207
contentmap.add("body", requestBodyToJSONObject(batchRequestStep.getRequest()));
196208
} catch (IOException | JsonParseException e) {
197-
e.printStackTrace();
209+
logger.logError("error pasing the request JSON body", e);
198210
}
199211
}
200212
return contentmap;

‎src/main/java/com/microsoft/graph/content/MSBatchRequestStep.java‎

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

33
import java.util.Arrays;
44
import java.util.HashSet;
5+
import java.util.Objects;
56

67
import javax.annotation.Nullable;
78
import javax.annotation.Nonnull;
@@ -23,15 +24,12 @@ public class MSBatchRequestStep {
2324
* @param arrayOfDependsOnIds the ids of steps this step depends on
2425
*/
2526
public MSBatchRequestStep(@Nonnull final String requestId, @Nonnull final Request request, @Nullable final String... arrayOfDependsOnIds) {
26-
if(requestId == null)
27-
throw new IllegalArgumentException("Request Id cannot be null.");
28-
if(requestId.length() == 0)
27+
Objects.requireNonNull(requestId, "Request Id cannot be null.");
28+
if(requestId.isEmpty())
2929
throw new IllegalArgumentException("Request Id cannot be empty.");
30-
if(request == null)
31-
throw new IllegalArgumentException("Request cannot be null.");
3230

3331
this.requestId = requestId;
34-
this.request = request;
32+
this.request = Objects.requireNonNull(request, "Request cannot be null.");
3533
this.dependsOnIds = new HashSet<>(Arrays.asList(arrayOfDependsOnIds));
3634
}
3735

‎src/main/java/com/microsoft/graph/content/MSBatchResponseContent.java‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import java.util.LinkedHashMap;
55
import java.util.Iterator;
66
import java.util.Map;
7+
import java.util.Objects;
78

89
import javax.annotation.Nullable;
910
import javax.annotation.Nonnull;
@@ -12,6 +13,8 @@
1213
import com.google.gson.JsonElement;
1314
import com.google.gson.JsonObject;
1415
import com.google.gson.JsonParser;
16+
import com.microsoft.graph.logger.DefaultLogger;
17+
import com.microsoft.graph.logger.ILogger;
1518
import com.google.gson.JsonParseException;
1619

1720
import okhttp3.MediaType;
@@ -32,11 +35,21 @@ public class MSBatchResponseContent {
3235
private LinkedHashMap<String, Request> batchRequestsHashMap = new LinkedHashMap<>();
3336
private JsonArray batchResponseArray;
3437
private String nextLink;
38+
private final ILogger logger;
3539

3640
/**
3741
* @param batchResponse OkHttp batch response on execution of batch requests
3842
*/
3943
public MSBatchResponseContent(@Nullable final Response batchResponse) {
44+
this(new DefaultLogger(), batchResponse);
45+
}
46+
47+
/**
48+
* @param batchResponse OkHttp batch response on execution of batch requests
49+
* @param logger logger to use for telemetry
50+
*/
51+
public MSBatchResponseContent(@Nonnull final ILogger logger, @Nullable final Response batchResponse) {
52+
this.logger = Objects.requireNonNull(logger, "logger parameter cannot be null");
4053
update(batchResponse);
4154
this.message = batchResponse.message();
4255
this.protocol = batchResponse.protocol();
@@ -47,8 +60,10 @@ public MSBatchResponseContent(@Nullable final Response batchResponse) {
4760
* @param baseUrl the base service URL without a trailing slash
4861
* @param batchRequestData the batch request payload data as a JSON string
4962
* @param batchResponseData the batch response body as a JSON string
63+
* @param logger logger to use for telemetry
5064
*/
51-
protected MSBatchResponseContent(@Nonnull final String baseUrl, @Nonnull final JsonObject batchRequestData, @Nonnull final JsonObject batchResponseData) {
65+
protected MSBatchResponseContent(@Nonnull final ILogger logger, @Nonnull final String baseUrl, @Nonnull final JsonObject batchRequestData, @Nonnull final JsonObject batchResponseData) {
66+
this.logger = logger;
5267
this.protocol = Protocol.HTTP_1_1;
5368
this.message = "OK";
5469
final Map<String, Request> requestMap = createBatchRequestsHashMap(baseUrl, batchRequestData);
@@ -157,10 +172,7 @@ public Iterator<Map.Entry<String, Response>> getResponsesIterator() {
157172
* @param batchResponse the response from the service.
158173
*/
159174
public void update(@Nonnull final Response batchResponse) {
160-
if (batchResponse == null)
161-
throw new IllegalArgumentException("Batch Response cannot be null");
162-
163-
final Map<String, Request> requestMap = createBatchRequestsHashMap(batchResponse);
175+
final Map<String, Request> requestMap = createBatchRequestsHashMap(Objects.requireNonNull(batchResponse, "Batch Response cannot be null"));
164176
if (requestMap != null)
165177
batchRequestsHashMap.putAll(requestMap);
166178

@@ -171,7 +183,7 @@ public void update(@Nonnull final Response batchResponse) {
171183
updateFromResponseBody(stringToJSONObject(batchResponseData));
172184
}
173185
} catch (final IOException e) {
174-
e.printStackTrace();
186+
logger.logError("error updating batch response content from response body", e);
175187
}
176188
}
177189
}
@@ -208,7 +220,7 @@ private Map<String, Request> createBatchRequestsHashMap(final Response batchResp
208220
final String baseUrl = batchResponse.request().url().toString().replace("$batch", "");
209221
return createBatchRequestsHashMap(baseUrl, requestJSONObject);
210222
} catch (IOException ex) {
211-
ex.printStackTrace();
223+
logger.logError("error parsing batch requests to get batch response content", ex);
212224
return null;
213225
}
214226
}
@@ -268,7 +280,7 @@ private Map<String, Request> createBatchRequestsHashMap(@Nonnull final String ba
268280
return batchRequestsHashMap;
269281

270282
} catch (JsonParseException e) {
271-
e.printStackTrace();
283+
logger.logError("error parsing batch request", e);
272284
}
273285
return null;
274286
}
@@ -280,7 +292,7 @@ private JsonObject stringToJSONObject(final String input) {
280292
JsonObject = JsonParser.parseString(input).getAsJsonObject();
281293
}
282294
} catch (final Exception e) {
283-
e.printStackTrace();
295+
logger.logError("error parsing input into JSONObject", e);
284296
}
285297
return JsonObject;
286298
}

‎src/main/java/com/microsoft/graph/core/BaseClient.java‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@
3333
import com.microsoft.graph.serializer.ISerializer;
3434

3535
import javax.annotation.Nullable;
36+
37+
import java.util.Objects;
38+
3639
import javax.annotation.Nonnull;
3740

3841
import okhttp3.OkHttpClient;
@@ -236,9 +239,7 @@ public Builder<httpClientType> authenticationProvider(@Nonnull final IAuthentica
236239
*/
237240
@Nonnull
238241
protected <ClientType extends BaseClient> ClientType buildClient(@Nonnull ClientType instance) throws ClientException {
239-
if(instance == null) {
240-
throw new IllegalArgumentException("The instance cannot be null");
241-
}
242+
Objects.requireNonNull(instance, "The instance cannot be null");
242243
instance.setHttpProvider(this.getHttpProvider());
243244
instance.setLogger(this.getLogger());
244245
instance.setSerializer(this.getSerializer());

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

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.microsoft.graph.httpcore;
22

33
import java.io.IOException;
4+
import java.util.Objects;
45

56
import javax.annotation.Nullable;
67
import javax.annotation.Nonnull;
@@ -9,6 +10,8 @@
910
import com.microsoft.graph.httpcore.middlewareoption.MiddlewareType;
1011
import com.microsoft.graph.httpcore.middlewareoption.RetryOptions;
1112
import com.microsoft.graph.httpcore.middlewareoption.TelemetryOptions;
13+
import com.microsoft.graph.logger.DefaultLogger;
14+
import com.microsoft.graph.logger.ILogger;
1215

1316
import okhttp3.Interceptor;
1417
import okhttp3.Request;
@@ -69,10 +72,20 @@ public class RetryHandler implements Interceptor{
6972
*/
7073
private final long DELAY_MILLISECONDS = 1000;
7174

75+
private final ILogger logger;
76+
7277
/**
7378
* @param retryOption Create Retry handler using retry option
7479
*/
7580
public RetryHandler(@Nullable final RetryOptions retryOption) {
81+
this(new DefaultLogger(), retryOption);
82+
}
83+
/**
84+
* @param retryOption Create Retry handler using retry option
85+
* @param logger logger to use for telemetry
86+
*/
87+
public RetryHandler(@Nonnull final ILogger logger, @Nullable final RetryOptions retryOption) {
88+
this.logger = Objects.requireNonNull(logger, "logger parameter cannot be null");
7689
this.mRetryOption = retryOption;
7790
if(this.mRetryOption == null) {
7891
this.mRetryOption = new RetryOptions();
@@ -111,7 +124,7 @@ && checkStatus(statusCode) && isBuffered(response, request)
111124
try {
112125
Thread.sleep(retryInterval);
113126
} catch (InterruptedException e) {
114-
e.printStackTrace();
127+
logger.logError("error retrying the request", e);
115128
}
116129
}
117130
return shouldRetry;

‎src/main/java/com/microsoft/graph/options/Option.java‎

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

2323
package com.microsoft.graph.options;
2424

25+
import java.util.Objects;
26+
2527
import javax.annotation.Nonnull;
2628

2729
/**
@@ -46,8 +48,9 @@ public class Option {
4648
* @param value the value of the option
4749
*/
4850
protected Option(@Nonnull final String name, @Nonnull final Object value) {
49-
if(name == null || name == "") {
50-
throw new IllegalArgumentException("name should not be null or empty");
51+
Objects.requireNonNull(name, "name should not be null");
52+
if(name.isEmpty()) {
53+
throw new IllegalArgumentException("name should not empty");
5154
}
5255
this.name = name;
5356
this.value = value;

‎src/test/java/com/microsoft/graph/authentication/TokenCredentialAuthProviderTest.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,10 +47,10 @@ public void providerDoesntAddTokenOnInvalidHostName() throws MalformedURLExcepti
4747
}
4848
@Test
4949
public void providerDefensiveProgramming() {
50-
assertThrows("should throw on null credentials", IllegalArgumentException.class, () -> { new TokenCredentialAuthProvider(null); });
50+
assertThrows("should throw on null credentials", NullPointerException.class, () -> { new TokenCredentialAuthProvider(null); });
5151
assertThrows("should throw on null scopes", IllegalArgumentException.class, () -> { new TokenCredentialAuthProvider(null, mock(TokenCredential.class)); });
5252
assertThrows("should throw on empty scopes", IllegalArgumentException.class, () -> { new TokenCredentialAuthProvider(new ArrayList<String>(), mock(TokenCredential.class)); });
5353
final TokenCredentialAuthProvider provider = new TokenCredentialAuthProvider(mock(TokenCredential.class));
54-
assertThrows("should throw on null url", IllegalArgumentException.class, () -> { provider.getAuthorizationTokenAsync(null); });
54+
assertThrows("should throw on null url", NullPointerException.class, () -> { provider.getAuthorizationTokenAsync(null); });
5555
}
5656
}

‎src/test/java/com/microsoft/graph/content/MSBatchRequestContentTest.java‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,15 +111,18 @@ public String answer(InvocationOnMock invocation) throws Throwable {
111111
});
112112

113113
assertThrows("the number of steps cannot exceed 20", IllegalArgumentException.class, () -> {
114-
new MSBatchRequestContent(null, null, null, null, null, null, null, null, null, null, null, null, null,
114+
new MSBatchRequestContent(mock(ILogger.class), null, null, null, null, null, null, null, null, null, null, null, null, null,
115115
null, null, null, null, null, null, null, null, null);
116116
});
117+
assertThrows("the logger cannot be null", NullPointerException.class, () -> {
118+
new MSBatchRequestContent((ILogger) null, (MSBatchRequestStep)null);
119+
});
117120

118121
new MSBatchRequestContent(mockStep, null); // addind a null step doesn't throw
119-
assertThrows("should throw argument exception", IllegalArgumentException.class, () -> {
122+
assertThrows("should throw argument exception", NullPointerException.class, () -> {
120123
new MSBatchRequestContent().addBatchRequestStep(null);
121124
});
122-
assertThrows("should throw argument exception", IllegalArgumentException.class, () -> {
125+
assertThrows("should throw argument exception", NullPointerException.class, () -> {
123126
new MSBatchRequestContent().addBatchRequestStep((Request) null);
124127
});
125128

@@ -188,7 +191,7 @@ public void executeBatchTest() throws Throwable {
188191
}
189192
@Test
190193
public void responseParsing() {
191-
final MSBatchResponseContent batchResponse = new MSBatchResponseContent("https://graph.microsoft.com/v1.0",
194+
final MSBatchResponseContent batchResponse = new MSBatchResponseContent(mock(ILogger.class), "https://graph.microsoft.com/v1.0",
192195
JsonParser.parseString("{\"requests\":[{\"id\":\"1\",\"method\":\"GET\",\"url\":\"/me\"}]}")
193196
.getAsJsonObject(),
194197
JsonParser.parseString("{\"responses\": [{\"id\": \"1\",\"status\": 200,\"body\": null}]}")

0 commit comments

Comments
 (0)