Search in sources :

Example 51 with Filter

use of javax.servlet.Filter in project spring-cloud-sleuth by spring-cloud.

the class MyFilter method should_assume_that_a_request_without_span_and_with_trace_is_a_root_span.

@Test
public void should_assume_that_a_request_without_span_and_with_trace_is_a_root_span() throws Exception {
    Long expectedTraceId = new Random().nextLong();
    whenSentRequestWithTraceIdAndNoSpanId(expectedTraceId);
    whenSentRequestWithTraceIdAndNoSpanId(expectedTraceId);
    then(this.reporter.getSpans().stream().filter(span -> span.id().equals(span.traceId())).findAny().isPresent()).as("a root span exists").isTrue();
    then(this.tracer.currentSpan()).isNull();
}
Also used : FilterChain(javax.servlet.FilterChain) Primary(org.springframework.context.annotation.Primary) ServletException(javax.servlet.ServletException) Span(brave.Span) Autowired(org.springframework.beans.factory.annotation.Autowired) Random(java.util.Random) Sampler(brave.sampler.Sampler) After(org.junit.After) ArrayListSpanReporter(org.springframework.cloud.sleuth.util.ArrayListSpanReporter) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) Filter(javax.servlet.Filter) SpringRunner(org.springframework.test.context.junit4.SpringRunner) DefaultTestAutoConfiguration(org.springframework.cloud.sleuth.instrument.DefaultTestAutoConfiguration) Tracer(brave.Tracer) MediaType(org.springframework.http.MediaType) BDDAssertions.then(org.assertj.core.api.BDDAssertions.then) RestController(org.springframework.web.bind.annotation.RestController) Configuration(org.springframework.context.annotation.Configuration) SpanUtil(org.springframework.cloud.sleuth.util.SpanUtil) Assertions.fail(org.assertj.core.api.Assertions.fail) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) ServletResponse(javax.servlet.ServletResponse) DefaultMockMvcBuilder(org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder) Optional(java.util.Optional) LogFactory(org.apache.commons.logging.LogFactory) MockMvcRequestBuilders.asyncDispatch(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch) TracingFilter(brave.servlet.TracingFilter) RunWith(org.junit.runner.RunWith) DeferredResult(org.springframework.web.context.request.async.DeferredResult) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) CompletableFuture(java.util.concurrent.CompletableFuture) TraceKeys(org.springframework.cloud.sleuth.TraceKeys) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) ManagementServerProperties(org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties) NestedServletException(org.springframework.web.util.NestedServletException) MvcResult(org.springframework.test.web.servlet.MvcResult) Before(org.junit.Before) Order(org.springframework.core.annotation.Order) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) HttpStatus(org.springframework.http.HttpStatus) Component(org.springframework.stereotype.Component) MDC(org.slf4j.MDC) BeanFactory(org.springframework.beans.factory.BeanFactory) Log(org.apache.commons.logging.Log) Bean(org.springframework.context.annotation.Bean) Random(java.util.Random) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 52 with Filter

use of javax.servlet.Filter in project spring-cloud-sleuth by spring-cloud.

the class MyFilter method should_add_a_custom_tag_to_the_span_created_in_controller.

