Java Code Examples for org.springframework.context.annotation.Conditional

The following examples show how to use org.springframework.context.annotation.Conditional. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Provide IDP Metadata
 * 
 * @return
 * @throws MetadataProviderException
 */
@Bean
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public ExtendedMetadataDelegate idpMetadata() throws MetadataProviderException {

	Timer backgroundTaskTimer = new Timer(true);

	HTTPMetadataProvider httpMetadataProvider = new HTTPMetadataProvider(backgroundTaskTimer, new HttpClient(),
			singleSignOnConfig.getMetadataUrl());

	httpMetadataProvider.setParserPool(parserPool());

	ExtendedMetadataDelegate extendedMetadataDelegate = new ExtendedMetadataDelegate(httpMetadataProvider,
			extendedMetadata());
	extendedMetadataDelegate.setMetadataTrustCheck(true);
	extendedMetadataDelegate.setMetadataRequireSignature(true);
	return extendedMetadataDelegate;
}
 
Example 2
Source Project: ambari-logsearch   Source File: ApplicationConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@DependsOn("logFeederSecurityConfig")
@Conditional(NonCloudStorageCondition.class)
public LogSearchConfigLogFeeder logSearchConfigLogFeeder() throws Exception {
  if (logFeederProps.isUseLocalConfigs()) {
    LogSearchConfigLogFeeder logfeederConfig = LogSearchConfigFactory.createLogSearchConfigLogFeeder(
      Maps.fromProperties(logFeederProps.getProperties()),
      logFeederProps.getClusterName(),
      LogSearchConfigLogFeederLocal.class, false);
    logfeederConfig.setLogLevelFilterManager(logLevelFilterManager());
    return logfeederConfig;
  } else {
    return LogSearchConfigFactory.createLogSearchConfigLogFeeder(
      Maps.fromProperties(logFeederProps.getProperties()),
      logFeederProps.getClusterName(),
      LogSearchConfigLogFeederZK.class, false);
  }
}
 
Example 3
Source Project: ambari-logsearch   Source File: ApplicationConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
@Conditional(NonCloudStorageCondition.class)
public LogLevelFilterManager logLevelFilterManager() throws Exception {
  if (logFeederProps.isSolrFilterStorage()) {
    SolrClient solrClient = new LogFeederSolrClientFactory().createSolrClient(
      logFeederProps.getSolrZkConnectString(), logFeederProps.getSolrUrls(), logFeederProps.getSolrMetadataCollection(),
      logFeederProps.isSolrCloudDiscover());
    return new LogLevelFilterManagerSolr(solrClient);
  } else if (logFeederProps.isUseLocalConfigs() && logFeederProps.isZkFilterStorage()) {
    final HashMap<String, String> map = new HashMap<>();
    for (final String name : logFeederProps.getProperties().stringPropertyNames()) {
      map.put(name, logFeederProps.getProperties().getProperty(name));
    }
    return new LogLevelFilterManagerZK(map);
  } else {
    return null;
  }
}
 
Example 4
@Bean
@Conditional({ SchedulerConfiguration.SchedulerConfigurationPropertyChecker.class })
public SchedulerService schedulerService(CommonApplicationProperties commonApplicationProperties,
		List<TaskPlatform> taskPlatforms, TaskDefinitionRepository taskDefinitionRepository,
		AppRegistryService registry, ResourceLoader resourceLoader,
		ApplicationConfigurationMetadataResolver metaDataResolver,
		SchedulerServiceProperties schedulerServiceProperties,
		AuditRecordService auditRecordService,
		TaskConfigurationProperties taskConfigurationProperties,
		DataSourceProperties dataSourceProperties) {
	return new DefaultSchedulerService(commonApplicationProperties,
			taskPlatforms, taskDefinitionRepository,
			registry, resourceLoader,
			taskConfigurationProperties, dataSourceProperties, null,
			metaDataResolver, schedulerServiceProperties, auditRecordService);
}
 
