Search in sources :

Example 1 with HttpFilter

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

the class DefaultFilterRoute method match.

@Override
public Optional<HttpFilter> match(HttpMethod method, URI uri) {
    if (httpMethods != null && !httpMethods.contains(method)) {
        return Optional.empty();
    }
    String uriStr = uri.getPath();
    PathMatcher matcher = getPatternStyle().getPathMatcher();
    for (String pattern : patterns) {
        if (matcher.matches(pattern, uriStr)) {
            HttpFilter filter = getFilter();
            if (filter instanceof Toggleable && !((Toggleable) filter).isEnabled()) {
                return Optional.empty();
            }
            return Optional.of(filter);
        }
    }
    return Optional.empty();
}
Also used : HttpFilter(io.micronaut.http.filter.HttpFilter)

Example 2 with HttpFilter

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

the class DefaultFilterRoute method getFilter.

@Override
public HttpFilter getFilter() {
    HttpFilter filter = this.filter;
    if (filter == null) {
        synchronized (this) {
            // double check
            filter = this.filter;
            if (filter == null) {
                filter = filterSupplier.get();
                this.filter = filter;
            }
        }
    }
    return filter;
}
Also used : HttpFilter(io.micronaut.http.filter.HttpFilter)

Example 3 with HttpFilter

use of io.micronaut.http.filter.HttpFilter 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)

Example 4 with HttpFilter

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

the class AnnotatedFilterRouteBuilder method process.

@Override
public void process(BeanDefinition<?> beanDefinition, BeanContext beanContext) {
    if (HttpClientFilter.class.isAssignableFrom(beanDefinition.getBeanType())) {
        // ignore http client filters
        return;
    }
    String[] patterns = getPatterns(beanDefinition);
    if (ArrayUtils.isNotEmpty(patterns)) {
        HttpMethod[] methods = beanDefinition.enumValues(Filter.class, "methods", HttpMethod.class);
        FilterPatternStyle patternStyle = beanDefinition.enumValue(Filter.class, "patternStyle", FilterPatternStyle.class).orElse(FilterPatternStyle.ANT);
        String first = patterns[0];
        @SuppressWarnings("unchecked") FilterRoute filterRoute = addFilter(first, beanContext, (BeanDefinition<? extends HttpFilter>) beanDefinition);
        if (patterns.length > 1) {
            for (int i = 1; i < patterns.length; i++) {
                String pattern = patterns[i];
                filterRoute.pattern(pattern);
            }
        }
        if (ArrayUtils.isNotEmpty(methods)) {
            filterRoute.methods(methods);
        }
        filterRoute.patternStyle(patternStyle);
    }
}
Also used : Filter(io.micronaut.http.annotation.Filter) HttpFilter(io.micronaut.http.filter.HttpFilter) HttpClientFilter(io.micronaut.http.filter.HttpClientFilter) FilterPatternStyle(io.micronaut.http.filter.FilterPatternStyle) HttpMethod(io.micronaut.http.HttpMethod)

Example 5 with HttpFilter

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

the class DefaultRouter method resolveFilters.

@Override
public List<HttpFilter> resolveFilters(HttpRequest<?> request, List<FilterEntry<HttpFilter>> filterEntries) {
    List<HttpFilter> httpFilters = new ArrayList<>(filterEntries.size());
    for (FilterEntry<HttpFilter> entry : filterEntries) {
        if (entry.hasMethods() && !entry.getFilterMethods().contains(request.getMethod())) {
            continue;
        }
        if (entry.hasPatterns()) {
            String path = request.getPath();
            String[] patterns = entry.getPatterns();
            FilterPatternStyle patternStyle = entry.getAnnotationMetadata().enumValue("patternStyle", FilterPatternStyle.class).orElse(FilterPatternStyle.ANT);
            boolean matches = true;
            for (String pattern : patterns) {
                if (!matches) {
                    break;
                }
                matches = Filter.MATCH_ALL_PATTERN.equals(pattern) || patternStyle.getPathMatcher().matches(pattern, path);
            }
            if (!matches) {
                continue;
            }
        }
        httpFilters.add(entry.getFilter());
    }
    httpFilters.sort(OrderUtil.COMPARATOR);
    return Collections.unmodifiableList(httpFilters);
}
Also used : FilterPatternStyle(io.micronaut.http.filter.FilterPatternStyle) HttpFilter(io.micronaut.http.filter.HttpFilter)

Aggregations

HttpFilter (io.micronaut.http.filter.HttpFilter)6 NonNull (io.micronaut.core.annotation.NonNull)2 HttpMethod (io.micronaut.http.HttpMethod)2 FilterPatternStyle (io.micronaut.http.filter.FilterPatternStyle)2 BeanContext (io.micronaut.context.BeanContext)1 BeanCreationException (io.micronaut.context.exceptions.BeanCreationException)1 Internal (io.micronaut.core.annotation.Internal)1 Nullable (io.micronaut.core.annotation.Nullable)1 Publishers (io.micronaut.core.async.publisher.Publishers)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 HttpRequest (io.micronaut.http.HttpRequest)1 HttpResponse (io.micronaut.http.HttpResponse)1 HttpStatus (io.micronaut.http.HttpStatus)1 MediaType (io.micronaut.http.MediaType)1 MutableHttpHeaders (io.micronaut.http.MutableHttpHeaders)1