Skip to content

Commit

Permalink
Add OKHttp as our client. This will add support for java 8.
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanLCox1 committed Aug 2, 2022
1 parent 76802a7 commit 54d2884
Show file tree
Hide file tree
Showing 8 changed files with 107 additions and 188 deletions.
19 changes: 15 additions & 4 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,8 @@
</distributionManagement>

<properties>
<maven.compiler.source>1.11</maven.compiler.source>
<maven.compiler.target>1.11</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

Expand All @@ -55,11 +55,22 @@
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.6.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.3</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.10.0</version>
</dependency>
</dependencies>

<build>
Expand Down Expand Up @@ -148,8 +159,8 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>11</source>
<target>11</target>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
Expand Down
5 changes: 2 additions & 3 deletions src/main/java/com/smartystreets/api/ClientBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
Expand All @@ -27,7 +26,7 @@ public class ClientBuilder {
private int maxRetries;
private int maxTimeout;
private String urlPrefix;
private ProxySelector proxy;
private Proxy proxy;
private Map<String, Object> customHeaders;
private List<String> licenses = new ArrayList<>();

Expand Down Expand Up @@ -112,7 +111,7 @@ public ClientBuilder withCustomHeaders(Map<String, Object> customHeaders) {
* @return Returns <b>this</b> to accommodate method chaining.
*/
public ClientBuilder withProxy(Proxy.Type proxyType, String proxyHost, int proxyPort) {
this.proxy = ProxySelector.of(new InetSocketAddress(proxyHost, proxyPort));
this.proxy = new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort));
return this;
}

Expand Down
3 changes: 1 addition & 2 deletions src/main/java/com/smartystreets/api/Request.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.smartystreets.api;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
Expand Down Expand Up @@ -36,7 +35,7 @@ public void putParameter(String name, String value) {

private static String urlEncode(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
return URLEncoder.encode(value, CHARSET);
} catch (Exception ex) {
return "";
}
Expand Down
6 changes: 5 additions & 1 deletion src/main/java/com/smartystreets/api/RetrySender.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ public Response send(Request request) throws SmartyException, IOException, Inter
for (int i = 0; i <= this.maxRetries; i++) {
Response response = this.trySend(request, i);
if (response instanceof TooManyRequestsResponse) {
long wait = ((TooManyRequestsResponse) response).getHeaders().firstValueAsLong("Retry-After").orElse(10L);
long wait = 10L;
String retryAfter = ((TooManyRequestsResponse) response).getHeaders().get("Retry-After");
if (retryAfter != null && retryAfter.length() > 0) {
wait = Long.parseLong(retryAfter);
}
if (wait < 1) {
wait = 1L;
}
Expand Down
71 changes: 42 additions & 29 deletions src/main/java/com/smartystreets/api/SmartySender.java
Original file line number Diff line number Diff line change
@@ -1,80 +1,93 @@
package com.smartystreets.api;

import com.smartystreets.api.exceptions.SmartyException;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;

import java.io.IOException;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.net.Proxy;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class SmartySender implements Sender {
private int maxTimeOut;
private HttpClient client;
private OkHttpClient client;

public SmartySender() {
this.maxTimeOut = 10000;
this.client = HttpClient.newHttpClient();
this.client = new OkHttpClient();
}

public SmartySender(int maxTimeout) {
this();
this.maxTimeOut = maxTimeout;
}

SmartySender(int maxTimeOut, ProxySelector proxy) {
SmartySender(int maxTimeOut, Proxy proxy) {
this.maxTimeOut = maxTimeOut;
this.client = HttpClient.newBuilder().proxy(proxy).build();
this.client = new OkHttpClient.Builder()
.proxy(proxy)
.writeTimeout(this.maxTimeOut, TimeUnit.MILLISECONDS)
.readTimeout(this.maxTimeOut, TimeUnit.MILLISECONDS)
.connectTimeout(this.maxTimeOut, TimeUnit.MILLISECONDS)
.build();
}

SmartySender(HttpClient client) {
SmartySender(OkHttpClient client) {
this();
this.client = client;
}

public Response send(Request smartyRequest) throws SmartyException, IOException {
HttpRequest httpRequest = buildHttpRequest(smartyRequest);
okhttp3.Request httpRequest = buildHttpRequest(smartyRequest);

try {
return buildResponse(this.client.send(httpRequest, HttpResponse.BodyHandlers.ofString()));
} catch(InterruptedException ex) {
try (okhttp3.Response httpResponse = client.newCall(httpRequest).execute()){
int statusCode = httpResponse.code();
if (statusCode == 429){
return new TooManyRequestsResponse(httpResponse.headers(), statusCode, httpResponse.body().bytes());
}
return new Response(statusCode, httpResponse.body().bytes());
} catch(IOException ex) {
return new Response(ex.hashCode(), new byte[0]);
}
}

private HttpRequest buildHttpRequest(Request smartyRequest) throws IOException {
java.net.http.HttpRequest.Builder builder = java.net.http.HttpRequest
.newBuilder(URI.create(smartyRequest.getUrl()))
.timeout(Duration.ofSeconds(maxTimeOut));
private okhttp3.Request buildHttpRequest(Request smartyRequest) throws IOException {

Map<String, Object> headers = smartyRequest.getHeaders();
for (String headerName : headers.keySet())
builder.setHeader(headerName, headers.get(headerName).toString());
Headers.Builder headersBuilder = new Headers.Builder();
for (String headerName : headers.keySet()) {
headersBuilder.add(headerName, headers.get(headerName).toString());
}

if (smartyRequest.getMethod().equals("GET"))
return builder.GET().build();
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder()
.url(smartyRequest.getUrl())
.headers(headersBuilder.build());

return builder
.POST(HttpRequest.BodyPublishers.ofByteArray(smartyRequest.getPayload()))
.build();
if (smartyRequest.getMethod().equals("GET")) {
return requestBuilder
.get()
.build();
}

return requestBuilder.post(RequestBody.create(smartyRequest.getPayload())).build();
}

private Response buildResponse(HttpResponse httpResponse) {
int statusCode = httpResponse.statusCode();
private Response buildResponse(okhttp3.Response httpResponse) {
int statusCode = httpResponse.code();
if (statusCode == 429){
return new TooManyRequestsResponse(httpResponse.headers(), statusCode, httpResponse.body().toString().getBytes());
}
return new Response(statusCode, httpResponse.body().toString().getBytes());
}

static void enableLogging() {
Logger logger = Logger.getLogger(HttpClient.class.getName());
Logger logger = Logger.getLogger(OkHttpClient.class.getName());
logger.setLevel(Level.ALL);
logger.addHandler(new Handler() {
@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package com.smartystreets.api;

import java.net.http.HttpHeaders;
import okhttp3.Headers;

public class TooManyRequestsResponse extends Response {

private HttpHeaders headers;
private Headers headers;

public TooManyRequestsResponse(HttpHeaders headers, int statusCode, byte[] payload) {
public TooManyRequestsResponse(Headers headers, int statusCode, byte[] payload) {
super(statusCode, payload);
this.headers = headers;
}

public HttpHeaders getHeaders() {
public Headers getHeaders() {
return headers;
}
}
Loading

0 comments on commit 54d2884

Please sign in to comment.