private MyResult invokeCallbackString(String url) { Client client = newClient(); WebTarget target = client.target(url); final AsyncInvoker asyncInvoker = target.request().async(); final MyResult myResponse = new MyResult(); asyncInvoker.get(new InvocationCallback<String>() { @Override public void completed(String response) { myResponse.setResponse(response); myResponse.setOk(true); } @Override public void failed(Throwable arg0) { myResponse.setResponse(arg0.getMessage()); myResponse.setOk(false); } }); try { sleep(2000); } catch (InterruptedException e) { logger.log(SEVERE, "error", e); } return myResponse; }
private MyResult invokeCallbackResponse(String url) { Client client = newClient(); WebTarget target = client.target(url); final AsyncInvoker asyncInvoker = target.request().async(); final MyResult myResponse = new MyResult(); asyncInvoker.get(new InvocationCallback<Response>() { @Override public void completed(Response response) { myResponse.setResponse(response.readEntity(String.class)); myResponse.setOk(response.hasEntity()); } @Override public void failed(Throwable arg0) { myResponse.setResponse(arg0.getMessage()); myResponse.setOk(false); } }); try { sleep(2000); } catch (InterruptedException e) { logger.log(SEVERE, "error", e); } return myResponse; }
private static InvocationCallback<Response> responseInvocationCallback() { return new InvocationCallback<Response>() { @Override public void completed(Response res) { System.out.println("Status:" + res.getStatusInfo()); System.out.println("Entity:" + res.getEntity()); System.out.println("Request success!"); } @Override public void failed(Throwable e) { System.out.println("Request failed!"); } }; }
@Override public CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadataAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<PartitionedTopicMetadata> future = new CompletableFuture<>(); asyncGetRequest(persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("partitions"), new InvocationCallback<PartitionedTopicMetadata>() { @Override public void completed(PartitionedTopicMetadata response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<List<String>> getSubscriptionsAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<List<String>> future = new CompletableFuture<>(); asyncGetRequest(persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("subscriptions"), new InvocationCallback<List<String>>() { @Override public void completed(List<String> response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<PersistentTopicStats> getStatsAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<PersistentTopicStats> future = new CompletableFuture<>(); asyncGetRequest(persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("stats"), new InvocationCallback<PersistentTopicStats>() { @Override public void completed(PersistentTopicStats response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<PersistentTopicInternalStats> getInternalStatsAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<PersistentTopicInternalStats> future = new CompletableFuture<>(); asyncGetRequest(persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("internalStats"), new InvocationCallback<PersistentTopicInternalStats>() { @Override public void completed(PersistentTopicInternalStats response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<JsonObject> getInternalInfoAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<JsonObject> future = new CompletableFuture<>(); asyncGetRequest(persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("internal-info"), new InvocationCallback<String>() { @Override public void completed(String response) { JsonObject json = new Gson().fromJson(response, JsonObject.class); future.complete(json); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<PartitionedTopicStats> getPartitionedStatsAsync(String destination, boolean perPartition) { DestinationName ds = validateTopic(destination); final CompletableFuture<PartitionedTopicStats> future = new CompletableFuture<>(); asyncGetRequest( persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("partitioned-stats"), new InvocationCallback<PartitionedTopicStats>() { @Override public void completed(PartitionedTopicStats response) { if (!perPartition) { response.partitions.clear(); } future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
private CompletableFuture<List<Message>> peekNthMessage(String destination, String subName, int messagePosition) { DestinationName ds = validateTopic(destination); String encodedSubName = Codec.encode(subName); final CompletableFuture<List<Message>> future = new CompletableFuture<List<Message>>(); asyncGetRequest(persistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("subscription") .path(encodedSubName).path("position").path(String.valueOf(messagePosition)), new InvocationCallback<Response>() { @Override public void completed(Response response) { try { future.complete(getMessageFromHttpResponse(response)); } catch (Exception e) { future.completeExceptionally(getApiException(e)); } } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<PartitionedTopicMetadata> getPartitionedTopicMetadataAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<PartitionedTopicMetadata> future = new CompletableFuture<>(); asyncGetRequest(nonPersistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("partitions"), new InvocationCallback<PartitionedTopicMetadata>() { @Override public void completed(PartitionedTopicMetadata response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<NonPersistentTopicStats> getStatsAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<NonPersistentTopicStats> future = new CompletableFuture<>(); asyncGetRequest(nonPersistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("stats"), new InvocationCallback<NonPersistentTopicStats>() { @Override public void completed(NonPersistentTopicStats response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
@Override public CompletableFuture<PersistentTopicInternalStats> getInternalStatsAsync(String destination) { DestinationName ds = validateTopic(destination); final CompletableFuture<PersistentTopicInternalStats> future = new CompletableFuture<>(); asyncGetRequest(nonPersistentTopics.path(ds.getNamespace()).path(ds.getEncodedLocalName()).path("internalStats"), new InvocationCallback<PersistentTopicInternalStats>() { @Override public void completed(PersistentTopicInternalStats response) { future.complete(response); } @Override public void failed(Throwable throwable) { future.completeExceptionally(getApiException(throwable.getCause())); } }); return future; }
public <T> CompletableFuture<Void> asyncPutRequest(final WebTarget target, Entity<T> entity) { final CompletableFuture<Void> future = new CompletableFuture<>(); try { request(target).async().put(entity, new InvocationCallback<ErrorData>() { @Override public void completed(ErrorData response) { future.complete(null); } @Override public void failed(Throwable throwable) { log.warn("[{}] Failed to perform http put request: {}", target.getUri(), throwable.getMessage()); future.completeExceptionally(getApiException(throwable.getCause())); } }); } catch (PulsarAdminException cae) { future.completeExceptionally(cae); } return future; }
public <T> CompletableFuture<Void> asyncPostRequest(final WebTarget target, Entity<T> entity) { final CompletableFuture<Void> future = new CompletableFuture<>(); try { request(target).async().post(entity, new InvocationCallback<ErrorData>() { @Override public void completed(ErrorData response) { future.complete(null); } @Override public void failed(Throwable throwable) { log.warn("[{}] Failed to perform http post request: {}", target.getUri(), throwable.getMessage()); future.completeExceptionally(getApiException(throwable.getCause())); } }); } catch (PulsarAdminException cae) { future.completeExceptionally(cae); } return future; }
public CompletableFuture<Void> asyncDeleteRequest(final WebTarget target) { final CompletableFuture<Void> future = new CompletableFuture<>(); try { request(target).async().delete(new InvocationCallback<ErrorData>() { @Override public void completed(ErrorData response) { future.complete(null); } @Override public void failed(Throwable throwable) { log.warn("[{}] Failed to perform http delete request: {}", target.getUri(), throwable.getMessage()); future.completeExceptionally(getApiException(throwable.getCause())); } }); } catch (PulsarAdminException cae) { future.completeExceptionally(cae); } return future; }
public void reloadUserDocs() { logger.debug("reloading docs by user!"); if (user != null) { conn.getAllDocsByUserAsync(0, 0, null, null, new InvocationCallback<List<TrpDocMetadata>>() { @Override public void failed(Throwable throwable) { logger.error("Error loading documents by user "+user+" - "+throwable.getMessage(), throwable); } @Override public void completed(List<TrpDocMetadata> response) { logger.debug("loaded docs by user "+user+" - "+response.size()+" thread: "+Thread.currentThread().getName()); synchronized (this) { userDocList.clear(); userDocList.addAll(response); sendEvent(new DocListLoadEvent(this, 0, userDocList, true)); } } }); } else { synchronized (this) { userDocList.clear(); sendEvent(new DocListLoadEvent(this, 0, userDocList, true)); } } }
public CompletableFuture<T> get(final String url) { CompletableFuture<T> result = new CompletableFuture(); client.target(url).request(accept).accept(accept).async() .get(new InvocationCallback<String>() { @Override public void completed(String complete) { buildResponse(result, complete); } @Override public void failed(Throwable ex) { result.completeExceptionally(ex); } }); return result; }
public <V> CompletableFuture<T> post(final String queryResourceUrl, final V request) { CompletableFuture<T> result = new CompletableFuture(); final WebTarget webResource = client.target(queryResourceUrl); webResource .request(accept) .accept(accept) .async() .post(Entity.entity(request, contentType), new InvocationCallback<String>() { @Override public void completed(String complete) { buildResponse(result,complete); } @Override public void failed(Throwable ex) { result.completeExceptionally(ex); } }); return result; }
public <V> CompletableFuture<T> put(final String queryResourceUrl, final V request) { CompletableFuture<T> result = new CompletableFuture<>(); final WebTarget webResource = client.target(queryResourceUrl); webResource .request(accept) .accept(accept) .async() .put(Entity.entity(request, contentType), new InvocationCallback<String>() { @Override public void completed(String complete) { buildResponse(result,complete); } @Override public void failed(Throwable ex) { result.completeExceptionally(ex); } }); return result; }
public CompletableFuture<T> delete(final String queryResourceUrl) { CompletableFuture<T> result = new CompletableFuture<>(); final WebTarget webResource = client.target(queryResourceUrl); webResource .request(accept) .accept(accept) .async() .delete(new InvocationCallback<String>() { @Override public void completed(String complete) { buildResponse(result,complete); } @Override public void failed(Throwable ex) { result.completeExceptionally(ex); } }); return result; }
@Test public void simpleTest() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/simpleTest"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .get( new InvocationCallback<String>() { @Override public void completed(String response) { System.out.println("Response entity '" + response + "' received."); vertx.runOnContext((e) -> assertEquals(response, "test exception")); latch.countDown(); } @Override public void failed(Throwable throwable) {} }); latch.await(); testComplete(); }
@Test public void simpleRetryTest() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/simpleRetryTest"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .get( new InvocationCallback<String>() { @Override public void completed(String response) { System.out.println("Response entity '" + response + "' received."); vertx.runOnContext((e) -> assertEquals(response, "test exception")); latch.countDown(); } @Override public void failed(Throwable throwable) {} }); latch.await(); testComplete(); }
@Test public void simpleTimeoutTest() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/simpleTimeoutTest"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .get( new InvocationCallback<String>() { @Override public void completed(String response) { System.out.println("Response entity '" + response + "' received."); vertx.runOnContext((e) -> assertEquals(response, "operation _timeout")); latch.countDown(); } @Override public void failed(Throwable throwable) {} }); latch.await(); testComplete(); }
@Test public void simpleTimeoutWithRetryTest() throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/simpleTimeoutWithRetryTest"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .get( new InvocationCallback<String>() { @Override public void completed(String response) { System.out.println("Response entity '" + response + "' received."); vertx.runOnContext((e) -> assertEquals(response, "operation _timeout")); latch.countDown(); } @Override public void failed(Throwable throwable) {} }); latch.await(); testComplete(); }
@Test public void stringPOST() throws InterruptedException, ExecutionException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/stringPOST"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .post( Entity.entity("hello", MediaType.APPLICATION_JSON_TYPE), new InvocationCallback<String>() { @Override public void completed(String response) { latch.countDown(); } @Override public void failed(Throwable throwable) {} }) .get(); latch.await(); testComplete(); }
@Test public void stringOPTIONSResponse() throws InterruptedException, ExecutionException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/stringOPTIONSResponse"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .options( new InvocationCallback<String>() { @Override public void completed(String response) { System.out.println("Response entity '" + response + "' received."); Assert.assertEquals(response, "hello"); latch.countDown(); } @Override public void failed(Throwable throwable) {} }) .get(); latch.await(); testComplete(); }
@Test public void stringDELETEResponse() throws InterruptedException, ExecutionException { CountDownLatch latch = new CountDownLatch(1); Client client = ClientBuilder.newClient(); WebTarget target = client.target("http://" + HOST + ":" + PORT).path("/wsService/stringDELETEResponse"); target .request(MediaType.APPLICATION_JSON_TYPE) .async() .delete( new InvocationCallback<String>() { @Override public void completed(String response) { System.out.println("Response entity '" + response + "' received."); Assert.assertEquals(response, "hello"); latch.countDown(); } @Override public void failed(Throwable throwable) {} }) .get(); latch.await(); testComplete(); }
private void RESTDeliveryMethod(WebTarget r, SensorDataSaveRequest saveRequest) { try { r.request(MediaType.APPLICATION_JSON).async() .post( Entity.entity(saveRequest, MediaType.APPLICATION_JSON), new InvocationCallback<Response>() { @Override public void completed(Response response) { // TODO Auto-generated method stub System.out.println("Status: " + response.getStatus()); } @Override public void failed(Throwable throwable) { // TODO Auto-generated method stub System.out.println("Error message: " + throwable.getMessage()); }}); } catch (Exception e) { } }
public void askForUptime(String pingUri, Consumer<String> sink, Consumer<String> errorSink, Runnable doneListener) { this.client.target(pingUri).path(START_TIME).request().accept(MediaType.TEXT_PLAIN).async().get(new InvocationCallback<String>() { @Override public void completed(String rspns) { sink.accept(rspns); doneListener.run(); } @Override public void failed(Throwable thrwbl) { errorSink.accept(thrwbl.getMessage()); doneListener.run(); } }); }
public void askForMemory(String pingUri, Consumer<Double> availableProperty, Consumer<Double> usedProperty, Consumer<String> errorSink, Runnable doneListener) { this.client.target(pingUri).path(MEMORY).request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback<JsonObject>() { @Override public void completed(JsonObject rspns) { System.out.println("Response: " + rspns); double available = rspns.getJsonNumber("Available memory in mb").doubleValue(); double used = rspns.getJsonNumber("Used memory in mb").doubleValue(); availableProperty.accept(available); usedProperty.accept(used); doneListener.run(); } @Override public void failed(Throwable thrwbl) { errorSink.accept(thrwbl.getMessage()); doneListener.run(); } }); }
public void askForOSInfo(String pingUri, Consumer<Double> loadAverage, Consumer<Integer> numberOfCores, Consumer<String> errorSink, Runnable doneListener) { this.client.target(pingUri).path(OS).request().accept(MediaType.APPLICATION_JSON).async().get(new InvocationCallback<JsonObject>() { @Override public void completed(JsonObject rspns) { System.out.println("Response: " + rspns); double load = rspns.getJsonNumber("System Load Average").doubleValue(); int cores = rspns.getJsonNumber("Available CPUs").intValue(); loadAverage.accept(load); numberOfCores.accept(cores); doneListener.run(); } @Override public void failed(Throwable thrwbl) { errorSink.accept(thrwbl.getMessage()); doneListener.run(); } }); }
public void ping(String pingUri, Consumer<Long> responseTime, Consumer<String> errorSink, Runnable doneListener) { long startTime = System.currentTimeMillis(); this.client.target(pingUri).path(PING).path(String.valueOf(startTime)). request().async(). get( new InvocationCallback<String>() { @Override public void completed(String rspns) { responseTime.accept(System.currentTimeMillis() - startTime); doneListener.run(); System.out.println("Response: " + rspns); } @Override public void failed(Throwable thrwbl) { errorSink.accept(thrwbl.getMessage()); doneListener.run(); } }); }
/** * You can also register a +InvocationCallback+ and get a callback when the +Request+ is done. */ @Test public void testInvocationCallback() throws InterruptedException, ExecutionException { target.request().async().get(new InvocationCallback<String>() { // <1> Build an asynchronous request callback for the body of the +Response+ @Override public void completed(String r) { // <2> Called when the +Request+ is completed and our entiy parsed assertEquals("apple", r); } @Override public void failed(Throwable t) { // <3> Called if the +Request+ failed to complete fail(t.getMessage()); } }); }
@Override public ListenableFuture<RequestVoteResponse> requestVote(RequestVote request) { final SettableFuture<RequestVoteResponse> result = SettableFuture.create(); client.target(baseUri).path("/raft/vote") .request().async() .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE), new InvocationCallback<Response>() { @Override public void completed(Response response) { result.set(response.readEntity(RequestVoteResponse.class)); } @Override public void failed(Throwable throwable) { result.setException(throwable); } }); return result; }
@Override public ListenableFuture<AppendEntriesResponse> appendEntries(AppendEntries request) { final SettableFuture<AppendEntriesResponse> result = SettableFuture.create(); client.target(baseUri).path("/raft/entries") .request().async() .post(Entity.entity(request, MediaType.APPLICATION_JSON_TYPE), new InvocationCallback<Response>() { @Override public void completed(Response response) { result.set(response.readEntity(AppendEntriesResponse.class)); } @Override public void failed(Throwable throwable) { result.setException(throwable); } }); return result; }