use of javax.ws.rs.container.AsyncResponse in project jersey by jersey.
the class AsyncTimeoutResource method setTimeOut.
@POST
@Path("timeout")
public void setTimeOut(final Integer millis) throws InterruptedException {
final AsyncResponse asyncResponse = queue.take();
final boolean timeout1 = asyncResponse.setTimeout(millis, TimeUnit.MILLISECONDS);
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(final AsyncResponse asyncResponse) {
final boolean timeout2 = asyncResponse.setTimeout(millis, TimeUnit.MILLISECONDS);
asyncResponse.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(final AsyncResponse asyncResponse) {
asyncResponse.resume("timeout1=" + timeout1 + "_timeout2=" + timeout2 + "_handled");
asyncResponse.cancel();
}
});
}
});
}
use of javax.ws.rs.container.AsyncResponse in project pulsar by yahoo.
the class DestinationLookup method lookupDestinationAsync.
@GET
@Path("persistent/{property}/{cluster}/{namespace}/{dest}")
@Produces(MediaType.APPLICATION_JSON)
public void lookupDestinationAsync(@PathParam("property") String property, @PathParam("cluster") String cluster, @PathParam("namespace") String namespace, @PathParam("dest") @Encoded String dest, @QueryParam("authoritative") @DefaultValue("false") boolean authoritative, @Suspended AsyncResponse asyncResponse) {
dest = Codec.decode(dest);
DestinationName topic = DestinationName.get("persistent", property, cluster, namespace, dest);
if (!pulsar().getBrokerService().getLookupRequestSemaphore().tryAcquire()) {
log.warn("No broker was found available for topic {}", topic);
asyncResponse.resume(new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
return;
}
try {
validateClusterOwnership(topic.getCluster());
checkConnect(topic);
validateReplicationSettingsOnNamespace(pulsar(), topic.getNamespaceObject());
} catch (WebApplicationException we) {
// Validation checks failed
log.error("Validation check failed: {}", we.getMessage());
completeLookupResponseExceptionally(asyncResponse, we);
return;
} catch (Throwable t) {
// Validation checks failed with unknown error
log.error("Validation check failed: {}", t.getMessage(), t);
completeLookupResponseExceptionally(asyncResponse, new RestException(t));
return;
}
CompletableFuture<LookupResult> lookupFuture = pulsar().getNamespaceService().getBrokerServiceUrlAsync(topic, authoritative);
lookupFuture.thenAccept(result -> {
if (result == null) {
log.warn("No broker was found available for topic {}", topic);
completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.Status.SERVICE_UNAVAILABLE));
return;
}
if (result.isRedirect()) {
boolean newAuthoritative = this.isLeaderBroker();
URI redirect;
try {
String redirectUrl = isRequestHttps() ? result.getLookupData().getHttpUrlTls() : result.getLookupData().getHttpUrl();
redirect = new URI(String.format("%s%s%s?authoritative=%s", redirectUrl, "/lookup/v2/destination/", topic.getLookupName(), newAuthoritative));
} catch (URISyntaxException e) {
log.error("Error in preparing redirect url for {}: {}", topic, e.getMessage(), e);
completeLookupResponseExceptionally(asyncResponse, e);
return;
}
if (log.isDebugEnabled()) {
log.debug("Redirect lookup for topic {} to {}", topic, redirect);
}
completeLookupResponseExceptionally(asyncResponse, new WebApplicationException(Response.temporaryRedirect(redirect).build()));
} else {
if (log.isDebugEnabled()) {
log.debug("Lookup succeeded for topic {} -- broker: {}", topic, result.getLookupData());
}
completeLookupResponseSuccessfully(asyncResponse, result.getLookupData());
}
}).exceptionally(exception -> {
log.warn("Failed to lookup broker for topic {}: {}", topic, exception.getMessage(), exception);
completeLookupResponseExceptionally(asyncResponse, exception);
return null;
});
}
use of javax.ws.rs.container.AsyncResponse in project pulsar by yahoo.
the class HttpDestinationLookupv2Test method testNotEnoughLookupPermits.
@Test
public void testNotEnoughLookupPermits() throws Exception {
BrokerService brokerService = pulsar.getBrokerService();
doReturn(new Semaphore(0)).when(brokerService).getLookupRequestSemaphore();
DestinationLookup destLookup = spy(new DestinationLookup());
doReturn(false).when(destLookup).isRequestHttps();
destLookup.setPulsar(pulsar);
doReturn("null").when(destLookup).clientAppId();
Field uriField = PulsarWebResource.class.getDeclaredField("uri");
uriField.setAccessible(true);
UriInfo uriInfo = mock(UriInfo.class);
uriField.set(destLookup, uriInfo);
URI uri = URI.create("http://localhost:8080/lookup/v2/destination/topic/myprop/usc/ns2/topic1");
doReturn(uri).when(uriInfo).getRequestUri();
doReturn(true).when(config).isAuthorizationEnabled();
AsyncResponse asyncResponse1 = mock(AsyncResponse.class);
destLookup.lookupDestinationAsync("myprop", "usc", "ns2", "topic1", false, asyncResponse1);
ArgumentCaptor<Throwable> arg = ArgumentCaptor.forClass(Throwable.class);
verify(asyncResponse1).resume(arg.capture());
assertEquals(arg.getValue().getClass(), WebApplicationException.class);
WebApplicationException wae = (WebApplicationException) arg.getValue();
assertEquals(wae.getResponse().getStatus(), Status.SERVICE_UNAVAILABLE.getStatusCode());
}
use of javax.ws.rs.container.AsyncResponse in project bisq-api by mrosseel.
the class OfferResource method takeOffer.
@ApiOperation(value = "Take offer", response = TradeDetails.class)
@POST
@Path("/{id}/take")
public void takeOffer(@Suspended final AsyncResponse asyncResponse, @PathParam("id") String id, @Valid TakeOffer data) {
// TODO how do we go about not blocking this REST thread?
final CompletableFuture<Trade> completableFuture = bisqProxy.offerTake(id, data.paymentAccountId, data.amount, true);
completableFuture.thenApply(trade -> asyncResponse.resume(new TradeDetails(trade))).exceptionally(e -> {
final Throwable cause = e.getCause();
final Response.ResponseBuilder responseBuilder;
if (cause instanceof ValidationException) {
final int status = 422;
responseBuilder = toValidationErrorResponse(cause, status);
} else if (cause instanceof IncompatiblePaymentAccountException) {
responseBuilder = toValidationErrorResponse(cause, 423);
} else if (cause instanceof NoAcceptedArbitratorException) {
responseBuilder = toValidationErrorResponse(cause, 424);
} else if (cause instanceof PaymentAccountNotFoundException) {
responseBuilder = toValidationErrorResponse(cause, 425);
} else if (cause instanceof InsufficientMoneyException) {
responseBuilder = toValidationErrorResponse(cause, 427);
} else if (cause instanceof NotFoundException) {
responseBuilder = toValidationErrorResponse(cause, 404);
} else {
final String message = cause.getMessage();
responseBuilder = Response.status(500);
if (null != message)
responseBuilder.entity(new ValidationErrorMessage(ImmutableList.of(message)));
log.error("Unable to take offer: " + id + " " + Json.pretty(data), cause);
}
return asyncResponse.resume(responseBuilder.build());
});
}
use of javax.ws.rs.container.AsyncResponse in project cxf by apache.
the class AsyncResource method takeAsyncResponse.
protected static AsyncResponse takeAsyncResponse(int stageId) {
AsyncResponse asyncResponse = null;
asyncResponse = ASYNC_RESPONSES[stageId].take();
return asyncResponse;
}
Aggregations