@Bean @Order(-1) PropertySource dispacherPropertySource() throws IOException { YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); // profile null is default PropertySource propertySource = loader.load("dispachers", new ClassPathResource("dispatch.yml"),null); env.getPropertySources().addLast(propertySource); return propertySource; }
private void findAndRegisterAnnotatedDelegateMethods(Object bean, Method method) { RequestMapping requestMapping = method .getAnnotation(RequestMapping.class); if (requestMapping != null) { String[] paths = requestMapping.value(); for (String path : paths) { if (path != null && !path.isEmpty()) { DelegateMethodInvoker delegate = new DelegateMethodInvoker( bean, method, findMatchingArgumentResolvers(method), findMatchingReturnValueHandler(method)); Order order = method.getAnnotation(Order.class); if (order == null) { registerDelegate(path, delegate); } else { registerDelegate(path, delegate, order.value()); } } } } }
@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); }
@Override @Order(1) protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers(publicPath) .permitAll() .and() .formLogin() .loginPage("/auth/login") .successForwardUrl("/auth/status") .failureForwardUrl("/auth/status") .permitAll() .and() .logout() .logoutUrl("/auth/logout") .logoutSuccessUrl("/") .invalidateHttpSession(true) .deleteCookies() .and() .sessionManagement() .maximumSessions(1) .maxSessionsPreventsLogin(false) ;// END HTTP CONFIG }
@Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesWithMetaAnnotationWithDefaultAttributes() throws Exception { Class<?> startClass = MetaConfigWithDefaultAttributesTestCase.class; Class<ContextConfiguration> annotationType = ContextConfiguration.class; UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class); assertNotNull(descriptor); assertEquals(startClass, descriptor.getRootDeclaringClass()); assertEquals(annotationType, descriptor.getAnnotationType()); assertArrayEquals(new Class[] {}, ((ContextConfiguration) descriptor.getAnnotation()).value()); assertArrayEquals(new Class[] { MetaConfig.DevConfig.class, MetaConfig.ProductionConfig.class }, descriptor.getAnnotationAttributes().getClassArray("classes")); assertNotNull(descriptor.getComposedAnnotation()); assertEquals(MetaConfig.class, descriptor.getComposedAnnotationType()); }
@Test @SuppressWarnings("unchecked") public void findAnnotationDescriptorForTypesWithMetaAnnotationWithOverriddenAttributes() throws Exception { Class<?> startClass = MetaConfigWithOverriddenAttributesTestCase.class; Class<ContextConfiguration> annotationType = ContextConfiguration.class; UntypedAnnotationDescriptor descriptor = findAnnotationDescriptorForTypes(startClass, Service.class, ContextConfiguration.class, Order.class, Transactional.class); assertNotNull(descriptor); assertEquals(startClass, descriptor.getRootDeclaringClass()); assertEquals(annotationType, descriptor.getAnnotationType()); assertArrayEquals(new Class[] {}, ((ContextConfiguration) descriptor.getAnnotation()).value()); assertArrayEquals(new Class[] { MetaAnnotationUtilsTests.class }, descriptor.getAnnotationAttributes().getClassArray("classes")); assertNotNull(descriptor.getComposedAnnotation()); assertEquals(MetaConfig.class, descriptor.getComposedAnnotationType()); }
@Order(Ordered.HIGHEST_PRECEDENCE + 3) @EventListener public void handleWorkspaceStatusEvent(WorkspaceStatusEvent event) { String spaceKey = event.getSpaceKey(); if (event instanceof WorkspaceOnlineEvent) { updateWorkingStatus(spaceKey, Online); watch(spaceKey); } else if (event instanceof WorkspaceOfflineEvent) { if (!wsRepo.isDeleted(spaceKey)) { updateWorkingStatus(spaceKey, Offline); } unwatch(spaceKey); } else if (event instanceof WorkspaceDeleteEvent) { updateWorkingStatus(spaceKey, Deleted); unwatch(spaceKey); } }
@Override @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) protected void configure(final HttpSecurity httpSecurity) throws Exception { httpSecurity .authorizeRequests() .antMatchers("/fonts/**").permitAll() .antMatchers("/register").permitAll() .anyRequest().authenticated() .and() .formLogin().loginPage("/login").permitAll() .and() .logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).permitAll() .and() .exceptionHandling().accessDeniedPage("/access?error") .and().headers().xssProtection().block(false).xssProtectionEnabled(false).and() // Default setting for Spring Boot to activate XSS Protection (dont fix!) .and().csrf().disable(); // FIXME [dh] Enabling CSRF prevents file upload, must be fixed }
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 10) @EventListener protected void onAppLoggedOut(AppLoggedOutEvent event) { if (webIdpConfig.getIdpEnabled() && event.getLoggedOutSession() != null && event.getLoggedOutSession().getAttribute(IdpService.IDP_USER_SESSION_ATTRIBUTE) != null && event.getRedirectUrl() == null) { RequestContext requestContext = RequestContext.get(); if (requestContext != null) { requestContext.getSession().removeAttribute(IDP_SESSION_ATTRIBUTE); } String idpBaseURL = webIdpConfig.getIdpBaseURL(); if (!Strings.isNullOrEmpty(idpBaseURL)) { event.setRedirectUrl(getIdpLogoutUrl()); } else { log.error("Application property cuba.web.idp.url is not set"); } } }
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 10) @EventListener protected void appStarted(AppStartedEvent event) { App app = event.getApp(); Locale locale = app.getLocale(); Principal principal = getSessionPrincipal(); // Login on start only on first request from user if (isTryLoginOnStart() && principal != null && webAuthConfig.getExternalAuthentication()) { String userName = principal.getName(); log.debug("Trying to login after external authentication as {}", userName); try { app.getConnection().loginAfterExternalAuthentication(userName, locale); } catch (LoginException e) { log.trace("Unable to login on start", e); } finally { // Close attempt login on start setTryLoginOnStart(false); } } }
@Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 10) @EventListener protected void pingExternalAuthentication(SessionHeartbeatEvent event) { Connection connection = event.getSource().getConnection(); if (connection.isAuthenticated() && isLoggedInWithExternalAuth(connection.getSessionNN())) { try { // Ping external authentication if (webAuthConfig.getExternalAuthentication()) { UserSession session = connection.getSession(); if (session != null) { authProvider.pingUserSession(session); } } } catch (NoUserSessionException ignored) { // ignore no user session exception } catch (Exception e) { log.warn("Exception while external authenticated session ping", e); } } }
@EventListener(AppContextInitializedEvent.class) @Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 10) protected void initMetadata() { if (session != null) { log.warn("Repetitive initialization\n" + StackTrace.asString()); return; } log.info("Initializing metadata"); long startTime = System.currentTimeMillis(); MetadataLoader metadataLoader = (MetadataLoader) applicationContext.getBean(MetadataLoader.NAME); metadataLoader.loadMetadata(); rootPackages = metadataLoader.getRootPackages(); session = new CachingMetadataSession(metadataLoader.getSession()); SessionImpl.setSerializationSupportSession(session); log.info("Metadata initialized in " + (System.currentTimeMillis() - startTime) + "ms"); }
@EventListener(AppContextInitializedEvent.class) @Order(Events.HIGHEST_PLATFORM_PRECEDENCE + 100) public void init() { String iconSetsProp = AppContext.getProperty("cuba.iconsConfig"); if (StringUtils.isEmpty(iconSetsProp)) return; for (String iconSetFqn : Splitter.on(' ').omitEmptyStrings().trimResults().split(iconSetsProp)) { try { Class<?> iconSetClass = ReflectionHelper.loadClass(iconSetFqn); if (!Icon.class.isAssignableFrom(iconSetClass)) { log.warn(iconSetClass + " is does not implement Icon"); continue; } //noinspection unchecked iconSets.add((Class<? extends Icon>) iconSetClass); } catch (ClassNotFoundException e) { throw new RuntimeException(String.format("Unable to load icon set class: %s", iconSetFqn), e); } } }
@Bean @Order(value = 1) public ResourceUrlEncodingFilter resourceUrlEncodingFilter() { // システムプロパティーが設定されていればデフォルト実装を使う String prop = System.getProperty("ResourceUrlEncodingFilter"); if (StringUtils.equals(prop, "original")) { logger.info("using ResourceUrlEncodingFilter"); return new ResourceUrlEncodingFilter(); } // そうでなければCachingResourceUrlEncodingFilterを使う else { logger.info("using CachingResourceUrlEncodingFilter"); return new CachingResourceUrlEncodingFilter("/static/"); } }
@Bean @Order(1) public DiscoveryClient customDiscoveryClient() { return new DiscoveryClient() { @Override public String description() { return "A custom discovery client"; } @Override public List<ServiceInstance> getInstances(String serviceId) { if (serviceId.equals("custom")) { ServiceInstance s1 = new DefaultServiceInstance("custom", "host", 123, false); return Arrays.asList(s1); } return Collections.emptyList(); } @Override public List<String> getServices() { return Arrays.asList("custom"); } }; }
@Order(value = 2) @Around("extensionPointcut() && @annotation(coreDataModificationStatus) && args(sc,..)") public Object interceptExtensionPoint(ProceedingJoinPoint p, CoreDataModificationStatus coreDataModificationStatus, ServiceContext sc) throws Throwable { Object ret = null; dataModificationStatus.setModificationType(coreDataModificationStatus.modificationType()); dataModificationStatus.setModificationState(ModificationState.REQUESTED); try { ret = p.proceed(); } catch (Throwable e) { dataModificationStatus.setModificationState(ModificationState.FAILURE); throw e; } dataModificationStatus.setModificationState(ModificationState.SUCCESS); return ret; }
@Bean @Order(-1) PropertySource consumerPropertySource() throws IOException { YamlPropertySourceLoader loader = new YamlPropertySourceLoader(); PropertySource propertySource = loader.load("consumers", new ClassPathResource("consumer.yml"),null); env.getPropertySources().addLast(propertySource); return propertySource; }
@ConditionalOnMissingBean(name = "duoMultifactorWebflowConfigurer") @Bean @Order(Ordered.HIGHEST_PRECEDENCE) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) public CasWebflowConfigurer duoMultifactorWebflowConfigurer() { final boolean deviceRegistrationEnabled = casProperties.getAuthn().getMfa().getTrusted().isDeviceRegistrationEnabled(); return new DuoMultifactorWebflowConfigurer(flowBuilderServices, loginFlowDefinitionRegistry, deviceRegistrationEnabled, duoMultifactorAuthenticationProvider()); }
@Bean @Order(2) @ConditionalOnExpression("${xm-config.enabled} && ${tenant.reject-suspended:true}") TenantVerifyInterceptor tenantVerifyInterceptor(TenantListRepository tenantListRepository, TenantContextHolder tenantContextHolder) { return new TenantVerifyInterceptor(tenantListRepository, tenantContextHolder); }
@Bean @Order(Ordered.HIGHEST_PRECEDENCE) public CharacterEncodingFilter characterEncodingFilter() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); filter.setForceEncoding(true); return filter; }
@ExceptionHandler({ServiceException.class, SystemException.class, Exception.class}) @Order(Ordered.LOWEST_PRECEDENCE) protected ResponseEntity<Object> handleServiceException(Exception e, WebRequest request) { log(request, e); ErrorResource error = new ErrorResource(getCode(e), getMessage(e)); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return handleExceptionInternal(e, error, headers, HttpStatus.INTERNAL_SERVER_ERROR, request); }
/** * Determine the order for this factory's target aspect, either * an instance-specific order expressed through implementing the * {@link org.springframework.core.Ordered} interface (only * checked for singleton beans), or an order expressed through the * {@link org.springframework.core.annotation.Order} annotation * at the class level. * @see org.springframework.core.Ordered * @see org.springframework.core.annotation.Order */ @Override public int getOrder() { Class<?> type = this.beanFactory.getType(this.name); if (type != null) { if (Ordered.class.isAssignableFrom(type) && this.beanFactory.isSingleton(this.name)) { return ((Ordered) this.beanFactory.getBean(this.name)).getOrder(); } Order order = AnnotationUtils.findAnnotation(type, Order.class); if (order != null) { return order.value(); } } return Ordered.LOWEST_PRECEDENCE; }
/** * Determine a fallback order for the case that the aspect instance * does not express an instance-specific order through implementing * the {@link org.springframework.core.Ordered} interface. * <p>The default implementation simply returns {@code Ordered.LOWEST_PRECEDENCE}. * @param aspectClass the aspect class */ @Override protected int getOrderForAspectClass(Class<?> aspectClass) { Order order = AnnotationUtils.findAnnotation(aspectClass, Order.class); if (order != null) { return order.value(); } return Ordered.LOWEST_PRECEDENCE; }
/** * Check whether the aspect class carries an * {@link org.springframework.core.annotation.Order} annotation, * falling back to {@code Ordered.LOWEST_PRECEDENCE}. * @see org.springframework.core.annotation.Order */ @Override protected int getOrderForAspectClass(Class<?> aspectClass) { Order order = AnnotationUtils.findAnnotation(aspectClass, Order.class); if (order != null) { return order.value(); } return Ordered.LOWEST_PRECEDENCE; }
@Bean @Order(value = 0) FilterRegistrationBean sessionRepositoryFilterRegistration( SessionRepositoryFilter filter) { FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean( new DelegatingFilterProxy(filter)); filterRegistrationBean.setUrlPatterns(Arrays.asList("/*")); return filterRegistrationBean; }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleAnnouncerHasStarted(final AnnouncerHasStartedEvent event) { logger.debug("Send AnnouncerHasStartedEvent to clients."); this.messagingTemplate.convertAndSend("/announce", new AnnouncerHasStartedPayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleAnnounceHasStopped(final AnnouncerHasStoppedEvent event) { logger.debug("Send AnnouncerHasStoppedEvent to clients."); this.messagingTemplate.convertAndSend("/announce", new AnnouncerHasStoppedPayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleAnnouncerWillAnnounce(final AnnouncerWillAnnounceEvent event) { logger.debug("Send AnnouncerWillAnnounceEvent to clients."); this.messagingTemplate.convertAndSend("/announce", new AnnouncerWillAnnouncePayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleAnnouncerHasAnnounced(final AnnouncerHasAnnouncedEvent event) { logger.debug("Send AnnouncerHasAnnouncedEvent to clients."); this.messagingTemplate.convertAndSend( "/announce", new AnnouncerHasAnnouncedPayload(event) ); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleAnnouncerFailedToAnnounce(final AnnouncerHasFailedToAnnounceEvent event) { logger.debug("Send AnnouncerHasFailedToAnnounceEvent to clients."); this.messagingTemplate.convertAndSend( "/announce", new AnnouncerHasFailedToAnnouncePayload(event) ); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleSeedSessionHasStarted(final SeedSessionHasStartedEvent event) { logger.debug("Send SeedSessionHasStartedPayload to clients."); final String client = event.getBitTorrentClient().getHeaders().stream() .filter(entry -> "User-Agent".equalsIgnoreCase(entry.getKey())) .map(Map.Entry::getValue) .findFirst() .orElse("Unknown"); this.messagingTemplate.convertAndSend("/global", new SeedSessionHasStartedPayload(client)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleSeedSessionHasEnded(final SeedSessionHasEndedEvent event) { logger.debug("Send SeedSessionHasEndedPayload to clients."); this.messagingTemplate.convertAndSend("/global", new SeedSessionHasEndedPayload()); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleTorrentFileAdded(final TorrentFileAddedEvent event) { logger.debug("Send TorrentFileAddedPayload to clients."); this.messagingTemplate.convertAndSend("/torrents", new TorrentFileAddedPayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleTorrentFileDeleted(final TorrentFileDeletedEvent event) { logger.debug("Send TorrentFileDeletedPayload to clients."); this.messagingTemplate.convertAndSend("/torrents", new TorrentFileDeletedPayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleFailedToAddTorrentFile(final FailedToAddTorrentFileEvent event) { logger.debug("Send FailedToAddTorrentFilePayload to clients."); this.messagingTemplate.convertAndSend("/torrents", new FailedToAddTorrentFilePayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleConfigHasChanged(final ConfigHasChangedEvent event) { logger.debug("Send ConfigHasChangedEvent to clients."); this.messagingTemplate.convertAndSend("/config", new ConfigHasChangedPayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleConfigHasBeenLoaded(final ConfigHasBeenLoadedEvent event) { logger.debug("Send ConfigHasBeenLoadedEvent to clients."); this.messagingTemplate.convertAndSend("/config", new ConfigHasBeenLoadedPayload(event)); }
@Order(Ordered.LOWEST_PRECEDENCE) @EventListener void handleClientFilesDiscovered(final ClientFilesDiscoveredEvent event) { logger.debug("Send ClientFilesDiscoveredEvent to clients."); this.messagingTemplate.convertAndSend("/config", new ClientFilesDiscoveredPayload(event)); }
@Async @Order(Ordered.HIGHEST_PRECEDENCE) @EventListener void handleAnnounceRequesting(final AnnouncerWillAnnounceEvent event) { final RequestEvent announceEvent = event.getEvent(); final TorrentWithStats torrent = event.getTorrent(); logger.info( "Announced {} for torrent {} Up={}/Down={}/Left={}", announceEvent == RequestEvent.NONE ? "" : announceEvent, torrent.getTorrent().getName(), FileUtils.byteCountToDisplaySize(torrent.getUploaded()), FileUtils.byteCountToDisplaySize(torrent.getDownloaded()), FileUtils.byteCountToDisplaySize(torrent.getLeft()) ); }
@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."); }