Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reuse http client #62

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions src/main/java/nl/martijndwars/webpush/PushService.java
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,11 @@ public class PushService {
*/
private PrivateKey privateKey;

/**
* Http client
*/
private CloseableHttpAsyncClient closeableHttpAsyncClient;

public PushService() {
}

Expand Down Expand Up @@ -115,10 +120,15 @@ public static Encrypted encrypt(byte[] buffer, PublicKey userPublicKey, byte[] u
* @throws InterruptedException
*/
public HttpResponse send(Notification notification) throws GeneralSecurityException, IOException, JoseException, ExecutionException, InterruptedException {
try {
return sendAsync(notification).get();
} catch (ExecutionException e) {
destroyClient();
throw e;
}
}

/**
/**
* Send a notification, but don't wait for the response.
*
* @param notification
Expand All @@ -129,14 +139,10 @@ public HttpResponse send(Notification notification) throws GeneralSecurityExcept
*/
public Future<HttpResponse> sendAsync(Notification notification) throws GeneralSecurityException, IOException, JoseException {
HttpPost httpPost = preparePost(notification);

final CloseableHttpAsyncClient closeableHttpAsyncClient = HttpAsyncClients.createSystem();
closeableHttpAsyncClient.start();

return closeableHttpAsyncClient.execute(httpPost, new ClosableCallback(closeableHttpAsyncClient));
return getClient().execute(httpPost, new ClosableCallback(closeableHttpAsyncClient));
}

/**
/**
* Prepare a HttpPost for Apache async http client
*
* @param notification
Expand Down Expand Up @@ -325,4 +331,20 @@ public PushService setPrivateKey(PrivateKey privateKey) {
protected boolean vapidEnabled() {
return publicKey != null && privateKey != null;
}

private CloseableHttpAsyncClient getClient() {
if(closeableHttpAsyncClient == null) {
closeableHttpAsyncClient = HttpAsyncClients.createSystem();
closeableHttpAsyncClient.start();
}
return closeableHttpAsyncClient;
}

private void destroyClient() throws IOException {
try {
getClient().close();
} finally {
closeableHttpAsyncClient = null;
}
}
}