Search in sources :

Example 1 with ServerFilterChain

use of io.micronaut.http.filter.ServerFilterChain in project akhq by tchiotludo.

the class StaticFilter method doFilter.

@Override
public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
    return Publishers.map(chain.proceed(request), response -> {
        boolean first = response.getBody(NettyStreamedFileCustomizableResponseType.class).filter(n -> n.getMediaType().getName().equals(MediaType.TEXT_HTML)).isPresent();
        boolean second = response.getBody(NettySystemFileCustomizableResponseType.class).filter(n -> n.getFile().getAbsoluteFile().toString().endsWith("ui/index.html")).isPresent();
        if (first || second) {
            try {
                InputStream inputStream = Objects.requireNonNull(StaticFilter.class.getClassLoader().getResourceAsStream("ui/index.html"));
                String content;
                try (Reader reader = new InputStreamReader(inputStream)) {
                    content = CharStreams.toString(reader);
                }
                String finalBody = replace(content);
                return HttpResponse.<String>ok().body(finalBody).contentType(MediaType.TEXT_HTML).contentLength(finalBody.length());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return response;
    });
}
Also used : Filter(io.micronaut.http.annotation.Filter) Publishers(io.micronaut.core.async.publisher.Publishers) ServerFilterChain(io.micronaut.http.filter.ServerFilterChain) Publisher(org.reactivestreams.Publisher) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) IOException(java.io.IOException) Value(io.micronaut.context.annotation.Value) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) NettyStreamedFileCustomizableResponseType(io.micronaut.http.server.netty.types.files.NettyStreamedFileCustomizableResponseType) Objects(java.util.Objects) CharStreams(com.google.common.io.CharStreams) MediaType(io.micronaut.http.MediaType) Nullable(io.micronaut.core.annotation.Nullable) HttpServerFilter(io.micronaut.http.filter.HttpServerFilter) HttpResponse(io.micronaut.http.HttpResponse) HttpRequest(io.micronaut.http.HttpRequest) NettySystemFileCustomizableResponseType(io.micronaut.http.server.netty.types.files.NettySystemFileCustomizableResponseType) InputStream(java.io.InputStream) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException)

Example 2 with ServerFilterChain

use of io.micronaut.http.filter.ServerFilterChain in project micronaut-core by micronaut-projects.

the class RouteExecutor method filterPublisher.

/**
 * Applies server filters to a request/response.
 *
 * @param requestReference          The request reference
 * @param upstreamResponsePublisher The original response publisher
 * @return A new response publisher that executes server filters
 */
