@GET @Path("{queryId}/{token}") @Produces(MediaType.APPLICATION_JSON) public void getQueryResults( @PathParam("queryId") QueryId queryId, @PathParam("token") long token, @QueryParam("maxWait") Duration maxWait, @QueryParam("targetResultSize") DataSize targetResultSize, @HeaderParam(X_FORWARDED_PROTO) String proto, @Context UriInfo uriInfo, @Suspended AsyncResponse asyncResponse) { Query query = queries.get(queryId); if (query == null) { asyncResponse.resume(Response.status(Status.NOT_FOUND).build()); return; } if (isNullOrEmpty(proto)) { proto = uriInfo.getRequestUri().getScheme(); } asyncQueryResults(query, OptionalLong.of(token), maxWait, targetResultSize, uriInfo, proto, asyncResponse); }
@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) { } } }); }
@GET @Path("test") public void test(final @Suspended AsyncResponse response) { response.setTimeout(5000, TimeUnit.MILLISECONDS); Thread t = new Thread() { @Override public void run() { try { LOG.info("TestResource: async thread started"); Thread.sleep(10000); Response jaxrs = Response.ok("test").type(MediaType.TEXT_PLAIN).build(); response.resume(jaxrs); LOG.info("TestResource: async thread finished"); } catch (Exception e) { LOG.error(e.getMessage(), e); } } }; t.start(); }
@GET @Path("{taskId}/results/{bufferId}/{token}") @Produces(PRESTO_PAGES) public void getResults( @PathParam("taskId") TaskId taskId, @PathParam("bufferId") OutputBufferId bufferId, @PathParam("token") final long token, @HeaderParam(PRESTO_MAX_SIZE) DataSize maxSize, @Suspended AsyncResponse asyncResponse) return Response.status(status) .entity(entity) .header(PRESTO_TASK_INSTANCE_ID, result.getTaskInstanceId()) .header(PRESTO_PAGE_TOKEN, result.getToken()) .header(PRESTO_PAGE_NEXT_TOKEN, result.getNextToken()) .header(PRESTO_BUFFER_COMPLETE, result.isBufferComplete()) bindAsyncResponse(asyncResponse, responseFuture, responseExecutor) .withTimeout(timeout, Response.status(Status.NO_CONTENT) .header(PRESTO_TASK_INSTANCE_ID, taskManager.getTaskInstanceId(taskId)) .header(PRESTO_PAGE_TOKEN, token) asyncResponse.register((CompletionCallback) throwable -> resultsRequestTime.add(Duration.nanosSince(start)));
@GET @Path("/{subject}/subscribers/{id}") @Produces(MediaType.TEXT_PLAIN) public void nextSession(@PathParam("subject") String subject, @PathParam("id") String id, @Context EventManager events, @Suspended AsyncResponse response) { EventLog<Consumer<String>, String> eventLog = events.getEventLog(ClusterEventService.class, getEventLogName(subject, id)); if (eventLog == null) { LOGGER.warn("Unknown subscriber {}", id); response.resume(Response.status(Status.NOT_FOUND).build()); return; } eventLog.nextEvent().whenComplete((event, error) -> { if (error == null) { response.resume(Response.ok(event).build()); } else { LOGGER.warn("Subscriber {} closed", id); response.resume(Response.noContent().build()); } }); }
@POST @Path("/{name}/clear") public void clear( @PathParam("name") String name, @Suspended AsyncResponse response) { getPrimitive(name).thenCompose(map -> map.clear()).whenComplete((result, error) -> { if (error == null) { response.resume(Response.noContent().build()); } else { LOGGER.warn("{}", error); response.resume(Response.serverError().build()); } }); }
@GET @Path("/setTimeOut") public String setTimeOut() { boolean setTimeout = asyncResponse.setTimeout(2, TimeUnit.SECONDS); return String.valueOf(setTimeout); }
@GET @ManagedAsync public void longGet(@Suspended final AsyncResponse ar, @QueryParam("id") int requestId) { try { Thread.sleep(SLEEP_TIME_IN_MILLIS); } catch (InterruptedException ex) { LOGGER.log(Level.SEVERE, "Response processing interrupted", ex); } ar.resume(requestId + " - " + NOTIFICATION_RESPONSE); } }
public static void setTimeout(long timeout, AsyncResponse asyncResponse) { asyncResponse.setTimeout(timeout, TimeUnit.MILLISECONDS); asyncResponse.setTimeoutHandler(resp -> resp.resume( Response.status(Response.Status.GATEWAY_TIMEOUT) .entity("HTTP GET timed out after " + timeout + " ms\n") .build())); }
@Override public void importBot(InputStream zippedBotConfigFiles, AsyncResponse response) { try { response.setTimeout(60, TimeUnit.SECONDS); File targetDir = new File(FileUtilities.buildPath(tmpPath.toString(), UUID.randomUUID().toString())); this.zipArchive.unzip(zippedBotConfigFiles, targetDir); String targetDirPath = targetDir.getPath(); Files.newDirectoryStream(Paths.get(targetDirPath), path -> path.toString().endsWith(BOT_FILE_ENDING)) .forEach(botFilePath -> { try { String botFileString = readFile(botFilePath); BotConfiguration botConfiguration = jsonSerialization.deserialize(botFileString, BotConfiguration.class); botConfiguration.getPackages().forEach(packageUri -> parsePackage(targetDirPath, packageUri, botConfiguration, response)); URI newBotUri = createNewBot(botConfiguration); updateDocumentDescriptor(Paths.get(targetDirPath), buildOldBotUri(botFilePath), newBotUri); response.resume(Response.ok().location(newBotUri).build()); } catch (IOException | RestInterfaceFactory.RestInterfaceFactoryException e) { log.error(e.getLocalizedMessage(), e); response.resume(new InternalServerErrorException()); } }); } catch (IOException e) { log.error(e.getLocalizedMessage(), e); response.resume(new InternalServerErrorException()); } }
@POST @Path("bid/{exchangeId}/{key}") public void handleBid(@PathParam("exchangeId") final String exchangeId, @PathParam("key") final String key, final OrtbBidRequest request, @Suspended final AsyncResponse asyncResponse) throws FilterException, IOException { // Timeout for clarity. asyncResponse.setTimeout(timeoutMs, TimeUnit.MILLISECONDS); asyncResponse.setTimeoutHandler(timeoutHandler); // Sending no data as an example asyncResponse.resume(Response.noContent().build()); }
logger.warn("DeviceCommand wait request failed. BAD REQUEST: Command with id = {} was not sent for device with id = {}", commandId, deviceId); asyncResponse.resume(ResponseFactory.response(BAD_REQUEST)); return; if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response( OK, com, future.thenAccept(pair -> { final DeviceCommand deviceCommand = pair.getRight(); if (!asyncResponse.isDone() && deviceCommand.getIsUpdated()) { asyncResponse.resume(ResponseFactory.response( OK, deviceCommand, asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause asyncResponse.setTimeout(timeout, TimeUnit.SECONDS); asyncResponse.register((CompletionCallback) throwable -> { try { commandService.sendUnsubscribeRequest(Collections.singleton(future.get().getLeft())); } catch (InterruptedException | ExecutionException e) { if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response(INTERNAL_SERVER_ERROR)); if (!asyncResponse.isDone()) {
@GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public void list(@Suspended final AsyncResponse asyncResponse) { asyncResponse.setTimeout(10, TimeUnit.SECONDS); executorService.submit(() -> { List<Product> res = super.listProducts(); Product[] arr = res.toArray(new Product[res.size()]); asyncResponse.resume(arr); }); }
@Override public void run() { try { Thread.sleep(SLEEP_TIME_IN_MILLIS); } catch (InterruptedException ex) { LOGGER.log(Level.SEVERE, "Response processing interrupted", ex); } ar.resume("Complex result for " + query); } });
asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(ResponseFactory.response(Response.Status.NO_CONTENT))); asyncResponse.resume(ResponseFactory.response(BAD_REQUEST)); return; asyncResponse.resume(ResponseFactory.response(NOT_FOUND)); return; logger.warn("DeviceCommand wait request failed. NOT FOUND: No command found with id = {} for deviceId = {}", commandId, deviceId); asyncResponse.resume(ResponseFactory.response(Response.Status.NO_CONTENT)); } else { waitForCommand(device, commandId, timeout, command.get(), asyncResponse);
@Path("/callback") public class AsyncCallback { @POST @Consumes(MediaType.APPLICATION_JSON) public void postWithAsync(@Suspended AsyncResponse asyncResponse, SomeObject object) { asyncResponse.register(new CompletionCallback() { @Override public void onComplete(Throwable error) { if (error == null) { System.out.println("Processing new Request"); } else { System.out.println("Exception in Request handling"); } } }); Response response = Response.ok("Success").build(); // Carry on like nothing happened asyncResponse.resume(response); } }
public static IInputStreamConsumer to(AsyncResponse asyncResponse, DocumentType targetType, long requestTimeout) { AsynchronousConversionResponse response = new AsynchronousConversionResponse(asyncResponse, targetType); asyncResponse.setTimeoutHandler(response); asyncResponse.setTimeout(requestTimeout, TimeUnit.MILLISECONDS); return response; }
@Path("/poll") @GET public void poll(@Suspended final AsyncResponse asyncResponse) throws InterruptedException { asyncResponse.setTimeout(30, TimeUnit.SECONDS); this.asyncResponse = asyncResponse; } @POST @Path("/printed") public Response printCallback(String barcode) throws IOException { // ... this.asyncResponse.resume("MESSAGE"); return Response.ok().build(); }