Search in sources :

Example 51 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project component-runtime by Talend.

the class ExecutionResource method read.

/**
 * Read inputs from an instance of mapper. The number of returned records if enforced to be limited to 1000.
 * The format is a JSON based format where each like is a json record.
 *
 * @param family the component family.
 * @param component the component name.
 * @param size the maximum number of records to read.
 * @param configuration the component configuration as key/values.
 */
@POST
@Deprecated
@Produces("talend/stream")
@Path("read/{family}/{component}")
public void read(@Suspended final AsyncResponse response, @Context final Providers providers, @PathParam("family") final String family, @PathParam("component") final String component, @QueryParam("size") @DefaultValue("50") final long size, final Map<String, String> configuration) {
    final long maxSize = Math.min(size, MAX_RECORDS);
    response.setTimeoutHandler(asyncResponse -> log.warn("Timeout on dataset retrieval"));
    response.setTimeout(appConfiguration.datasetRetrieverTimeout(), SECONDS);
    executorService.submit(() -> {
        final Optional<Mapper> mapperOptional = manager.findMapper(family, component, getConfigComponentVersion(configuration), configuration);
        if (!mapperOptional.isPresent()) {
            response.resume(new WebApplicationException(Response.status(BAD_REQUEST).entity(new ErrorPayload(COMPONENT_MISSING, "Didn't find the input component")).build()));
            return;
        }
        final Mapper mapper = mapperOptional.get();
        mapper.start();
        try {
            final Input input = mapper.create();
            try {
                input.start();
                response.resume((StreamingOutput) output -> {
                    Object data;
                    int current = 0;
                    while (current++ < maxSize && (data = input.next()) != null) {
                        if (CharSequence.class.isInstance(data) || Number.class.isInstance(data) || Boolean.class.isInstance(data)) {
                            final PrimitiveWrapper wrapper = new PrimitiveWrapper();
                            wrapper.setValue(data);
                            data = wrapper;
                        }
                        inlineStreamingMapper.toJson(data, output);
                        output.write(EOL);
                    }
                });
            } finally {
                input.stop();
            }
        } finally {
            mapper.stop();
        }
    });
}
Also used : PrimitiveWrapper(org.talend.sdk.component.server.front.model.execution.PrimitiveWrapper) Produces(javax.ws.rs.Produces) Path(javax.ws.rs.Path) BAD_FORMAT(org.talend.sdk.component.server.front.model.ErrorDictionary.BAD_FORMAT) PreDestroy(javax.annotation.PreDestroy) MediaType(javax.ws.rs.core.MediaType) JsonNumber(javax.json.JsonNumber) QueryParam(javax.ws.rs.QueryParam) Collectors.toMap(java.util.stream.Collectors.toMap) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) DefaultValue(javax.ws.rs.DefaultValue) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) JsonObject(javax.json.JsonObject) JsonbBuilder(javax.json.bind.JsonbBuilder) Context(javax.ws.rs.core.Context) Providers(javax.ws.rs.ext.Providers) AsyncResponse(javax.ws.rs.container.AsyncResponse) StreamingOutput(javax.ws.rs.core.StreamingOutput) Processor(org.talend.sdk.component.runtime.output.Processor) Suspended(javax.ws.rs.container.Suspended) StandardCharsets(java.nio.charset.StandardCharsets) ErrorPayload(org.talend.sdk.component.server.front.model.error.ErrorPayload) OutputEmitter(org.talend.sdk.component.api.processor.OutputEmitter) Branches(org.talend.sdk.component.runtime.output.Branches) Slf4j(lombok.extern.slf4j.Slf4j) Response(javax.ws.rs.core.Response) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) ApplicationScoped(javax.enterprise.context.ApplicationScoped) ACTION_ERROR(org.talend.sdk.component.server.front.model.ErrorDictionary.ACTION_ERROR) WriteStatistics(org.talend.sdk.component.server.front.model.execution.WriteStatistics) PathParam(javax.ws.rs.PathParam) OutputFactory(org.talend.sdk.component.runtime.output.OutputFactory) Inject(javax.inject.Inject) ComponentServerConfiguration(org.talend.sdk.component.server.configuration.ComponentServerConfiguration) Input(org.talend.sdk.component.runtime.input.Input) ExecutorService(java.util.concurrent.ExecutorService) POST(javax.ws.rs.POST) Optional.ofNullable(java.util.Optional.ofNullable) COMPONENT_MISSING(org.talend.sdk.component.server.front.model.ErrorDictionary.COMPONENT_MISSING) InputStreamReader(java.io.InputStreamReader) JsonString(javax.json.JsonString) Mapper(org.talend.sdk.component.runtime.input.Mapper) Jsonb(javax.json.bind.Jsonb) BufferedReader(java.io.BufferedReader) ComponentManager(org.talend.sdk.component.runtime.manager.ComponentManager) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) Mapper(org.talend.sdk.component.runtime.input.Mapper) PrimitiveWrapper(org.talend.sdk.component.server.front.model.execution.PrimitiveWrapper) ErrorPayload(org.talend.sdk.component.server.front.model.error.ErrorPayload) Input(org.talend.sdk.component.runtime.input.Input) WebApplicationException(javax.ws.rs.WebApplicationException) JsonNumber(javax.json.JsonNumber) JsonObject(javax.json.JsonObject) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces)

