@ConditionalOnMissingBean(name = "restAuthenticationThrottle") @Bean public HandlerInterceptor restAuthenticationThrottle() { final String throttler = casProperties.getRest().getThrottler(); if (StringUtils.isNotBlank(throttler) && this.applicationContext.containsBean(throttler)) { return this.applicationContext.getBean(throttler, HandlerInterceptor.class); } return new HandlerInterceptorAdapter() { @Override public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) { return true; } }; }
/** * Registered interceptor to all request except passed urls. * @param registry helps with configuring a list of mapped interceptors. * @param interceptor the interceptor */ protected void registerTenantInterceptorWithIgnorePathPattern( InterceptorRegistry registry, HandlerInterceptor interceptor) { InterceptorRegistration tenantInterceptorRegistration = registry.addInterceptor(interceptor); tenantInterceptorRegistration.addPathPatterns("/**"); List<String> tenantIgnorePathPatterns = getTenantIgnorePathPatterns(); Objects.requireNonNull(tenantIgnorePathPatterns, "tenantIgnorePathPatterns can't be null"); for (String pattern : tenantIgnorePathPatterns) { tenantInterceptorRegistration.excludePathPatterns(pattern); } LOGGER.info("Added handler interceptor '{}' to all urls, exclude {}", interceptor.getClass() .getSimpleName(), tenantIgnorePathPatterns); }
/** * Return a handler mapping ordered at Integer.MAX_VALUE-1 with mapped * resource handlers. To configure resource handling, override * {@link #addResourceHandlers}. */ @Bean public HandlerMapping resourceHandlerMapping() { ResourceHandlerRegistry registry = new ResourceHandlerRegistry(this.applicationContext, this.servletContext); addResourceHandlers(registry); AbstractHandlerMapping handlerMapping = registry.getHandlerMapping(); if (handlerMapping != null) { handlerMapping.setPathMatcher(mvcPathMatcher()); handlerMapping.setUrlPathHelper(mvcUrlPathHelper()); handlerMapping.setInterceptors(new HandlerInterceptor[] { new ResourceUrlProviderExposingInterceptor(mvcResourceUrlProvider())}); handlerMapping.setCorsConfigurations(getCorsConfigurations()); } else { handlerMapping = new EmptyHandlerMapping(); } return handlerMapping; }
@Test public void mappedInterceptors() throws Exception { String path = "/foo"; HandlerInterceptor interceptor = new HandlerInterceptorAdapter() {}; MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] {path}, interceptor); TestRequestMappingInfoHandlerMapping hm = new TestRequestMappingInfoHandlerMapping(); hm.registerHandler(new TestController()); hm.setInterceptors(new Object[] { mappedInterceptor }); hm.setApplicationContext(new StaticWebApplicationContext()); HandlerExecutionChain chain = hm.getHandler(new MockHttpServletRequest("GET", path)); assertNotNull(chain); assertNotNull(chain.getInterceptors()); assertSame(interceptor, chain.getInterceptors()[0]); chain = hm.getHandler(new MockHttpServletRequest("GET", "/invalid")); assertNull(chain); }
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) { PathMatcher pathMatcher = new AntPathMatcher(); List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>(); for (Object interceptor : this.registry.getInterceptors()) { if (interceptor instanceof MappedInterceptor) { MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor; if (mappedInterceptor.matches(lookupPath, pathMatcher)) { result.add(mappedInterceptor.getInterceptor()); } } else if (interceptor instanceof HandlerInterceptor) { result.add((HandlerInterceptor) interceptor); } else { fail("Unexpected interceptor type: " + interceptor.getClass().getName()); } } return result; }
/** * Print the handler. */ protected void printHandler(Object handler, HandlerInterceptor[] interceptors) throws Exception { if (handler == null) { this.printer.printValue("Type", null); } else { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; this.printer.printValue("Type", handlerMethod.getBeanType().getName()); this.printer.printValue("Method", handlerMethod); } else { this.printer.printValue("Type", handler.getClass().getName()); } } }
@Test public void sitePreferenceHandlerInterceptorRegistered() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, SitePreferenceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); RequestMappingHandlerMapping mapping = this.context .getBean(RequestMappingHandlerMapping.class); HandlerInterceptor[] interceptors = mapping .getHandler(new MockHttpServletRequest()).getInterceptors(); assertThat(interceptors) .hasAtLeastOneElementOfType(SitePreferenceHandlerInterceptor.class); }
@Test public void sitePreferenceHandlerInterceptorRegistered() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, SitePreferenceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); RequestMappingHandlerMapping mapping = this.context .getBean(RequestMappingHandlerMapping.class); HandlerInterceptor[] interceptors = mapping .getHandler(new MockHttpServletRequest()).getInterceptors(); assertThat(interceptors, hasItemInArray(instanceOf(SitePreferenceHandlerInterceptor.class))); }
@Test public void deviceResolverHandlerInterceptorRegistered() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, DeviceResolverAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); this.context.refresh(); RequestMappingHandlerMapping mapping = this.context .getBean(RequestMappingHandlerMapping.class); HandlerInterceptor[] interceptors = mapping .getHandler(new MockHttpServletRequest()).getInterceptors(); assertThat(interceptors, hasItemInArray(instanceOf(DeviceResolverHandlerInterceptor.class))); }
@Override public void addInterceptors(InterceptorRegistry registry) { /*Optional.ofNullable(interceptorList).ifPresent(list->{ list.stream().forEach(inter->registry.addInterceptor(inter)); });*/ if(LangUtils.isEmpty(interceptorList)){ return ; } for(HandlerInterceptor inter : interceptorList){ InterceptorRegistration reg = registry.addInterceptor(inter); if(inter instanceof WebInterceptorAdapter){ WebInterceptorAdapter webinter = (WebInterceptorAdapter) inter; if(LangUtils.isEmpty(webinter.getPathPatterns())){ continue; } reg.addPathPatterns(webinter.getPathPatterns()); } } // registry.addInterceptor(new BootFirstInterceptor()); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private List<HandlerInterceptor> getHandlerInterceptors(Class<? extends Object> clazz, Interceptors interceptorAnnotation) { List<HandlerInterceptor> interceptors = new ArrayList<HandlerInterceptor>(); if (interceptorAnnotation != null) { Class[] interceptorClasses = interceptorAnnotation.value(); if (interceptorClasses != null) { for (Class interceptorClass : interceptorClasses) { if (!HandlerInterceptor.class.isAssignableFrom(interceptorClass)) { raiseIllegalInterceptorValue(clazz, interceptorClass); } interceptors.add((HandlerInterceptor) getApplicationContext().getBean(interceptorClass)); } } } return interceptors; }
/** Print the handler */ protected void printHandler(Object handler, HandlerInterceptor[] interceptors) throws Exception { if (handler == null) { this.printer.printValue("Type", null); } else { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; this.printer.printValue("Type", handlerMethod.getBeanType().getName()); this.printer.printValue("Method", handlerMethod); } else { this.printer.printValue("Type", handler.getClass().getName()); } } }
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) { PathMatcher pathMatcher = new AntPathMatcher(); List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>(); for (Object i : registry.getInterceptors()) { if (i instanceof MappedInterceptor) { MappedInterceptor mappedInterceptor = (MappedInterceptor) i; if (mappedInterceptor.matches(lookupPath, pathMatcher)) { result.add(mappedInterceptor.getInterceptor()); } } else if (i instanceof HandlerInterceptor){ result.add((HandlerInterceptor) i); } else { fail("Unexpected interceptor type: " + i.getClass().getName()); } } return result; }
public void testShouldMergeInterceptors() throws Throwable { HandlerInterceptor interceptorOfFramework = new HandlerInterceptorSub(); HandlerInterceptor interceptorOfTab = new HandlerInterceptorSub(); HandlerInterceptor[] interceptorsOfFramework = new HandlerInterceptor[] {interceptorOfFramework}; HandlerInterceptor[] interceptorsOfTab = new HandlerInterceptor[] {interceptorOfTab}; Mock proceedingJoinPoint = mock(ProceedingJoinPoint.class); proceedingJoinPoint.expects(once()).method("proceed").will( returnValue(new HandlerExecutionChain(null, interceptorsOfTab))); InterceptorInjector injector = new InterceptorInjector(); injector.setInterceptors(interceptorsOfFramework); HandlerExecutionChain handlers = injector.mergeInterceptorsToTabs((ProceedingJoinPoint) proceedingJoinPoint.proxy()); assertEquals(2, handlers.getInterceptors().length); assertSame(interceptorOfFramework, handlers.getInterceptors()[0]); assertSame(interceptorOfTab, handlers.getInterceptors()[1]); }
public void testShouldJustReturnInterceptorsOfFrameworkIfNoTabInterceptors() throws Throwable { HandlerInterceptor interceptorOfFramework = new HandlerInterceptorSub(); HandlerInterceptor[] interceptorsOfFramework = new HandlerInterceptor[] {interceptorOfFramework}; Mock proceedingJoinPoint = mock(ProceedingJoinPoint.class); proceedingJoinPoint.expects(once()).method("proceed").will( returnValue(new HandlerExecutionChain(null, null))); InterceptorInjector injector = new InterceptorInjector(); injector.setInterceptors(interceptorsOfFramework); HandlerExecutionChain handlers = injector.mergeInterceptorsToTabs((ProceedingJoinPoint) proceedingJoinPoint.proxy()); assertEquals(1, handlers.getInterceptors().length); assertSame(interceptorOfFramework, handlers.getInterceptors()[0]); }
@Lazy @Bean public Object[] loginFlowHandlerMappingInterceptors() { final List interceptors = new ArrayList<>(); interceptors.add(localeChangeInterceptor()); if (this.applicationContext.containsBean("authenticationThrottle")) { interceptors.add(this.applicationContext.getBean("authenticationThrottle", HandlerInterceptor.class)); } return interceptors.toArray(); }
@Lazy @Bean public Object[] loginFlowHandlerMappingInterceptors() { List interceptors = new ArrayList(); interceptors.add(this.localeChangeInterceptor()); if (this.applicationContext.containsBean("authenticationThrottle")) { interceptors.add(this.applicationContext.getBean("authenticationThrottle", HandlerInterceptor.class)); } return interceptors.toArray(); }
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { List<? extends HandlerInterceptor> interceptors = getInterceptors(request, handler); if (!CollectionUtils.isEmpty(interceptors)) { for (HandlerInterceptor interceptor : interceptors) { boolean ret = interceptor.preHandle(request, response, handler); if (!ret) return false; } } return true; }
@Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { List<? extends HandlerInterceptor> interceptors = getInterceptors(request, handler); if (!CollectionUtils.isEmpty(interceptors)) { for (HandlerInterceptor interceptor : interceptors) { interceptor.postHandle(request, response, handler, modelAndView); } } }
@Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { List<? extends HandlerInterceptor> interceptors = getInterceptors(request, handler); if (!CollectionUtils.isEmpty(interceptors)) { for (HandlerInterceptor interceptor : interceptors) { interceptor.afterCompletion(request, response, handler, ex); } } }
private List<? extends HandlerInterceptor> getInterceptors(HttpServletRequest request, Object handler) { if (handler instanceof HandlerMethod) { HandlerMethod hm = (HandlerMethod) handler; Class<?> c = hm.getBeanType(); Method method = hm.getMethod(); List<? extends HandlerInterceptor> interceptors = interceptorCaches.get(method); if (interceptors == null) { interceptors = searchInterceptors(c, method, request); } return interceptors; } return null; }
private List<? extends HandlerInterceptor> searchInterceptors(Class<?> clazz, Method method, HttpServletRequest request) { // search class Annotation[] annotations = clazz.getAnnotations(); List<HandlerInterceptor> list = instantiateInterceptors(request, annotations); // search method List<HandlerInterceptor> mlist = instantiateInterceptors(request, method.getAnnotations()); if (!mlist.isEmpty()) { list.addAll(mlist); } // sort interceptors Collections.sort(list, new Comparator<HandlerInterceptor>() { @Override public int compare(HandlerInterceptor o1, HandlerInterceptor o2) { int s1 = 0; int s2 = 0; if (o1 instanceof Ordered) s1 = ((Ordered) o1).getOrder(); if (o2 instanceof Ordered) s2 = ((Ordered) o2).getOrder(); return s1 > s2 ? 1 : (s1 < s2 ? -1 : 0); } }); LOG.info("Sorted interceptor:" + method.getName() + ",list=" + list); // print log if (!list.isEmpty()) { StringBuilder log = new StringBuilder("Handler interceptors : class=" + clazz.getSimpleName() + ",method=" + method + "["); for (int i = 0; i < list.size(); i++) { log.append(list.get(i).getClass().getCanonicalName()); if (i < list.size() - 1) log.append(","); } log.append("]"); LOG.info(log.toString()); } interceptorCaches.put(method, list); return list; }
/** * Return all configured {@link MappedInterceptor}s as an array. * @return the array of {@link MappedInterceptor}s, or {@code null} if none */ protected final MappedInterceptor[] getMappedInterceptors() { List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>(); for (HandlerInterceptor interceptor : this.adaptedInterceptors) { if (interceptor instanceof MappedInterceptor) { mappedInterceptors.add((MappedInterceptor) interceptor); } } int count = mappedInterceptors.size(); return (count > 0 ? mappedInterceptors.toArray(new MappedInterceptor[count]) : null); }
@Test public void preHandle() throws Exception { HandlerInterceptor interceptor = mock(HandlerInterceptor.class); MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor); mappedInterceptor.preHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), null); then(interceptor).should().preHandle(any(HttpServletRequest.class), any(HttpServletResponse.class), any()); }
@Test public void postHandle() throws Exception { HandlerInterceptor interceptor = mock(HandlerInterceptor.class); MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor); mappedInterceptor.postHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), null, mock(ModelAndView.class)); then(interceptor).should().postHandle(any(), any(), any(), any()); }
@Test public void afterCompletion() throws Exception { HandlerInterceptor interceptor = mock(HandlerInterceptor.class); MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor); mappedInterceptor.afterCompletion(mock(HttpServletRequest.class), mock(HttpServletResponse.class), null, mock(Exception.class)); then(interceptor).should().afterCompletion(any(), any(), any(), any()); }
private HandlerExecutionChain getHandler(MockHttpServletRequest req) throws Exception { HandlerExecutionChain hec = hm.getHandler(req); HandlerInterceptor[] interceptors = hec.getInterceptors(); if (interceptors != null) { for (HandlerInterceptor interceptor : interceptors) { interceptor.preHandle(req, null, hec.getHandler()); } } return hec; }
private HandlerExecutionChain getHandler(HandlerMapping hm, MockHttpServletRequest req) throws Exception { HandlerExecutionChain hec = hm.getHandler(req); HandlerInterceptor[] interceptors = hec.getInterceptors(); if (interceptors != null) { for (HandlerInterceptor interceptor : interceptors) { interceptor.preHandle(req, null, hec.getHandler()); } } return hec; }
@Test public void orderedInterceptors() throws Exception { MappedInterceptor firstMappedInterceptor = new MappedInterceptor(new String[]{"/**"}, Mockito.mock(HandlerInterceptor.class)); HandlerInterceptor secondHandlerInterceptor = Mockito.mock(HandlerInterceptor.class); MappedInterceptor thirdMappedInterceptor = new MappedInterceptor(new String[]{"/**"}, Mockito.mock(HandlerInterceptor.class)); HandlerInterceptor fourthHandlerInterceptor = Mockito.mock(HandlerInterceptor.class); this.handlerMapping.setInterceptors(new Object[]{firstMappedInterceptor, secondHandlerInterceptor, thirdMappedInterceptor, fourthHandlerInterceptor}); this.handlerMapping.setApplicationContext(this.context); HandlerExecutionChain chain = this.handlerMapping.getHandlerExecutionChain(new SimpleHandler(), this.request); Assert.assertThat(chain.getInterceptors(), Matchers.arrayContaining(firstMappedInterceptor.getInterceptor(), secondHandlerInterceptor, thirdMappedInterceptor.getInterceptor(), fourthHandlerInterceptor)); }
@Test public void testResources() throws Exception { loadBeanDefinitions("mvc-config-resources.xml", 10); HttpRequestHandlerAdapter adapter = appContext.getBean(HttpRequestHandlerAdapter.class); assertNotNull(adapter); ResourceHttpRequestHandler handler = appContext.getBean(ResourceHttpRequestHandler.class); assertNotNull(handler); SimpleUrlHandlerMapping mapping = appContext.getBean(SimpleUrlHandlerMapping.class); assertNotNull(mapping); assertEquals(Ordered.LOWEST_PRECEDENCE - 1, mapping.getOrder()); BeanNameUrlHandlerMapping beanNameMapping = appContext.getBean(BeanNameUrlHandlerMapping.class); assertNotNull(beanNameMapping); assertEquals(2, beanNameMapping.getOrder()); ResourceUrlProvider urlProvider = appContext.getBean(ResourceUrlProvider.class); assertNotNull(urlProvider); MappedInterceptor mappedInterceptor = appContext.getBean(MappedInterceptor.class); assertNotNull(urlProvider); assertEquals(ResourceUrlProviderExposingInterceptor.class, mappedInterceptor.getInterceptor().getClass()); MockHttpServletRequest request = new MockHttpServletRequest(); request.setRequestURI("/resources/foo.css"); request.setMethod("GET"); HandlerExecutionChain chain = mapping.getHandler(request); assertTrue(chain.getHandler() instanceof ResourceHttpRequestHandler); MockHttpServletResponse response = new MockHttpServletResponse(); for (HandlerInterceptor interceptor : chain.getInterceptors()) { interceptor.preHandle(request, response, chain.getHandler()); } ModelAndView mv = adapter.handle(request, response, chain.getHandler()); assertNull(mv); }
@Test public void addTwoInterceptors() { this.registry.addInterceptor(this.interceptor1); this.registry.addInterceptor(this.interceptor2); List<HandlerInterceptor> interceptors = getInterceptorsForPath(null); assertEquals(Arrays.asList(this.interceptor1, this.interceptor2), interceptors); }
@Test public void addWebRequestInterceptor() throws Exception { this.registry.addWebRequestInterceptor(this.webInterceptor1); List<HandlerInterceptor> interceptors = getInterceptorsForPath(null); assertEquals(1, interceptors.size()); verifyWebInterceptor(interceptors.get(0), this.webInterceptor1); }
@Test public void addWebRequestInterceptors() throws Exception { this.registry.addWebRequestInterceptor(this.webInterceptor1); this.registry.addWebRequestInterceptor(this.webInterceptor2); List<HandlerInterceptor> interceptors = getInterceptorsForPath(null); assertEquals(2, interceptors.size()); verifyWebInterceptor(interceptors.get(0), this.webInterceptor1); verifyWebInterceptor(interceptors.get(1), this.webInterceptor2); }
@Test public void addWebRequestInterceptorsWithUrlPatterns() throws Exception { this.registry.addWebRequestInterceptor(this.webInterceptor1).addPathPatterns("/path1"); this.registry.addWebRequestInterceptor(this.webInterceptor2).addPathPatterns("/path2"); List<HandlerInterceptor> interceptors = getInterceptorsForPath("/path1"); assertEquals(1, interceptors.size()); verifyWebInterceptor(interceptors.get(0), this.webInterceptor1); interceptors = getInterceptorsForPath("/path2"); assertEquals(1, interceptors.size()); verifyWebInterceptor(interceptors.get(0), this.webInterceptor2); }
/** * Add interceptors mapped to a set of path patterns. */ public StandaloneMockMvcBuilder addMappedInterceptors(String[] pathPatterns, HandlerInterceptor... interceptors) { for (HandlerInterceptor interceptor : interceptors) { this.mappedInterceptors.add(new MappedInterceptor(pathPatterns, interceptor)); } return this; }
public StubMvcResult(MockHttpServletRequest request, Object handler, HandlerInterceptor[] interceptors, Exception resolvedException, ModelAndView mav, FlashMap flashMap, MockHttpServletResponse response) { this.request = request; this.handler = handler; this.interceptors = interceptors; this.resolvedException = resolvedException; this.mav = mav; this.flashMap = flashMap; this.response = response; }
@Test public void deviceResolverHandlerInterceptorRegistered() throws Exception { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(Config.class); this.context.refresh(); RequestMappingHandlerMapping mapping = this.context .getBean(RequestMappingHandlerMapping.class); HandlerInterceptor[] interceptors = mapping .getHandler(new MockHttpServletRequest()).getInterceptors(); assertThat(interceptors) .hasAtLeastOneElementOfType(DeviceResolverHandlerInterceptor.class); }