diff --git a/src/main/java/nl/martijndwars/webpush/PushService.java b/src/main/java/nl/martijndwars/webpush/PushService.java index f47c4b7..d330933 100644 --- a/src/main/java/nl/martijndwars/webpush/PushService.java +++ b/src/main/java/nl/martijndwars/webpush/PushService.java @@ -50,6 +50,11 @@ public class PushService { */ private PrivateKey privateKey; + /** + * Http client + */ + private CloseableHttpAsyncClient closeableHttpAsyncClient; + public PushService() { } @@ -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 @@ -129,14 +139,10 @@ public HttpResponse send(Notification notification) throws GeneralSecurityExcept */ public Future 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 @@ -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; + } + } }