Example 5
@Bean
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public SAMLProcessorImpl processor() {

	Collection<SAMLBinding> bindings = new ArrayList<>();

	ArtifactResolutionProfileImpl artifactResolutionProfile = new ArtifactResolutionProfileImpl(httpClient());
	HTTPSOAP11Binding soapBinding = new HTTPSOAP11Binding(parserPool());
	artifactResolutionProfile.setProcessor(new SAMLProcessorImpl(soapBinding));

	bindings.add(httpRedirectDeflateBinding());
	bindings.add(httpPostBinding());
	bindings.add(new HTTPArtifactBinding(parserPool(), velocityEngine(), artifactResolutionProfile));
	bindings.add(new HTTPSOAP11Binding(parserPool()));
	bindings.add(new HTTPPAOS11Binding(parserPool()));
	return new SAMLProcessorImpl(bindings);
}
 
Example 6
Source Project: resilience4j   Source File: TimeLimiterConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Conditional(AspectJOnClasspathCondition.class)
public TimeLimiterAspect timeLimiterAspect(
    TimeLimiterConfigurationProperties timeLimiterConfigurationProperties,
    TimeLimiterRegistry timeLimiterRegistry,
    @Autowired(required = false) List<TimeLimiterAspectExt> timeLimiterAspectExtList,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    return new TimeLimiterAspect(timeLimiterRegistry, timeLimiterConfigurationProperties, timeLimiterAspectExtList, fallbackDecorators, spelResolver);
}
 
Example 7
/**
 * Creates a GrpcServerFactory using the shaded netty. This is the recommended default for gRPC.
 *
 * @param properties The properties used to configure the server.
 * @param serviceDiscoverer The discoverer used to identify the services that should be served.
 * @param serverConfigurers The server configurers that contain additional configuration for the server.
 * @return The shadedNettyGrpcServerFactory bean.
 */
@ConditionalOnClass(name = {"io.grpc.netty.shaded.io.netty.channel.Channel",
        "io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder"})
@Conditional(ConditionalOnInterprocessServer.class)
@Bean
public ShadedNettyGrpcServerFactory shadedNettyGrpcServerFactory(final GrpcServerProperties properties,
        final GrpcServiceDiscoverer serviceDiscoverer, final List<GrpcServerConfigurer> serverConfigurers) {
    final ShadedNettyGrpcServerFactory factory = new ShadedNettyGrpcServerFactory(properties, serverConfigurers);
    for (final GrpcServiceDefinition service : serviceDiscoverer.findGrpcServices()) {
        factory.addService(service);
    }
    return factory;
}
 
Example 8
Source Project: resilience4j   Source File: RetryConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param retryConfigurationProperties retry configuration spring properties
 * @param retryRegistry                retry in memory registry
 * @return the spring retry AOP aspect
 */
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public RetryAspect retryAspect(
    RetryConfigurationProperties retryConfigurationProperties,
    RetryRegistry retryRegistry,
    @Autowired(required = false) List<RetryAspectExt> retryAspectExtList,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    return new RetryAspect(retryConfigurationProperties, retryRegistry, retryAspectExtList,
        fallbackDecorators, spelResolver);
}
 
Example 9
Source Project: resilience4j   Source File: CircuitBreakerConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public CircuitBreakerAspect circuitBreakerAspect(
    CircuitBreakerRegistry circuitBreakerRegistry,
    @Autowired(required = false) List<CircuitBreakerAspectExt> circuitBreakerAspectExtList,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    return new CircuitBreakerAspect(circuitBreakerProperties, circuitBreakerRegistry,
        circuitBreakerAspectExtList, fallbackDecorators, spelResolver);
}
 
Example 10
Source Project: springdoc-openapi   Source File: SpringDocConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
	 * Springdoc bean factory post processor 2 bean factory post processor.
	 *
	 * @return the bean factory post processor
	 */
