use of javax.ws.rs.container.AsyncResponse in project presto by prestodb.
the class ResourceManagerProxy method performRequest.
public void performRequest(HttpServletRequest servletRequest, AsyncResponse asyncResponse, URI remoteUri) {
try {
BodyGenerator bodyGenerator = new InputStreamBodyGenerator(servletRequest.getInputStream());
Request request = createRequest(servletRequest, servletRequest.getMethod(), remoteUri, bodyGenerator);
ListenableFuture<ProxyResponse> proxyResponse = httpClient.executeAsync(request, new ResponseHandler());
ListenableFuture<Response> future = transform(proxyResponse, this::toResponse, executor);
setupAsyncResponse(servletRequest, asyncResponse, future);
} catch (IOException e) {
asyncResponse.resume(e);
}
}
use of javax.ws.rs.container.AsyncResponse in project javaee7-samples by javaee-samples.
the class MyResource method getList.
// @Resource(name = "DefaultManagedThreadFactory")
// ManagedThreadFactory threadFactory;
@GET
public void getList(@Suspended final AsyncResponse ar) throws NamingException {
ar.setTimeoutHandler(new TimeoutHandler() {
@Override
public void handleTimeout(AsyncResponse ar) {
ar.resume("Operation timed out");
}
});
ar.setTimeout(4000, TimeUnit.MILLISECONDS);
ar.register(new MyCompletionCallback());
ar.register(new MyConnectionCallback());
ManagedThreadFactory threadFactory = (ManagedThreadFactory) new InitialContext().lookup("java:comp/DefaultManagedThreadFactory");
Executors.newSingleThreadExecutor(threadFactory).submit(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
ar.resume(response[0]);
} catch (InterruptedException ex) {
}
}
});
}
use of javax.ws.rs.container.AsyncResponse in project bisq-api by mrosseel.
the class OfferResource method createOffer.
@ApiOperation(value = "Create offer", response = OfferDetail.class)
@POST
public void createOffer(@Suspended final AsyncResponse asyncResponse, @Valid OfferToCreate offer) {
final OfferPayload.Direction direction = OfferPayload.Direction.valueOf(offer.direction);
final PriceType priceType = PriceType.valueOf(offer.priceType);
final Double marketPriceMargin = null == offer.percentageFromMarketPrice ? null : offer.percentageFromMarketPrice.doubleValue();
final CompletableFuture<Offer> completableFuture = bisqProxy.offerMake(offer.fundUsingBisqWallet, offer.offerId, offer.accountId, direction, offer.amount, offer.minAmount, PriceType.PERCENTAGE.equals(priceType), marketPriceMargin, offer.marketPair, offer.fixedPrice, offer.buyerSecurityDeposit);
completableFuture.thenApply(response -> asyncResponse.resume(new OfferDetail(response))).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 AmountTooHighException) {
responseBuilder = toValidationErrorResponse(cause, 426);
} else if (cause instanceof InsufficientMoneyException) {
responseBuilder = toValidationErrorResponse(cause, 427);
} else {
final String message = cause.getMessage();
responseBuilder = Response.status(500);
if (null != message)
responseBuilder.entity(new ValidationErrorMessage(ImmutableList.of(message)));
log.error("Unable to create offer: " + Json.pretty(offer), cause);
}
return asyncResponse.resume(responseBuilder.build());
});
}
use of javax.ws.rs.container.AsyncResponse in project pravega by pravega.
the class StreamMetadataResourceImpl method listScopes.
/**
* Implementation of listScopes REST API.
*
* @param securityContext The security for API access.
* @param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
*/
@Override
public void listScopes(final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "listScopes");
long requestId = requestIdGenerator.nextLong();
final Principal principal;
final List<String> authHeader = getAuthorizationHeader();
try {
principal = restAuthHelper.authenticate(authHeader);
restAuthHelper.authorize(authHeader, authorizationResource.ofScopes(), principal, READ);
} catch (AuthException e) {
log.warn(requestId, "Get scopes failed due to authentication failure.", e);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return;
}
controllerService.listScopes(requestId).thenApply(scopesList -> {
ScopesList scopes = new ScopesList();
scopesList.forEach(scope -> {
try {
if (restAuthHelper.isAuthorized(authHeader, authorizationResource.ofScope(scope), principal, READ)) {
scopes.addScopesItem(new ScopeProperty().scopeName(scope));
}
} catch (AuthException e) {
log.warn(requestId, e.getMessage(), e);
// Ignore. This exception occurs under abnormal circumstances and not to determine
// whether the user is authorized. In case it does occur, we assume that the user
// is unauthorized.
}
});
return Response.status(Status.OK).entity(scopes).build();
}).exceptionally(exception -> {
log.warn(requestId, "listScopes failed with exception: ", exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}).thenApply(response -> {
asyncResponse.resume(response);
LoggerHelpers.traceLeave(log, "listScopes", traceId);
return response;
});
}
use of javax.ws.rs.container.AsyncResponse in project pravega by pravega.
the class StreamMetadataResourceImpl method updateStream.
/**
* Implementation of updateStream REST API.
*
* @param scopeName The scope name of stream.
* @param streamName The name of stream.
* @param updateStreamRequest The object conforming to updateStreamConfig request json.
* @param securityContext The security for API access.
* @param asyncResponse AsyncResponse provides means for asynchronous server side response processing.
*/
@Override
public void updateStream(final String scopeName, final String streamName, final UpdateStreamRequest updateStreamRequest, final SecurityContext securityContext, final AsyncResponse asyncResponse) {
long traceId = LoggerHelpers.traceEnter(log, "updateStream");
long requestId = requestIdGenerator.nextLong();
try {
restAuthHelper.authenticateAuthorize(getAuthorizationHeader(), authorizationResource.ofStreamInScope(scopeName, streamName), READ_UPDATE);
} catch (AuthException e) {
log.warn(requestId, "Update stream for {} failed due to authentication failure.", scopeName + "/" + streamName);
asyncResponse.resume(Response.status(Status.fromStatusCode(e.getResponseCode())).build());
LoggerHelpers.traceLeave(log, "Update stream", traceId);
return;
}
StreamConfiguration streamConfiguration = ModelHelper.getUpdateStreamConfig(updateStreamRequest);
controllerService.updateStream(scopeName, streamName, streamConfiguration, requestId).thenApply(streamStatus -> {
if (streamStatus.getStatus() == UpdateStreamStatus.Status.SUCCESS) {
log.info(requestId, "Successfully updated stream config for: {}/{}", scopeName, streamName);
return Response.status(Status.OK).entity(ModelHelper.encodeStreamResponse(scopeName, streamName, streamConfiguration)).build();
} else if (streamStatus.getStatus() == UpdateStreamStatus.Status.STREAM_NOT_FOUND || streamStatus.getStatus() == UpdateStreamStatus.Status.SCOPE_NOT_FOUND) {
log.warn(requestId, "Stream: {}/{} not found", scopeName, streamName);
return Response.status(Status.NOT_FOUND).build();
} else {
log.warn(requestId, "updateStream failed for {}/{}", scopeName, streamName);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}
}).exceptionally(exception -> {
log.warn(requestId, "updateStream for {}/{} failed with exception: {}", scopeName, streamName, exception);
return Response.status(Status.INTERNAL_SERVER_ERROR).build();
}).thenApply(asyncResponse::resume).thenAccept(x -> LoggerHelpers.traceLeave(log, "updateStream", traceId));
}
Aggregations