Skip to content

Commit 2e5db91

Browse files
authored
Merge pull request #4 from evolv-ai/httpclient
Refactoring HttpClient implementations
2 parents 55f9815 + 7e78855 commit 2e5db91

File tree

5 files changed

+265
-130
lines changed

5 files changed

+265
-130
lines changed

README.md

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,27 +27,27 @@
2727
```
2828

2929
*Note: The SDK uses a standard interface for the http backend see [HttpClient.](https://github.com/evolv-ai/ascend-java-sdk/blob/master/src/main/java/ai/evolv/HttpClient.java).
30-
When configuring the client you must specify what implementation of HttpClient to use (or implement your own). See "Custom Http Backend" for more details.*
30+
When configuring the AscendClient you must specify what implementation of HttpClient to use (or implement your own). See "Custom Http Backend" for more details.*
3131

3232
2. Initialize the AscendClient.
3333
```java
34-
AscendClient client = AscendClientFactory.init(config);
34+
AscendClient ascendClient = AscendClientFactory.init(config);
3535
```
3636

3737
### Confirm the Allocation
3838

39-
1. Once the client has been initialized, confirm the participant into the experiment.
39+
1. Once the AscendClient has been initialized, confirm the participant into the experiment.
4040
```java
41-
client.confirm();
41+
ascendClient.confirm();
4242
```
43-
*Note: After the client has initialized, it is important to confirm the participant into the experiment. This action
43+
*Note: After the AscendClient has initialized, it is important to confirm the participant into the experiment. This action
4444
records the participant's allocation and sends the info back to Ascend.*
4545

4646
### Value Retrieval
4747

4848
1. Retrieve values from Ascend.
4949
```java
50-
T value = client.get(<key_for_value>, <default_value>);
50+
T value = ascendClient.get(<key_for_value>, <default_value>);
5151
```
5252

5353
*Note: The return value's type is decided by the provided default value's type. If there is an issue retrieving the
@@ -61,7 +61,7 @@ subscribe to a value and apply any actions as a result of it asynchronously.
6161

6262
1. Subscribe to a value from Ascend.
6363
```java
64-
client.subscribe(<key_for_value>, <default_value>, value -> {
64+
ascendClient.subscribe(<key_for_value>, <default_value>, value -> {
6565
Your code...
6666
});
6767
```
@@ -80,14 +80,14 @@ that is important to record is a "conversion" event. If you implemented the SDK
8080

8181
1. Emit a custom event.
8282
```java
83-
client.emitEvent(<event_type>);
83+
ascendClient.emitEvent(<event_type>);
8484
```
8585

8686
AND / OR
8787

8888
2. Emit a custom event with an associated score.
8989
```java
90-
client.emitEvent(<event_type>, <score>);
90+
ascendClient.emitEvent(<event_type>, <score>);
9191
```
9292

9393
### Contaminate the Allocation (optional)
@@ -96,7 +96,7 @@ Sometimes it may be necessary to contaminate the participant's allocation. Meani
9696

9797
1. Contaminate the participant's allocation.
9898
```java
99-
client.contaminate();
99+
ascendClient.contaminate();
100100
```
101101

102102

@@ -109,24 +109,25 @@ AscendConfig class.
109109
1. Choose an HttpClient and pass it to the AscendConfig.
110110

111111
```java
112-
HttpClient httpClient = new AsyncHttpClientImpl(<request_timeout>);
113-
AscendConfig config = AscendConfig.builder(<environment_id>, httpClient).build();
114-
AscendClient client = AscendClientFactory.init(config);
112+
HttpClient httpClient = new AsyncHttpClient();
113+
AscendConfig config = AscendConfig.builder('sandbox', httpClient).build();
114+
AscendClient ascendClient = AscendClientFactory.init(config);
115115
```
116-
*Note: The above HttpClient implementation uses org.asynchttpclient:async-http-client as its http client. In order to use
116+
*Note: Replace 'sandbox' with your own environment id.
117+
*Note: The above HttpClient implementation uses org.asynchttpclient:async-http-httpClient as its http httpClient. In order to use
117118
the implementation you will need to bring the package into your dependencies.*
118119

119120
### Custom Allocation Store (optional)
120121

121122
Once a participant has been allocated into an experiment you may want to retain the allocations they received. To do this, create a custom allocation store by implementing the AscendAllocationStore interface. You can supply the
122-
custom allocation store to the client when you build the AscendConfig.
123+
custom allocation store to the AscendClient when you build the AscendConfig.
123124

124-
1. Supply the allocation store to the client.
125+
1. Supply the allocation store to the AscendClient.
125126
```java
126127
AscendConfig config = AscendConfig.builder(<environment_id>, <http_client>)
127128
.setAscendAllocationStore(<custom_store>)
128129
.build();
129-
AscendClient client = AscendClientFactory.init(config);
130+
AscendClient ascendClient = AscendClientFactory.init(config);
130131
```
131132

132133
### Optional Configurations
Lines changed: 13 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,21 @@
11
package ai.evolv;
22

3-
import static org.asynchttpclient.Dsl.asyncHttpClient;
4-
import static org.asynchttpclient.Dsl.config;
5-
6-
import java.io.IOException;
73
import java.util.concurrent.CompletableFuture;
4+
import java.util.concurrent.TimeUnit;
85

9-
import org.asynchttpclient.AsyncHandler;
10-
import org.asynchttpclient.AsyncHttpClient;
11-
import org.asynchttpclient.HttpResponseBodyPart;
12-
import org.asynchttpclient.HttpResponseHeaders;
13-
import org.asynchttpclient.HttpResponseStatus;
14-
15-
public class AsyncHttpClientImpl implements HttpClient {
16-
17-
private final AsyncHttpClient httpClient;
6+
@Deprecated
7+
public class AsyncHttpClientImpl
8+
extends ai.evolv.httpclients.AsyncHttpClient implements HttpClient {
189

10+
/**
11+
*
12+
* @param timeout The milliseconds before the client should timeout and return the default
13+
* value.
14+
*
15+
* @deprecated use {@link ai.evolv.httpclients.AsyncHttpClient} instead.
16+
*/
1917
public AsyncHttpClientImpl(long timeout) {
20-
this.httpClient = asyncHttpClient(config()
21-
.setRequestTimeout(new Long(timeout).intValue()));
18+
super(TimeUnit.MILLISECONDS, Math.toIntExact(timeout));
2219
}
2320

2421
/**
@@ -29,55 +26,7 @@ public AsyncHttpClientImpl(long timeout) {
2926
* the API
3027
*/
3128
public CompletableFuture<String> get(String url) {
32-
33-
final CompletableFuture<String> responseFuture = new CompletableFuture<>();
34-
35-
StringBuilder chunks = new StringBuilder();
36-
37-
httpClient.prepareGet(url)
38-
.execute(new AsyncHandler<String>() {
39-
private Integer status;
40-
41-
@Override
42-
public State onStatusReceived(HttpResponseStatus responseStatus)
43-
throws Exception {
44-
int code = responseStatus.getStatusCode();
45-
if (code >= 200 && code < 300) {
46-
return State.CONTINUE;
47-
}
48-
throw new IOException("The request returned a bad status code.");
49-
}
50-
51-
@Override
52-
public State onHeadersReceived(HttpResponseHeaders headers)
53-
throws Exception {
54-
return State.CONTINUE;
55-
}
56-
57-
@Override
58-
public State onBodyPartReceived(HttpResponseBodyPart bodyPart)
59-
throws Exception {
60-
String chunk = new String(bodyPart.getBodyPartBytes()).trim();
61-
if (chunk.length() != 0) {
62-
chunks.append(chunk);
63-
}
64-
return State.CONTINUE;
65-
}
66-
67-
@Override
68-
public String onCompleted() throws Exception {
69-
String response = chunks.toString();
70-
responseFuture.complete(response);
71-
return response;
72-
}
73-
74-
@Override
75-
public void onThrowable(Throwable t) {
76-
responseFuture.completeExceptionally(t);
77-
}
78-
});
79-
80-
return responseFuture;
29+
return getStringCompletableFuture(url, httpClient);
8130
}
8231

8332
}
Lines changed: 8 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -1,72 +1,31 @@
11
package ai.evolv;
22

3-
import java.io.IOException;
43
import java.util.concurrent.CompletableFuture;
54
import java.util.concurrent.TimeUnit;
65

7-
import okhttp3.Call;
8-
import okhttp3.Callback;
9-
import okhttp3.ConnectionPool;
10-
import okhttp3.OkHttpClient;
11-
import okhttp3.Request;
12-
import okhttp3.Response;
13-
import okhttp3.ResponseBody;
14-
15-
public class OkHttpClientImpl implements HttpClient {
16-
17-
private final OkHttpClient client;
6+
@Deprecated
7+
public class OkHttpClientImpl extends ai.evolv.httpclients.OkHttpClient implements HttpClient {
188

199
/**
2010
* Initializes the OhHttp# client.
11+
*
2112
* @param timeout specify a request timeout for the client.
13+
*
14+
* @deprecated use {@link ai.evolv.httpclients.OkHttpClient} instead.
2215
*/
2316
public OkHttpClientImpl(long timeout) {
24-
this.client = new OkHttpClient.Builder()
25-
.callTimeout(timeout, TimeUnit.MILLISECONDS)
26-
.connectionPool(new ConnectionPool(3, 1000, TimeUnit.MILLISECONDS))
27-
.build();
17+
super(TimeUnit.MILLISECONDS, Math.toIntExact(timeout));
2818
}
2919

3020
/**
3121
* Performs a GET request with the given url using the client from
3222
* okhttp3.
23+
*
3324
* @param url a valid url representing a call to the Participant API.
3425
* @return a Completable future instance containing a response from
3526
* the API
3627
*/
3728
public CompletableFuture<String> get(String url) {
38-
CompletableFuture<String> responseFuture = new CompletableFuture<>();
39-
final Request request = new Request.Builder()
40-
.url(url)
41-
.build();
42-
43-
client.newCall(request).enqueue(new Callback() {
44-
@Override
45-
public void onFailure(Call call, IOException e) {
46-
responseFuture.completeExceptionally(e);
47-
}
48-
49-
@Override
50-
public void onResponse(Call call, Response response) {
51-
String body = "";
52-
try (ResponseBody responseBody = response.body()) {
53-
if (responseBody != null) {
54-
body = responseBody.string();
55-
}
56-
57-
if (!response.isSuccessful()) {
58-
throw new IOException(String.format("Unexpected response " +
59-
"when making GET request: %s using url: %s with body: %s",
60-
response, request.url(), body));
61-
}
62-
63-
responseFuture.complete(body);
64-
} catch (Exception e) {
65-
responseFuture.completeExceptionally(e);
66-
}
67-
}
68-
});
69-
70-
return responseFuture;
29+
return getStringCompletableFuture(url, httpClient);
7130
}
7231
}

0 commit comments

Comments
 (0)