// For spring-boot-1 compatibility
	@Bean
	@Conditional(CacheOrGroupedOpenApiCondition.class)
	@ConditionalOnMissingClass(value = BINDRESULT_CLASS)
	@Lazy(false)
	static BeanFactoryPostProcessor springdocBeanFactoryPostProcessor2() {
		return SpringdocBeanFactoryConfigurer::initBeanFactoryPostProcessor;
	}
 
Example 11
/**
 * Default Kerberos ticket validator
 * 
 * @return
 */
@Bean
@Conditional(InsightsKerberosBeanInitializationCondition.class)
public SunJaasKerberosTicketValidator sunJaasKerberosTicketValidator() {
	Resource storeFile = resourceLoaderService
			.getResource("file:" + singleSignOnConfig.getKeyTabLocationKerberos());
	SunJaasKerberosTicketValidator ticketValidator = new SunJaasKerberosTicketValidator();
	ticketValidator.setServicePrincipal(singleSignOnConfig.getServicePrincipalKerberos());
	ticketValidator.setKeyTabLocation(storeFile);
	ticketValidator.setDebug(true);
	return ticketValidator;
}
 
Example 12
/**
 * used to provide Metadata Manager
 * 
 * @return
 * @throws MetadataProviderException
 */
@Bean
@Qualifier("metadata")
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public CachingMetadataManager metadata() throws MetadataProviderException {
	List<MetadataProvider> providers = new ArrayList<>();
	providers.add(idpMetadata());
	return new CachingMetadataManager(providers);
}
 
Example 13
@Bean
@Conditional(IgniteConditionalCache.class)
public IgniteCache<?, ?> messageIdCache() throws Exception {
	@SuppressWarnings("rawtypes")
	CacheConfiguration<?, ?> cacheConfiguration = new CacheConfiguration().setDataRegionName("not-persistence-data-region")
		.setCacheMode(CacheMode.LOCAL).setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL).setName("messageIdCache");
	return ignite().getOrCreateCache(cacheConfiguration);
}
 
Example 14
@Bean
@Conditional(IgniteConditionalCache.class)
public IgniteCache<?, ?> messageCache() throws Exception {
	@SuppressWarnings("rawtypes")
	CacheConfiguration<?, ?> cacheConfiguration = new CacheConfiguration().setDataRegionName("persistence-data-region")
		.setCacheMode(CacheMode.LOCAL).setName("retainMessageCache");
	return ignite().getOrCreateCache(cacheConfiguration);
}
 
Example 15
Source Project: bugsnag-java   Source File: SpringBootConfiguration.java    License: MIT License 5 votes vote down vote up
/**
 * The {@link com.bugsnag.servlet.BugsnagServletContainerInitializer} does not work for Spring Boot, need to
 * register the {@link BugsnagServletRequestListener} using a Spring Boot
 * {@link ServletListenerRegistrationBean} instead. This adds session tracking and
 * automatic servlet request metadata collection.
 */
@Bean
@Conditional(SpringWebMvcLoadedCondition.class)
ServletListenerRegistrationBean<ServletRequestListener> listenerRegistrationBean() {
    ServletListenerRegistrationBean<ServletRequestListener> srb =
            new ServletListenerRegistrationBean<ServletRequestListener>();
    srb.setListener(new BugsnagServletRequestListener());
    return srb;
}
 
Example 16
Source Project: resilience4j   Source File: RateLimiterConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Conditional(value = {AspectJOnClasspathCondition.class})
public RateLimiterAspect rateLimiterAspect(
    RateLimiterConfigurationProperties rateLimiterProperties,
    RateLimiterRegistry rateLimiterRegistry,
    @Autowired(required = false) List<RateLimiterAspectExt> rateLimiterAspectExtList,
    FallbackDecorators fallbackDecorators,
    SpelResolver spelResolver
) {
    return new RateLimiterAspect(rateLimiterRegistry, rateLimiterProperties,
        rateLimiterAspectExtList, fallbackDecorators, spelResolver);
}
 
