Skip to content

Commit 7472381

Browse files
Added response handler for okhttp response
1 parent 1c1c575 commit 7472381

File tree

5 files changed

+36
-107
lines changed

5 files changed

+36
-107
lines changed

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ public ChunkedUploadResult<UploadType> generateResult(
125125
* Generate the chunked upload response result
126126
*
127127
* @param request the HTTP request
128-
* @param connection the HTTP connection
128+
* @param response the HTTP response
129129
* @param serializer the serializer
130130
* @param logger the system logger
131131
* @return the chunked upload result, which could be either an uploaded item or error

src/main/java/com/microsoft/graph/core/DefaultClientConfig.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,12 @@
2626
import com.microsoft.graph.concurrency.DefaultExecutors;
2727
import com.microsoft.graph.concurrency.IExecutors;
2828
import com.microsoft.graph.http.IHttpProvider;
29+
import com.microsoft.graph.http.OkHttpProvider;
2930
import com.microsoft.graph.logger.DefaultLogger;
3031
import com.microsoft.graph.logger.ILogger;
3132
import com.microsoft.graph.serializer.DefaultSerializer;
3233
import com.microsoft.graph.serializer.ISerializer;
3334

34-
import demo.OkHttpProvider;
35-
3635
/**
3736
* The default configuration for a service client
3837
*/
@@ -99,7 +98,6 @@ public IAuthenticationProvider getAuthenticationProvider() {
9998
@Override
10099
public IHttpProvider getHttpProvider() {
101100
if (httpProvider == null) {
102-
System.out.println("---------------------------USING OKHTTP PROVIDER----------------------------");
103101
httpProvider = new OkHttpProvider(getSerializer(),
104102
getAuthenticationProvider(),
105103
getExecutors(),

src/main/java/com/microsoft/graph/http/BaseStreamRequest.java

Lines changed: 0 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,6 @@ public abstract class BaseStreamRequest<T> implements IHttpStreamRequest {
4545
* The base request for this collection request
4646
*/
4747
private final BaseRequest baseRequest;
48-
49-
private int maxRedirect;
50-
private IShouldRedirect shouldRedirect;
51-
private long delay;
52-
private int maxRetries;
53-
private IShouldRetry shouldRetry;
5448

5549
/**
5650
* Creates the stream request.
@@ -184,48 +178,4 @@ public List<Option> getOptions() {
184178
return baseRequest.getOptions();
185179
}
186180

187-
/**
188-
* Sets maximum number of redirects
189-
* @param maxRedirect Maximum number of redirects <= 20
190-
*/
191-
public IHttpRequest setMaxRedirect(int maxRedirect) {
192-
this.maxRedirect = maxRedirect;
193-
return this;
194-
}
195-
196-
/**
197-
* Sets IShouldRedirect callback
198-
* @param shouldRedirect Callbacks to IShouldRedirect to decides to redirect or not
199-
*/
200-
public IHttpRequest setShouldRedirect(IShouldRedirect shouldRedirect) {
201-
this.shouldRedirect = shouldRedirect;
202-
return this;
203-
}
204-
205-
/**
206-
* Sets Delay in seconds between retries
207-
* @param delay Delay in seconds between retries
208-
*/
209-
public IHttpRequest setDelay(long delay) {
210-
this.delay = delay;
211-
return this;
212-
}
213-
214-
/**
215-
* Sets maximum number of retries
216-
* @param maxRetries Maximum number of retries <= 10
217-
*/
218-
public IHttpRequest setMaxRetries(int maxRetries) {
219-
this.maxRetries = maxRetries;
220-
return this;
221-
}
222-
223-
/**
224-
* Sets IShouldRetry callback
225-
* @param shouldRetry Callback to decide to retry or not
226-
*/
227-
public IHttpRequest setShouldRetry(IShouldRetry shouldRetry) {
228-
this.shouldRetry = shouldRetry;
229-
return this;
230-
}
231181
}

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,6 @@
3636
import com.microsoft.graph.options.HeaderOption;
3737
import com.microsoft.graph.serializer.ISerializer;
3838

39-
import demo.OkHttpProvider;
4039
import okhttp3.Response;
4140

4241
/**
@@ -355,7 +354,7 @@ public static <T> GraphServiceException createFromConnection(final IHttpRequest
355354
* @param request the request that resulted in this failure
356355
* @param serializable the serialized object that was sent with this request
357356
* @param serializer the serializer to re-create the option in its over the wire state
358-
* @param connection the connection that was used to extract the response information from
357+
* @param response the response being used to extract information from
359358
* @param logger the logger to log exception information to
360359
* @param <T> the type of the serializable object
361360
* @return the new GraphServiceException instance

src/main/java/demo/OkHttpProvider.java renamed to src/main/java/com/microsoft/graph/http/OkHttpProvider.java

Lines changed: 33 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
// THE SOFTWARE.
2121
// ------------------------------------------------------------------------------
2222

23-
package demo;
23+
package com.microsoft.graph.http;
2424

2525
import java.io.BufferedInputStream;
2626
import java.io.BufferedOutputStream;
@@ -29,8 +29,6 @@
2929
import java.io.InputStream;
3030
import java.io.OutputStream;
3131
import java.io.UnsupportedEncodingException;
32-
import java.net.HttpURLConnection;
33-
import java.net.ProtocolException;
3432
import java.net.URL;
3533
import java.util.ArrayList;
3634
import java.util.HashMap;
@@ -51,18 +49,20 @@
5149
import com.microsoft.graph.http.GraphServiceException;
5250
import com.microsoft.graph.http.HttpMethod;
5351
import com.microsoft.graph.http.HttpResponseCode;
54-
import com.microsoft.graph.http.IConnection;
5552
import com.microsoft.graph.http.IConnectionFactory;
5653
import com.microsoft.graph.http.IHttpProvider;
5754
import com.microsoft.graph.http.IHttpRequest;
5855
import com.microsoft.graph.http.IStatefulResponseHandler;
5956
import com.microsoft.graph.httpcore.HttpClients;
57+
import com.microsoft.graph.httpcore.RedirectHandler;
58+
import com.microsoft.graph.httpcore.RetryHandler;
6059
import com.microsoft.graph.logger.ILogger;
6160
import com.microsoft.graph.logger.LoggerLevel;
6261
import com.microsoft.graph.options.HeaderOption;
6362
import com.microsoft.graph.serializer.ISerializer;
6463

6564
import okhttp3.Headers;
65+
import okhttp3.Interceptor;
6666
import okhttp3.MediaType;
6767
import okhttp3.OkHttpClient;
6868
import okhttp3.Request;
@@ -110,16 +110,14 @@ public class OkHttpProvider implements IHttpProvider {
110110
*/
111111
private final ILogger logger;
112112

113-
/**
114-
* The connection factory
115-
*/
116-
private IConnectionFactory connectionFactory;
117-
118113
/**
119114
* The connection config
120115
*/
121116
private IConnectionConfig connectionConfig;
122117

118+
/**
119+
* The OkHttpClient that handles all requests
120+
*/
123121
private OkHttpClient okhttpClient;
124122

125123
/**
@@ -138,7 +136,6 @@ public OkHttpProvider(final ISerializer serializer,
138136
this.authenticationProvider = authenticationProvider;
139137
this.executors = executors;
140138
this.logger = logger;
141-
connectionFactory = new DefaultConnectionFactory();
142139
}
143140

144141
/**
@@ -265,24 +262,33 @@ private <Result, Body, DeserializeType> Result sendRequestInternal(final IHttpRe
265262
logger.logDebug("Starting to send request, URL " + requestUrl.toString());
266263

267264
if(okhttpClient == null) {
268-
OkHttpClient.Builder okBuilder = HttpClients.custom();
265+
OkHttpClient.Builder okBuilder = HttpClients
266+
.custom()
267+
.addInterceptor(new RetryHandler())
268+
.addInterceptor(new RedirectHandler());
269269
if(this.connectionConfig == null) {
270270
this.connectionConfig = new DefaultConnectionConfig();
271271
}
272272
okBuilder.connectTimeout(connectionConfig.getConnectTimeout(), TimeUnit.MILLISECONDS);
273273
okBuilder.readTimeout(connectionConfig.getReadTimeout(), TimeUnit.MILLISECONDS);
274274
okhttpClient = okBuilder.build();
275275
}
276-
// edit the options and handlers over here
277276

278277
Request okhttpRequest = convertIHttpRequestToOkHttpRequest(request);
279278
Request.Builder okhttpRequestBuilder = okhttpRequest.newBuilder();
280279

281-
String contenttype = "";
280+
String contenttype = null;
282281

283282
try {
284283
logger.logDebug("Request Method " + request.getHttpMethod().toString());
285284
List<HeaderOption> requestHeaders = request.getHeaders();
285+
286+
for(HeaderOption headerOption : requestHeaders) {
287+
if(headerOption.getName().equalsIgnoreCase(CONTENT_TYPE_HEADER_NAME)) {
288+
contenttype = headerOption.getValue().toString();
289+
break;
290+
}
291+
}
286292

287293
final byte[] bytesToWrite;
288294
okhttpRequestBuilder.addHeader("Accept", "*/*");
@@ -304,8 +310,6 @@ private <Result, Body, DeserializeType> Result sendRequestInternal(final IHttpRe
304310
okhttpRequestBuilder.addHeader(CONTENT_TYPE_HEADER_NAME, binaryContentType);
305311
contenttype = binaryContentType;
306312
}
307-
// Dont know if this is useful in okhttp
308-
//connection.setContentLength(bytesToWrite.length);
309313
} else {
310314
logger.logDebug("Sending " + serializable.getClass().getName() + " as request body");
311315
final String serializeObject = serializer.serializeObject(serializable);
@@ -316,8 +320,6 @@ private <Result, Body, DeserializeType> Result sendRequestInternal(final IHttpRe
316320
okhttpRequestBuilder.addHeader(CONTENT_TYPE_HEADER_NAME, JSON_CONTENT_TYPE);
317321
contenttype = JSON_CONTENT_TYPE;
318322
}
319-
//Dont know if
320-
//connection.setContentLength(bytesToWrite.length);
321323
}
322324

323325
RequestBody requestBody = null;
@@ -329,7 +331,6 @@ private <Result, Body, DeserializeType> Result sendRequestInternal(final IHttpRe
329331
public long contentLength() throws IOException {
330332
return bytesToWrite.length;
331333
}
332-
333334
@Override
334335
public void writeTo(BufferedSink sink) throws IOException {
335336
OutputStream out = sink.outputStream();
@@ -356,15 +357,7 @@ public MediaType contentType() {
356357

357358
}
358359

359-
// try {
360360
okhttpRequestBuilder.method(request.getHttpMethod().toString(), requestBody);
361-
// } catch (final ProtocolException ignored) {
362-
// // Some HTTP verbs are not supported by older HTTP implementations, use method override as an alternative
363-
// requestBuilder.method(HttpMethod.POST.toString(), requestBody);
364-
// requestBuilder.header("X-HTTP-Method-Override", request.getHttpMethod().toString());
365-
// requestBuilder.header("X-HTTP-Method", request.getHttpMethod().toString());
366-
// }
367-
368361
okhttpRequest = okhttpRequestBuilder.build();
369362

370363
Response response = okhttpClient.newCall(okhttpRequest).execute();
@@ -442,18 +435,18 @@ public MediaType contentType() {
442435
}
443436

444437
/**
445-
* Gets the response headers from an HTTP URL connection
438+
* Gets the response headers from OkHttp Response
446439
*
447-
* @param connection the HTTP connection
440+
* @param response the OkHttp response
448441
* @return the set of headers names and value
449442
*/
450-
public static HashMap<String, String> getResponseHeadersAsMapStringString(final Response response) {
443+
static HashMap<String, String> getResponseHeadersAsMapStringString(final Response response) {
451444
final HashMap<String, String> headers = new HashMap<>();
452445
int index = 0;
453-
Headers connection = response.headers();
454-
while (index < connection.size()) {
455-
final String headerName = connection.name(index);
456-
final String headerValue = connection.value(index);
446+
Headers responseHeaders = response.headers();
447+
while (index < responseHeaders.size()) {
448+
final String headerName = responseHeaders.name(index);
449+
final String headerValue = responseHeaders.value(index);
457450
if (headerName == null && headerValue == null) {
458451
break;
459452
}
@@ -464,15 +457,13 @@ public static HashMap<String, String> getResponseHeadersAsMapStringString(final
464457
}
465458

466459
public static Map<String, List<String>> getResponseHeadersAsMapOfStringList(Response response) {
467-
// Copy unmodifiable map to hashmap
468-
Map<String, List<String>> headerFields = response.headers().toMultimap();
469-
470-
// Add the response code
471-
List<String> list = new ArrayList<>();
472-
list.add(String.format("%d", response.code()));
473-
headerFields.put("responseCode", list);
474-
return headerFields;
475-
}
460+
Map<String, List<String>> headerFields = response.headers().toMultimap();
461+
// Add the response code
462+
List<String> list = new ArrayList<>();
463+
list.add(String.format("%d", response.code()));
464+
headerFields.put("responseCode", list);
465+
return headerFields;
466+
}
476467

477468
private Request convertIHttpRequestToOkHttpRequest(IHttpRequest request) {
478469
if(request != null) {
@@ -545,15 +536,6 @@ private <Result> Result handleEmptyResponse(Map<String, List<String>> responseHe
545536
return handleJsonResponse(in, responseHeaders, clazz);
546537
}
547538

548-
/**
549-
* Sets the connection factory for this provider
550-
*
551-
* @param factory the new factory
552-
*/
553-
void setConnectionFactory(final IConnectionFactory factory) {
554-
connectionFactory = factory;
555-
}
556-
557539
/**
558540
* Reads in a stream and converts it into a string
559541
*

0 commit comments

Comments
 (0)