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

The following examples show how to use org.springframework.context.annotation.ConditionContext. 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
Source Project: atlas   Source File: SetupSteps.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    try {
        Configuration configuration = ApplicationProperties.get();
        boolean shouldRunSetup = configuration.getBoolean(ATLAS_SERVER_RUN_SETUP_KEY, false);
        if (shouldRunSetup) {
            LOG.warn("Running setup per configuration {}.", ATLAS_SERVER_RUN_SETUP_KEY);
            return true;
        } else {
            LOG.info("Not running setup per configuration {}.", ATLAS_SERVER_RUN_SETUP_KEY);
        }
    } catch (AtlasException e) {
        LOG.error("Unable to read config to determine if setup is needed. Not running setup.");
    }
    return false;
}
 
Example 2
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	Environment environment = context.getEnvironment();
	if (hasProperty(environment, "encrypt.key-store.location")) {
		if (hasProperty(environment, "encrypt.key-store.password")) {
			return ConditionOutcome.match("Keystore found in Environment");
		}
		return ConditionOutcome
				.noMatch("Keystore found but no password in Environment");
	}
	else if (hasProperty(environment, "encrypt.key")) {
		return ConditionOutcome.match("Key found in Environment");
	}
	return ConditionOutcome.noMatch("Keystore nor key found in Environment");
}
 
Example 3
@Override
public boolean matches(
    ConditionContext context, AnnotatedTypeMetadata metadata
) {
    if (
        // Springboot 1
        isClassAvailableOnClasspath("org.springframework.boot.autoconfigure.web.ErrorController")
        // Springboot 2
        || isClassAvailableOnClasspath("org.springframework.boot.web.servlet.error.ErrorController")
    ) {
        // We're in a Springboot 1 or Springboot 2 application. Return false to prevent registration.
        return false;
    }

    // Didn't detect ErrorController on the classpath, so return true.
    return true;
}
 
Example 4
private boolean isComponentEnable(ConditionContext context, AnnotatedTypeMetadata metadata) {
    boolean isImporter = metadata.isAnnotated(ConditionalOnImporterComponent.class.getName());

    MultiValueMap<String, Object> map = null;
    if (isImporter) {
        map = metadata.getAllAnnotationAttributes(ConditionalOnImporterComponent.class
            .getName());
    } else {
        map = metadata.getAllAnnotationAttributes(ConditionalOnExporterComponent.class
            .getName());
    }

    String importerExporterName = getFirstAnnotationValueFromMetadata(map, "value");
    MonitorComponent monitorComponent = getFirstAnnotationValueFromMetadata(map, "type");
    List<String> activeComponents = getActivatedComponentsFromConfiguration(context,
        isImporter, monitorComponent);
    boolean active = activeComponents.contains(importerExporterName);
    LOGGER.info("gateway {} {}:{} active:{}", monitorComponent.name().toLowerCase(),
        (isImporter ? "importer" : "exporter"), importerExporterName, active);
    return active;
}
 
Example 5
Source Project: loc-framework   Source File: PrefixPropertyCondition.java    License: MIT License 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
    AnnotatedTypeMetadata metadata) {
  String prefix = (String) attribute(metadata, "prefix");
  Class<?> value = (Class<?>) attribute(metadata, "value");
  ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
  try {
    new Binder(ConfigurationPropertySources.from(environment.getPropertySources()))
        .bind(prefix, Bindable.of(value))
        .orElseThrow(
            () -> new FatalBeanException("Could not bind DataSourceSettings properties"));
    return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix));
  } catch (Exception e) {
    //ignore
  }
  return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix));
}
 
Example 6
@Test
public void testGetResourceOutcomeForSystemProperty() {
	System.setProperty("anyProperty", "anyValue");
	QuickFixJConfigResourceCondition resourceCondition =
			new ClientConfigAvailableCondition("anyProperty");

	ConditionOutcome conditionOutcome =
			resourceCondition.getResourceOutcome(mock(ConditionContext.class), mock(AnnotatedTypeMetadata.class));
	assertThat(conditionOutcome).isNotNull();
	assertThat(conditionOutcome.getMessage()).contains("ResourceCondition (quickfixj.client) System property 'anyProperty' is set.");
}
 
