org.springframework.core.env.ConfigurableEnvironment

Here are the examples of the java api org.springframework.core.env.ConfigurableEnvironment taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

835 Examples 7

19 View Source File : MultiVersionPropertySourceFactory.java
License : Apache License 2.0
Project Creator : zouzhirong

/**
 * 返回Environment的多版本属性源中,指定版本的属性源
 *
 * @param version
 * @param environment
 * @return
 */
public static VersionPropertySource<?> getVersionPropertySource(long version, ConfigurableEnvironment environment) {
    MultiVersionPropertySource multiVersionPropertySource = getMultiVersionPropertySource(environment);
    return multiVersionPropertySource.getPropertySource(version);
}

19 View Source File : MultiVersionPropertySourceFactory.java
License : Apache License 2.0
Project Creator : zouzhirong

/**
 * 向Environment中添加版本属性源
 *
 * @param versionPropertySource
 * @param applicationContext
 * @param environment
 */
public static void addVersionPropertySource(VersionPropertySource<ConfigItemList> versionPropertySource, ApplicationContext applicationContext, ConfigurableEnvironment environment) {
    if (versionPropertySource == null) {
        return;
    }
    MultiVersionPropertySource multiVersionPropertySource = getMultiVersionPropertySource(environment);
    multiVersionPropertySource.addPropertySource(versionPropertySource);
}

19 View Source File : EnvironmentHolder.java
License : MIT License
Project Creator : zhang-rf

public clreplaced EnvironmentHolder implements EnvironmentPostProcessor {

    private static volatile ConfigurableEnvironment environment;

    public static ConfigurableEnvironment getEnvironment() {
        if (environment == null) {
            throw new EnvironmentNotSetException();
        }
        return environment;
    }

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        EnvironmentHolder.environment = environment;
    }

    public static clreplaced EnvironmentNotSetException extends RuntimeException {
    }
}

19 View Source File : ApolloApplicationContextInitializer.java
License : MIT License
Project Creator : YunaiV

/**
 * To fill system properties from environment config
 */
void initializeSystemProperty(ConfigurableEnvironment environment) {
    for (String propertyName : APOLLO_SYSTEM_PROPERTIES) {
        fillSystemPropertyFromEnvironment(environment, propertyName);
    }
}

19 View Source File : TestPropertyValuesTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link TestPropertyValues}.
 *
 * @author Madhura Bhave
 * @author Phillip Webb
 */
public clreplaced TestPropertyValuesTests {

    private final ConfigurableEnvironment environment = new StandardEnvironment();

    @Test
    public void applyToEnvironmentShouldAttachConfigurationPropertySource() {
        TestPropertyValues.of("foo.bar=baz").applyTo(this.environment);
        PropertySource<?> source = this.environment.getPropertySources().get("configurationProperties");
        replacedertThat(source).isNotNull();
    }

    @Test
    public void applyToDefaultPropertySource() {
        TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment);
        replacedertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz");
        replacedertThat(this.environment.getProperty("hello.world")).isEqualTo("hi");
    }

    @Test
    public void applyToSystemPropertySource() {
        TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT);
        replacedertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ");
        replacedertThat(this.environment.getPropertySources().contains("test-" + StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)).isTrue();
    }

    @Test
    public void applyToWithSpecificName() {
        TestPropertyValues.of("foo.bar=baz").applyTo(this.environment, Type.MAP, "other");
        replacedertThat(this.environment.getPropertySources().get("other")).isNotNull();
        replacedertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz");
    }

    @Test
    public void applyToExistingNameAndDifferentTypeShouldOverrideExistingOne() {
        TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP, "other");
        TestPropertyValues.of("FOO_BAR=BAZ").applyTo(this.environment, Type.SYSTEM_ENVIRONMENT, "other");
        replacedertThat(this.environment.getPropertySources().get("other")).isInstanceOf(SystemEnvironmentPropertySource.clreplaced);
        replacedertThat(this.environment.getProperty("foo.bar")).isEqualTo("BAZ");
        replacedertThat(this.environment.getProperty("hello.world")).isNull();
    }

    @Test
    public void applyToExistingNameAndSameTypeShouldMerge() {
        TestPropertyValues.of("foo.bar=baz", "hello.world=hi").applyTo(this.environment, Type.MAP);
        TestPropertyValues.of("foo.bar=new").applyTo(this.environment, Type.MAP);
        replacedertThat(this.environment.getProperty("foo.bar")).isEqualTo("new");
        replacedertThat(this.environment.getProperty("hello.world")).isEqualTo("hi");
    }

    @Test
    public void andShouldChainAndAddSingleKeyValue() {
        TestPropertyValues.of("foo.bar=baz").and("hello.world=hi").and("bling.blah=bing").applyTo(this.environment, Type.MAP);
        replacedertThat(this.environment.getProperty("foo.bar")).isEqualTo("baz");
        replacedertThat(this.environment.getProperty("hello.world")).isEqualTo("hi");
        replacedertThat(this.environment.getProperty("bling.blah")).isEqualTo("bing");
    }

    @Test
    public void applyToSystemPropertiesShouldSetSystemProperties() {
        TestPropertyValues.of("foo=bar").applyToSystemProperties(() -> {
            replacedertThat(System.getProperty("foo")).isEqualTo("bar");
            return null;
        });
    }

    @Test
    public void applyToSystemPropertiesShouldRestoreSystemProperties() {
        System.setProperty("foo", "bar1");
        System.clearProperty("baz");
        try {
            TestPropertyValues.of("foo=bar2", "baz=bing").applyToSystemProperties(() -> {
                replacedertThat(System.getProperty("foo")).isEqualTo("bar2");
                replacedertThat(System.getProperty("baz")).isEqualTo("bing");
                return null;
            });
            replacedertThat(System.getProperty("foo")).isEqualTo("bar1");
            replacedertThat(System.getProperties()).doesNotContainKey("baz");
        } finally {
            System.clearProperty("foo");
        }
    }

    @Test
    public void applyToSystemPropertiesWhenValueIsNullShouldRemoveProperty() {
        System.setProperty("foo", "bar1");
        try {
            TestPropertyValues.of("foo").applyToSystemProperties(() -> {
                replacedertThat(System.getProperties()).doesNotContainKey("foo");
                return null;
            });
            replacedertThat(System.getProperty("foo")).isEqualTo("bar1");
        } finally {
            System.clearProperty("foo");
        }
    }
}

19 View Source File : TestPropertyValues.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Add the properties from the underlying map to the environment using the specified
 * property source type.
 * @param environment the environment that needs to be modified
 * @param type the type of {@link PropertySource} to be added. See {@link Type}
 */
public void applyTo(ConfigurableEnvironment environment, Type type) {
    applyTo(environment, type, type.applySuffix("test"));
}

19 View Source File : PropertiesMigrationReporterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link PropertiesMigrationReporter}.
 *
 * @author Stephane Nicoll
 */
public clreplaced PropertiesMigrationReporterTests {

    private ConfigurableEnvironment environment = new MockEnvironment();

    @Test
    public void reportIsNullWithNoMatchingKeys() {
        String report = createWarningReport(new SimpleConfigurationMetadataRepository());
        replacedertThat(report).isNull();
    }

    @Test
    public void replacementKeysAreRemapped() throws IOException {
        MutablePropertySources propertySources = this.environment.getPropertySources();
        PropertySource<?> one = loadPropertySource("one", "config/config-error.properties");
        PropertySource<?> two = loadPropertySource("two", "config/config-warnings.properties");
        propertySources.addFirst(one);
        propertySources.addAfter("one", two);
        replacedertThat(propertySources).hreplacedize(3);
        createreplacedyzer(loadRepository("metadata/sample-metadata.json")).getReport();
        replacedertThat(mapToNames(propertySources)).containsExactly("one", "migrate-two", "two", "mockProperties");
        replacedertMappedProperty(propertySources.get("migrate-two"), "test.two", "another", getOrigin(two, "wrong.two"));
    }

    @Test
    public void warningReport() throws IOException {
        this.environment.getPropertySources().addFirst(loadPropertySource("test", "config/config-warnings.properties"));
        this.environment.getPropertySources().addFirst(loadPropertySource("ignore", "config/config-error.properties"));
        String report = createWarningReport(loadRepository("metadata/sample-metadata.json"));
        replacedertThat(report).isNotNull();
        replacedertThat(report).containsSubsequence("Property source 'test'", "wrong.four.test", "Line: 5", "test.four.test", "wrong.two", "Line: 2", "test.two");
        replacedertThat(report).doesNotContain("wrong.one");
    }

    @Test
    public void errorReport() throws IOException {
        this.environment.getPropertySources().addFirst(loadPropertySource("test1", "config/config-warnings.properties"));
        this.environment.getPropertySources().addFirst(loadPropertySource("test2", "config/config-error.properties"));
        String report = createErrorReport(loadRepository("metadata/sample-metadata.json"));
        replacedertThat(report).isNotNull();
        replacedertThat(report).containsSubsequence("Property source 'test2'", "wrong.one", "Line: 2", "This is no longer supported.");
        replacedertThat(report).doesNotContain("wrong.four.test").doesNotContain("wrong.two");
    }

    @Test
    public void errorReportNoReplacement() throws IOException {
        this.environment.getPropertySources().addFirst(loadPropertySource("first", "config/config-error-no-replacement.properties"));
        this.environment.getPropertySources().addFirst(loadPropertySource("second", "config/config-error.properties"));
        String report = createErrorReport(loadRepository("metadata/sample-metadata.json"));
        replacedertThat(report).isNotNull();
        replacedertThat(report).containsSubsequence("Property source 'first'", "wrong.three", "Line: 6", "none", "Property source 'second'", "wrong.one", "Line: 2", "This is no longer supported.");
        replacedertThat(report).doesNotContain("null").doesNotContain("server.port").doesNotContain("debug");
    }

    @Test
    public void durationTypeIsHandledTransparently() {
        MutablePropertySources propertySources = this.environment.getPropertySources();
        Map<String, Object> content = new LinkedHashMap<>();
        content.put("test.cache-seconds", 50);
        content.put("test.time-to-live-ms", 1234L);
        content.put("test.ttl", 5678L);
        propertySources.addFirst(new MapPropertySource("test", content));
        replacedertThat(propertySources).hreplacedize(2);
        String report = createWarningReport(loadRepository("metadata/type-conversion-metadata.json"));
        replacedertThat(report).contains("Property source 'test'", "test.cache-seconds", "test.cache", "test.time-to-live-ms", "test.time-to-live", "test.ttl", "test.mapped.ttl");
        replacedertThat(mapToNames(propertySources)).containsExactly("migrate-test", "test", "mockProperties");
        PropertySource<?> propertySource = propertySources.get("migrate-test");
        replacedertMappedProperty(propertySource, "test.cache", 50, null);
        replacedertMappedProperty(propertySource, "test.time-to-live", 1234L, null);
        replacedertMappedProperty(propertySource, "test.mapped.ttl", 5678L, null);
    }

    @Test
    public void reasonIsProvidedIfPropertyCouldNotBeRenamed() throws IOException {
        this.environment.getPropertySources().addFirst(loadPropertySource("test", "config/config-error-no-compatible-type.properties"));
        String report = createErrorReport(loadRepository("metadata/type-conversion-metadata.json"));
        replacedertThat(report).isNotNull();
        replacedertThat(report).containsSubsequence("Property source 'test'", "wrong.inconvertible", "Line: 1", "Reason: Replacement key " + "'test.inconvertible' uses an incompatible target type");
    }

    private List<String> mapToNames(PropertySources sources) {
        List<String> names = new ArrayList<>();
        for (PropertySource<?> source : sources) {
            names.add(source.getName());
        }
        return names;
    }

    @SuppressWarnings("unchecked")
    private Origin getOrigin(PropertySource<?> propertySource, String name) {
        return ((OriginLookup<String>) propertySource).getOrigin(name);
    }

    @SuppressWarnings("unchecked")
    private void replacedertMappedProperty(PropertySource<?> propertySource, String name, Object value, Origin origin) {
        replacedertThat(propertySource.containsProperty(name)).isTrue();
        replacedertThat(propertySource.getProperty(name)).isEqualTo(value);
        if (origin != null) {
            replacedertThat(propertySource).isInstanceOf(OriginLookup.clreplaced);
            replacedertThat(((OriginLookup<Object>) propertySource).getOrigin(name)).isEqualTo(origin);
        }
    }

    private PropertySource<?> loadPropertySource(String name, String path) throws IOException {
        ClreplacedPathResource resource = new ClreplacedPathResource(path);
        List<PropertySource<?>> propertySources = new PropertiesPropertySourceLoader().load(name, resource);
        replacedertThat(propertySources).isNotEmpty();
        return propertySources.get(0);
    }

    private ConfigurationMetadataRepository loadRepository(String... content) {
        try {
            ConfigurationMetadataRepositoryJsonBuilder builder = ConfigurationMetadataRepositoryJsonBuilder.create();
            for (String path : content) {
                Resource resource = new ClreplacedPathResource(path);
                builder.withJsonResource(resource.getInputStream());
            }
            return builder.build();
        } catch (IOException ex) {
            throw new IllegalStateException("Failed to load metadata", ex);
        }
    }

    private String createWarningReport(ConfigurationMetadataRepository repository) {
        return createreplacedyzer(repository).getReport().getWarningReport();
    }

    private String createErrorReport(ConfigurationMetadataRepository repository) {
        return createreplacedyzer(repository).getReport().getErrorReport();
    }

    private PropertiesMigrationReporter createreplacedyzer(ConfigurationMetadataRepository repository) {
        return new PropertiesMigrationReporter(repository, this.environment);
    }
}

