@Override public void aroundRequest(HttpRequest req, RunnableWithException<IOException> continuation) throws IOException { BoundRequestContext cdiContext = CDI.current().select(BoundRequestContext.class).get(); Map<String,Object> contextMap = new HashMap<String,Object>(); cdiContext.associate(contextMap); cdiContext.activate(); try { // FIXME: associate CDI thread context on thread change, like Resteasy context? continuation.run(); }finally { if(req.getAsyncContext().isSuspended()) { req.getAsyncContext().getAsyncResponse().register((CompletionCallback)(t) -> { cdiContext.invalidate(); cdiContext.deactivate(); cdiContext.dissociate(contextMap); }); }else { cdiContext.invalidate(); cdiContext.deactivate(); cdiContext.dissociate(contextMap); } } }
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(); }); }
@GET @Path("/withCallback") public void asyncGetWithCallback(@Suspended final AsyncResponse asyncResponse) { asyncResponse.register(new CompletionCallback() { @Override public void onComplete(Throwable throwable) { if (throwable == null) { numberOfSuccessResponses++; } else { numberOfFailures++; lastException = throwable; } } }); new Thread(new Runnable() { @Override public void run() { String result = veryExpensiveOperation(); asyncResponse.resume(result); } private String veryExpensiveOperation() { return new MagicNumber(22) + ""; } }).start(); }
@Override public Object[] preProcess(Method method, Object[] args, MonitorContext context) { int i = INIT; AsyncResponse asyncResponse = null; if (cache.containsKey(method)) { i = cache.get(method); if (i == IGNORE) return args; asyncResponse = (AsyncResponse) args[i]; } else { for (Annotation a : method.getDeclaredAnnotations()) { if (a.annotationType().isAnnotationPresent(HttpMethod.class)) { Parameter[] params = method.getParameters(); for (i = 0; i < args.length; i++) { Object arg = args[i]; Parameter param = params[i]; if (arg instanceof AsyncResponse && param.isAnnotationPresent(Suspended.class)) { cache.putIfAbsent(method, i); asyncResponse = (AsyncResponse) arg; break; } } break; } } if (asyncResponse == null) cache.putIfAbsent(method, IGNORE); } if (asyncResponse != null) { context.setAsync(true); asyncResponse.register(new CompletionCallback() { @Override public void onComplete(Throwable throwable) { context.doReport(); } }); } return args; }
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 = filterBuilderService.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); } } }
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 = filterBuilderService.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); } } }
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)); } } }