Example 7
Source Project: SnowJena   Source File: RedisExistsCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    if (redisTemplate==null){
        return false;
    }
    return true;
}
 
Example 8
Source Project: SnowJena   Source File: RedisNoExistsCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    if (redisTemplate==null){
        return true;
    }
    return false;
}
 
Example 9
@Test
public void needsNoAdditionalConfigurationTest1() {
  NeedsHistoryAutoConfigurationCondition condition = spy(new NeedsHistoryAutoConfigurationCondition());
  ConditionContext context = mock(ConditionContext.class);
  Environment environment = mock(Environment.class);
  when(context.getEnvironment()).thenReturn(environment);
  assertFalse(condition.needsAdditionalConfiguration(context));
}
 
Example 10
Source Project: frostmourne   Source File: OnProfileCondition.java    License: MIT License 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Set<String> activeProfiles = Sets.newHashSet(context.getEnvironment().getActiveProfiles());

    Set<String> requiredActiveProfiles = retrieveAnnotatedProfiles(metadata, ConditionalOnProfile.class.getName());
    Set<String> requiredInactiveProfiles = retrieveAnnotatedProfiles(metadata, ConditionalOnMissingProfile.class
            .getName());

    return Sets.difference(requiredActiveProfiles, activeProfiles).isEmpty()
            && Sets.intersection(requiredInactiveProfiles, activeProfiles).isEmpty();
}
 
Example 11
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    // System property for server configuration found, match
    if (System.getProperty(configSystemProperty) != null) {
        return ConditionOutcome.match(
                startConditionMessage().because("System property '" + configSystemProperty + "' is set."));
    }
    // Environment property for server configuration found, match
    if (context.getEnvironment().containsProperty(CONFIG_ENVIRONMENT_PROPERTY)) {
        return ConditionOutcome.match(startConditionMessage()
                .foundExactly("property " + CONFIG_ENVIRONMENT_PROPERTY));
    }
    // System property for client configuration found, no match
    if (System.getProperty(HazelcastJetClientConfigAvailableCondition.CONFIG_SYSTEM_PROPERTY) != null) {
        return ConditionOutcome.noMatch(startConditionMessage().because("System property '"
                + HazelcastJetClientConfigAvailableCondition.CONFIG_SYSTEM_PROPERTY + "' is set."));
    }
    // Environment property for client configuration found, no match
    if (context.getEnvironment()
               .containsProperty(HazelcastJetClientConfigAvailableCondition.CONFIG_ENVIRONMENT_PROPERTY)) {
        return ConditionOutcome.noMatch(startConditionMessage().because("Environment property '"
                + HazelcastJetClientConfigAvailableCondition.CONFIG_ENVIRONMENT_PROPERTY + "' is set."));
    }
    ConditionOutcome resourceOutcome = getResourceOutcome(context, metadata);
    // Found a configuration file for server, match
    if (resourceOutcome.isMatch()) {
        return resourceOutcome;
    }
    // Found a configuration file for client, no match
    ConditionOutcome clientResourceOutcome = clientConfigAvailableCondition.getMatchOutcome(context, metadata);
    if (clientResourceOutcome.isMatch()) {
        return ConditionOutcome.noMatch(clientResourceOutcome.getConditionMessage());
    }
    return ConditionOutcome.match(startConditionMessage().because(
            "No configuration option found, using default configuration."));
}
 
Example 12
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    if (System.getProperty(this.configSystemProperty) != null) {
        return ConditionOutcome.match(
                startConditionMessage().because("System property '" + this.configSystemProperty + "' is set."));
    }
    return super.getMatchOutcome(context, metadata);
}
 
Example 13
@Test
public void assertMatch() {
    MockEnvironment mockEnvironment = new MockEnvironment();
    mockEnvironment.setProperty("spring.shardingsphere.rules.shadow.column", "user_id");
    ConditionContext context = Mockito.mock(ConditionContext.class);
    AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class);
    when(context.getEnvironment()).thenReturn(mockEnvironment);
    ShadowSpringBootCondition condition = new ShadowSpringBootCondition();
    ConditionOutcome matchOutcome = condition.getMatchOutcome(context, metadata);
    assertThat(matchOutcome.isMatch(), is(true));
}
 
