@Bean FilterRegistrationBean corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; }
@Test public void testSort(@Mocked Ordered o1, @Mocked Ordered o2) { Map<String, Ordered> map = new LinkedHashMap<>(); map.put("a", o1); map.put("b", o2); ServiceLoader<Ordered> serviceLoader = ServiceLoader.load(Ordered.class); Deencapsulation.setField(serviceLoader, "providers", map); new Expectations(ServiceLoader.class) { { o1.getOrder(); result = -1; o2.getOrder(); result = Integer.MAX_VALUE; ServiceLoader.load(Ordered.class); result = serviceLoader; } }; Assert.assertThat(SPIServiceUtils.getSortedService(Ordered.class), Matchers.contains(o1, o2)); Assert.assertThat(SPIServiceUtils.getPriorityHighestService(Ordered.class), Matchers.is(o1)); }
@Bean public FilterRegistrationBean casClientInfoLoggingFilter() { final AuditProperties audit = casProperties.getAudit(); final FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new ClientInfoThreadLocalFilter()); bean.setUrlPatterns(Collections.singleton("/*")); bean.setName("CAS Client Info Logging Filter"); bean.setAsyncSupported(true); bean.setOrder(Ordered.HIGHEST_PRECEDENCE); final Map<String, String> initParams = new HashMap<>(); if (StringUtils.isNotBlank(audit.getAlternateClientAddrHeaderName())) { initParams.put(ClientInfoThreadLocalFilter.CONST_IP_ADDRESS_HEADER, audit.getAlternateClientAddrHeaderName()); } if (StringUtils.isNotBlank(audit.getAlternateServerAddrHeaderName())) { initParams.put(ClientInfoThreadLocalFilter.CONST_SERVER_IP_ADDRESS_HEADER, audit.getAlternateServerAddrHeaderName()); } initParams.put(ClientInfoThreadLocalFilter.CONST_USE_SERVER_HOST_ADDRESS, String.valueOf(audit.isUseServerHostAddress())); bean.setInitParameters(initParams); return bean; }
@Override public final void configureTicketCatalog(final TicketCatalog plan) { LOGGER.debug("Registering core CAS protocol ticket definitions..."); buildAndRegisterProxyTicketDefinition(plan, buildTicketDefinition(plan, ProxyTicket.PROXY_TICKET_PREFIX, ProxyTicketImpl.class, Ordered.HIGHEST_PRECEDENCE)); buildAndRegisterServiceTicketDefinition(plan, buildTicketDefinition(plan, ServiceTicket.PREFIX, ServiceTicketImpl.class, Ordered.HIGHEST_PRECEDENCE)); buildAndRegisterProxyGrantingTicketDefinition(plan, buildTicketDefinition(plan, ProxyGrantingTicket.PROXY_GRANTING_TICKET_PREFIX, ProxyGrantingTicketImpl.class, Ordered.LOWEST_PRECEDENCE)); buildAndRegisterTicketGrantingTicketDefinition(plan, buildTicketDefinition(plan, TicketGrantingTicket.PREFIX, TicketGrantingTicketImpl.class, Ordered.LOWEST_PRECEDENCE)); }
@Bean public WebMvcConfigurer webMvcConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addViewControllers(ViewControllerRegistry viewControllerRegistry) { // 首页默认加载web端 viewControllerRegistry.addViewController("/").setViewName("/web/index.html"); viewControllerRegistry.addViewController("/index.html").setViewName("redirect:/"); // web首页 viewControllerRegistry.addViewController("/web").setViewName("/web/index.html"); // webapp首页 viewControllerRegistry.addViewController("/webapp").setViewName("/webapp/index.html"); viewControllerRegistry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(viewControllerRegistry); } }; }
@Bean(name = "VIFilterRegistrationBeanNew") public org.springframework.boot.web.servlet.FilterRegistrationBean factory() { if(environment != null) { String port = environment.getProperty("server.port"); if(port !=null) { System.setProperty(SysKeys.SPRINGBOOTPORTKEY, port); } } org.springframework.boot.web.servlet.FilterRegistrationBean filter = new org.springframework.boot.web.servlet.FilterRegistrationBean(); filter.setFilter(new VIFilter()); filter.setName("vi-filter"); filter.addUrlPatterns(URLPATTERNS); filter.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD); filter.setAsyncSupported(true); filter.setOrder(Ordered.HIGHEST_PRECEDENCE); return filter; }
@Bean public JmsMessageSender requestMessageSender(@Value("${jms-sender.ring-buffer-size}") int ringBufferSize) throws JMSException { DisruptorJmsMessageSender messageSender = DisruptorJmsMessageSenderFactory.create( requestSession(), requestMessageProducer(), new ArtemisMessageDtoDupMessageDetectStrategy(), ringBufferSize ); BeanRegisterUtils.registerSingleton( applicationContext, "RequestDtoEventDisruptorLifeCycleContainer", new DisruptorLifeCycleContainer("RequestDtoEventDisruptor", messageSender.getDisruptor(), Ordered.HIGHEST_PRECEDENCE)); return messageSender; }
@Override protected void doParse(Element element, BeanDefinitionBuilder builder) { String namespaces = element.getAttribute("namespaces"); //default to application if (Strings.isNullOrEmpty(namespaces)) { namespaces = ConfigConsts.NAMESPACE_APPLICATION; } int order = Ordered.LOWEST_PRECEDENCE; String orderAttribute = element.getAttribute("order"); if (!Strings.isNullOrEmpty(orderAttribute)) { try { order = Integer.parseInt(orderAttribute); } catch (Throwable ex) { throw new IllegalArgumentException( String.format("Invalid order: %s for namespaces: %s", orderAttribute, namespaces)); } } PropertySourcesProcessor.addNamespaces(NAMESPACE_SPLITTER.splitToList(namespaces), order); }
@ResponseBody @Order(Ordered.HIGHEST_PRECEDENCE) @ExceptionHandler(Throwable.class) public final ResponseEntity<Result<String>> handleUncaughtException(final Throwable exception, final WebRequest request) { // adds information about encountered error to application log LOG.error(MessageHelper.getMessage("logger.error", request.getDescription(true)), exception); HttpStatus code = HttpStatus.OK; String message; if (exception instanceof FileNotFoundException) { // any details about real path of a resource should be normally prevented to send to the client message = MessageHelper.getMessage("error.io.not.found"); } else if (exception instanceof DataAccessException) { // any details about data access error should be normally prevented to send to the client, // as its message can contain information about failed SQL query or/and database schema if (exception instanceof BadSqlGrammarException) { // for convenience we need to provide detailed information about occurred BadSqlGrammarException, // but it can be retrieved SQLException root = ((BadSqlGrammarException) exception).getSQLException(); if (root.getNextException() != null) { LOG.error(MessageHelper.getMessage("logger.error.root.cause", request.getDescription(true)), root.getNextException()); } message = MessageHelper.getMessage("error.sql.bad.grammar"); } else { message = MessageHelper.getMessage("error.sql"); } } else if (exception instanceof UnauthorizedClientException) { message = exception.getMessage(); code = HttpStatus.UNAUTHORIZED; } else { message = exception.getMessage(); } return new ResponseEntity<>(Result.error(StringUtils.defaultString(StringUtils.trimToNull(message), MessageHelper.getMessage("error" + ".default"))), code); }
/** * CORS: * <p> * Do not do any of below, which are the wrong way to attempt solving the ajax problem: * - http.authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll(); * - web.ignoring().antMatchers(HttpMethod.OPTIONS) * <p> * Global CORS configuration * https://spring.io/blog/2015/06/08/cors-support-in-spring-framework * https://docs.spring.io/spring-security/site/docs/current/reference/html/cors.html * <p> * Solution 1 * add CrossOrigin annotation to Controller class or methods * <p> * Solution 2 * override addCorsMappings(CorsRegistry registry) method of WebMvcConfigurerAdapter class * <p> * <p> * The follow method will override CORS Configuration provided by Spring MVC. */ @Bean public FilterRegistrationBean initCorsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); // setAllowCredentials(true) is important, otherwise: // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. config.setAllowCredentials(true); // setAllowedHeaders is important! Without it, OPTIONS preflight request // will fail with 403 Invalid CORS request config.setAllowedHeaders(ImmutableList.of("Authorization", "Cache-Control", "Content-Type")); config.addAllowedMethod("*"); String origins = this.applicationConfig.getAllowedOrigins(); if (origins != null && !"".equals(origins)) { config.setAllowedOrigins(Arrays.asList(StringHelper.splitWithoutWhitespace(origins, ","))); } source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(Ordered.HIGHEST_PRECEDENCE); return bean; }
@Override public String toString() { StringBuilder sb = new StringBuilder(); Advice advice = this.advisor.getAdvice(); sb.append(ClassUtils.getShortName(advice.getClass())); sb.append(": "); if (this.advisor instanceof Ordered) { sb.append("order ").append(((Ordered) this.advisor).getOrder()).append(", "); } if (advice instanceof AbstractAspectJAdvice) { AbstractAspectJAdvice ajAdvice = (AbstractAspectJAdvice) advice; sb.append(ajAdvice.getAspectName()); sb.append(", declaration order "); sb.append(ajAdvice.getDeclarationOrder()); } return sb.toString(); }
@Override public void addViewControllers(final ViewControllerRegistry registry) { super.addViewControllers(registry); registry.addViewController("/login/form") .setViewName("login"); registry.addViewController("/errors/403") .setViewName("/errors/403"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); }
@Bean DelegatingFilterProxyRegistrationBean delegatingFilterProxyRegistrationBean() { DelegatingFilterProxyRegistrationBean bean = new DelegatingFilterProxyRegistrationBean("traceLoggingFilter"); bean.setDispatcherTypes(ASYNC, ERROR, FORWARD, INCLUDE, REQUEST); bean.setOrder(Ordered.LOWEST_PRECEDENCE); return bean; }
@Async @Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleSomethingHasFuckedUp(final SomethingHasFuckedUpEvent event) { // We caught an unrecoverable exception in a thread, we better stop right now. logger.error("Event SomethingHasFuckedUpEvent caught.", event.getException()); // Stop the application SpringApplication.exit(appContext, () -> 42); }
@Override public void addViewControllers(final ViewControllerRegistry registry) { registry.addViewController("/ui").setViewName("redirect:ui/"); registry.addViewController("/ui/").setViewName("forward:index.html"); registry.setOrder(Ordered.HIGHEST_PRECEDENCE); super.addViewControllers(registry); }
@Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController( "/" ) .setViewName( "index" ); registry.addViewController( "/login" ) .setViewName( "login" ); registry.setOrder( Ordered.HIGHEST_PRECEDENCE ); super.addViewControllers( registry ); }
@Async @Order(Ordered.HIGHEST_PRECEDENCE) @EventListener void handleNoMoreTorrents(final NoMoreTorrentsFileAvailableEvent event) { logger.debug("Event NoMoreTorrentsFileAvailableEvent caught."); // logger.warn("There is no more .torrent file, add some more to resume seed."); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleConfigHasChanged(final ConfigHasChangedEvent event) { logger.debug("Send ConfigHasChangedEvent to clients."); this.messagingTemplate.convertAndSend("/config", new ConfigHasChangedPayload(event)); }
/** * 配置默认路径为文档 * @param registry */ @Override public void addViewControllers( ViewControllerRegistry registry ) { registry.addViewController( "" ).setViewName( "redirect:/swagger-ui.html" ); registry.setOrder( Ordered.HIGHEST_PRECEDENCE ); super.addViewControllers( registry ); }
@Async @Order(Ordered.HIGHEST_PRECEDENCE) @EventListener void handleSeedSessionHasEnded(final SeedSessionHasEndedEvent event) { logger.debug("Event SeedSessionHasEndedEvent caught."); // TODO : log that the seed session is over }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleAnnouncerHasAnnounced(final AnnouncerHasAnnouncedEvent event) { logger.debug("Send AnnouncerHasAnnouncedEvent to clients."); this.messagingTemplate.convertAndSend( "/announce", new AnnouncerHasAnnouncedPayload(event) ); }