Java Code Examples for javax.ws.rs.container.AsyncResponse#setTimeoutHandler()

The following examples show how to use javax.ws.rs.container.AsyncResponse#setTimeoutHandler() . 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: AsyncResource.java    From ee8-sandbox with Apache License 2.0 6 votes vote down vote up
@GET
public void getAsync(final @Suspended AsyncResponse res) {
    res.setTimeoutHandler(
        (ar) -> {
            ar.resume(Response.status(Response.Status.SERVICE_UNAVAILABLE)
                .entity("Operation timed out --- please try again.").build());
        }
    );
    res.setTimeout(1000, TimeUnit.MILLISECONDS);
    executor.submit(() -> {
        //do long run operations.
        try {
            LOG.log(Level.INFO, " execute long run task in AsyncResource");
            //Thread.sleep(new Random().nextInt(1005));
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            LOG.log(Level.SEVERE, "error :{0}", ex.getMessage());
        }
        res.resume(Response.ok("asynchronous resource").build());
    });
}
 
Example 2
Source File: AsyncResource.java    From ee8-sandbox with Apache License 2.0 6 votes vote down vote up
@GET
public void getAsync(final @Suspended AsyncResponse res) {
    res.setTimeoutHandler(
            (ar) -> {
                ar.resume(Response.status(Response.Status.SERVICE_UNAVAILABLE)
                        .entity("Operation timed out --- please try again.").build());
            }
    );
    res.setTimeout(1000, TimeUnit.MILLISECONDS);
    executor.submit(() -> {
        //do long run operations.
        try {
            LOG.log(Level.INFO, " execute long run task in AsyncResource");
            //Thread.sleep(new Random().nextInt(1005));
            Thread.sleep(500);
        } catch (InterruptedException ex) {
            LOG.log(Level.SEVERE, "error :" + ex.getMessage());
        }
        res.resume(Response.ok("asynchronous resource").build());
    });
}
 
Example 3
Source File: CoreJavaxRestFramework.java    From heroic with Apache License 2.0 6 votes vote down vote up
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 4
Source File: AsynchronousResources.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
@Produces(TEXT_PLAIN)
@Path("/suspended/timeout-expire-handled")
@GET
public void getAsyncResponseTimeoutExpireHandled(@Suspended final AsyncResponse ar) {
    ar.setTimeoutHandler(ar2 -> ar2.resume(status(GATEWAY_TIMEOUT).build()));
    ar.setTimeout(1, NANOSECONDS);
}
 
Example 5
Source File: OrderService.java    From qcon-microservices with Apache License 2.0 5 votes vote down vote up
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()));
}
 
Example 6
Source File: UsersResource.java    From Architecting-Modern-Java-EE-Applications with MIT License 5 votes vote down vote up
@POST
public void createUserAsync(User user, @Suspended AsyncResponse response) {

    response.setTimeout(5, TimeUnit.SECONDS);
    response.setTimeoutHandler(r ->
            r.resume(Response.status(Response.Status.SERVICE_UNAVAILABLE)));

    mes.submit(() -> response.resume(createUser(user)));
}
 
Example 7
Source File: MessagesResource.java    From porcupine with Apache License 2.0 5 votes vote down vote up
@GET
@Path("light")
public void getLightMessage(@Suspended AsyncResponse ar) {
    service.getLightMessage(ar::resume);
    ar.setTimeoutHandler(this::onTimeout);
    ar.setTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
}
 
Example 8
Source File: MessagesResource.java    From porcupine with Apache License 2.0 5 votes vote down vote up
@GET
@Path("heavy")
public void getHeavyMessage(@Suspended AsyncResponse ar) {
    service.getHeavyMessage(ar::resume);
    ar.setTimeoutHandler(this::onTimeout);
    ar.setTimeout(TIMEOUT_IN_SECONDS, TimeUnit.SECONDS);
}
 