Example 14
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  try {
    return conditionContext.getEnvironment().getProperty("realMongo", Boolean.class);
  }
  catch (Exception e){
    return false;
  }
}
 
Example 15
protected Object getParameterByIndex(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  Assert.isAssignable(AggregateQueryMethodConditionContext.class, conditionContext.getClass());
  AggregateQueryMethodConditionContext ctx = (AggregateQueryMethodConditionContext) conditionContext;
  List<Object> parameters = ctx.getParameterValues();
  int parameterIndex = getParameterIndex(annotatedTypeMetadata);
  int paramCount = parameters.size();
  if (parameterIndex < paramCount) {
    return parameters.get(parameterIndex);
  }
  throw new IllegalArgumentException("Argument index " + parameterIndex + " out of bounds, max count: " + paramCount);
}
 
Example 16
Source Project: initializr   Source File: OnPackagingCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matches(ProjectDescription description, ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	if (description.getPackaging() == null) {
		return false;
	}
	String packagingId = (String) metadata.getAllAnnotationAttributes(ConditionalOnPackaging.class.getName())
			.getFirst("value");
	Packaging packaging = Packaging.forId(packagingId);
	return description.getPackaging().id().equals(packaging.id());
}
 
Example 17
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
  LOGGER.trace(">>>> ParameterValueFalseCondition::matches");
  Object parameter = getParameterByIndex(conditionContext, annotatedTypeMetadata);
  if(Boolean.class.isAssignableFrom(parameter.getClass())) {
    return !(Boolean) parameter;
  }
  int parameterIndex = getParameterIndex(annotatedTypeMetadata);
  throw new IllegalArgumentException("Argument at index " + parameterIndex + " not convertible to boolean");
}
 
Example 18
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	String clientId = context.getEnvironment().getProperty("security.oauth2.client.client-id");
	ConditionMessage.Builder message = ConditionMessage.forCondition("OAuth Client ID");
	if (StringUtils.hasLength(clientId)) {
		return ConditionOutcome.match(message.foundExactly("security.oauth2.client.client-id property"));
	}
	return ConditionOutcome.noMatch(message.didNotFind("security.oauth2.client.client-id property").atAll());
}
 
Example 19
Source Project: initializr   Source File: OnLanguageCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matches(ProjectDescription description, ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	if (description.getLanguage() == null) {
		return false;
	}
	String languageId = (String) metadata.getAllAnnotationAttributes(ConditionalOnLanguage.class.getName())
			.getFirst("value");
	Language language = Language.forId(languageId, null);
	return description.getLanguage().id().equals(language.id());
}
 
Example 20
Source Project: jasypt-spring-boot   Source File: OnMissingBeanCondition.java    License: MIT License 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Map<String, Object> beanAttributes = metadata.getAnnotationAttributes(Bean.class.getName());
    String beanName = ((String[]) beanAttributes.get("name"))[0];
    if(StringUtils.isEmpty(beanName)) {
        throw new IllegalStateException("OnMissingBeanCondition can't detect bean name!");
    }
    boolean missingBean = !context.getBeanFactory().containsBean(context.getEnvironment().resolveRequiredPlaceholders(beanName));
    return missingBean ? ConditionOutcome.match(beanName + " not found") : ConditionOutcome.noMatch(beanName + " found");
}
 
Example 21
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    Environment env = context.getEnvironment();
    MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(ConditionOnPropertyExists.class.getName());
    if (attrs != null) {
        Object value = attrs.get("value");
        return value != null && null != env && env.getProperty(value.toString()) != null;
    }
    return false;
}
 
Example 22
Source Project: onetwo   Source File: OAuth2SsoClientAutoContextConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	ConditionOutcome cond = super.getMatchOutcome(context, metadata);
	if(cond.isMatch()){
		return ConditionOutcome.noMatch("not @EnableOAuth2Sso bean found!");
	}else{
		return ConditionOutcome.match("@EnableOAuth2Sso sso client!");
	}
}
 
