org.springframework.context.annotation.ConditionContext Java Examples

The following examples show how to use org.springframework.context.annotation.ConditionContext. 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 File: PrefixPropertyCondition.java    From loc-framework with 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 #2
Source File: SpringContainerErrorController.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: EncryptionBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: ImporterExporterComponentConditional.java    From sofa-lookout with Apache License 2.0 6 votes vote down vote up
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 File: SetupSteps.java    From atlas with 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 #6
Source File: OAuth2ResourceServerConfiguration.java    From spring-security-oauth2-boot with Apache License 2.0 5 votes vote down vote up
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 #7
Source File: AbstractCondition.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
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 #8
Source File: RedisDisabledCondition.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean matches( ConditionContext context, AnnotatedTypeMetadata metadata )
{
    if ( !isTestRun( context ) )
    {
        return !getConfiguration().getProperty( ConfigurationKey.REDIS_ENABLED ).equalsIgnoreCase( "true" );
    }

    return true;
}
 
Example #9
Source File: MySQLAutoconfiguration.java    From tutorials with 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 #10
Source File: AspectUtil.java    From resilience4j with 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 #11
Source File: MsgQueryEnabledCondition.java    From joyqueue with 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 #12
Source File: NeedsHistoryAutoConfigurationConditionTest.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: NeedsHistoryAutoConfigurationCondition.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
protected boolean needsAdditionalConfiguration(ConditionContext context) {
  String historyLevel = context.getEnvironment().getProperty("camunda.bpm.history-level");
  if (HISTORY_AUTO.equals(historyLevel)) {
    return !isHistoryAutoSupported();
  }
  return false;
}
 
Example #14
Source File: NeedsHistoryAutoConfigurationCondition.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected boolean needsAdditionalConfiguration(ConditionContext context) {
  String historyLevel = context.getEnvironment().getProperty("camunda.bpm.history-level");
  if (HISTORY_AUTO.equals(historyLevel)) {
    return !isHistoryAutoSupported();
  }
  return false;
}
 
Example #15
Source File: QuickFixJConfigResourceConditionTest.java    From quickfixj-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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 #16
Source File: OnPlatformVersionCondition.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean matches(ProjectDescription description, ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	Version platformVersion = description.getPlatformVersion();
	if (platformVersion == null) {
		return false;
	}
	return Arrays.stream(
			(String[]) metadata.getAnnotationAttributes(ConditionalOnPlatformVersion.class.getName()).get("value"))
			.anyMatch((range) -> VersionParser.DEFAULT.parseRange(range).match(platformVersion));

}
 
Example #17
Source File: JuiserSpringSecurityCondition.java    From juiser with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {

    ConditionMessage matchMessage = ConditionMessage.empty();

    boolean enabled = isSpringSecurityEnabled(context);

    if (metadata.isAnnotated(ConditionalOnJuiserSpringSecurityEnabled.class.getName())) {
        if (!enabled) {
            return ConditionOutcome.noMatch(
                ConditionMessage.forCondition(ConditionalOnJuiserSpringSecurityEnabled.class)
                    .didNotFind("spring security enabled").atAll());
        }
        matchMessage = matchMessage.andCondition(ConditionalOnJuiserSpringSecurityEnabled.class)
            .foundExactly("spring security enabled");
    }

    if (metadata.isAnnotated(ConditionalOnJuiserSpringSecurityDisabled.class.getName())) {
        if (enabled) {
            return ConditionOutcome.noMatch(
                ConditionMessage.forCondition(ConditionalOnJuiserSpringSecurityDisabled.class)
                    .didNotFind("spring security disabled").atAll());
        }
        matchMessage = matchMessage.andCondition(ConditionalOnJuiserSpringSecurityDisabled.class)
            .didNotFind("spring security disabled").atAll();
    }

    return ConditionOutcome.match(matchMessage);
}
 
Example #18
Source File: OnMissingAmazonClientCondition.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
	MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes(
			ConditionalOnMissingAmazonClient.class.getName(), true);

	for (Object amazonClientClass : attributes.get("value")) {
		if (isAmazonClientMissing(context, (String) amazonClientClass)) {
			return true;
		}
	}

	return false;
}
 
Example #19
Source File: NeedsHistoryAutoConfigurationConditionTest.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example #20
Source File: RxJava2OnClasspathCondition.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    return AspectUtil.checkClassIfFound(context, CLASS_TO_CHECK, (e) -> logger.info(
        "RxJava2 related Aspect extensions are not activated, because RxJava2 is not on the classpath."))
        && AspectUtil.checkClassIfFound(context, R4J_RXJAVA, (e) -> logger.info(
        "RxJava2 related Aspect extensions are not activated because Resilience4j RxJava2 module is not on the classpath."));
}
 
Example #21
Source File: ZipkinSQSCredentialsConfiguration.java    From zipkin-aws with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata a) {

  String queueUrl = context.getEnvironment().getProperty(PROPERTY_NAME);

  return isEmpty(queueUrl)
      ? ConditionOutcome.noMatch(PROPERTY_NAME + " isn't set")
      : ConditionOutcome.match();
}
 
Example #22
Source File: ShardingSpringBootConditionTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertMatch() {
    MockEnvironment mockEnvironment = new MockEnvironment();
    mockEnvironment.setProperty("spring.shardingsphere.rules.sharding.binding-tables", "t_order");
    ConditionContext context = Mockito.mock(ConditionContext.class);
    AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class);
    when(context.getEnvironment()).thenReturn(mockEnvironment);
    ShardingSpringBootCondition condition = new ShardingSpringBootCondition();
    ConditionOutcome matchOutcome = condition.getMatchOutcome(context, metadata);
    assertThat(matchOutcome.isMatch(), is(true));
}
 
