Java Code Examples for javax.ws.rs.container.AsyncResponse#register()
The following examples show how to use
javax.ws.rs.container.AsyncResponse#register() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CoreJavaxRestFramework.java From heroic with Apache License 2.0 | 6 votes |
void doBind(final AsyncResponse response, final AsyncFuture<?> callback) { response.setTimeoutHandler(asyncResponse -> { log.debug("client timed out"); callback.cancel(); }); response.register((CompletionCallback) throwable -> { log.debug("client completed"); callback.cancel(); }); response.register((ConnectionCallback) disconnected -> { log.debug("client disconnected"); callback.cancel(); }); }
Example 2
Source File: BookContinuationStore.java From cxf with Apache License 2.0 | 6 votes |
@GET @Path("/disconnect") public void handleClientDisconnects(@Suspended AsyncResponse response) { response.setTimeout(0, TimeUnit.SECONDS); response.register(new ConnectionCallback() { @Override public void onDisconnect(AsyncResponse disconnected) { System.out.println("ConnectionCallback: onDisconnect, client disconnects"); } }); try { Thread.sleep(3000); } catch (InterruptedException ex) { // ignore } response.resume(books.values().toString()); }
Example 3
Source File: BookContinuationStore.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("books/notfound") @Produces("text/plain") public void handleContinuationRequestNotFound(@Suspended AsyncResponse response) { response.register(new CallbackImpl()); resumeSuspendedNotFound(response); }
Example 4
Source File: BookContinuationStore.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("books/notfound/unmapped") @Produces("text/plain") public void handleContinuationRequestNotFoundUnmapped(@Suspended AsyncResponse response) { response.register(new CallbackImpl()); resumeSuspendedNotFoundUnmapped(response); }
Example 5
Source File: BookContinuationStore.java From cxf with Apache License 2.0 | 5 votes |
@GET @Path("books/unmappedFromFilter") @Produces("text/plain") public void handleContinuationRequestUnmappedFromFilter(@Suspended AsyncResponse response) { response.register(new CallbackImpl()); response.resume(Response.ok().build()); }
Example 6
Source File: TaskResource.java From presto with Apache License 2.0 | 4 votes |
@ResourceSecurity(INTERNAL_ONLY) @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) { requireNonNull(taskId, "taskId is null"); requireNonNull(bufferId, "bufferId is null"); long start = System.nanoTime(); ListenableFuture<BufferResult> bufferResultFuture = taskManager.getTaskResults(taskId, bufferId, token, maxSize); Duration waitTime = randomizeWaitTime(DEFAULT_MAX_WAIT_TIME); bufferResultFuture = addTimeout( bufferResultFuture, () -> BufferResult.emptyResults(taskManager.getTaskInstanceId(taskId), token, false), waitTime, timeoutExecutor); ListenableFuture<Response> responseFuture = Futures.transform(bufferResultFuture, result -> { List<SerializedPage> serializedPages = result.getSerializedPages(); GenericEntity<?> entity = null; Status status; if (serializedPages.isEmpty()) { status = Status.NO_CONTENT; } else { entity = new GenericEntity<>(serializedPages, new TypeToken<List<SerializedPage>>() {}.getType()); status = Status.OK; } 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()) .build(); }, directExecutor()); // For hard timeout, add an additional time to max wait for thread scheduling contention and GC Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS); bindAsyncResponse(asyncResponse, responseFuture, responseExecutor) .withTimeout(timeout, Response.status(Status.NO_CONTENT) .header(PRESTO_TASK_INSTANCE_ID, taskManager.getTaskInstanceId(taskId)) .header(PRESTO_PAGE_TOKEN, token) .header(PRESTO_PAGE_NEXT_TOKEN, token) .header(PRESTO_BUFFER_COMPLETE, false) .build()); responseFuture.addListener(() -> readFromOutputBufferTime.add(Duration.nanosSince(start)), directExecutor()); asyncResponse.register((CompletionCallback) throwable -> resultsRequestTime.add(Duration.nanosSince(start))); }
Example 7
Source File: BookContinuationStore.java From cxf with Apache License 2.0 | 4 votes |
@GET @Path("/books/defaulttimeout") public void getBookDescriptionWithTimeout(@Suspended AsyncResponse async) { async.register(new CallbackImpl()); async.setTimeout(2000, TimeUnit.MILLISECONDS); }
Example 8
Source File: DeviceNotificationResourceImpl.java From devicehive-java-server with Apache License 2.0 | 4 votes |
private void poll(final long timeout, final String deviceId, final String networkIdsCsv, final String deviceTypeIdsCsv, final String namesCsv, final String timestamp, final AsyncResponse asyncResponse) throws InterruptedException { final HiveAuthentication authentication = (HiveAuthentication) SecurityContextHolder.getContext().getAuthentication(); final Date ts = Optional.ofNullable(timestamp).map(TimestampQueryParamParser::parse) .orElse(timestampService.getDate()); final Response response = ResponseFactory.response( Response.Status.OK, Collections.emptyList(), JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT); asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response)); Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ',')) .map(Arrays::asList) .map(list -> list.stream().collect(Collectors.toSet())) .orElse(null); Set<Long> networks = Optional.ofNullable(StringUtils.split(networkIdsCsv, ',')) .map(Arrays::asList) .map(list -> list.stream() .map(n -> gson.fromJson(n, Long.class)) .collect(Collectors.toSet()) ).orElse(null); Set<Long> deviceTypes = Optional.ofNullable(StringUtils.split(deviceTypeIdsCsv, ',')) .map(Arrays::asList) .map(list -> list.stream() .map(dt -> gson.fromJson(dt, Long.class)) .collect(Collectors.toSet()) ).orElse(null); BiConsumer<DeviceNotification, Long> callback = (notification, subscriptionId) -> { if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response( Response.Status.OK, Collections.singleton(notification), JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT)); } }; Set<Filter> filters = filterService.getFilterList(deviceId, networks, deviceTypes, NOTIFICATION_EVENT.name(), names, authentication); if (!filters.isEmpty()) { Pair<Long, CompletableFuture<List<DeviceNotification>>> pair = notificationService .subscribe(filters, names, ts, callback); pair.getRight().thenAccept(collection -> { if (!collection.isEmpty() && !asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response( Response.Status.OK, collection, JsonPolicyDef.Policy.NOTIFICATION_TO_CLIENT)); } if (timeout == 0) { asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause // the thread to suspend indefinitely, see AsyncResponse docs } else { asyncResponse.setTimeout(timeout, TimeUnit.SECONDS); } }); asyncResponse.register((CompletionCallback) throwable -> notificationService.unsubscribe(Collections.singleton(pair.getLeft()))); } else { if (!asyncResponse.isDone()) { asyncResponse.resume(response); } } }
Example 9
Source File: DeviceCommandResourceImpl.java From devicehive-java-server with Apache License 2.0 | 4 votes |
private void poll(final long timeout, final String deviceId, final String networkIdsCsv, final String deviceTypeIdsCsv, final String namesCsv, final String timestamp, final boolean returnUpdated, final Integer limit, final AsyncResponse asyncResponse) throws InterruptedException { final HiveAuthentication authentication = (HiveAuthentication) SecurityContextHolder.getContext().getAuthentication(); final Date ts = Optional.ofNullable(timestamp).map(TimestampQueryParamParser::parse) .orElse(timestampService.getDate()); final Response response = ResponseFactory.response( OK, Collections.emptyList(), Policy.COMMAND_LISTED); asyncResponse.setTimeoutHandler(asyncRes -> asyncRes.resume(response)); Set<String> names = Optional.ofNullable(StringUtils.split(namesCsv, ',')) .map(Arrays::asList) .map(list -> list.stream().collect(Collectors.toSet())) .orElse(null); Set<Long> networks = Optional.ofNullable(StringUtils.split(networkIdsCsv, ',')) .map(Arrays::asList) .map(list -> list.stream() .map(n -> gson.fromJson(n, Long.class)) .collect(Collectors.toSet()) ).orElse(null); Set<Long> deviceTypes = Optional.ofNullable(StringUtils.split(deviceTypeIdsCsv, ',')) .map(Arrays::asList) .map(list -> list.stream() .map(dt -> gson.fromJson(dt, Long.class)) .collect(Collectors.toSet()) ).orElse(null); BiConsumer<DeviceCommand, Long> callback = (command, subscriptionId) -> { if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response( OK, Collections.singleton(command), Policy.COMMAND_LISTED)); } }; Set<Filter> filters = filterService.getFilterList(deviceId, networks, deviceTypes, COMMAND_EVENT.name(), names, authentication); if (!filters.isEmpty()) { Pair<Long, CompletableFuture<List<DeviceCommand>>> pair = commandService .sendSubscribeRequest(filters, names, ts, returnUpdated, limit, callback); pair.getRight().thenAccept(collection -> { if (!collection.isEmpty() && !asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response( OK, collection, Policy.COMMAND_LISTED)); } if (timeout == 0) { asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause // the thread to suspend indefinitely, see AsyncResponse docs } else { asyncResponse.setTimeout(timeout, TimeUnit.SECONDS); } }); asyncResponse.register((CompletionCallback) throwable -> commandService.sendUnsubscribeRequest(Collections.singleton(pair.getLeft()))); } else { if (!asyncResponse.isDone()) { asyncResponse.resume(response); } } }
Example 10
Source File: DeviceCommandResourceImpl.java From devicehive-java-server with Apache License 2.0 | 4 votes |
private void waitForCommand(DeviceVO device, final String commandId, final long timeout, DeviceCommand command, final AsyncResponse asyncResponse) { String deviceId = device.getDeviceId(); if (!command.getDeviceId().equals(device.getDeviceId())) { 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; } BiConsumer<DeviceCommand, Long> callback = (com, subscriptionId) -> { if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response( OK, com, COMMAND_TO_DEVICE)); } }; if (!command.getIsUpdated()) { CompletableFuture<Pair<Long, DeviceCommand>> future = commandService .sendSubscribeToUpdateRequest(Long.valueOf(commandId), device, callback); future.thenAccept(pair -> { final DeviceCommand deviceCommand = pair.getRight(); if (!asyncResponse.isDone() && deviceCommand.getIsUpdated()) { asyncResponse.resume(ResponseFactory.response( OK, deviceCommand, COMMAND_TO_DEVICE)); } if (timeout == 0) { asyncResponse.setTimeout(1, TimeUnit.MILLISECONDS); // setting timeout to 0 would cause // the thread to suspend indefinitely, see AsyncResponse docs } else { 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)); } } }); } else { if (!asyncResponse.isDone()) { asyncResponse.resume(ResponseFactory.response(OK, command, COMMAND_TO_DEVICE)); } } }