下面列出了怎么用javax.ws.rs.container.CompletionCallback的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
});
}
@Override
public Map<Class<?>, Collection<Class<?>>> register(Object callback, Object... callbacks)
throws NullPointerException {
Map<Class<?>, Collection<Class<?>>> map = new HashMap<>();
Object[] allCallbacks = new Object[1 + callbacks.length];
allCallbacks[0] = callback;
System.arraycopy(callbacks, 0, allCallbacks, 1, callbacks.length);
for (int i = 0; i < allCallbacks.length; i++) {
if (allCallbacks[i] == null) {
throw new NullPointerException();
}
Class<?> callbackCls = allCallbacks[i].getClass();
Collection<Class<?>> knownCallbacks = map.get(callbackCls);
if (knownCallbacks == null) {
knownCallbacks = new HashSet<>();
map.put(callbackCls, knownCallbacks);
}
if (allCallbacks[i] instanceof CompletionCallback) {
knownCallbacks.add(CompletionCallback.class);
completionCallbacks.add((CompletionCallback)allCallbacks[i]);
} else if (allCallbacks[i] instanceof ConnectionCallback) {
knownCallbacks.add(ConnectionCallback.class);
connectionCallbacks.add((ConnectionCallback)allCallbacks[i]);
}
}
return map;
}
@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)));
}
private void updateCompletionCallbacks(Throwable error) {
Throwable actualError = error instanceof Fault ? ((Fault)error).getCause() : error;
for (CompletionCallback completionCallback : completionCallbacks) {
completionCallback.onComplete(actualError);
}
}
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);
}
}
}
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);
}
}
}
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));
}
}
}