Search in sources :

Example 1 with WebAsyncTask

use of org.springframework.web.context.request.async.WebAsyncTask in project brewery by spring-cloud-samples.

the class IngredientsFetchController method ingredients.

/**
 * [SLEUTH] WebAsyncTask
 */
@RequestMapping(value = "/{ingredient}", method = RequestMethod.POST)
public WebAsyncTask<Ingredient> ingredients(@PathVariable("ingredient") IngredientType ingredientType, @RequestHeader("PROCESS-ID") String processId, @RequestHeader(TestConfigurationHolder.TEST_COMMUNICATION_TYPE_HEADER_NAME) String testCommunicationType) {
    log.info("Received a request to [/{}] with process id [{}] and communication type [{}]", ingredientType, processId, testCommunicationType);
    return new WebAsyncTask<>(() -> {
        Span span = tracer.nextSpan().name("inside_ingredients").start();
        try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
            Ingredient ingredient = new Ingredient(ingredientType, stubbedIngredientsProperties.getReturnedIngredientsQuantity());
            log.info("Returning [{}] as fetched ingredient from an external service", ingredient);
            return ingredient;
        } finally {
            span.finish();
        }
    });
}
Also used : Ingredient(io.spring.cloud.samples.brewery.common.model.Ingredient) Tracer(brave.Tracer) WebAsyncTask(org.springframework.web.context.request.async.WebAsyncTask) Span(brave.Span) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 2 with WebAsyncTask

use of org.springframework.web.context.request.async.WebAsyncTask in project cas by apereo.

the class HealthCheckController method handleRequestInternal.

/**
     * Handle request.
     *
     * @param request  the request
     * @param response the response
     * @return the model and view
     * @throws Exception the exception
     */
@GetMapping
@ResponseBody
protected WebAsyncTask<HealthStatus> handleRequestInternal(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    ensureEndpointAccessIsAuthorized(request, response);
    final Callable<HealthStatus> asyncTask = () -> {
        final HealthStatus healthStatus = healthCheckMonitor.observe();
        response.setStatus(healthStatus.getCode().value());
        if (StringUtils.equals(request.getParameter("format"), "json")) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            JsonUtils.render(healthStatus.getDetails(), response);
        } else {
            final StringBuilder sb = new StringBuilder();
            sb.append("Health: ").append(healthStatus.getCode());
            final AtomicInteger i = new AtomicInteger();
            healthStatus.getDetails().forEach((name, status) -> {
                response.addHeader("X-CAS-" + name, String.format("%s;%s", status.getCode(), status.getDescription()));
                sb.append("\n\n\t").append(i.incrementAndGet()).append('.').append(name).append(": ");
                sb.append(status.getCode());
                if (status.getDescription() != null) {
                    sb.append(" - ").append(status.getDescription());
                }
            });
            response.setContentType(MediaType.TEXT_PLAIN_VALUE);
            try (Writer writer = response.getWriter()) {
                IOUtils.copy(new ByteArrayInputStream(sb.toString().getBytes(response.getCharacterEncoding())), writer, StandardCharsets.UTF_8);
                writer.flush();
            }
        }
        return null;
    };
    return new WebAsyncTask<>(casProperties.getHttpClient().getAsyncTimeout(), asyncTask);
}
Also used : CasConfigurationProperties(org.apereo.cas.configuration.CasConfigurationProperties) HealthCheckMonitor(org.apereo.cas.monitor.HealthCheckMonitor) MediaType(org.springframework.http.MediaType) HttpServletResponse(javax.servlet.http.HttpServletResponse) JsonUtils(org.apereo.cas.util.JsonUtils) Callable(java.util.concurrent.Callable) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) StandardCharsets(java.nio.charset.StandardCharsets) IOUtils(org.apache.commons.io.IOUtils) HttpServletRequest(javax.servlet.http.HttpServletRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Writer(java.io.Writer) StringUtils(org.apache.commons.codec.binary.StringUtils) HealthStatus(org.apereo.cas.monitor.HealthStatus) GetMapping(org.springframework.web.bind.annotation.GetMapping) Monitor(org.apereo.cas.monitor.Monitor) WebAsyncTask(org.springframework.web.context.request.async.WebAsyncTask) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ByteArrayInputStream(java.io.ByteArrayInputStream) HealthStatus(org.apereo.cas.monitor.HealthStatus) WebAsyncTask(org.springframework.web.context.request.async.WebAsyncTask) Writer(java.io.Writer) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 3 with WebAsyncTask

use of org.springframework.web.context.request.async.WebAsyncTask in project spring-cloud-sleuth by spring-cloud.

the class TraceWebAspect method wrapWebAsyncTaskWithCorrelationId.

@Around("anyControllerOrRestControllerWithPublicWebAsyncTaskMethod()")
public Object wrapWebAsyncTaskWithCorrelationId(ProceedingJoinPoint pjp) throws Throwable {
    final WebAsyncTask<?> webAsyncTask = (WebAsyncTask<?>) pjp.proceed();
    if (this.tracer.currentSpan() != null) {
        try {
            if (log.isDebugEnabled()) {
                log.debug("Wrapping callable with span [" + this.tracer.currentSpan() + "]");
            }
            Field callableField = WebAsyncTask.class.getDeclaredField("callable");
            callableField.setAccessible(true);
            callableField.set(webAsyncTask, new TraceCallable<>(this.tracer, this.spanNamer, this.errorParser, webAsyncTask.getCallable()));
        } catch (NoSuchFieldException ex) {
            log.warn("Cannot wrap webAsyncTask's callable with TraceCallable", ex);
        }
    }
    return webAsyncTask;
}
Also used : Field(java.lang.reflect.Field) WebAsyncTask(org.springframework.web.context.request.async.WebAsyncTask) Around(org.aspectj.lang.annotation.Around)

Aggregations

WebAsyncTask (org.springframework.web.context.request.async.WebAsyncTask)3 Span (brave.Span)1 Tracer (brave.Tracer)1 Ingredient (io.spring.cloud.samples.brewery.common.model.Ingredient)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Writer (java.io.Writer)1 Field (java.lang.reflect.Field)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Callable (java.util.concurrent.Callable)1 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)1 HttpServletRequest (javax.servlet.http.HttpServletRequest)1 HttpServletResponse (javax.servlet.http.HttpServletResponse)1 StringUtils (org.apache.commons.codec.binary.StringUtils)1 IOUtils (org.apache.commons.io.IOUtils)1 CasConfigurationProperties (org.apereo.cas.configuration.CasConfigurationProperties)1 HealthCheckMonitor (org.apereo.cas.monitor.HealthCheckMonitor)1 HealthStatus (org.apereo.cas.monitor.HealthStatus)1 Monitor (org.apereo.cas.monitor.Monitor)1 JsonUtils (org.apereo.cas.util.JsonUtils)1 Around (org.aspectj.lang.annotation.Around)1