19 View Source File : PropertiesMigrationReporter.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Report on {@link PropertyMigration properties migration}.
 *
 * @author Stephane Nicoll
 */
clreplaced PropertiesMigrationReporter {

    private final Map<String, ConfigurationMetadataProperty> allProperties;

    private final ConfigurableEnvironment environment;

    PropertiesMigrationReporter(ConfigurationMetadataRepository metadataRepository, ConfigurableEnvironment environment) {
        this.allProperties = Collections.unmodifiableMap(metadataRepository.getAllProperties());
        this.environment = environment;
    }

    /**
     * replacedyse the {@link ConfigurableEnvironment environment} and attempt to rename
     * legacy properties if a replacement exists.
     * @return a report of the migration
     */
    public PropertiesMigrationReport getReport() {
        PropertiesMigrationReport report = new PropertiesMigrationReport();
        Map<String, List<PropertyMigration>> properties = getMatchingProperties(deprecatedFilter());
        if (properties.isEmpty()) {
            return report;
        }
        properties.forEach((name, candidates) -> {
            PropertySource<?> propertySource = mapPropertiesWithReplacement(report, name, candidates);
            if (propertySource != null) {
                this.environment.getPropertySources().addBefore(name, propertySource);
            }
        });
        return report;
    }

    private PropertySource<?> mapPropertiesWithReplacement(PropertiesMigrationReport report, String name, List<PropertyMigration> properties) {
        List<PropertyMigration> renamed = new ArrayList<>();
        List<PropertyMigration> unsupported = new ArrayList<>();
        properties.forEach((property) -> (isRenamed(property) ? renamed : unsupported).add(property));
        report.add(name, renamed, unsupported);
        if (renamed.isEmpty()) {
            return null;
        }
        String target = "migrate-" + name;
        Map<String, OriginTrackedValue> content = new LinkedHashMap<>();
        for (PropertyMigration candidate : renamed) {
            OriginTrackedValue value = OriginTrackedValue.of(candidate.getProperty().getValue(), candidate.getProperty().getOrigin());
            content.put(candidate.getMetadata().getDeprecation().getReplacement(), value);
        }
        return new OriginTrackedMapPropertySource(target, content);
    }

    private boolean isRenamed(PropertyMigration property) {
        ConfigurationMetadataProperty metadata = property.getMetadata();
        String replacementId = metadata.getDeprecation().getReplacement();
        if (StringUtils.hasText(replacementId)) {
            ConfigurationMetadataProperty replacement = this.allProperties.get(replacementId);
            if (replacement != null) {
                return isCompatibleType(metadata.getType(), replacement.getType());
            }
            return isCompatibleType(metadata.getType(), detectMapValueReplacementType(replacementId));
        }
        return false;
    }

    private boolean isCompatibleType(String currentType, String replacementType) {
        if (replacementType == null || currentType == null) {
            return false;
        }
        if (replacementType.equals(currentType)) {
            return true;
        }
        if (replacementType.equals(Duration.clreplaced.getName()) && (currentType.equals(Long.clreplaced.getName()) || currentType.equals(Integer.clreplaced.getName()))) {
            return true;
        }
        return false;
    }

    private String detectMapValueReplacementType(String fullId) {
        int lastDot = fullId.lastIndexOf('.');
        if (lastDot != -1) {
            ConfigurationMetadataProperty property = this.allProperties.get(fullId.substring(0, lastDot));
            String type = property.getType();
            if (type != null && type.startsWith(Map.clreplaced.getName())) {
                int lastComma = type.lastIndexOf(',');
                if (lastComma != -1) {
                    return type.substring(lastComma + 1, type.length() - 1).trim();
                }
            }
        }
        return null;
    }

    private Map<String, List<PropertyMigration>> getMatchingProperties(Predicate<ConfigurationMetadataProperty> filter) {
        MultiValueMap<String, PropertyMigration> result = new LinkedMultiValueMap<>();
        List<ConfigurationMetadataProperty> candidates = this.allProperties.values().stream().filter(filter).collect(Collectors.toList());
        getPropertySourcesAsMap().forEach((name, source) -> {
            candidates.forEach((metadata) -> {
                ConfigurationProperty configurationProperty = source.getConfigurationProperty(ConfigurationPropertyName.of(metadata.getId()));
                if (configurationProperty != null) {
                    result.add(name, new PropertyMigration(metadata, configurationProperty));
                }
            });
        });
        return result;
    }

    private Predicate<ConfigurationMetadataProperty> deprecatedFilter() {
        return (property) -> property.getDeprecation() != null && property.getDeprecation().getLevel() == Deprecation.Level.ERROR;
    }

    private Map<String, ConfigurationPropertySource> getPropertySourcesAsMap() {
        Map<String, ConfigurationPropertySource> map = new LinkedHashMap<>();
        for (ConfigurationPropertySource source : ConfigurationPropertySources.get(this.environment)) {
            map.put(determinePropertySourceName(source), source);
        }
        return map;
    }

    private String determinePropertySourceName(ConfigurationPropertySource source) {
        if (source.getUnderlyingSource() instanceof PropertySource) {
            return ((PropertySource<?>) source.getUnderlyingSource()).getName();
        }
        return source.getUnderlyingSource().toString();
    }
}

19 View Source File : DevToolsPropertyDefaultsPostProcessor.java
License : Apache License 2.0
Project Creator : yuanmabiji

private boolean isLocalApplication(ConfigurableEnvironment environment) {
    return environment.getPropertySources().get("remoteUrl") == null;
}

19 View Source File : ConditionalOnPropertyTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Tests for {@link ConditionalOnProperty}.
 *
 * @author Maciej Walkowiak
 * @author Stephane Nicoll
 * @author Phillip Webb
 * @author Andy Wilkinson
 */