@Test
public void should_add_a_custom_tag_to_the_span_created_in_controller() throws Exception {
    Long expectedTraceId = new Random().nextLong();
    MvcResult mvcResult = whenSentDeferredWithTraceId(expectedTraceId);
    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk()).andReturn();
    Optional<zipkin2.Span> taggedSpan = this.reporter.getSpans().stream().filter(span -> span.tags().containsKey("tag")).findFirst();
    then(taggedSpan.isPresent()).isTrue();
    then(taggedSpan.get().tags()).containsEntry("tag", "value").containsEntry("mvc.controller.method", "deferredMethod").containsEntry("mvc.controller.class", "TestController");
    then(this.tracer.currentSpan()).isNull();
}
Also used : FilterChain(javax.servlet.FilterChain) Primary(org.springframework.context.annotation.Primary) ServletException(javax.servlet.ServletException) Span(brave.Span) Autowired(org.springframework.beans.factory.annotation.Autowired) Random(java.util.Random) Sampler(brave.sampler.Sampler) After(org.junit.After) ArrayListSpanReporter(org.springframework.cloud.sleuth.util.ArrayListSpanReporter) GenericFilterBean(org.springframework.web.filter.GenericFilterBean) Filter(javax.servlet.Filter) SpringRunner(org.springframework.test.context.junit4.SpringRunner) DefaultTestAutoConfiguration(org.springframework.cloud.sleuth.instrument.DefaultTestAutoConfiguration) Tracer(brave.Tracer) MediaType(org.springframework.http.MediaType) BDDAssertions.then(org.assertj.core.api.BDDAssertions.then) RestController(org.springframework.web.bind.annotation.RestController) Configuration(org.springframework.context.annotation.Configuration) SpanUtil(org.springframework.cloud.sleuth.util.SpanUtil) Assertions.fail(org.assertj.core.api.Assertions.fail) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) ServletResponse(javax.servlet.ServletResponse) DefaultMockMvcBuilder(org.springframework.test.web.servlet.setup.DefaultMockMvcBuilder) Optional(java.util.Optional) LogFactory(org.apache.commons.logging.LogFactory) MockMvcRequestBuilders.asyncDispatch(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch) TracingFilter(brave.servlet.TracingFilter) RunWith(org.junit.runner.RunWith) DeferredResult(org.springframework.web.context.request.async.DeferredResult) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) CompletableFuture(java.util.concurrent.CompletableFuture) TraceKeys(org.springframework.cloud.sleuth.TraceKeys) MockMvcResultMatchers.status(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status) ManagementServerProperties(org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties) NestedServletException(org.springframework.web.util.NestedServletException) MvcResult(org.springframework.test.web.servlet.MvcResult) Before(org.junit.Before) Order(org.springframework.core.annotation.Order) ServletRequest(javax.servlet.ServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) HttpStatus(org.springframework.http.HttpStatus) Component(org.springframework.stereotype.Component) MDC(org.slf4j.MDC) BeanFactory(org.springframework.beans.factory.BeanFactory) Log(org.apache.commons.logging.Log) Bean(org.springframework.context.annotation.Bean) Random(java.util.Random) MvcResult(org.springframework.test.web.servlet.MvcResult) Span(brave.Span) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 53 with Filter

use of javax.servlet.Filter in project openmrs-core by openmrs.

the class WebModuleUtil method getFiltersForRequest.

/**
 * Return List of Filters that have been loaded through Modules that have mappings that pass for
 * the passed request
 *
 * @param request - The request to check for matching {@link Filter}s
 * @return List of all {@link Filter}s that have filter mappings that match the passed request
 */