public Publisher<MutableHttpResponse<?>> filterPublisher(AtomicReference<HttpRequest<?>> requestReference, Publisher<MutableHttpResponse<?>> upstreamResponsePublisher) {
    List<HttpFilter> httpFilters = router.findFilters(requestReference.get());
    if (httpFilters.isEmpty()) {
        return upstreamResponsePublisher;
    }
    List<HttpFilter> filters = new ArrayList<>(httpFilters);
    AtomicInteger integer = new AtomicInteger();
    int len = filters.size();
    final Function<MutableHttpResponse<?>, Publisher<MutableHttpResponse<?>>> handleStatusException = (response) -> handleStatusException(requestReference.get(), response);
    final Function<Throwable, Publisher<MutableHttpResponse<?>>> onError = (t) -> onError(t, requestReference.get());
    ServerFilterChain filterChain = new ServerFilterChain() {

        @SuppressWarnings("unchecked")
        @Override
        public Publisher<MutableHttpResponse<?>> proceed(io.micronaut.http.HttpRequest<?> request) {
            int pos = integer.incrementAndGet();
            if (pos > len) {
                throw new IllegalStateException("The FilterChain.proceed(..) method should be invoked exactly once per filter execution. The method has instead been invoked multiple times by an erroneous filter definition.");
            }
            if (pos == len) {
                return upstreamResponsePublisher;
            }
            HttpFilter httpFilter = filters.get(pos);
            HttpRequest<?> requestForFilter = requestReference.getAndSet(request);
            try {
                return Flux.from((Publisher<MutableHttpResponse<?>>) httpFilter.doFilter(requestForFilter, this)).flatMap(handleStatusException).onErrorResume(onError);
            } catch (Throwable t) {
                return onError.apply(t);
            }
        }
    };
    HttpFilter httpFilter = filters.get(0);
    HttpRequest<?> request = requestReference.get();
    try {
        return Flux.from((Publisher<MutableHttpResponse<?>>) httpFilter.doFilter(request, filterChain)).flatMap(handleStatusException).onErrorResume(onError);
    } catch (Throwable t) {
        return onError.apply(t);
    }
}
Also used : Publishers(io.micronaut.core.async.publisher.Publishers) ServerFilterChain(io.micronaut.http.filter.ServerFilterChain) BeanContext(io.micronaut.context.BeanContext) KotlinExecutableMethodUtils.isKotlinFunctionReturnTypeUnit(io.micronaut.inject.util.KotlinExecutableMethodUtils.isKotlinFunctionReturnTypeUnit) LoggerFactory(org.slf4j.LoggerFactory) HttpHeaders(io.micronaut.http.HttpHeaders) Internal(io.micronaut.core.annotation.Internal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpStatus(io.micronaut.http.HttpStatus) MediaType(io.micronaut.http.MediaType) ReferenceCounted(io.micronaut.core.io.buffer.ReferenceCounted) HttpResponse(io.micronaut.http.HttpResponse) MethodReference(io.micronaut.inject.MethodReference) MethodBasedRouteMatch(io.micronaut.web.router.MethodBasedRouteMatch) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) MutableHttpHeaders(io.micronaut.http.MutableHttpHeaders) CompletionException(java.util.concurrent.CompletionException) HttpFilter(io.micronaut.http.filter.HttpFilter) RequestArgumentSatisfier(io.micronaut.http.server.binding.RequestArgumentSatisfier) List(java.util.List) RouteInfo(io.micronaut.web.router.RouteInfo) BeanCreationException(io.micronaut.context.exceptions.BeanCreationException) Optional(java.util.Optional) HttpAttributes(io.micronaut.http.HttpAttributes) Pattern(java.util.regex.Pattern) RouteMatch(io.micronaut.web.router.RouteMatch) UnsatisfiedRouteException(io.micronaut.web.router.exceptions.UnsatisfiedRouteException) LocalDateTime(java.time.LocalDateTime) CompletableFuture(java.util.concurrent.CompletableFuture) Scheduler(reactor.core.scheduler.Scheduler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ExceptionHandler(io.micronaut.http.server.exceptions.ExceptionHandler) ExecutableMethod(io.micronaut.inject.ExecutableMethod) ArrayList(java.util.ArrayList) ErrorContext(io.micronaut.http.server.exceptions.response.ErrorContext) Nullable(io.micronaut.core.annotation.Nullable) ReturnType(io.micronaut.core.type.ReturnType) Schedulers(reactor.core.scheduler.Schedulers) Argument(io.micronaut.core.type.Argument) HttpRequest(io.micronaut.http.HttpRequest) ServerRequestContext(io.micronaut.http.context.ServerRequestContext) ErrorResponseProcessor(io.micronaut.http.server.exceptions.response.ErrorResponseProcessor) ExecutorService(java.util.concurrent.ExecutorService) HttpStatusException(io.micronaut.http.exceptions.HttpStatusException) HttpMethod(io.micronaut.http.HttpMethod) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ExecutorSelector(io.micronaut.scheduling.executor.ExecutorSelector) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) IOException(java.io.IOException) BeanType(io.micronaut.inject.BeanType) ExecutionException(java.util.concurrent.ExecutionException) NonNull(io.micronaut.core.annotation.NonNull) Flux(reactor.core.publisher.Flux) ContinuationArgumentBinder(io.micronaut.http.bind.binders.ContinuationArgumentBinder) KotlinUtils.isKotlinCoroutineSuspended(io.micronaut.core.util.KotlinUtils.isKotlinCoroutineSuspended) BeanDefinition(io.micronaut.inject.BeanDefinition) Router(io.micronaut.web.router.Router) Collections(java.util.Collections) HttpRequest(io.micronaut.http.HttpRequest) MutableHttpResponse(io.micronaut.http.MutableHttpResponse) ArrayList(java.util.ArrayList) Publisher(org.reactivestreams.Publisher) ServerFilterChain(io.micronaut.http.filter.ServerFilterChain) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HttpFilter(io.micronaut.http.filter.HttpFilter)

Aggregations

Nullable (io.micronaut.core.annotation.Nullable)2 Publishers (io.micronaut.core.async.publisher.Publishers)2 HttpRequest (io.micronaut.http.HttpRequest)2 HttpResponse (io.micronaut.http.HttpResponse)2 MediaType (io.micronaut.http.MediaType)2 MutableHttpResponse (io.micronaut.http.MutableHttpResponse)2 ServerFilterChain (io.micronaut.http.filter.ServerFilterChain)2 CharStreams (com.google.common.io.CharStreams)1 BeanContext (io.micronaut.context.BeanContext)1 Value (io.micronaut.context.annotation.Value)1 BeanCreationException (io.micronaut.context.exceptions.BeanCreationException)1 Internal (io.micronaut.core.annotation.Internal)1 NonNull (io.micronaut.core.annotation.NonNull)1 ReferenceCounted (io.micronaut.core.io.buffer.ReferenceCounted)1 Argument (io.micronaut.core.type.Argument)1 ReturnType (io.micronaut.core.type.ReturnType)1 KotlinUtils.isKotlinCoroutineSuspended (io.micronaut.core.util.KotlinUtils.isKotlinCoroutineSuspended)1 HttpAttributes (io.micronaut.http.HttpAttributes)1 HttpHeaders (io.micronaut.http.HttpHeaders)1 HttpMethod (io.micronaut.http.HttpMethod)1