Example #23
Source File: MissingSpringCloudRegistryConfigPropertyCondition.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	ConfigurableEnvironment environment = (ConfigurableEnvironment) context
			.getEnvironment();

	String protocol = environment.getProperty("dubbo.registry.protocol");

	if (PROTOCOL.equals(protocol)) {
		return ConditionOutcome.noMatch(
				"'spring-cloud' protocol was found from 'dubbo.registry.protocol'");
	}

	String address = environment.getProperty("dubbo.registry.address");

	if (StringUtils.startsWithIgnoreCase(address, PROTOCOL)) {
		return ConditionOutcome.noMatch(
				"'spring-cloud' protocol was found from 'dubbo.registry.address'");
	}

	Map<String, Object> properties = getSubProperties(
			environment.getPropertySources(), "dubbo.registries.");

	boolean found = properties.entrySet().stream().anyMatch(entry -> {
		String key = entry.getKey();
		String value = String.valueOf(entry.getValue());
		return (key.endsWith(".address") && value.startsWith(PROTOCOL))
				|| (key.endsWith(".protocol") && PROTOCOL.equals(value));

	});

	return found
			? ConditionOutcome.noMatch(
					"'spring-cloud' protocol was found in 'dubbo.registries.*'")
			: ConditionOutcome.match();
}
 
Example #24
Source File: EncryptSpringBootConditionTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertMatch() {
    MockEnvironment mockEnvironment = new MockEnvironment();
    mockEnvironment.setProperty("spring.shardingsphere.rules.encrypt.encryptors.aes_encryptor.type", "AES");
    ConditionContext context = Mockito.mock(ConditionContext.class);
    AnnotatedTypeMetadata metadata = Mockito.mock(AnnotatedTypeMetadata.class);
    when(context.getEnvironment()).thenReturn(mockEnvironment);
    EncryptSpringBootCondition condition = new EncryptSpringBootCondition();
    ConditionOutcome matchOutcome = condition.getMatchOutcome(context, metadata);
    assertThat(matchOutcome.isMatch(), is(true));
}
 
Example #25
Source File: NeedsHistoryAutoConfigurationConditionTest.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Test
public void needsAdditionalConfigurationTest() {
  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(false);
  assertTrue(condition.needsAdditionalConfiguration(context));
}
 
Example #26
Source File: SpringbootErrorControllerIsNotOnClasspathTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "true   |   true    |   false",
    "false  |   true    |   false",
    "true   |   false   |   false",
    "false  |   false   |   true",
}, splitBy = "\\|")
@Test
public void matches_method_works_as_expected(
    boolean sb1IsOnClasspath, boolean sb2IsOnClasspath, boolean expectedResult
) {
    // given
    SpringbootErrorControllerIsNotOnClasspath implSpy = spy(impl);
    ConditionContext contextMock = mock(ConditionContext.class);
    AnnotatedTypeMetadata metadataMock = mock(AnnotatedTypeMetadata.class);

    doReturn(sb1IsOnClasspath)
        .when(implSpy)
        .isClassAvailableOnClasspath("org.springframework.boot.autoconfigure.web.ErrorController");

    doReturn(sb2IsOnClasspath)
        .when(implSpy)
        .isClassAvailableOnClasspath("org.springframework.boot.web.servlet.error.ErrorController");

    // when
    boolean result = implSpy.matches(contextMock, metadataMock);

    // then
    assertThat(result).isEqualTo(expectedResult);
}
 
Example #27
Source File: ParameterValueFalseCondition.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
@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 #28
Source File: CompatibleOnEnabledEndpointCondition.java    From dubbo-spring-boot-project with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
    ClassLoader classLoader = context.getClassLoader();

    Condition condition = Stream.of(CONDITION_CLASS_NAMES)                         // Iterate class names
            .filter(className -> ClassUtils.isPresent(className, classLoader))     // Search class existing or not by name
            .findFirst()                                                           // Find the first candidate
            .map(className -> ClassUtils.resolveClassName(className, classLoader)) // Resolve class name to Class
            .filter(Condition.class::isAssignableFrom)                             // Accept the Condition implementation
            .map(BeanUtils::instantiateClass)                                      // Instantiate Class to be instance
            .map(Condition.class::cast)                                            // Cast the instance to be Condition one
            .orElse(NegativeCondition.INSTANCE);                                   // Or else get a negative condition

    return condition.matches(context, metadata);
}
 
Example #29
Source File: NoneFilterRegistrationCondition.java    From vi with Apache License 2.0 5 votes vote down vote up
@Override
public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
    try {
        Class.forName("org.springframework.boot.context.embedded.FilterRegistrationBean");
        return false;
    }catch (Throwable e){
        try{
            Class.forName("org.springframework.boot.web.servlet.FilterRegistrationBean");
            return true;
        }catch (Throwable e1){
            return false;
        }
    }
}
 
Example #30
Source File: ClusterAwareConfiguration.java    From spring-boot-data-geode with Apache License 2.0 5 votes vote down vote up
ConditionContext registerApplicationListener(ConditionContext conditionContext) {

			Optional.ofNullable(conditionContext)
				.map(ConditionContext::getResourceLoader)
				.filter(ConfigurableApplicationContext.class::isInstance)
				.map(ConfigurableApplicationContext.class::cast)
				.ifPresent(applicationContext ->
					applicationContext.addApplicationListener(clusterAwareConditionResetApplicationListener()));

			return conditionContext;
		}