public clreplaced ConditionalOnPropertyTests {

    private ConfigurableApplicationContext context;

    private ConfigurableEnvironment environment = new StandardEnvironment();

    @After
    public void tearDown() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void allPropertiesAreDefined() {
        load(MultiplePropertiesRequiredConfiguration.clreplaced, "property1=value1", "property2=value2");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void notAllPropertiesAreDefined() {
        load(MultiplePropertiesRequiredConfiguration.clreplaced, "property1=value1");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void propertyValueEqualsFalse() {
        load(MultiplePropertiesRequiredConfiguration.clreplaced, "property1=false", "property2=value2");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void propertyValueEqualsFALSE() {
        load(MultiplePropertiesRequiredConfiguration.clreplaced, "property1=FALSE", "property2=value2");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void relaxedName() {
        load(RelaxedPropertiesRequiredConfiguration.clreplaced, "spring.theRelaxedProperty=value1");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void prefixWithoutPeriod() {
        load(RelaxedPropertiesRequiredConfigurationWithShortPrefix.clreplaced, "spring.property=value1");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public // Enabled by default
    void enabledIfNotConfiguredOtherwise() {
        load(EnabledIfNotConfiguredOtherwiseConfig.clreplaced);
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void enabledIfNotConfiguredOtherwiseWithConfig() {
        load(EnabledIfNotConfiguredOtherwiseConfig.clreplaced, "simple.myProperty:false");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void enabledIfNotConfiguredOtherwiseWithConfigDifferentCase() {
        load(EnabledIfNotConfiguredOtherwiseConfig.clreplaced, "simple.my-property:FALSE");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public // Disabled by default
    void disableIfNotConfiguredOtherwise() {
        load(DisabledIfNotConfiguredOtherwiseConfig.clreplaced);
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void disableIfNotConfiguredOtherwiseWithConfig() {
        load(DisabledIfNotConfiguredOtherwiseConfig.clreplaced, "simple.myProperty:true");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void disableIfNotConfiguredOtherwiseWithConfigDifferentCase() {
        load(DisabledIfNotConfiguredOtherwiseConfig.clreplaced, "simple.myproperty:TrUe");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void simpleValueIsSet() {
        load(SimpleValueConfig.clreplaced, "simple.myProperty:bar");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void caseInsensitive() {
        load(SimpleValueConfig.clreplaced, "simple.myProperty:BaR");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void defaultValueIsSet() {
        load(DefaultValueConfig.clreplaced, "simple.myProperty:bar");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void defaultValueIsNotSet() {
        load(DefaultValueConfig.clreplaced);
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void defaultValueIsSetDifferentValue() {
        load(DefaultValueConfig.clreplaced, "simple.myProperty:another");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void prefix() {
        load(PrefixValueConfig.clreplaced, "simple.myProperty:bar");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void relaxedEnabledByDefault() {
        load(PrefixValueConfig.clreplaced, "simple.myProperty:bar");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void multiValuesAllSet() {
        load(MultiValuesConfig.clreplaced, "simple.my-property:bar", "simple.my-another-property:bar");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void multiValuesOnlyOneSet() {
        load(MultiValuesConfig.clreplaced, "simple.my-property:bar");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void usingValueAttribute() {
        load(ValueAttribute.clreplaced, "some.property");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void nameOrValueMustBeSpecified() {
        replacedertThatIllegalStateException().isThrownBy(() -> load(NoNameOrValueAttribute.clreplaced, "some.property")).satisfies(causeMessageContaining("The name or value attribute of @ConditionalOnProperty must be specified"));
    }

    @Test
    public void nameAndValueMustNotBeSpecified() {
        replacedertThatIllegalStateException().isThrownBy(() -> load(NameAndValueAttribute.clreplaced, "some.property")).satisfies(causeMessageContaining("The name and value attributes of @ConditionalOnProperty are exclusive"));
    }

    private <T extends Exception> Consumer<T> causeMessageContaining(String message) {
        return (ex) -> replacedertThat(ex.getCause()).hasMessageContaining(message);
    }

    @Test
    public void metaAnnotationConditionMatchesWhenPropertyIsSet() {
        load(MetaAnnotation.clreplaced, "my.feature.enabled=true");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    @Test
    public void metaAnnotationConditionDoesNotMatchWhenPropertyIsNotSet() {
        load(MetaAnnotation.clreplaced);
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyDirectPropertyIsSet() {
        load(MetaAnnotationAndDirectAnnotation.clreplaced, "my.other.feature.enabled=true");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void metaAndDirectAnnotationConditionDoesNotMatchWhenOnlyMetaPropertyIsSet() {
        load(MetaAnnotationAndDirectAnnotation.clreplaced, "my.feature.enabled=true");
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void metaAndDirectAnnotationConditionDoesNotMatchWhenNeitherPropertyIsSet() {
        load(MetaAnnotationAndDirectAnnotation.clreplaced);
        replacedertThat(this.context.containsBean("foo")).isFalse();
    }

    @Test
    public void metaAndDirectAnnotationConditionMatchesWhenBothPropertiesAreSet() {
        load(MetaAnnotationAndDirectAnnotation.clreplaced, "my.feature.enabled=true", "my.other.feature.enabled=true");
        replacedertThat(this.context.containsBean("foo")).isTrue();
    }

    private void load(Clreplaced<?> config, String... environment) {
        TestPropertyValues.of(environment).applyTo(this.environment);
        this.context = new SpringApplicationBuilder(config).environment(this.environment).web(WebApplicationType.NONE).run();
    }

    @Configuration
    @ConditionalOnProperty(name = { "property1", "property2" })
    protected static clreplaced MultiplePropertiesRequiredConfiguration {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(prefix = "spring.", name = "the-relaxed-property")
    protected static clreplaced RelaxedPropertiesRequiredConfiguration {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(prefix = "spring", name = "property")
    protected static clreplaced RelaxedPropertiesRequiredConfigurationWithShortPrefix {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    // i.e ${simple.myProperty:true}
    @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", matchIfMissing = true)
    static clreplaced EnabledIfNotConfiguredOtherwiseConfig {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    // i.e ${simple.myProperty:false}
    @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "true", matchIfMissing = false)
    static clreplaced DisabledIfNotConfiguredOtherwiseConfig {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "bar")
    static clreplaced SimpleValueConfig {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(name = "simple.myProperty", havingValue = "bar", matchIfMissing = true)
    static clreplaced DefaultValueConfig {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(prefix = "simple", name = "my-property", havingValue = "bar")
    static clreplaced PrefixValueConfig {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(prefix = "simple", name = { "my-property", "my-another-property" }, havingValue = "bar")
    static clreplaced MultiValuesConfig {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty("some.property")
    protected static clreplaced ValueAttribute {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty
    protected static clreplaced NoNameOrValueAttribute {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnProperty(value = "x", name = "y")
    protected static clreplaced NameAndValueAttribute {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnMyFeature
    protected static clreplaced MetaAnnotation {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Configuration
    @ConditionalOnMyFeature
    @ConditionalOnProperty(prefix = "my.other.feature", name = "enabled", havingValue = "true", matchIfMissing = false)
    protected static clreplaced MetaAnnotationAndDirectAnnotation {

        @Bean
        public String foo() {
            return "foo";
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target({ ElementType.TYPE, ElementType.METHOD })
    @ConditionalOnProperty(prefix = "my.feature", name = "enabled", havingValue = "true", matchIfMissing = false)
    public @interface ConditionalOnMyFeature {
    }
}

19 View Source File : MustacheEnvironmentCollector.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Mustache {@link Collector} to expose properties from the Spring {@link Environment}.
 *
 * @author Dave Syer
 * @author Madhura Bhave
 * @since 1.2.2
 */
public clreplaced MustacheEnvironmentCollector extends DefaultCollector implements EnvironmentAware {

    private ConfigurableEnvironment environment;

    private final VariableFetcher propertyFetcher = new PropertyVariableFetcher();

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
    }

    @Override
    public VariableFetcher createFetcher(Object ctx, String name) {
        VariableFetcher fetcher = super.createFetcher(ctx, name);
        if (fetcher != null) {
            return fetcher;
        }
        if (this.environment.containsProperty(name)) {
            return this.propertyFetcher;
        }
        return null;
    }

    private clreplaced PropertyVariableFetcher implements VariableFetcher {

        @Override
        public Object get(Object ctx, String name) throws Exception {
            return MustacheEnvironmentCollector.this.environment.getProperty(name);
        }
    }
}

19 View Source File : InfoContributorAutoConfiguration.java
License : Apache License 2.0
Project Creator : yuanmabiji

@Bean
@ConditionalOnEnabledInfoContributor("env")
@Order(DEFAULT_ORDER)
public EnvironmentInfoContributor envInfoContributor(ConfigurableEnvironment environment) {
    return new EnvironmentInfoContributor(environment);
}

19 View Source File : EnvironmentInfoContributorTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private static Info contributeFrom(ConfigurableEnvironment environment) {
    EnvironmentInfoContributor contributor = new EnvironmentInfoContributor(environment);
    Info.Builder builder = new Info.Builder();
    contributor.contribute(builder);
    return builder.build();
}

/**
 * Tests for {@link SystemEnvironmentPropertySourceEnvironmentPostProcessor}.
 *
 * @author Madhura Bhave
 */
public clreplaced SystemEnvironmentPropertySourceEnvironmentPostProcessorTests {

    private ConfigurableEnvironment environment;

    @Before
    public void setUp() {
        this.environment = new StandardEnvironment();
    }

    @Test
    public void postProcessShouldReplaceSystemEnvironmentPropertySource() {
        SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor();
        postProcessor.postProcessEnvironment(this.environment, null);
        PropertySource<?> replaced = this.environment.getPropertySources().get("systemEnvironment");
        replacedertThat(replaced).isInstanceOf(OriginAwareSystemEnvironmentPropertySource.clreplaced);
    }

    @Test
    @SuppressWarnings("unchecked")
    public void replacedPropertySourceShouldBeOriginAware() {
        SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor();
        PropertySource<?> original = this.environment.getPropertySources().get("systemEnvironment");
        postProcessor.postProcessEnvironment(this.environment, null);
        OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment.getPropertySources().get("systemEnvironment");
        Map<String, Object> originalMap = (Map<String, Object>) original.getSource();
        Map<String, Object> replacedMap = replaced.getSource();
        originalMap.forEach((key, value) -> {
            Object actual = replacedMap.get(key);
            replacedertThat(actual).isEqualTo(value);
            replacedertThat(replaced.getOrigin(key)).isInstanceOf(SystemEnvironmentOrigin.clreplaced);
        });
    }

    @Test
    public void replacedPropertySourceWhenPropertyAbsentShouldReturnNullOrigin() {
        SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor();
        postProcessor.postProcessEnvironment(this.environment, null);
        OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment.getPropertySources().get("systemEnvironment");
        replacedertThat(replaced.getOrigin("NON_EXISTENT")).isNull();
    }

    @Test
    public void replacedPropertySourceShouldResolveProperty() {
        SystemEnvironmentPropertySourceEnvironmentPostProcessor postProcessor = new SystemEnvironmentPropertySourceEnvironmentPostProcessor();
        Map<String, Object> source = Collections.singletonMap("FOO_BAR_BAZ", "hello");
        this.environment.getPropertySources().replace("systemEnvironment", new SystemEnvironmentPropertySource("systemEnvironment", source));
        postProcessor.postProcessEnvironment(this.environment, null);
        OriginAwareSystemEnvironmentPropertySource replaced = (OriginAwareSystemEnvironmentPropertySource) this.environment.getPropertySources().get("systemEnvironment");
        SystemEnvironmentOrigin origin = (SystemEnvironmentOrigin) replaced.getOrigin("foo.bar.baz");
        replacedertThat(origin.getProperty()).isEqualTo("FOO_BAR_BAZ");
        replacedertThat(replaced.getProperty("foo.bar.baz")).isEqualTo("hello");
    }
}

/**
 * Tests for {@link SpringApplicationJsonEnvironmentPostProcessor}.
 *
 * @author Dave Syer
 * @author Madhura Bhave
 * @author Phillip Webb
 * @author Artsiom Yudovin
 */
public clreplaced SpringApplicationJsonEnvironmentPostProcessorTests {

    private SpringApplicationJsonEnvironmentPostProcessor processor = new SpringApplicationJsonEnvironmentPostProcessor();

    private ConfigurableEnvironment environment = new StandardEnvironment();

    @Test
    public void error() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json=foo:bar");
        replacedertThatExceptionOfType(JsonParseException.clreplaced).isThrownBy(() -> this.processor.postProcessEnvironment(this.environment, null)).withMessageContaining("Cannot parse JSON");
    }

    @Test
    public void missing() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
    }

    @Test
    public void empty() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
    }

    @Test
    public void periodSeparated() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={\"foo\":\"bar\"}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEqualTo("bar");
    }

    @Test
    public void envVar() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":\"bar\"}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEqualTo("bar");
    }

    @Test
    public void nested() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":{\"bar\":\"spam\",\"rab\":\"maps\"}}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo.bar:}")).isEqualTo("spam");
        replacedertThat(this.environment.resolvePlaceholders("${foo.rab:}")).isEqualTo("maps");
    }

    @Test
    public void prefixed() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo.bar\":\"spam\"}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo.bar:}")).isEqualTo("spam");
    }

    @Test
    public void list() {
        replacedertThat(this.environment.resolvePlaceholders("${foo[1]:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[\"bar\",\"spam\"]}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo[1]:}")).isEqualTo("spam");
    }

    @Test
    public void listOfObject() {
        replacedertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "SPRING_APPLICATION_JSON={\"foo\":[{\"bar\":\"spam\"}]}");
        this.processor.postProcessEnvironment(this.environment, null);
        replacedertThat(this.environment.resolvePlaceholders("${foo[0].bar:}")).isEqualTo("spam");
    }

    @Test
    public void propertySourceShouldTrackOrigin() {
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEmpty();
        TestPropertySourceUtils.addInlinedPropertiesToEnvironment(this.environment, "spring.application.json={\"foo\":\"bar\"}");
        this.processor.postProcessEnvironment(this.environment, null);
        PropertySource<?> propertySource = this.environment.getPropertySources().get("spring.application.json");
        PropertySourceOrigin origin = (PropertySourceOrigin) PropertySourceOrigin.get(propertySource, "foo");
        replacedertThat(origin.getPropertySource().getName()).isEqualTo("Inlined Test Properties");
        replacedertThat(origin.getPropertyName()).isEqualTo("spring.application.json");
        replacedertThat(this.environment.resolvePlaceholders("${foo:}")).isEqualTo("bar");
    }
}

19 View Source File : ApplicationPidFileWriterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private SpringApplicationEvent createReadyEvent(String propName, String propValue) {
    ConfigurableEnvironment environment = createEnvironment(propName, propValue);
    ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.clreplaced);
    given(context.getEnvironment()).willReturn(environment);
    return new ApplicationReadyEvent(new SpringApplication(), new String[] {}, context);
}

19 View Source File : ApplicationPidFileWriterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private SpringApplicationEvent createPreparedEvent(String propName, String propValue) {
    ConfigurableEnvironment environment = createEnvironment(propName, propValue);
    ConfigurableApplicationContext context = mock(ConfigurableApplicationContext.clreplaced);
    given(context.getEnvironment()).willReturn(environment);
    return new ApplicationPreparedEvent(new SpringApplication(), new String[] {}, context);
}

19 View Source File : ApplicationPidFileWriterTests.java
License : Apache License 2.0
Project Creator : yuanmabiji

private SpringApplicationEvent createEnvironmentPreparedEvent(String propName, String propValue) {
    ConfigurableEnvironment environment = createEnvironment(propName, propValue);
    return new ApplicationEnvironmentPreparedEvent(new SpringApplication(), new String[] {}, environment);
}

19 View Source File : XmlServletWebServerApplicationContext.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * {@inheritDoc}
 * <p>
 * Delegates the given environment to underlying {@link XmlBeanDefinitionReader}.
 * Should be called before any call to {@link #load}.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
    super.setEnvironment(environment);
    this.reader.setEnvironment(this.getEnvironment());
}

/**
 * {@inheritDoc}
 * <p>
 * Delegates given environment to underlying {@link AnnotatedBeanDefinitionReader} and
 * {@link ClreplacedPathBeanDefinitionScanner} members.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
    super.setEnvironment(environment);
    this.reader.setEnvironment(environment);
    this.scanner.setEnvironment(environment);
}

19 View Source File : SpringApplicationRunListeners.java
License : Apache License 2.0
Project Creator : yuanmabiji

public void environmentPrepared(ConfigurableEnvironment environment) {
    for (SpringApplicationRunListener listener : this.listeners) {
        listener.environmentPrepared(environment);
    }
}

19 View Source File : LoggingInitializationContext.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Context preplaceded to the {@link LoggingSystem} during initialization.
 *
 * @author Phillip Webb
 * @since 1.3.0
 */
public clreplaced LoggingInitializationContext {

    private final ConfigurableEnvironment environment;

    /**
     * Create a new {@link LoggingInitializationContext} instance.
     * @param environment the Spring environment.
     */
    public LoggingInitializationContext(ConfigurableEnvironment environment) {
        this.environment = environment;
    }

    /**
     * Return the Spring environment if available.
     * @return the {@link Environment} or {@code null}
     */
    public Environment getEnvironment() {
        return this.environment;
    }
}

/**
 * A {@link Failurereplacedyzer} that performs replacedysis of failures caused by an
 * {@link InvalidConfigurationPropertyValueException}.
 *
 * @author Stephane Nicoll
 */
clreplaced InvalidConfigurationPropertyValueFailurereplacedyzer extends AbstractFailurereplacedyzer<InvalidConfigurationPropertyValueException> implements EnvironmentAware {

    private ConfigurableEnvironment environment;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = (ConfigurableEnvironment) environment;
    }

    @Override
    protected Failurereplacedysis replacedyze(Throwable rootFailure, InvalidConfigurationPropertyValueException cause) {
        List<Descriptor> descriptors = getDescriptors(cause.getName());
        if (descriptors.isEmpty()) {
            return null;
        }
        StringBuilder description = new StringBuilder();
        appendDetails(description, cause, descriptors);
        appendReason(description, cause);
        appendAdditionalProperties(description, descriptors);
        return new Failurereplacedysis(description.toString(), getAction(cause), cause);
    }

    private List<Descriptor> getDescriptors(String propertyName) {
        return getPropertySources().filter((source) -> source.containsProperty(propertyName)).map((source) -> Descriptor.get(source, propertyName)).collect(Collectors.toList());
    }

    private Stream<PropertySource<?>> getPropertySources() {
        if (this.environment == null) {
            return Stream.empty();
        }
        return this.environment.getPropertySources().stream().filter((source) -> !ConfigurationPropertySources.isAttachedConfigurationPropertySource(source));
    }

    private void appendDetails(StringBuilder message, InvalidConfigurationPropertyValueException cause, List<Descriptor> descriptors) {
        Descriptor mainDescriptor = descriptors.get(0);
        message.append("Invalid value '" + mainDescriptor.getValue() + "' for configuration property '" + cause.getName() + "'");
        mainDescriptor.appendOrigin(message);
        message.append(".");
    }

    private void appendReason(StringBuilder message, InvalidConfigurationPropertyValueException cause) {
        if (StringUtils.hasText(cause.getReason())) {
            message.append(String.format(" Validation failed for the following " + "reason:%n%n"));
            message.append(cause.getReason());
        } else {
            message.append(" No reason was provided.");
        }
    }

    private void appendAdditionalProperties(StringBuilder message, List<Descriptor> descriptors) {
        List<Descriptor> others = descriptors.subList(1, descriptors.size());
        if (!others.isEmpty()) {
            message.append(String.format("%n%nAdditionally, this property is also set in the following " + "property %s:%n%n", (others.size() > 1) ? "sources" : "source"));
            for (Descriptor other : others) {
                message.append("\t- In '" + other.getPropertySource() + "'");
                message.append(" with the value '" + other.getValue() + "'");
                other.appendOrigin(message);
                message.append(String.format(".%n"));
            }
        }
    }

    private String getAction(InvalidConfigurationPropertyValueException cause) {
        StringBuilder action = new StringBuilder();
        action.append("Review the value of the property");
        if (cause.getReason() != null) {
            action.append(" with the provided reason");
        }
        action.append(".");
        return action.toString();
    }

    private static final clreplaced Descriptor {

        private final String propertySource;

        private final Object value;

        private final Origin origin;

        private Descriptor(String propertySource, Object value, Origin origin) {
            this.propertySource = propertySource;
            this.value = value;
            this.origin = origin;
        }

        public String getPropertySource() {
            return this.propertySource;
        }

        public Object getValue() {
            return this.value;
        }

        public void appendOrigin(StringBuilder message) {
            if (this.origin != null) {
                message.append(" (originating from '" + this.origin + "')");
            }
        }

        static Descriptor get(PropertySource<?> source, String propertyName) {
            Object value = source.getProperty(propertyName);
            Origin origin = OriginLookup.getOrigin(source, propertyName);
            return new Descriptor(source.getName(), value, origin);
        }
    }
}

19 View Source File : LoggingApplicationListener.java
License : Apache License 2.0
Project Creator : yuanmabiji

private boolean isSet(ConfigurableEnvironment environment, String property) {
    String value = environment.getProperty(property);
    return (value != null && !value.equals("false"));
}

19 View Source File : LoggingApplicationListener.java
License : Apache License 2.0
Project Creator : yuanmabiji

private void initializeEarlyLoggingLevel(ConfigurableEnvironment environment) {
    if (this.parseArgs && this.springBootLogging == null) {
        if (isSet(environment, "debug")) {
            this.springBootLogging = LogLevel.DEBUG;
        }
        if (isSet(environment, "trace")) {
            this.springBootLogging = LogLevel.TRACE;
        }
    }
}

19 View Source File : EventPublishingRunListener.java
License : Apache License 2.0
Project Creator : yuanmabiji

// 》》》》》发射【ApplicationEnvironmentPreparedEvent】事件
@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
    this.initialMulticaster.multicastEvent(new ApplicationEnvironmentPreparedEvent(this.application, this.args, environment));
}

19 View Source File : ApplicationEnvironmentPreparedEvent.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Event published when a {@link SpringApplication} is starting up and the
 * {@link Environment} is first available for inspection and modification.
 *
 * @author Dave Syer
 */
@SuppressWarnings("serial")
public clreplaced ApplicationEnvironmentPreparedEvent extends SpringApplicationEvent {

    private final ConfigurableEnvironment environment;

    /**
     * Create a new {@link ApplicationEnvironmentPreparedEvent} instance.
     * @param application the current application
     * @param args the arguments the application is running with
     * @param environment the environment that was just created
     */
    public ApplicationEnvironmentPreparedEvent(SpringApplication application, String[] args, ConfigurableEnvironment environment) {
        super(application, args);
        this.environment = environment;
    }

    /**
     * Return the environment.
     * @return the environment
     */
    public ConfigurableEnvironment getEnvironment() {
        return this.environment;
    }
}

19 View Source File : SpringApplicationBuilder.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Environment for the application context.
 * @param environment the environment to set.
 * @return the current builder
 */
public SpringApplicationBuilder environment(ConfigurableEnvironment environment) {
    this.application.setEnvironment(environment);
    this.environment = environment;
    return this;
}

19 View Source File : BeanDefinitionLoader.java
License : Apache License 2.0
Project Creator : yuanmabiji

/**
 * Set the environment to be used by the underlying readers and scanner.
 * @param environment the environment
 */
public void setEnvironment(ConfigurableEnvironment environment) {
    this.annotatedReader.setEnvironment(environment);
    this.xmlReader.setEnvironment(environment);
    this.scanner.setEnvironment(environment);
}

19 View Source File : ConfigServiceBootstrapConfiguration.java
License : Apache License 2.0
Project Creator : Xlinlin

/**
 * @author Dave Syer
 */
@Configuration
@EnableConfigurationProperties
public clreplaced ConfigServiceBootstrapConfiguration {

    @Autowired
    private ConfigurableEnvironment environment;

    @Bean
    public ConfigClientProperties configClientProperties() {
        ConfigClientProperties client = new ConfigClientProperties(this.environment);
        return client;
    }

    @Bean
    @ConditionalOnProperty(value = "spring.cloud.config.enabled", matchIfMissing = true)
    public ConfigServicePropertySourceLocator configServicePropertySource(ConfigClientProperties properties) {
        ConfigServicePropertySourceLocator locator = new ConfigServicePropertySourceLocator(properties);
        return locator;
    }

    @ConditionalOnProperty(value = "spring.cloud.config.failFast", matchIfMissing = false)
    @ConditionalOnClreplaced({ Retryable.clreplaced, Aspect.clreplaced, AopAutoConfiguration.clreplaced })
    @Configuration
    @EnableRetry(proxyTargetClreplaced = true)
    @Import(AopAutoConfiguration.clreplaced)
    @EnableConfigurationProperties(RetryProperties.clreplaced)
    protected static clreplaced RetryConfiguration {

        @Bean
        @ConditionalOnMissingBean(name = "configServerRetryInterceptor")
        public RetryOperationsInterceptor configServerRetryInterceptor(RetryProperties properties) {
            return RetryInterceptorBuilder.stateless().backOffOptions(properties.getInitialInterval(), properties.getMultiplier(), properties.getMaxInterval()).maxAttempts(properties.getMaxAttempts()).build();
        }
    }
}

19 View Source File : MiraiPlusRegistrar.java
License : GNU Affero General Public License v3.0
Project Creator : xiaoxu97

/**
 * @author xiaoxu
 * @date 2020-08-07 10:44
 */
@Slf4j
public clreplaced MiraiPlusRegistrar implements ImportBeanDefinitionRegistrar, EnvironmentAware {

    private ConfigurableEnvironment environment;

    @Override
    public void setEnvironment(@NotNull Environment environment) {
        replacedert.isInstanceOf(ConfigurableEnvironment.clreplaced, environment);
        this.environment = (ConfigurableEnvironment) environment;
    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, @NotNull BeanDefinitionRegistry beanDefinitionRegistry) {
        BeanDefinitionBuilder configFactory = BeanDefinitionBuilder.rootBeanDefinition(MiraiPlusConfigFactory.clreplaced);
        configFactory.addPropertyValue("miraiPlusConfigs", this.loadConfig());
        BeanRegistryUtils.registerBeanDefinition(beanDefinitionRegistry, configFactory.getBeanDefinition(), "miraiPlusConfigFactory");
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(EnableMiraiPlus.clreplaced.getName()));
        replacedert.notNull(attributes, "Mirai plus attributes is must be not null!");
        String[] scanBasePackages = attributes.getStringArray("scanBasePackages");
        for (String scanBasePackage : scanBasePackages) {
            for (String clreplacedName : ClreplacedUtils.getClreplacedName(scanBasePackage, true)) {
                try {
                    Clreplaced<?> aClreplaced = Clreplaced.forName(clreplacedName);
                    if (aClreplaced.getAnnotation(MiraiPlusHandler.clreplaced) != null) {
                        BeanRegistryUtils.registerBeanDefinition(beanDefinitionRegistry, aClreplaced);
                    }
                } catch (ClreplacedNotFoundException e) {
                    log.error("clreplaced not found", e);
                }
            }
        }
        for (String clreplacedName : ClreplacedUtils.getClreplacedName("com.zhuangxv.miraiplus.injector.parameter", true)) {
            try {
                Clreplaced<?> aClreplaced = Clreplaced.forName(clreplacedName);
                BeanRegistryUtils.registerBeanDefinition(beanDefinitionRegistry, aClreplaced);
            } catch (ClreplacedNotFoundException e) {
                log.error("clreplaced not found", e);
            }
        }
        BeanRegistryUtils.registerBeanDefinition(beanDefinitionRegistry, BeanDefinitionBuilder.rootBeanDefinition(MiraiPlusInit.clreplaced).getBeanDefinition(), "miraiPlusInit");
        BeanRegistryUtils.registerBeanDefinition(beanDefinitionRegistry, BeanDefinitionBuilder.rootBeanDefinition(MiraiPlusMessageDispatcher.clreplaced).getBeanDefinition(), "miraiPlusMessageDispatcher");
    }

    private List<MiraiPlusConfig> loadConfig() {
        List<MiraiPlusConfig> miraiPlusConfigs = new ArrayList<>();
        if (PropertySourcesUtils.getSubProperties(this.environment.getPropertySources(), ConfigKeys.MIRAI_SINGLE_KEY).isEmpty() && PropertySourcesUtils.getSubProperties(this.environment.getPropertySources(), ConfigKeys.MIRAI_MULTIPLE_KEY).isEmpty()) {
            throw new MiraiPlusException("未发现配置文件。");
        } else {
            Binder binder = Binder.get(this.environment);
            if (!PropertySourcesUtils.getSubProperties(this.environment.getPropertySources(), ConfigKeys.MIRAI_SINGLE_KEY).isEmpty()) {
                miraiPlusConfigs.add(binder.bind(ConfigKeys.MIRAI_SINGLE_KEY, Bindable.of(MiraiPlusConfig.clreplaced)).get());
            } else {
                miraiPlusConfigs.addAll(binder.bind(ConfigKeys.MIRAI_SINGLE_KEY, Bindable.listOf(MiraiPlusConfig.clreplaced)).get());
            }
            return miraiPlusConfigs;
        }
    }
}

19 View Source File : HelloApplicationRunListener.java
License : MIT License
Project Creator : wuyouzhuguli

@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
}

19 View Source File : DispatcherServletTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void environmentOperations() {
    DispatcherServlet servlet = new DispatcherServlet();
    ConfigurableEnvironment defaultEnv = servlet.getEnvironment();
    replacedertThat(defaultEnv, notNullValue());
    ConfigurableEnvironment env1 = new StandardServletEnvironment();
    // should succeed
    servlet.setEnvironment(env1);
    replacedertThat(servlet.getEnvironment(), sameInstance(env1));
    try {
        servlet.setEnvironment(new DummyEnvironment());
        fail("expected IllegalArgumentException for non-configurable Environment");
    } catch (IllegalArgumentException ex) {
    }
    clreplaced CustomServletEnvironment extends StandardServletEnvironment {
    }
    @SuppressWarnings("serial")
    DispatcherServlet custom = new DispatcherServlet() {

        @Override
        protected ConfigurableWebEnvironment createEnvironment() {
            return new CustomServletEnvironment();
        }
    };
    replacedertThat(custom.getEnvironment(), instanceOf(CustomServletEnvironment.clreplaced));
}

19 View Source File : HttpServletBean.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Simple extension of {@link javax.servlet.http.HttpServlet} which treats
 * its config parameters ({@code init-param} entries within the
 * {@code servlet} tag in {@code web.xml}) as bean properties.
 *
 * <p>A handy superclreplaced for any type of servlet. Type conversion of config
 * parameters is automatic, with the corresponding setter method getting
 * invoked with the converted value. It is also possible for subclreplacedes to
 * specify required properties. Parameters without matching bean property
 * setter will simply be ignored.
 *
 * <p>This servlet leaves request handling to subclreplacedes, inheriting the default
 * behavior of HttpServlet ({@code doGet}, {@code doPost}, etc).
 *
 * <p>This generic servlet base clreplaced has no dependency on the Spring
 * {@link org.springframework.context.ApplicationContext} concept. Simple
 * servlets usually don't load their own context but rather access service
 * beans from the Spring root application context, accessible via the
 * filter's {@link #getServletContext() ServletContext} (see
 * {@link org.springframework.web.context.support.WebApplicationContextUtils}).
 *
 * <p>The {@link FrameworkServlet} clreplaced is a more specific servlet base
 * clreplaced which loads its own application context. FrameworkServlet serves
 * as direct base clreplaced of Spring's full-fledged {@link DispatcherServlet}.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see #addRequiredProperty
 * @see #initServletBean
 * @see #doGet
 * @see #doPost
 */
@SuppressWarnings("serial")
public abstract clreplaced HttpServletBean extends HttpServlet implements EnvironmentCapable, EnvironmentAware {

    /**
     * Logger available to subclreplacedes.
     */
    protected final Log logger = LogFactory.getLog(getClreplaced());

    @Nullable
    private ConfigurableEnvironment environment;

    private final Set<String> requiredProperties = new HashSet<>(4);

    /**
     * Subclreplacedes can invoke this method to specify that this property
     * (which must match a JavaBean property they expose) is mandatory,
     * and must be supplied as a config parameter. This should be called
     * from the constructor of a subclreplaced.
     * <p>This method is only relevant in case of traditional initialization
     * driven by a ServletConfig instance.
     * @param property name of the required property
     */
    protected final void addRequiredProperty(String property) {
        this.requiredProperties.add(property);
    }

    /**
     * Set the {@code Environment} that this servlet runs in.
     * <p>Any environment set here overrides the {@link StandardServletEnvironment}
     * provided by default.
     * @throws IllegalArgumentException if environment is not replacedignable to
     * {@code ConfigurableEnvironment}
     */
    @Override
    public void setEnvironment(Environment environment) {
        replacedert.isInstanceOf(ConfigurableEnvironment.clreplaced, environment, "ConfigurableEnvironment required");
        this.environment = (ConfigurableEnvironment) environment;
    }

    /**
     * Return the {@link Environment} replacedociated with this servlet.
     * <p>If none specified, a default environment will be initialized via
     * {@link #createEnvironment()}.
     */
    @Override
    public ConfigurableEnvironment getEnvironment() {
        if (this.environment == null) {
            this.environment = createEnvironment();
        }
        return this.environment;
    }

    /**
     * Create and return a new {@link StandardServletEnvironment}.
     * <p>Subclreplacedes may override this in order to configure the environment or
     * specialize the environment type returned.
     */
    protected ConfigurableEnvironment createEnvironment() {
        return new StandardServletEnvironment();
    }

    /**
     * Map config parameters onto bean properties of this servlet, and
     * invoke subclreplaced initialization.
     * @throws ServletException if bean properties are invalid (or required
     * properties are missing), or if subclreplaced initialization fails.
     */
    @Override
    public final void init() throws ServletException {
        // Set bean properties from init parameters.
        // 解析 init-param 并封装到 pvs 变量中
        PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
        if (!pvs.isEmpty()) {
            try {
                // 将当前的这个 Servlet 类转换为一个 BeanWrapper,从而能够以 Spring 的方式对 init—param 的值注入
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
                ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
                // 注册自定义属性编辑器,一旦遇到 Resource 类型的属性将会使用 ResourceEditor 进行解析
                bw.registerCustomEditor(Resource.clreplaced, new ResourceEditor(resourceLoader, getEnvironment()));
                // 空实现,留给子类覆盖
                initBeanWrapper(bw);
                bw.setPropertyValues(pvs, true);
            } catch (BeansException ex) {
                if (logger.isErrorEnabled()) {
                    logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
                }
                throw ex;
            }
        }
        // Let subclreplacedes do whatever initialization they like.
        // 初始化 servletBean (让子类实现,这里它的实现子类是 FrameworkServlet)
        initServletBean();
    }

    /**
     * Initialize the BeanWrapper for this HttpServletBean,
     * possibly with custom editors.
     * <p>This default implementation is empty.
     * @param bw the BeanWrapper to initialize
     * @throws BeansException if thrown by BeanWrapper methods
     * @see org.springframework.beans.BeanWrapper#registerCustomEditor
     */
    protected void initBeanWrapper(BeanWrapper bw) throws BeansException {
    }

    /**
     * Subclreplacedes may override this to perform custom initialization.
     * All bean properties of this servlet will have been set before this
     * method is invoked.
     * <p>This default implementation is empty.
     * @throws ServletException if subclreplaced initialization fails
     */
    protected void initServletBean() throws ServletException {
    }

    /**
     * Overridden method that simply returns {@code null} when no
     * ServletConfig set yet.
     * @see #getServletConfig()
     */
    @Override
    @Nullable
    public String getServletName() {
        return (getServletConfig() != null ? getServletConfig().getServletName() : null);
    }

    /**
     * PropertyValues implementation created from ServletConfig init parameters.
     */
    private static clreplaced ServletConfigPropertyValues extends MutablePropertyValues {

        /**
         * Create new ServletConfigPropertyValues.
         * @param config the ServletConfig we'll use to take PropertyValues from
         * @param requiredProperties set of property names we need, where
         * we can't accept default values
         * @throws ServletException if any required properties are missing
         */
        public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties) throws ServletException {
            Set<String> missingProps = (!CollectionUtils.isEmpty(requiredProperties) ? new HashSet<>(requiredProperties) : null);
            Enumeration<String> paramNames = config.getInitParameterNames();
            while (paramNames.hasMoreElements()) {
                String property = paramNames.nextElement();
                Object value = config.getInitParameter(property);
                addPropertyValue(new PropertyValue(property, value));
                if (missingProps != null) {
                    missingProps.remove(property);
                }
            }
            // Fail if we are still missing properties.
            if (!CollectionUtils.isEmpty(missingProps)) {
                throw new ServletException("Initialization from ServletConfig for servlet '" + config.getServletName() + "' failed; the following required properties were missing: " + StringUtils.collectionToDelimitedString(missingProps, ", "));
            }
        }
    }
}

19 View Source File : GenericWebApplicationContext.java
License : MIT License
Project Creator : Vip-Augus

/**
 * {@inheritDoc}
 * <p>Replace {@code Servlet}-related property sources.
 */
@Override
protected void initPropertySources() {
    ConfigurableEnvironment env = getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, null);
    }
}

19 View Source File : AbstractRefreshableWebApplicationContext.java
License : MIT License
Project Creator : Vip-Augus

/**
 * {@inheritDoc}
 * <p>Replace {@code Servlet}-related property sources.
 */
@Override
protected void initPropertySources() {
    ConfigurableEnvironment env = getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(this.servletContext, this.servletConfig);
    }
}

19 View Source File : GenericXmlApplicationContext.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Delegates the given environment to underlying {@link XmlBeanDefinitionReader}.
 * Should be called before any call to {@code #load}.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
    super.setEnvironment(environment);
    this.reader.setEnvironment(getEnvironment());
}

19 View Source File : GenericGroovyApplicationContext.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Delegates the given environment to underlying {@link GroovyBeanDefinitionReader}.
 * Should be called before any call to {@code #load}.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
    super.setEnvironment(environment);
    this.reader.setEnvironment(getEnvironment());
}

19 View Source File : AnnotationConfigApplicationContext.java
License : MIT License
Project Creator : Vip-Augus

/**
 * Propagates the given custom {@code Environment} to the underlying
 * {@link AnnotatedBeanDefinitionReader} and {@link ClreplacedPathBeanDefinitionScanner}.
 */
@Override
public void setEnvironment(ConfigurableEnvironment environment) {
    super.setEnvironment(environment);
    this.reader.setEnvironment(environment);
    this.scanner.setEnvironment(environment);
}

19 View Source File : ProfileXmlBeanDefinitionTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void testDefaultAndNonDefaultProfile() {
    replacedertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, NONE_ACTIVE), containsTargetBean());
    replacedertThat(beanFactoryFor(DEFAULT_ELIGIBLE_XML, "other"), not(containsTargetBean()));
    {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        ConfigurableEnvironment env = new StandardEnvironment();
        env.setActiveProfiles(DEV_ACTIVE);
        env.setDefaultProfiles("default");
        reader.setEnvironment(env);
        reader.loadBeanDefinitions(new ClreplacedPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClreplaced()));
        replacedertThat(beanFactory, containsTargetBean());
    }
    {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        ConfigurableEnvironment env = new StandardEnvironment();
        // env.setActiveProfiles(DEV_ACTIVE);
        env.setDefaultProfiles("default");
        reader.setEnvironment(env);
        reader.loadBeanDefinitions(new ClreplacedPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClreplaced()));
        replacedertThat(beanFactory, containsTargetBean());
    }
    {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        ConfigurableEnvironment env = new StandardEnvironment();
        // env.setActiveProfiles(DEV_ACTIVE);
        // env.setDefaultProfiles("default");
        reader.setEnvironment(env);
        reader.loadBeanDefinitions(new ClreplacedPathResource(DEFAULT_AND_DEV_ELIGIBLE_XML, getClreplaced()));
        replacedertThat(beanFactory, containsTargetBean());
    }
}

19 View Source File : ProfileXmlBeanDefinitionTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void testDefaultProfile() {
    {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        ConfigurableEnvironment env = new StandardEnvironment();
        env.setDefaultProfiles("custom-default");
        reader.setEnvironment(env);
        reader.loadBeanDefinitions(new ClreplacedPathResource(DEFAULT_ELIGIBLE_XML, getClreplaced()));
        replacedertThat(beanFactory, not(containsTargetBean()));
    }
    {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory);
        ConfigurableEnvironment env = new StandardEnvironment();
        env.setDefaultProfiles("custom-default");
        reader.setEnvironment(env);
        reader.loadBeanDefinitions(new ClreplacedPathResource(CUSTOM_DEFAULT_ELIGIBLE_XML, getClreplaced()));
        replacedertThat(beanFactory, containsTargetBean());
    }
}

19 View Source File : NestedBeansElementTests.java
License : MIT License
Project Creator : Vip-Augus

@Test
public void getBean_withActiveProfile() {
    ConfigurableEnvironment env = new StandardEnvironment();
    env.setActiveProfiles("dev");
    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(bf);
    reader.setEnvironment(env);
    reader.loadBeanDefinitions(XML);
    // should not throw NSBDE
    bf.getBean("devOnlyBean");
    Object foo = bf.getBean("foo");
    replacedertThat(foo, instanceOf(Integer.clreplaced));
    bf.getBean("devOnlyBean");
}

19 View Source File : SpringTestAPI.java
License : GNU Lesser General Public License v2.1
Project Creator : Verdoso

@RestController
@Slf4j
@Data
public clreplaced SpringTestAPI {

    public static final String TEST_XSLT_SOURCE = "pojo_process";

    public static enum TestEnum {

        TEST_ENUM_A, TEST_ENUM_B
    }

    @Autowired
    private ConfigurableEnvironment env;

    @Data
    public static clreplaced TestClreplaced implements Logable {

        private int code;

        private String name;

        @Override
        public String formatted() {
            final String toString = toString();
            return toString.substring(toString.indexOf("("));
        }
    }

    @RequestMapping(value = "/test")
    public ModelAndView testInterface() {
        return new XsltModelAndView(TEST_XSLT_SOURCE, generateAppObject(), HttpStatus.OK);
    }

    // http://localhost:9090/param_test?name_x=x&name_int=1&name_array=name1,name2,name3&int_array=1,2,3&enum_array=TEST_ENUM_A,TEST_ENUM_B
    @RequestMapping(value = "/param_test")
    public ResponseEnreplacedy<String> testParameters(@RequestParam(name = "name_x") String nameString, @RequestParam(name = "name_int") int nameInteger, @RequestParam(name = "name_array") String[] theValues, @RequestParam(name = "int_array") int[] intValues, @RequestParam(name = "enum_array") TestEnum[] enumValues) {
        return new ResponseEnreplacedy<>(TEST_XSLT_SOURCE, HttpStatus.BAD_REQUEST);
    }

    // http://localhost:9090/param_clreplaced_test?code=1&&name=aName
    @RequestMapping(value = "/param_clreplaced_test")
    public ResponseEnreplacedy<String> testParameters(TestClreplaced testValue) {
        return new ResponseEnreplacedy<>(TEST_XSLT_SOURCE, HttpStatus.OK);
    }

    @RequestMapping(value = "/json", produces = MediaType.APPLICATION_JSON_VALUE)
    public App testJSON() {
        return generateAppObject();
    }

    @RequestMapping(value = "/jolt")
    public ModelAndView testJOLT() {
        log.debug("Testing");
        return new JoltModelAndView("jolt-test", generateAppObject(), HttpStatus.OK);
    }

    private App generateAppObject() {
        App app = new App(Arrays.asList(new MyPojo("anId", "aName"), new MyPojo("anotherId", "anotherName")));
        return app;
    }
}

19 View Source File : SystemLoadListener.java
License : Apache License 2.0
Project Creator : tiankong0310

@Override
public void environmentPrepared(ConfigurableEnvironment environment) {
// 不在这里触发,是避免跟优先于日志的调整
}

19 View Source File : MultRegisterCenterServerMgmtConfig.java
License : Apache License 2.0
Project Creator : SpringCloud

private String getProperty(String property, ConfigurableEnvironment env) {
    return env.containsProperty(property) ? env.getProperty(property) : "";
}

19 View Source File : MultRegisterCenterServerMgmtConfig.java
License : Apache License 2.0
Project Creator : SpringCloud

public EurekaClientConfigBean eurekaClientConfigBean(ConfigurableEnvironment env) {
    EurekaClientConfigBean client = new EurekaClientConfigBean();
    if ("bootstrap".equals(env.getProperty("spring.config.name"))) {
        // We don't register during bootstrap by default, but there will be another
        // chance later.
        client.setRegisterWithEureka(false);
    }
    return client;
}

19 View Source File : FunctionalInstallerListener.java
License : Apache License 2.0
Project Creator : spring-projects-experimental

private boolean isEnabled(ConfigurableEnvironment environment) {
    return environment.getProperty("spring.functional.enabled", Boolean.clreplaced, true);
}

19 View Source File : EnvironmentVaultConfigurationUnitTests.java
License : Apache License 2.0
Project Creator : spring-projects

/**
 * Unit tests for {@link EnvironmentVaultConfiguration}.
 *
 * @author Mark Paluch
 */
@ExtendWith(SpringExtension.clreplaced)
@TestPropertySource(properties = { "vault.uri=https://localhost:8123", "vault.token=my-token", "vault.ssl.key-store-preplacedword=key store preplacedword", "vault.ssl.trust-store-preplacedword=trust store preplacedword" })
clreplaced EnvironmentVaultConfigurationUnitTests {

    @Configuration
    @Import(EnvironmentVaultConfiguration.clreplaced)
    static clreplaced ApplicationConfiguration {
    }

    @Autowired
    EnvironmentVaultConfiguration configuration;

    @Autowired
    ConfigurableEnvironment configurableEnvironment;

    @Test
    void shouldConfigureEndpoint() {
        replacedertThat(this.configuration.vaultEndpoint().getPort()).isEqualTo(8123);
    }

    @Test
    void shouldConfigureTokenAuthentication() {
        ClientAuthentication clientAuthentication = this.configuration.clientAuthentication();
        replacedertThat(clientAuthentication).isInstanceOf(TokenAuthentication.clreplaced);
        replacedertThat(clientAuthentication.login()).isEqualTo(VaultToken.of("my-token"));
    }

    @Test
    void shouldConfigureSsl() {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("vault.ssl.key-store", "clreplacedpath:certificate.json");
        map.put("vault.ssl.trust-store", "clreplacedpath:certificate.json");
        MapPropertySource propertySource = new MapPropertySource("shouldConfigureSsl", map);
        this.configurableEnvironment.getPropertySources().addFirst(propertySource);
        SslConfiguration sslConfiguration = this.configuration.sslConfiguration();
        replacedertThat(sslConfiguration.getKeyStore()).isInstanceOf(ClreplacedPathResource.clreplaced);
        replacedertThat(sslConfiguration.getKeyStorePreplacedword()).isEqualTo("key store preplacedword");
        replacedertThat(sslConfiguration.getTrustStore()).isInstanceOf(ClreplacedPathResource.clreplaced);
        replacedertThat(sslConfiguration.getTrustStorePreplacedword()).isEqualTo("trust store preplacedword");
        this.configurableEnvironment.getPropertySources().remove(propertySource.getName());
    }
}

/**
 * Tests for {@link ResourceServerTokenServicesConfiguration}.
 *
 * @author Dave Syer
 * @author Madhura Bhave
 * @author Eddú Meléndez
 */
public clreplaced ResourceServerTokenServicesConfigurationTests {

    private static String PUBLIC_KEY = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnGp/Q5lh0P8nPL21oMMrt2RrkT9" + "AW5jgYwLfSUnJVc9G6uR3cXRRDCjHqWU5WYwivcF180A6CWp/ireQFFBNowgc5XaA0kPpzE" + "tgsA5YsNX7iSnUibB004iBTfU9hZ2Rbsc8cWqynT0RyN4TP1RYVSeVKvMQk4GT1r7JCEC+T" + "Nu1ELmbNwMQyzKjsfBXyIOCFU/E94ktvsTZUHF4Oq44DBylCDsS1k7/sfZC2G5EU7Oz0mhG" + "8+Uz6MSEQHtoIi6mc8u64Rwi3Z3tscuWG2ShtsUFuNSAFNkY7LkLn+/hxLCu2bNISMaESa8" + "dG22CIMuIeRLVcAmEWEWH5EEforTg+QIDAQAB\n-----END PUBLIC KEY-----";

    private ConfigurableApplicationContext context;

    private ConfigurableEnvironment environment = new StandardEnvironment();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @After
    public void close() {
        if (this.context != null) {
            this.context.close();
        }
    }

    @Test
    public void useRemoteTokenServices() {
        TestPropertyValues.of("security.oauth2.resource.tokenInfoUri:https://example.com").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        RemoteTokenServices services = this.context.getBean(RemoteTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
    }

    @Test
    public void overrideRemoteTokenServices() {
        TestPropertyValues.of("security.oauth2.resource.tokenInfoUri:https://example.com").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(CustomRemoteTokenService.clreplaced, ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        CustomRemoteTokenService services = this.context.getBean(CustomRemoteTokenService.clreplaced);
        replacedertThat(services).isNotNull();
        this.thrown.expect(NoSuchBeanDefinitionException.clreplaced);
        this.context.getBean(RemoteTokenServices.clreplaced);
    }

    @Test
    public void switchToUserInfo() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
    }

    @Test
    public void userInfoWithAuthorities() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(AuthoritiesConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
        replacedertThat(services).extracting("authoritiesExtractor").isSameAs(this.context.getBean(AuthoritiesExtractor.clreplaced));
    }

    @Test
    public void userInfoWithPrincipal() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(PrincipalConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
        replacedertThat(services).extracting("principalExtractor").isSameAs(this.context.getBean(PrincipalExtractor.clreplaced));
    }

    @Test
    public void userInfoWithClient() {
        TestPropertyValues.of("security.oauth2.client.client-id=acme", "security.oauth2.resource.userInfoUri:https://example.com", "server.port=-1", "debug=true").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceNoClientConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.SERVLET).run();
        BeanDefinition bean = ((BeanDefinitionRegistry) this.context).getBeanDefinition("scopedTarget.oauth2ClientContext");
        replacedertThat(bean.getScope()).isEqualTo("request");
    }

    @Test
    public void preferUserInfo() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com", "security.oauth2.resource.tokenInfoUri:https://example.com", "security.oauth2.resource.preferTokenInfo:false").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
    }

    @Test
    public void userInfoWithCustomizer() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com", "security.oauth2.resource.tokenInfoUri:https://example.com", "security.oauth2.resource.preferTokenInfo:false").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced, Customizer.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        UserInfoTokenServices services = this.context.getBean(UserInfoTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
    }

    @Test
    public void switchToJwt() {
        TestPropertyValues.of("security.oauth2.resource.jwt.keyValue=FOOBAR").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        DefaultTokenServices services = this.context.getBean(DefaultTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
        this.thrown.expect(NoSuchBeanDefinitionException.clreplaced);
        this.context.getBean(RemoteTokenServices.clreplaced);
    }

    @Test
    public void asymmetricJwt() {
        TestPropertyValues.of("security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY).applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        DefaultTokenServices services = this.context.getBean(DefaultTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
    }

    @Test
    public void jwkConfiguration() throws Exception {
        TestPropertyValues.of("security.oauth2.resource.jwk.key-set-uri=https://idp.example.com/token_keys").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        DefaultTokenServices services = this.context.getBean(DefaultTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
        this.thrown.expect(NoSuchBeanDefinitionException.clreplaced);
        this.context.getBean(RemoteTokenServices.clreplaced);
    }

    @Test
    public void springSocialUserInfo() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com", "spring.social.facebook.app-id=foo", "spring.social.facebook.app-secret=bar").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(SocialResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.SERVLET).run();
        ConnectionFactoryLocator connectionFactory = this.context.getBean(ConnectionFactoryLocator.clreplaced);
        replacedertThat(connectionFactory).isNotNull();
        SpringSocialTokenServices services = this.context.getBean(SpringSocialTokenServices.clreplaced);
        replacedertThat(services).isNotNull();
    }

    @Test
    public void customUserInfoRestTemplateFactory() {
        TestPropertyValues.of("security.oauth2.resource.userInfoUri:https://example.com").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(CustomUserInfoRestTemplateFactory.clreplaced, ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(UserInfoRestTemplateFactory.clreplaced)).hreplacedize(1);
        replacedertThat(this.context.getBean(UserInfoRestTemplateFactory.clreplaced)).isInstanceOf(CustomUserInfoRestTemplateFactory.clreplaced);
    }

    @Test
    public void jwtAccessTokenConverterIsConfiguredWhenKeyUriIsProvided() {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-uri=http://localhost:12345/banana").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced, JwtAccessTokenConverterRestTemplateCustomizerConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwtAccessTokenConverter.clreplaced)).hreplacedize(1);
    }

    @Test
    public void jwkTokenStoreShouldBeConditionalOnMissingBean() throws Exception {
        TestPropertyValues.of("security.oauth2.resource.jwk.key-set-uri=https://idp.example.com/token_keys").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(JwkTokenStoreConfiguration.clreplaced, ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwkTokenStore.clreplaced)).hreplacedize(1);
    }

    @Test
    public void jwtTokenStoreShouldBeConditionalOnMissingBean() throws Exception {
        TestPropertyValues.of("security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY).applyTo(this.environment);
        this.context = new SpringApplicationBuilder(JwtTokenStoreConfiguration.clreplaced, ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwtTokenStore.clreplaced)).hreplacedize(1);
    }

    @Test
    public void jwtAccessTokenConverterForKeyValueShouldBeConditionalOnMissingBean() throws Exception {
        TestPropertyValues.of("security.oauth2.resource.jwt.keyValue=" + PUBLIC_KEY).applyTo(this.environment);
        this.context = new SpringApplicationBuilder(JwtTokenStoreConfiguration.clreplaced, ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwtAccessTokenConverter.clreplaced)).hreplacedize(1);
    }

    @Test
    public void jwtAccessTokenConverterForKeyStoreShouldBeConditionalOnMissingBean() throws Exception {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-store=clreplacedpath:" + "org/springframework/boot/autoconfigure/security/oauth2/resource/keystore.jks", "security.oauth2.resource.jwt.key-store-preplacedword=changeme", "security.oauth2.resource.jwt.key-alias=jwt").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(JwtTokenStoreConfiguration.clreplaced, ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwtAccessTokenConverter.clreplaced)).hreplacedize(1);
    }

    @Test
    public void configureWhenKeyStoreIsProvidedThenExposesJwtTokenStore() {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-store=clreplacedpath:" + "org/springframework/boot/autoconfigure/security/oauth2/resource/keystore.jks", "security.oauth2.resource.jwt.key-store-preplacedword=changeme", "security.oauth2.resource.jwt.key-alias=jwt").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(TokenStore.clreplaced)).hreplacedize(1);
        replacedertThat(this.context.getBean(TokenStore.clreplaced)).isInstanceOf(JwtTokenStore.clreplaced);
    }

    @Test
    public void configureWhenKeyStoreIsProvidedThenExposesJwtAccessTokenConverter() {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-store=clreplacedpath:" + "org/springframework/boot/autoconfigure/security/oauth2/resource/keystore.jks", "security.oauth2.resource.jwt.key-store-preplacedword=changeme", "security.oauth2.resource.jwt.key-alias=jwt").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwtAccessTokenConverter.clreplaced)).hreplacedize(1);
    }

    @Test
    public void configureWhenKeyStoreIsProvidedWithKeyPreplacedwordThenExposesJwtAccessTokenConverter() {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-store=clreplacedpath:" + "org/springframework/boot/autoconfigure/security/oauth2/resource/keyhaspreplacedword.jks", "security.oauth2.resource.jwt.key-store-preplacedword=changeme", "security.oauth2.resource.jwt.key-alias=jwt", "security.oauth2.resource.jwt.key-preplacedword=preplacedword").applyTo(this.environment);
        this.context = new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run();
        replacedertThat(this.context.getBeansOfType(JwtAccessTokenConverter.clreplaced)).hreplacedize(1);
    }

    @Test
    public void configureWhenKeyStoreIsProvidedButNoAliasThenThrowsException() {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-store=clreplacedpath:" + "org/springframework/boot/autoconfigure/security/oauth2/resource/keystore.jks", "security.oauth2.resource.jwt.key-store-preplacedword=changeme").applyTo(this.environment);
        replacedertThatCode(() -> new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run()).isInstanceOf(UnsatisfiedDependencyException.clreplaced);
    }

    @Test
    public void configureWhenKeyStoreIsProvidedButNoPreplacedwordThenThrowsException() {
        TestPropertyValues.of("security.oauth2.resource.jwt.key-store=clreplacedpath:" + "org/springframework/boot/autoconfigure/security/oauth2/resource/keystore.jks", "security.oauth2.resource.jwt.key-alias=jwt").applyTo(this.environment);
        replacedertThatCode(() -> new SpringApplicationBuilder(ResourceConfiguration.clreplaced).environment(this.environment).web(WebApplicationType.NONE).run());
    }

    @Configuration
    @Import({ ResourceServerTokenServicesConfiguration.clreplaced, ResourceServerPropertiesConfiguration.clreplaced, PropertyPlaceholderAutoConfiguration.clreplaced })
    @EnableConfigurationProperties(OAuth2ClientProperties.clreplaced)
    protected static clreplaced ResourceConfiguration {
    }

    @Configuration
    protected static clreplaced AuthoritiesConfiguration extends ResourceConfiguration {

        @Bean
        AuthoritiesExtractor authoritiesExtractor() {
            return (map) -> AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
        }
    }

    @Configuration
    protected static clreplaced PrincipalConfiguration extends ResourceConfiguration {

        @Bean
        PrincipalExtractor principalExtractor() {
            return (map) -> "boot";
        }
    }

    @Import({ OAuth2RestOperationsConfiguration.clreplaced })
    protected static clreplaced ResourceNoClientConfiguration extends ResourceConfiguration {

        @Bean
        public MockServletWebServerFactory webServerFactory() {
            return new MockServletWebServerFactory();
        }
    }

    @Configuration
    protected static clreplaced ResourceServerPropertiesConfiguration {

        private OAuth2ClientProperties credentials;

        public ResourceServerPropertiesConfiguration(OAuth2ClientProperties credentials) {
            this.credentials = credentials;
        }

        @Bean
        public ResourceServerProperties resourceServerProperties() {
            return new ResourceServerProperties(this.credentials.getClientId(), this.credentials.getClientSecret());
        }
    }

    @Import({ FacebookAutoConfiguration.clreplaced, SocialWebAutoConfiguration.clreplaced })
    protected static clreplaced SocialResourceConfiguration extends ResourceConfiguration {

        @Bean
        public ServletWebServerFactory webServerFactory() {
            return new MockServletWebServerFactory();
        }
    }

    @Component
    protected static clreplaced Customizer implements UserInfoRestTemplateCustomizer {

        @Override
        public void customize(OAuth2RestTemplate template) {
            template.getInterceptors().add((request, body, execution) -> execution.execute(request, body));
        }
    }

    @Component
    protected static clreplaced CustomUserInfoRestTemplateFactory implements UserInfoRestTemplateFactory {

        private final OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(new AuthorizationCodeResourceDetails());

        @Override
        public OAuth2RestTemplate getUserInfoRestTemplate() {
            return this.restTemplate;
        }
    }

    @Component
    protected static clreplaced CustomRemoteTokenService implements ResourceServerTokenServices {

        @Override
        public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException, InvalidTokenException {
            return null;
        }

        @Override
        public OAuth2AccessToken readAccessToken(String accessToken) {
            return null;
        }
    }

    @Configuration
    static clreplaced JwtAccessTokenConverterRestTemplateCustomizerConfiguration {

        @Bean
        public JwtAccessTokenConverterRestTemplateCustomizer restTemplateCustomizer() {
            return new MockRestCallCustomizer();
        }
    }

    @Configuration
    static clreplaced JwtTokenStoreConfiguration {

        @Bean
        public TokenStore tokenStore(JwtAccessTokenConverter jwtTokenEnhancer) {
            return new JwtTokenStore(jwtTokenEnhancer);
        }
    }

    @Configuration
    static clreplaced JwkTokenStoreConfiguration {

        @Bean
        public TokenStore tokenStore() {
            return new JwkTokenStore("https://idp.example.com/token_keys");
        }
    }

    private static clreplaced MockRestCallCustomizer implements JwtAccessTokenConverterRestTemplateCustomizer {

        @Override
        public void customize(RestTemplate template) {
            template.getInterceptors().add((request, body, execution) -> {
                String payload = "{\"value\":\"FOO\"}";
                MockClientHttpResponse response = new MockClientHttpResponse(payload.getBytes(), HttpStatus.OK);
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                return response;
            });
        }
    }
}

19 View Source File : OAuth2RestOperationsConfigurationTests.java
License : Apache License 2.0
Project Creator : spring-projects

/**
 * Tests for {@link OAuth2RestOperationsConfiguration}.
 *
 * @author Madhura Bhave
 */
public clreplaced OAuth2RestOperationsConfigurationTests {

    private ConfigurableApplicationContext context;

    private ConfigurableEnvironment environment = new StandardEnvironment();

    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void clientCredentialsWithClientId() throws Exception {
        TestPropertyValues.of("security.oauth2.client.client-id=acme").applyTo(this.environment);
        initializeContext(OAuth2RestOperationsConfiguration.clreplaced, true);
        replacedertThat(this.context.getBean(OAuth2RestOperationsConfiguration.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(ClientCredentialsResourceDetails.clreplaced)).isNotNull();
    }

    @Test
    public void clientCredentialsWithNoClientId() throws Exception {
        initializeContext(OAuth2RestOperationsConfiguration.clreplaced, true);
        replacedertThat(this.context.getBean(OAuth2RestOperationsConfiguration.clreplaced)).isNotNull();
        replacedertThat(this.context.getBean(ClientCredentialsResourceDetails.clreplaced)).isNotNull();
    }

    @Test
    public void requestScopedWithClientId() throws Exception {
        TestPropertyValues.of("security.oauth2.client.client-id=acme").applyTo(this.environment);
        initializeContext(ConfigForRequestScopedConfiguration.clreplaced, false);
        replacedertThat(this.context.containsBean("oauth2ClientContext")).isTrue();
    }

    @Test
    public void requestScopedWithNoClientId() throws Exception {
        initializeContext(ConfigForRequestScopedConfiguration.clreplaced, false);
        this.thrown.expect(NoSuchBeanDefinitionException.clreplaced);
        this.context.getBean(DefaultOAuth2ClientContext.clreplaced);
    }

    @Test
    public void sessionScopedWithClientId() throws Exception {
        TestPropertyValues.of("security.oauth2.client.client-id=acme").applyTo(this.environment);
        initializeContext(ConfigForSessionScopedConfiguration.clreplaced, false);
        replacedertThat(this.context.containsBean("oauth2ClientContext")).isTrue();
    }

    @Test
    public void sessionScopedWithNoClientId() throws Exception {
        initializeContext(ConfigForSessionScopedConfiguration.clreplaced, false);
        this.thrown.expect(NoSuchBeanDefinitionException.clreplaced);
        this.context.getBean(DefaultOAuth2ClientContext.clreplaced);
    }

    private void initializeContext(Clreplaced<?> configuration, boolean clientCredentials) {
        this.context = new SpringApplicationBuilder(configuration).environment(this.environment).web(clientCredentials ? WebApplicationType.NONE : WebApplicationType.SERVLET).run();
    }

    @Configuration
    @Import({ OAuth2RestOperationsConfiguration.clreplaced })
    protected static clreplaced WebApplicationConfiguration {

        @Bean
        public MockServletWebServerFactory webServerFactory() {
            return new MockServletWebServerFactory();
        }
    }

    @Configuration
    @Import({ SecurityProperties.clreplaced, OAuth2ClientConfiguration.clreplaced, OAuth2RestOperationsConfiguration.clreplaced })
    protected static clreplaced ConfigForSessionScopedConfiguration extends WebApplicationConfiguration {
    }

    @Configuration
    protected static clreplaced ConfigForRequestScopedConfiguration extends WebApplicationConfiguration {
    }
}

See More Examples