Example 17
/** Setup {@link AWSSecurityTokenService} client an IAM role to assume is given. */
@Bean
@ConditionalOnMissingBean
@Conditional(STSSetCondition.class)
AWSSecurityTokenService securityTokenService(ZipkinSQSCollectorProperties properties) {
  return AWSSecurityTokenServiceClientBuilder.standard()
      .withCredentials(getDefaultCredentialsProvider(properties))
      .withRegion(properties.awsStsRegion)
      .build();
}
 
Example 18
/**
 * 当用户的环境配置了redisTemplate时则使用Redis做缓存
 *
 * @param realm         realm
 * @param redisTemplate spring RedisTemplate
 * @return DefaultWebSecurityManager
 */
@Bean
@Conditional(RedisEnableCondition.class)
public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm, RedisTemplate<Object, Object> redisTemplate) {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(realm);
    //使用自定义的Redis缓存实现,依赖redisTemplate,keyNamespace可以默认为空
    securityManager.setCacheManager(this.getCacheManager(redisTemplate));
    return securityManager;
}
 
Example 19
/**
 * 当用户的环境没有配置redisTemplate时则使用ehcache做缓存
 *
 * @param realm realm
 * @return DefaultWebSecurityManager
 */
@Bean
@Conditional(RedisDisabledCondition.class)
public DefaultWebSecurityManager webSecurityManager(Realm realm) {
    DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
    securityManager.setRealm(realm);
    //使用ehcache当缓存
    EhCacheManager cacheManager = new EhCacheManager();
    securityManager.setCacheManager(cacheManager);
    return securityManager;
}
 
Example 20
/***
 * 密码凭证匹配器,采用redis记录重试次数,超过指定次数则不允许登录
 * @return
 */
@Bean
@Conditional(RedisEnableCondition.class)
public CredentialsMatcher retryLimitHashedCredentialsMatcher(RedisTemplate<Object, Object> redisTemplate) {
    return credentialsMatcher(redisTemplate);

}
 
Example 21
@SuppressWarnings( "unchecked" )
@Bean
@Qualifier( "notifier" )
@Conditional( RedisEnabledCondition.class )
public Notifier redisNotifier( ObjectMapper objectMapper )
{
    return new RedisNotifier( (RedisTemplate<String, String>) redisTemplate, objectMapper );
}
 
Example 22
Source Project: ambari-logsearch   Source File: ApplicationConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
@Conditional(NonCloudStorageCondition.class)
@DependsOn({"inputConfigHandler"})
public InputConfigUploader inputConfigUploader() throws Exception {
  return new InputConfigUploader("Input Config Loader", logSearchConfigLogFeeder(),
    inputConfigManager(), logLevelFilterHandler());
}
 
Example 23
Source Project: micro-service   Source File: ConditionConfig.java    License: MIT License 5 votes vote down vote up
@Conditional(MicroServiceCondition.class)
@Bean(name = "defaultConfigBean")
public Object defaultConfigBean() {
	
	logger.info("create new DefaultConfigBean...");
	
	return new Object();
}
 
Example 24
Source Project: tutorials   Source File: MySQLAutoconfiguration.java    License: MIT License 5 votes vote down vote up
@ConditionalOnResource(resources = "classpath:mysql.properties")
@Conditional(HibernateCondition.class)
final Properties additionalProperties() {
    final Properties hibernateProperties = new Properties();

    hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("mysql-hibernate.hbm2ddl.auto"));
    hibernateProperties.setProperty("hibernate.dialect", env.getProperty("mysql-hibernate.dialect"));
    hibernateProperties.setProperty("hibernate.show_sql", env.getProperty("mysql-hibernate.show_sql") != null ? env.getProperty("mysql-hibernate.show_sql") : "false");

    return hibernateProperties;
}
 