Example 52 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project wildfly by wildfly.

the class AsyncResource method getBasic.

@GET
@Path("basic")
@Produces("text/plain")
public void getBasic(@Suspended final AsyncResponse response) throws Exception {
    response.setTimeout(1, TimeUnit.SECONDS);
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                Response jaxrs = Response.ok("basic").type(MediaType.TEXT_PLAIN).build();
                response.resume(jaxrs);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}
Also used : Response(javax.ws.rs.core.Response) AsyncResponse(javax.ws.rs.container.AsyncResponse) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 53 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project tomee by apache.

the class JAXRSInvoker method invoke.

public Object invoke(Exchange exchange, Object request) {
    MessageContentsList responseList = checkExchangeForResponse(exchange);
    if (responseList != null) {
        return responseList;
    }
    AsyncResponse asyncResp = exchange.get(AsyncResponse.class);
    if (asyncResp != null) {
        AsyncResponseImpl asyncImpl = (AsyncResponseImpl) asyncResp;
        asyncImpl.prepareContinuation();
        try {
            asyncImpl.handleTimeout();
            return handleAsyncResponse(exchange, asyncImpl);
        } catch (Throwable t) {
            return handleAsyncFault(exchange, asyncImpl, t);
        }
    }
    ResourceProvider provider = getResourceProvider(exchange);
    Object rootInstance = null;
    Message inMessage = exchange.getInMessage();
    try {
        rootInstance = getServiceObject(exchange);
        Object serviceObject = getActualServiceObject(exchange, rootInstance);
        return invoke(exchange, request, serviceObject);
    } catch (WebApplicationException ex) {
        responseList = checkExchangeForResponse(exchange);
        if (responseList != null) {
            return responseList;
        }
        return handleFault(ex, inMessage);
    } finally {
        boolean suspended = isSuspended(exchange);
        if (suspended || exchange.isOneWay() || inMessage.get(Message.THREAD_CONTEXT_SWITCHED) != null) {
            ServerProviderFactory.clearThreadLocalProxies(inMessage);
        }
        if (suspended || isServiceObjectRequestScope(inMessage)) {
            persistRoots(exchange, rootInstance, provider);
        } else {
            provider.releaseInstance(inMessage, rootInstance);
        }
    }
}
Also used : MessageContentsList(org.apache.cxf.message.MessageContentsList) Message(org.apache.cxf.message.Message) WebApplicationException(javax.ws.rs.WebApplicationException) ResourceProvider(org.apache.cxf.jaxrs.lifecycle.ResourceProvider) AsyncResponseImpl(org.apache.cxf.jaxrs.impl.AsyncResponseImpl) AsyncResponse(javax.ws.rs.container.AsyncResponse)