public static List<Filter> getFiltersForRequest(ServletRequest request) {
    List<Filter> filters = new ArrayList<>();
    if (request != null) {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestPath = httpRequest.getRequestURI();
        if (requestPath != null) {
            if (requestPath.startsWith(httpRequest.getContextPath())) {
                requestPath = requestPath.substring(httpRequest.getContextPath().length());
            }
            for (ModuleFilterMapping filterMapping : WebModuleUtil.getFilterMappings()) {
                if (ModuleFilterMapping.filterMappingPasses(filterMapping, requestPath)) {
                    Filter passedFilter = moduleFiltersByName.get(filterMapping.getFilterName());
                    if (passedFilter != null) {
                        filters.add(passedFilter);
                    } else {
                        log.warn("Unable to retrieve filter that has a name of " + filterMapping.getFilterName() + " in filter mapping.");
                    }
                }
            }
        }
    }
    return filters;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Filter(javax.servlet.Filter) ArrayList(java.util.ArrayList) ModuleFilterMapping(org.openmrs.module.web.filter.ModuleFilterMapping)

Example 54 with Filter

use of javax.servlet.Filter in project openmrs-core by openmrs.

the class WebModuleUtil method loadFilters.

/**
 * This method will initialize and store this module's filters
 *
 * @param module - The Module to load and register Filters
 * @param servletContext - The servletContext within which this method is called
 */
public static void loadFilters(Module module, ServletContext servletContext) {
    // Load Filters
    Map<String, Filter> filters = new HashMap<>();
    try {
        for (ModuleFilterDefinition def : ModuleFilterDefinition.retrieveFilterDefinitions(module)) {
            if (moduleFiltersByName.containsKey(def.getFilterName())) {
                throw new ModuleException("A filter with name <" + def.getFilterName() + "> has already been registered.");
            }
            ModuleFilterConfig config = ModuleFilterConfig.getInstance(def, servletContext);
            Filter f = (Filter) ModuleFactory.getModuleClassLoader(module).loadClass(def.getFilterClass()).newInstance();
            f.init(config);
            filters.put(def.getFilterName(), f);
        }
    } catch (ModuleException e) {
        throw e;
    } catch (Exception e) {
        throw new ModuleException("An error occurred initializing Filters for module: " + module.getModuleId(), e);
    }
    moduleFilters.put(module, filters.values());
    moduleFiltersByName.putAll(filters);
    log.debug("Module: " + module.getModuleId() + " successfully loaded " + filters.size() + " filters.");
    // Load Filter Mappings
    List<ModuleFilterMapping> modMappings = ModuleFilterMapping.retrieveFilterMappings(module);
    moduleFilterMappings.addAll(modMappings);
    log.debug("Module: " + module.getModuleId() + " successfully loaded " + modMappings.size() + " filter mappings.");
}
Also used : Filter(javax.servlet.Filter) HashMap(java.util.HashMap) ModuleFilterDefinition(org.openmrs.module.web.filter.ModuleFilterDefinition) ModuleFilterConfig(org.openmrs.module.web.filter.ModuleFilterConfig) ModuleException(org.openmrs.module.ModuleException) ServletException(javax.servlet.ServletException) ModuleException(org.openmrs.module.ModuleException) SchedulerException(org.openmrs.scheduler.SchedulerException) FileNotFoundException(java.io.FileNotFoundException) TransformerException(javax.xml.transform.TransformerException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) ModuleFilterMapping(org.openmrs.module.web.filter.ModuleFilterMapping)

Example 55 with Filter

use of javax.servlet.Filter in project oozie by apache.

the class TestHostnameFilter method testMissingHostname.

public void testMissingHostname() throws Exception {
    ServletRequest request = Mockito.mock(ServletRequest.class);
    Mockito.when(request.getRemoteAddr()).thenReturn(null);
    ServletResponse response = Mockito.mock(ServletResponse.class);
    final AtomicBoolean invoked = new AtomicBoolean();
    FilterChain chain = new FilterChain() {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
            Assert.assertTrue(HostnameFilter.get().contains("???"));
            invoked.set(true);
        }
    };
    Filter filter = new HostnameFilter();
    filter.init(null);
    Assert.assertNull(HostnameFilter.get());
    filter.doFilter(request, response, chain);
    Assert.assertTrue(invoked.get());
    Assert.assertNull(HostnameFilter.get());
    filter.destroy();
}
Also used : ServletRequest(javax.servlet.ServletRequest) ServletResponse(javax.servlet.ServletResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Filter(javax.servlet.Filter) FilterChain(javax.servlet.FilterChain)

Aggregations

Filter (javax.servlet.Filter)185 FilterChain (javax.servlet.FilterChain)67 Test (org.junit.Test)57 HttpServletRequest (javax.servlet.http.HttpServletRequest)53 HttpServletResponse (javax.servlet.http.HttpServletResponse)44 ServletRequest (javax.servlet.ServletRequest)43 ServletResponse (javax.servlet.ServletResponse)43 ServletException (javax.servlet.ServletException)28 FilterConfig (javax.servlet.FilterConfig)25 IOException (java.io.IOException)23 ServletContext (javax.servlet.ServletContext)20 Injector (com.google.inject.Injector)17 FilterHolder (org.eclipse.jetty.servlet.FilterHolder)16 OncePerRequestFilter (org.springframework.web.filter.OncePerRequestFilter)13 AnnotationConfigApplicationContext (org.springframework.context.annotation.AnnotationConfigApplicationContext)12 Map (java.util.Map)9 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)9 ArrayList (java.util.ArrayList)8 Hashtable (java.util.Hashtable)8 DispatcherType (javax.servlet.DispatcherType)8