Example 25
Source Project: ambari-logsearch   Source File: ApplicationConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "cloudLogSearchLogFeederConfig")
@Conditional(CloudStorageCondition.class)
public LogSearchConfigLogFeeder cloudLogSearchLogFeederConfig() throws Exception {
  return LogSearchConfigFactory.createLogSearchConfigLogFeeder(
    Maps.fromProperties(logFeederProps.getProperties()),
    logFeederProps.getClusterName(),
    LogSearchConfigLogFeederLocal.class, false);
}
 
Example 26
Source Project: spring-init   Source File: ConditionEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private List<String[]> getConditionClasses(AnnotatedTypeMetadata metadata) {
	MultiValueMap<String, Object> attributes = metadata
			.getAllAnnotationAttributes(Conditional.class.getName(), true);
	Object values = (attributes != null ? attributes.get("value") : null);
	return (List<String[]>) (values != null ? values : Collections.emptyList());
}
 
Example 27
public static boolean matches(ConditionContext context) {
	Class<AuthorizationServerEndpointsConfigurationBeanCondition> type = AuthorizationServerEndpointsConfigurationBeanCondition.class;
	Conditional conditional = AnnotationUtils.findAnnotation(type, Conditional.class);
	StandardAnnotationMetadata metadata = new StandardAnnotationMetadata(type);
	for (Class<? extends Condition> conditionType : conditional.value()) {
		Condition condition = BeanUtils.instantiateClass(conditionType);
		if (condition.matches(context, metadata)) {
			return true;
		}
	}
	return false;
}
 
Example 28
/**
 * Used to add filter chain based on Request Matcher
 * 
 * @return
 * @throws Exception
 */
@Bean
@Conditional(InsightsKerberosBeanInitializationCondition.class)
public FilterChainProxy kerberosFilter() throws Exception {
	LOG.debug("message Inside InsightsSecurityConfigurationAdapterKerberos FilterChainProxy, initial bean **** ");

	/*AuthenticationUtils.setSecurityFilterchain(
			new DefaultSecurityFilterChain(new AntPathRequestMatcher("/kerberos/login/**"), spnegoEntryPoint()));*/

	/*AuthenticationUtils.setSecurityFilterchain(new DefaultSecurityFilterChain(
			new AntPathRequestMatcher("/user/insightsso/**"), insightsSSOProcessingFilter()));*/

	List<Filter> filters = new ArrayList<>();
	filters.add(0, new InsightsCustomCsrfFilter());
	filters.add(1, new InsightsCrossScriptingFilter());
	filters.add(2, insightsServiceProcessingFilter());
	filters.add(3, new InsightsResponseHeaderWriterFilter());

	AuthenticationUtils
			.setSecurityFilterchain(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/**"), filters));

	ListIterator<SecurityFilterChain> securityFilters = AuthenticationUtils.getSecurityFilterchains()
			.listIterator();
	while (securityFilters.hasNext()) {
		SecurityFilterChain as = securityFilters.next();
		LOG.debug("message Inside FilterChainProxy, initial bean name {} **** ",
				Arrays.toString(as.getFilters().toArray()));
	}

	return new FilterChainProxy(AuthenticationUtils.getSecurityFilterchains());//chains
}
 
Example 29
Source Project: micro-service   Source File: ConditionConfig.java    License: MIT License 5 votes vote down vote up
@Conditional(MicroServiceCondition.class)
@Bean(name = "conditionConfigBean")
public Object conditionConfigBean() {
	
	logger.info("create new ConditionConfigBean...");
	
	return new Object();
}
 
Example 30
/**
 * SAML 2.0 WebSSO Assertion Consumer
 * 
 * @return
 */
@Bean
@Conditional(InsightsSAMLBeanInitializationCondition.class)
public WebSSOProfileConsumer webSSOprofileConsumer() {
	WebSSOProfileConsumerImpl webSSOProfileConsumerImpl = new WebSSOProfileConsumerImpl();
	webSSOProfileConsumerImpl.setResponseSkew(600);
	webSSOProfileConsumerImpl.setMaxAuthenticationAge(36000);
	return webSSOProfileConsumerImpl;
}