Example 23
@Override
public boolean matches( ConditionContext context, AnnotatedTypeMetadata metadata )
{
    if ( !isTestRun( context ) )
    {
        return !getConfiguration().getProperty( ConfigurationKey.REDIS_ENABLED ).equalsIgnoreCase( "true" );
    }

    return true;
}
 
Example 24
Source Project: tutorials   Source File: MySQLAutoconfiguration.java    License: MIT License 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    ConditionMessage.Builder message = ConditionMessage.forCondition("Hibernate");

    return Arrays.stream(CLASS_NAMES).filter(className -> ClassUtils.isPresent(className, context.getClassLoader())).map(className -> ConditionOutcome.match(message.found("class").items(Style.NORMAL, className))).findAny()
            .orElseGet(() -> ConditionOutcome.noMatch(message.didNotFind("class", "classes").items(Style.NORMAL, Arrays.asList(CLASS_NAMES))));
}
 
Example 25
Source Project: resilience4j   Source File: AspectUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param context           the spring condition context
 * @param classToCheck      the class to check in spring class loader
 * @param exceptionConsumer the custom exception consumer
 * @return true or false if the class is found or not
 */
static boolean checkClassIfFound(ConditionContext context, String classToCheck,
    Consumer<Exception> exceptionConsumer) {
    try {
        final Class<?> aClass = requireNonNull(context.getClassLoader(),
            "context must not be null").loadClass(classToCheck);
        return aClass != null;
    } catch (ClassNotFoundException e) {
        exceptionConsumer.accept(e);
        return false;
    }
}
 
Example 26
Source Project: joyqueue   Source File: MsgQueryEnabledCondition.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
    MsgQueryConfigurationProperties msgQueryConfigurationProperties=getMsgQueryProperties(context);
    if(!msgQueryConfigurationProperties.getEnabled()){
        logger.warn("message query function is disabled, because [message.query.enabled = false]");
        return ConditionOutcome.noMatch("message query function is disabled, because [message.query.enabled = false]");
    }
    logger.info("message query function is enabled");
    return ConditionOutcome.match();
}
 
Example 27
@Test
public void getMatchOutcomeNoMatchTest() {
  NeedsHistoryAutoConfigurationCondition condition = spy(new NeedsHistoryAutoConfigurationCondition());
  ConditionContext context = mock(ConditionContext.class);
  Environment environment = mock(Environment.class);
  when(context.getEnvironment()).thenReturn(environment);
  when(environment.getProperty("camunda.bpm.history-level")).thenReturn(NeedsHistoryAutoConfigurationCondition.HISTORY_AUTO);
  when(condition.needsAdditionalConfiguration(context)).thenReturn(false);
  assertFalse(condition.getMatchOutcome(context, null).isMatch());
}
 
Example 28
protected boolean needsAdditionalConfiguration(ConditionContext context) {
  String historyLevel = context.getEnvironment().getProperty("camunda.bpm.history-level");
  if (HISTORY_AUTO.equals(historyLevel)) {
    return !isHistoryAutoSupported();
  }
  return false;
}
 
Example 29
protected boolean needsAdditionalConfiguration(ConditionContext context) {
  String historyLevel = context.getEnvironment().getProperty("camunda.bpm.history-level");
  if (HISTORY_AUTO.equals(historyLevel)) {
    return !isHistoryAutoSupported();
  }
  return false;
}
 
Example 30
@Test
public void needsNoAdditionalConfigurationTest2() {
  NeedsHistoryAutoConfigurationCondition condition = spy(new NeedsHistoryAutoConfigurationCondition());
  ConditionContext context = mock(ConditionContext.class);
  Environment environment = mock(Environment.class);
  when(context.getEnvironment()).thenReturn(environment);
  when(environment.getProperty("camunda.bpm.history-level")).thenReturn(NeedsHistoryAutoConfigurationCondition.HISTORY_AUTO);
  when(condition.isHistoryAutoSupported()).thenReturn(true);
  assertFalse(condition.needsAdditionalConfiguration(context));
}