Example 54 with AsyncResponse

use of javax.ws.rs.container.AsyncResponse in project bisq-api by mrosseel.

the class TradeResource method handlePaymentStatusChange.

private void handlePaymentStatusChange(String tradeId, AsyncResponse asyncResponse, CompletableFuture<Void> completableFuture) {
    completableFuture.thenApply(response -> asyncResponse.resume(Response.status(Response.Status.OK).build())).exceptionally(e -> {
        final Throwable cause = e.getCause();
        final Response.ResponseBuilder responseBuilder;
        if (cause instanceof ValidationException) {
            responseBuilder = toValidationErrorResponse(cause, 422);
        } else if (cause instanceof NotFoundException) {
            responseBuilder = toValidationErrorResponse(cause, 404);
        } else {
            final String message = cause.getMessage();
            responseBuilder = Response.status(500);
            if (null != message)
                responseBuilder.entity(new ValidationErrorMessage(ImmutableList.of(message)));
            log.error("Unable to confirm payment started for trade: " + tradeId, cause);
        }
        return asyncResponse.resume(responseBuilder.build());
    });
}
Also used : BisqProxy(network.bisq.api.BisqProxy) AsyncResponse(javax.ws.rs.container.AsyncResponse) ResourceHelper.toValidationErrorResponse(network.bisq.api.service.ResourceHelper.toValidationErrorResponse) TradeList(network.bisq.api.model.TradeList) CompletableFuture(java.util.concurrent.CompletableFuture) Suspended(javax.ws.rs.container.Suspended) ApiOperation(io.swagger.annotations.ApiOperation) Slf4j(lombok.extern.slf4j.Slf4j) MediaType(javax.ws.rs.core.MediaType) Collectors.toList(java.util.stream.Collectors.toList) TradeDetails(network.bisq.api.model.TradeDetails) ImmutableList(com.google.common.collect.ImmutableList) javax.ws.rs(javax.ws.rs) Response(javax.ws.rs.core.Response) ValidationException(javax.validation.ValidationException) NotEmpty(org.hibernate.validator.constraints.NotEmpty) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage) Api(io.swagger.annotations.Api) Authorization(io.swagger.annotations.Authorization) NotFoundException(network.bisq.api.NotFoundException) AsyncResponse(javax.ws.rs.container.AsyncResponse) ResourceHelper.toValidationErrorResponse(network.bisq.api.service.ResourceHelper.toValidationErrorResponse) Response(javax.ws.rs.core.Response) ValidationException(javax.validation.ValidationException) NotFoundException(network.bisq.api.NotFoundException) ValidationErrorMessage(io.dropwizard.jersey.validation.ValidationErrorMessage)

Aggregations

AsyncResponse (javax.ws.rs.container.AsyncResponse)54 Response (javax.ws.rs.core.Response)20 Test (org.junit.Test)14 CompletableFuture (java.util.concurrent.CompletableFuture)12 Path (javax.ws.rs.Path)11 Slf4j (lombok.extern.slf4j.Slf4j)11 List (java.util.List)10 GET (javax.ws.rs.GET)10 Suspended (javax.ws.rs.container.Suspended)10 WebApplicationException (javax.ws.rs.WebApplicationException)9 Status (javax.ws.rs.core.Response.Status)9 ArrayList (java.util.ArrayList)8 Context (javax.ws.rs.core.Context)8 MediaType (javax.ws.rs.core.MediaType)8 AuthHandler (io.pravega.auth.AuthHandler)6 READ (io.pravega.auth.AuthHandler.Permissions.READ)6 READ_UPDATE (io.pravega.auth.AuthHandler.Permissions.READ_UPDATE)6 ReaderGroupManager (io.pravega.client.admin.ReaderGroupManager)6 ReaderGroupManagerImpl (io.pravega.client.admin.impl.ReaderGroupManagerImpl)6 ConnectionFactory (io.pravega.client.netty.impl.ConnectionFactory)6