Example 9
Source File: BookContinuationStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books/cancel")
public void getBookDescriptionWithCancel(@PathParam("id") String id,
                                         @Suspended AsyncResponse async) {
    PhaseInterceptorChain.getCurrentMessage().getClass();
    async.setTimeout(2000, TimeUnit.MILLISECONDS);
    async.setTimeoutHandler(new CancelTimeoutHandlerImpl());
}
 
Example 10
Source File: BookContinuationStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books/timeouthandler/{id}")
public void getBookDescriptionWithHandler(@PathParam("id") String id,
                                          @Suspended AsyncResponse async) {
    async.setTimeout(1000, TimeUnit.MILLISECONDS);
    async.setTimeoutHandler(new TimeoutHandlerImpl(id, false));
}
 
Example 11
Source File: BookContinuationStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/books/timeouthandlerresume/{id}")
public void getBookDescriptionWithHandlerResumeOnly(@PathParam("id") String id,
                                                    @Suspended AsyncResponse async) {
    async.setTimeout(1000, TimeUnit.MILLISECONDS);
    async.setTimeoutHandler(new TimeoutHandlerImpl(id, true));
}
 
Example 12
Source File: BookContinuationStore.java    From cxf with Apache License 2.0 5 votes vote down vote up
@GET
@Path("books/suspend/unmapped")
@Produces("text/plain")
public void handleNotMappedAfterSuspend(@Suspended AsyncResponse response) throws BookNotFoundFault {
    response.setTimeout(2000, TimeUnit.MILLISECONDS);
    response.setTimeoutHandler(new CancelTimeoutHandlerImpl());
    throw new BookNotFoundFault("");
}
 
Example 13
Source File: StreamingAsyncSubscriber.java    From cxf with Apache License 2.0 5 votes vote down vote up
public StreamingAsyncSubscriber(AsyncResponse ar, String openTag, String closeTag, String sep,
                                long pollTimeout, long asyncTimeout) {
    super(ar);
    this.openTag = openTag;
    this.closeTag = closeTag;
    this.separator = sep;
    this.pollTimeout = pollTimeout;
    this.asyncTimeout = 0;
    if (asyncTimeout > 0) {
        ar.setTimeout(asyncTimeout, TimeUnit.MILLISECONDS);
        ar.setTimeoutHandler(new TimeoutHandlerImpl());
    }
}
 
Example 14
Source File: DeviceCommandResourceImpl.java    From devicehive-java-server with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of <a href="http://www.devicehive.com/restful#Reference/DeviceCommand/wait">DeviceHive RESTful
 * API: DeviceCommand: wait</a>
 *
 * @param timeout Waiting timeout in seconds (default: 30 seconds, maximum: 60 seconds). Specify 0 to disable
 *                waiting.
 */
@Override
public void wait(final String deviceId, final String commandId, final long timeout, final AsyncResponse asyncResponse) {

    logger.debug("DeviceCommand wait requested, deviceId = {},  commandId = {}", deviceId, commandId);

    asyncResponse.setTimeoutHandler(asyncRes ->
            asyncRes.resume(ResponseFactory.response(Response.Status.NO_CONTENT)));

    if (deviceId == null || commandId == null) {
        logger.warn("DeviceCommand wait request failed. BAD REQUEST: deviceId and commandId required", deviceId);
        asyncResponse.resume(ResponseFactory.response(BAD_REQUEST));
        return;
    }

    DeviceVO device = deviceService.findById(deviceId);

    if (device == null) {
        logger.warn("DeviceCommand wait request failed. NOT FOUND: device {} not found", deviceId);
        asyncResponse.resume(ResponseFactory.response(NOT_FOUND));
        return;
    }

    commandService.findOne(Long.valueOf(commandId), device.getDeviceId())
            .thenAccept(command -> {
                if (!command.isPresent()) {
                    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);        
                }
            });
}
 
Example 15
Source File: DeviceNotificationResourceImpl.java    From devicehive-java-server with Apache License 2.0 4 votes vote down vote up
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 16
Source File: DeviceCommandResourceImpl.java    From devicehive-java-server with Apache License 2.0 4 votes vote down vote up
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);
        }
    }

}