org.springframework.boot.context.properties.bind.Binder Java Examples

The following examples show how to use org.springframework.boot.context.properties.bind.Binder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExternalizedConfigurationBinderBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) throws IOException {
    // application.properties 文件资源 classpath 路径
    String location = "application.properties";
    // 编码化的 Resource 对象(解决乱码问题)
    EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8");
    // 加载 application.properties 文件,转化为 Properties 对象
    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    // 创建 Properties 类型的 PropertySource
    PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties);
    // 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource);
    // 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力)
    Binder binder = new Binder(propertySources, null, conversionService());
    // 执行绑定,返回绑定结果
    BindResult<User> bindResult = binder.bind("user", User.class);
    // 获取绑定对象
    User user = bindResult.get();
    // 输出结果
    System.out.println(user);

}
 
Example #2
Source File: BinderBootstrap.java    From thinking-in-spring-boot-samples with Apache License 2.0 7 votes vote down vote up
public static void main(String[] args) {
    ConfigurableApplicationContext context = new SpringApplicationBuilder(BinderBootstrap.class)
            .web(WebApplicationType.NONE) // 非 Web 应用
            .properties("user.city.postCode=0731")
            .run(args);
    ConfigurableEnvironment environment = context.getEnvironment();
    // 从 Environment 中获取 ConfigurationPropertySource 集合
    Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
    // 构造 Binder 对象,并使用 ConfigurationPropertySource 集合作为配置源
    Binder binder = new Binder(sources);
    // 构造 ConfigurationPropertyName(Spring Boot 2.0 API)
    ConfigurationPropertyName propertyName = ConfigurationPropertyName.of("user.city.post-code");
    // 构造 Bindable 对象,包装 postCode
    Bindable<String> postCodeBindable = Bindable.of(String.class);
    BindResult<String> result = binder.bind(propertyName, postCodeBindable);
    String postCode = result.get();
    System.out.println("postCode = " + postCode);
    // 关闭上下文
    context.close();
}
 
Example #3
Source File: AbstractExtendedBindingProperties.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void bindToDefault(String binding) {
	T extendedBindingPropertiesTarget = (T) BeanUtils
			.instantiateClass(this.getExtendedPropertiesEntryClass());
	Binder binder = new Binder(
			ConfigurationPropertySources
					.get(this.applicationContext.getEnvironment()),
			new PropertySourcesPlaceholdersResolver(
					this.applicationContext.getEnvironment()),
			IntegrationUtils.getConversionService(
					this.applicationContext.getBeanFactory()),
			null);
	binder.bind(this.getDefaultsPrefix(),
			Bindable.ofInstance(extendedBindingPropertiesTarget));
	this.bindings.put(binding, extendedBindingPropertiesTarget);
}
 
Example #4
Source File: Front50PluginsConfiguration.java    From kork with Apache License 2.0 6 votes vote down vote up
/**
 * We are a bit inconsistent with how we configure service URLs, so we proceed in this order:
 *
 * <p>1) {@code spinnaker.extensibility.repositories.front50.url} 2) {@code front50.base-url} 3)
 * {@code services.front50.base-url}
 *
 * @param environment The Spring environment
 * @param front50RepositoryProps Front50 update repository configuration
 * @return The configured Front50 URL
 */
private static URL getFront50Url(
    Environment environment, PluginRepositoryProperties front50RepositoryProps) {
  try {
    return front50RepositoryProps.getUrl();
  } catch (Exception e) {
    log.warn(
        "Front50 update repository URL is either not specified or malformed, falling back "
            + "to default configuration",
        e);
    return Binder.get(environment)
        .bind("front50.base-url", Bindable.of(URL.class))
        .orElseGet(
            () ->
                Binder.get(environment)
                    .bind("services.front50.base-url", Bindable.of(URL.class))
                    .get());
  }
}
 
Example #5
Source File: SpringBoot2IntroApplication.java    From Spring-Boot-2.0-Projects with MIT License 6 votes vote down vote up
@Bean
public ApplicationRunner runner(DemoApplicationProperties myApplicationProperties, Environment environment) {
	return args -> {

		List<Address> addresses = Binder.get(environment)
				.bind("demo.addresses", Bindable.listOf(Address.class))
				.orElseThrow(IllegalStateException::new);

		System.out.printf("Demo Addresses : %s\n", addresses);

		// DEMO_ENV_1 Environment Variable
		System.out.printf("Demo Env 1 : %s\n", environment.getProperty("demo.env[1]"));

		System.out.printf("Demo First Name : %s\n", myApplicationProperties.getFirstName());
		System.out.printf("Demo Last Name : %s\n", myApplicationProperties.getLastName());
		System.out.printf("Demo Username : %s\n", myApplicationProperties.getUsername());
		System.out.printf("Demo Working Time (Hours) : %s\n", myApplicationProperties.getWorkingTime().toHours());
		System.out.printf("Demo Number : %d\n", myApplicationProperties.getNumber());
		System.out.printf("Demo Telephone Number : %s\n", myApplicationProperties.getTelephoneNumber());
		System.out.printf("Demo Email 1 : %s\n", myApplicationProperties.getEmailAddresses().get(0));
		System.out.printf("Demo Email 2 : %s\n", myApplicationProperties.getEmailAddresses().get(1));
	};
}
 
Example #6
Source File: BrpcProperties.java    From brpc-java with Apache License 2.0 6 votes vote down vote up
public BrpcConfig getServiceConfig(Class<?> serviceInterface) {
    BrpcConfig brpcConfig = new BrpcConfig(global);
    if (brpcConfig.getClient() == null) {
        brpcConfig.setClient(new RpcClientConfig());
    }
    if (brpcConfig.getServer() == null) {
        brpcConfig.setServer(new RpcServerConfig());
    }
    if (brpcConfig.getNaming() == null) {
        brpcConfig.setNaming(new RpcNamingConfig());
    }
    String prefix = "brpc.custom." + normalizeName(serviceInterface.getName()) + ".";
    Binder binder = Binder.get(environment);
    binder.bind(prefix + "client", Bindable.ofInstance(brpcConfig.getClient()));
    binder.bind(prefix + "server", Bindable.ofInstance(brpcConfig.getServer()));
    binder.bind(prefix + "naming", Bindable.ofInstance(brpcConfig.getNaming()));
    rewriteMap(brpcConfig.getNaming().getExtra());
    return brpcConfig;
}
 
Example #7
Source File: NacosBootConfigurationPropertiesBinder.java    From nacos-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@Override
protected void doBind(Object bean, String beanName, String dataId, String groupId,
		String configType, NacosConfigurationProperties properties, String content,
		ConfigService configService) {
	String name = "nacos-bootstrap-" + beanName;
	NacosPropertySource propertySource = new NacosPropertySource(name, dataId,
			groupId, content, configType);
	environment.getPropertySources().addLast(propertySource);
	Binder binder = Binder.get(environment);
	ResolvableType type = getBeanType(bean, beanName);
	Bindable<?> target = Bindable.of(type).withExistingValue(bean);
	binder.bind(properties.prefix(), target);
	publishBoundEvent(bean, beanName, dataId, groupId, properties, content,
			configService);
	publishMetadataEvent(bean, beanName, dataId, groupId, properties);
	environment.getPropertySources().remove(name);
}
 
Example #8
Source File: ApplicationPropertiesTests.java    From github-release-notes-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void loadYaml() throws Exception {
	YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
	List<PropertySource<?>> yaml = yamlLoader.load("application",
			new ClassPathResource("test-application.yml", getClass()));
	Binder binder = new Binder(ConfigurationPropertySources.from(yaml));
	ApplicationProperties properties = binder.bind("releasenotes", ApplicationProperties.class).get();
	Github github = properties.getGithub();
	assertThat(github.getUsername()).isEqualTo("testuser");
	assertThat(github.getPassword()).isEqualTo("testpass");
	assertThat(github.getOrganization()).isEqualTo("testorg");
	assertThat(github.getRepository()).isEqualTo("testrepo");
	List<Section> sections = properties.getSections();
	assertThat(sections.get(0).getTitle()).isEqualTo("New Features");
	assertThat(sections.get(0).getEmoji()).isEqualTo(":star:");
	assertThat(sections.get(0).getLabels()).containsExactly("enhancement");
}
 
Example #9
Source File: GenericPropertiesConfiguration.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
Example #10
Source File: GenericPropertiesConfiguration.java    From camunda-bpm-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@Override
public void preInit(SpringProcessEngineConfiguration springProcessEngineConfiguration) {
  GenericProperties genericProperties = camundaBpmProperties.getGenericProperties();
  final Map<String, Object> properties = genericProperties.getProperties();

  if (!CollectionUtils.isEmpty(properties)) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source);
    try {
      if (genericProperties.isIgnoreUnknownFields()) {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration));
      } else {
        binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(springProcessEngineConfiguration), new NoUnboundElementsBindHandler(BindHandler.DEFAULT));
      }
    } catch (Exception e) {
      throw LOG.exceptionDuringBinding(e.getMessage());
    }
    logger.debug("properties bound to configuration: {}", genericProperties);
  }
}
 
Example #11
Source File: RpcDefinitionPostProcessor.java    From joyrpc with Apache License 2.0 6 votes vote down vote up
/**
 * 构造方法
 */
public RpcDefinitionPostProcessor(final ApplicationContext applicationContext,
                                  final ConfigurableEnvironment environment,
                                  final ResourceLoader resourceLoader) {
    this.applicationContext = applicationContext;
    this.environment = environment;
    this.resourceLoader = resourceLoader;
    this.counter = Counter.getOrCreate(applicationContext);
    this.rpcProperties = Binder.get(environment).bind(RPC_PREFIX, RpcProperties.class).orElseGet(RpcProperties::new);
    //值引用前缀
    this.refPrefix = environment.getProperty(REF_PREFIX_KEY, REF_PREFIX);
    //添加消费者
    if (rpcProperties.getConsumers() != null) {
        rpcProperties.getConsumers().forEach(c -> addConfig(c, CONSUMER_PREFIX, consumerNameCounters, consumers));
    }
    //添加消费组
    if (rpcProperties.getGroups() != null) {
        rpcProperties.getGroups().forEach(c -> addConfig(c, CONSUMER_PREFIX, consumerNameCounters, groups));
    }
    //添加服务提供者
    if (rpcProperties.getProviders() != null) {
        rpcProperties.getProviders().forEach(c -> addConfig(c, PROVIDER_PREFIX, providerNameCounters, providers));
    }
}
 
Example #12
Source File: PropertiesUtil.java    From liiklus with MIT License 6 votes vote down vote up
public static <T> T bind(ConfigurableEnvironment environment, @NonNull T properties) {
    var configurationProperties = AnnotationUtils.findAnnotation(properties.getClass(), ConfigurationProperties.class);

    if (configurationProperties == null) {
        throw new IllegalArgumentException(properties.getClass() + " Must be annotated with @ConfigurationProperties");
    }

    var property = configurationProperties.prefix();

    var validationBindHandler = new ValidationBindHandler(
            new SpringValidatorAdapter(Validation.buildDefaultValidatorFactory().getValidator())
    );

    var bindable = Bindable.ofInstance(properties);
    return Binder.get(environment).bind(property, bindable, validationBindHandler).orElseGet(bindable.getValue());
}
 
Example #13
Source File: SpacedLogbackSystem.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
protected LoggingProperties parseProperties(ConfigurableEnvironment environment) {
    LoggingProperties properties = Binder.get(environment)
            .bind(LoggingProperties.PREFIX, LoggingProperties.class)
            .orElseGet(LoggingProperties::new);

    if (isSet(environment, "trace")) {
        logger.info("debug mode, set default threshold to trace");
        properties.getDefaultSpec().setThreshold("trace");
    } else if (isSet(environment, "debug")) {
        logger.info("debug mode, set default threshold to debug");
        properties.getDefaultSpec().setThreshold("debug");
    } else {
        properties.getDefaultSpec().setThreshold("info");
    }

    return properties;
}
 
Example #14
Source File: VersionsFetcher.java    From spring-cloud-release-tools with Apache License 2.0 6 votes vote down vote up
InitializrProperties toProperties(String url) {
	return CACHE.computeIfAbsent(url, s -> {
		String retrievedFile = this.rawGithubRetriever.raw(s);
		if (StringUtils.isEmpty(retrievedFile)) {
			return null;
		}
		YamlPropertiesFactoryBean yamlProcessor = new YamlPropertiesFactoryBean();
		yamlProcessor.setResources(new InputStreamResource(new ByteArrayInputStream(
				retrievedFile.getBytes(StandardCharsets.UTF_8))));
		Properties properties = yamlProcessor.getObject();
		return new Binder(
				new MapConfigurationPropertySource(properties.entrySet().stream()
						.collect(Collectors.toMap(e -> e.getKey().toString(),
								e -> e.getValue().toString()))))
										.bind("initializr",
												InitializrProperties.class)
										.get();
	});
}
 
Example #15
Source File: ConfigurationService.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
static <T> T bindOrCreate(Bindable<T> bindable,
		Map<String, Object> properties, String configurationPropertyName,
		Validator validator, ConversionService conversionService) {
	// see ConfigurationPropertiesBinder from spring boot for this definition.
	BindHandler handler = new IgnoreTopLevelConverterNotFoundBindHandler();

	if (validator != null) { // TODO: list of validators?
		handler = new ValidationBindHandler(handler, validator);
	}

	List<ConfigurationPropertySource> propertySources = Collections
			.singletonList(new MapConfigurationPropertySource(properties));

	return new Binder(propertySources, null, conversionService)
			.bindOrCreate(configurationPropertyName, bindable, handler);
}
 
Example #16
Source File: BinderDubboConfigBinder.java    From dubbo-spring-boot-project with Apache License 2.0 6 votes vote down vote up
@Override
public void bind(Map<String, Object> configurationProperties, boolean ignoreUnknownFields,
                 boolean ignoreInvalidFields, Object configurationBean) {

    Iterable<PropertySource<?>> propertySources = asList(new MapPropertySource("internal", configurationProperties));

    // Converts ConfigurationPropertySources
    Iterable<ConfigurationPropertySource> configurationPropertySources = from(propertySources);

    // Wrap Bindable from DubboConfig instance
    Bindable bindable = Bindable.ofInstance(configurationBean);

    Binder binder = new Binder(configurationPropertySources, new PropertySourcesPlaceholdersResolver(propertySources));

    // Get BindHandler
    BindHandler bindHandler = getBindHandler(ignoreUnknownFields, ignoreInvalidFields);

    // Bind
    binder.bind("", bindable, bindHandler);
}
 
Example #17
Source File: OSSCondition.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
	String sourceClass = "";
	if (metadata instanceof ClassMetadata) {
		sourceClass = ((ClassMetadata) metadata).getClassName();
	}
	ConditionMessage.Builder message = ConditionMessage.forCondition("OSS", sourceClass);
	Environment environment = context.getEnvironment();
	try {
		BindResult<OSSType> specified = Binder.get(environment).bind("oss.type", OSSType.class);
		if (!specified.isBound()) {
			return ConditionOutcome.match(message.because("automatic OSS type"));
		}
		OSSType required = OSSConfigurations.getType(((AnnotationMetadata) metadata).getClassName());
		if (specified.get() == required) {
			return ConditionOutcome.match(message.because(specified.get() + " OSS type"));
		}
	}
	catch (BindException ex) {
	}
	return ConditionOutcome.noMatch(message.because("unknown OSS type"));
}
 
Example #18
Source File: PrefixPropertyCondition.java    From loc-framework with MIT License 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
    AnnotatedTypeMetadata metadata) {
  String prefix = (String) attribute(metadata, "prefix");
  Class<?> value = (Class<?>) attribute(metadata, "value");
  ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
  try {
    new Binder(ConfigurationPropertySources.from(environment.getPropertySources()))
        .bind(prefix, Bindable.of(value))
        .orElseThrow(
            () -> new FatalBeanException("Could not bind DataSourceSettings properties"));
    return new ConditionOutcome(true, String.format("Map property [%s] is not empty", prefix));
  } catch (Exception e) {
    //ignore
  }
  return new ConditionOutcome(false, String.format("Map property [%s] is empty", prefix));
}
 
Example #19
Source File: SpringdocBeanFactoryConfigurer.java    From springdoc-openapi with Apache License 2.0 6 votes vote down vote up
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)  {
	final BindResult<SpringDocConfigProperties> result = Binder.get(environment)
			.bind(SPRINGDOC_PREFIX, SpringDocConfigProperties.class);
	if (result.isBound()) {
		SpringDocConfigProperties springDocGroupConfig = result.get();
		List<GroupedOpenApi> groupedOpenApis = springDocGroupConfig.getGroupConfigs().stream()
				.map(elt -> {
					GroupedOpenApi.Builder builder = GroupedOpenApi.builder();
					if (!CollectionUtils.isEmpty(elt.getPackagesToScan()))
						builder.packagesToScan(elt.getPackagesToScan().toArray(new String[0]));
					if (!CollectionUtils.isEmpty(elt.getPathsToMatch()))
						builder.pathsToMatch(elt.getPathsToMatch().toArray(new String[0]));
					return builder.group(elt.getGroup()).build();
				})
				.collect(Collectors.toList());
		groupedOpenApis.forEach(elt -> beanFactory.registerSingleton(elt.getGroup(), elt));
	}
	initBeanFactoryPostProcessor(beanFactory);
}
 
Example #20
Source File: PropertySourceBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private void reinitializeLoggingSystem(ConfigurableEnvironment environment,
		String oldLogConfig, LogFile oldLogFile) {
	Map<String, Object> props = Binder.get(environment)
			.bind("logging", Bindable.mapOf(String.class, Object.class))
			.orElseGet(Collections::emptyMap);
	if (!props.isEmpty()) {
		String logConfig = environment.resolvePlaceholders("${logging.config:}");
		LogFile logFile = LogFile.get(environment);
		LoggingSystem system = LoggingSystem
				.get(LoggingSystem.class.getClassLoader());
		try {
			ResourceUtils.getURL(logConfig).openStream().close();
			// Three step initialization that accounts for the clean up of the logging
			// context before initialization. Spring Boot doesn't initialize a logging
			// system that hasn't had this sequence applied (since 1.4.1).
			system.cleanUp();
			system.beforeInitialize();
			system.initialize(new LoggingInitializationContext(environment),
					logConfig, logFile);
		}
		catch (Exception ex) {
			PropertySourceBootstrapConfiguration.logger
					.warn("Error opening logging config file " + logConfig, ex);
		}
	}
}
 
Example #21
Source File: CloudFoundryApplicationPropertiesTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void bind() {
	String vcap = "{\"application_users\":[]," + "\"application_id\":\"9958288f-9842-4ddc-93dd-1ea3c90634cd\","
			+ "\"instance_id\":\"bb7935245adf3e650dfb7c58a06e9ece\","
			+ "\"instance_index\":0,\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\","
			+ "\"name\":\"foo\",\"uris\":[\"foo.cfapps.io\"]," + "\"started_at\":\"2013-05-29 02:37:59 +0000\","
			+ "\"started_at_timestamp\":1369795079," + "\"host\":\"0.0.0.0\",\"port\":61034,"
			+ "\"limits\":{\"mem\":128,\"disk\":1024,\"fds\":16384},"
			+ "\"version\":\"3464e092-1c13-462e-a47c-807c30318a50\","
			+ "\"name\":\"dsyerenv\",\"uris\":[\"dsyerenv.cfapps.io\"],"
			+ "\"users\":[],\"start\":\"2013-05-29 02:37:59 +0000\"," + "\"state_timestamp\":1369795079}";

	MockEnvironment env = new MockEnvironment();
	env.setProperty("VCAP_APPLICATION", vcap);
	new CloudFoundryVcapEnvironmentPostProcessor().postProcessEnvironment(env, null);

	CloudFoundryApplicationProperties cfProperties = Binder.get(env)
			.bind("vcap.application", Bindable.of(CloudFoundryApplicationProperties.class)).get();
	assertThat(cfProperties.getApplicationId()).isEqualTo("9958288f-9842-4ddc-93dd-1ea3c90634cd");
	assertThat(cfProperties.getInstanceIndex()).isEqualTo("0");
}
 
Example #22
Source File: DeploymentPropertiesResolver.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 6 votes vote down vote up
/**
 * Binds the YAML formatted value of a deployment property to a {@link KubernetesDeployerProperties} instance.
 *
 * @param kubernetesDeployerProperties the map of Kubernetes deployer properties
 * @param propertyKey the property key to obtain the value to bind for
 * @param yamlLabel the label representing the field to bind to
 * @return a {@link KubernetesDeployerProperties} with the bound property data
 */
private static KubernetesDeployerProperties bindProperties(Map<String, String> kubernetesDeployerProperties,
		String propertyKey, String yamlLabel) {
	String deploymentPropertyValue = kubernetesDeployerProperties.getOrDefault(propertyKey, "");

	KubernetesDeployerProperties deployerProperties = new KubernetesDeployerProperties();

	if (!StringUtils.isEmpty(deploymentPropertyValue)) {
		try {
			YamlPropertiesFactoryBean properties = new YamlPropertiesFactoryBean();
			String tmpYaml = "{ " + yamlLabel + ": " + deploymentPropertyValue + " }";
			properties.setResources(new ByteArrayResource(tmpYaml.getBytes()));
			Properties yaml = properties.getObject();
			MapConfigurationPropertySource source = new MapConfigurationPropertySource(yaml);
			deployerProperties = new Binder(source)
					.bind("", Bindable.of(KubernetesDeployerProperties.class)).get();
		} catch (Exception e) {
			throw new IllegalArgumentException(
					String.format("Invalid binding property '%s'", deploymentPropertyValue), e);
		}
	}

	return deployerProperties;
}
 
Example #23
Source File: DependenciesPassedCondition.java    From spring-cloud-zookeeper with Apache License 2.0 6 votes vote down vote up
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context,
		AnnotatedTypeMetadata metadata) {
	Map<String, String> subProperties = Binder.get(context.getEnvironment())
			.bind(ZOOKEEPER_DEPENDENCIES_PROP, STRING_STRING_MAP)
			.orElseGet(Collections::emptyMap);
	if (!subProperties.isEmpty()) {
		return ConditionOutcome.match("Dependencies are defined in configuration");
	}
	Boolean dependenciesEnabled = context.getEnvironment().getProperty(
			"spring.cloud.zookeeper.dependency.enabled", Boolean.class, false);
	if (dependenciesEnabled) {
		return ConditionOutcome.match(
				"Dependencies are not defined in configuration, but switch is turned on");
	}
	return ConditionOutcome
			.noMatch("No dependencies have been passed for the service");
}
 
Example #24
Source File: JavaCommandBuilder.java    From spring-cloud-deployer-local with Apache License 2.0 5 votes vote down vote up
/**
 * This will merge the deployment properties that were passed in at runtime with the deployment properties
 * of the Deployer instance.
 * @param runtimeDeploymentProperties deployment properties passed in at runtime
 * @return merged deployer properties
 */
protected LocalDeployerProperties bindDeploymentProperties(Map<String, String> runtimeDeploymentProperties) {
	LocalDeployerProperties copyOfDefaultProperties = new LocalDeployerProperties();
	BeanUtils.copyProperties(this.properties, copyOfDefaultProperties );
	return new Binder(new MapConfigurationPropertySource(runtimeDeploymentProperties))
			.bind(LocalDeployerProperties.PREFIX, Bindable.ofInstance(copyOfDefaultProperties))
			.orElse(copyOfDefaultProperties);
}
 
Example #25
Source File: ConfigureAgentStage.java    From genie with Apache License 2.0 5 votes vote down vote up
@Override
protected void attemptStageAction(
    final ExecutionContext executionContext
) throws RetryableJobExecutionException, FatalJobExecutionException {

    final AgentClientMetadata agentClientMetadata = executionContext.getAgentClientMetadata();
    final AgentProperties agentProperties = executionContext.getAgentProperties();

    // Obtain server-provided properties
    final Map<String, String> serverPropertiesMap;
    try {
        serverPropertiesMap = this.agentJobService.configure(agentClientMetadata);
    } catch (ConfigureException e) {
        throw new RetryableJobExecutionException("Failed to obtain configuration", e);
    }

    for (final Map.Entry<String, String> entry : serverPropertiesMap.entrySet()) {
        log.info("Received property {}={}", entry.getKey(), entry.getValue());
    }

    // Bind properties received
    final ConfigurationPropertySource serverPropertiesSource =
        new MapConfigurationPropertySource(serverPropertiesMap);

    new Binder(serverPropertiesSource)
        .bind(
            AgentProperties.PREFIX,
            Bindable.ofInstance(agentProperties)
        );
}
 
Example #26
Source File: RefreshAutoConfiguration.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private void bindEnvironmentIfNeeded(BeanDefinitionRegistry registry) {
	if (!this.bound) { // only bind once
		if (this.environment == null) {
			this.environment = new StandardEnvironment();
		}
		Binder.get(this.environment).bind("spring.cloud.refresh",
				Bindable.ofInstance(this));
		this.bound = true;
	}
}
 
Example #27
Source File: RiptidePostProcessor.java    From riptide with MIT License 5 votes vote down vote up
@Override
public void setEnvironment(final Environment environment) {
    final Iterable<ConfigurationPropertySource> sources =
            from(((ConfigurableEnvironment) environment).getPropertySources());
    final Binder binder = new Binder(sources,
            new PropertySourcesPlaceholdersResolver(environment));

    this.properties = Defaulting.withDefaults(binder.bindOrCreate("riptide", RiptideProperties.class));
}
 
Example #28
Source File: InitializrAutoConfiguration.java    From initializr with Apache License 2.0 5 votes vote down vote up
private Cache determineCache(Environment environment, CacheManager cacheManager) {
	if (cacheManager != null) {
		Binder binder = Binder.get(environment);
		boolean cache = binder.bind("spring.mustache.cache", Boolean.class).orElse(true);
		if (cache) {
			return cacheManager.getCache("initializr.templates");
		}
	}
	return new NoOpCache("templates");
}
 
Example #29
Source File: KafkaStreamsBinderSupportAutoConfiguration.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
@Bean
@ConfigurationProperties(prefix = "spring.cloud.stream.kafka.streams.binder")
public KafkaStreamsBinderConfigurationProperties binderConfigurationProperties(
		KafkaProperties kafkaProperties, ConfigurableEnvironment environment,
		BindingServiceProperties properties, ConfigurableApplicationContext context) throws Exception {
	final Map<String, BinderConfiguration> binderConfigurations = getBinderConfigurations(
			properties);
	for (Map.Entry<String, BinderConfiguration> entry : binderConfigurations
			.entrySet()) {
		final BinderConfiguration binderConfiguration = entry.getValue();
		final String binderType = binderConfiguration.getBinderType();
		if (binderType != null && (binderType.equals(KSTREAM_BINDER_TYPE)
				|| binderType.equals(KTABLE_BINDER_TYPE)
				|| binderType.equals(GLOBALKTABLE_BINDER_TYPE))) {
			Map<String, Object> binderProperties = new HashMap<>();
			this.flatten(null, binderConfiguration.getProperties(), binderProperties);
			environment.getPropertySources().addFirst(
					new MapPropertySource(entry.getKey() + "-kafkaStreamsBinderEnv", binderProperties));

			Binder binder = new Binder(ConfigurationPropertySources.get(environment),
					new PropertySourcesPlaceholdersResolver(environment),
					IntegrationUtils.getConversionService(context.getBeanFactory()), null);
			final Constructor<KafkaStreamsBinderConfigurationProperties> kafkaStreamsBinderConfigurationPropertiesConstructor =
					ReflectionUtils.accessibleConstructor(KafkaStreamsBinderConfigurationProperties.class, KafkaProperties.class);
			final KafkaStreamsBinderConfigurationProperties kafkaStreamsBinderConfigurationProperties =
					BeanUtils.instantiateClass(kafkaStreamsBinderConfigurationPropertiesConstructor, kafkaProperties);
			final BindResult<KafkaStreamsBinderConfigurationProperties> bind = binder.bind("spring.cloud.stream.kafka.streams.binder", Bindable.ofInstance(kafkaStreamsBinderConfigurationProperties));
			context.getBeanFactory().registerSingleton(
					entry.getKey() + "-KafkaStreamsBinderConfigurationProperties",
					bind.get());
		}
	}
	return new KafkaStreamsBinderConfigurationProperties(kafkaProperties);
}
 
Example #30
Source File: KubernetesAppDeployerTests.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 5 votes vote down vote up
private KubernetesDeployerProperties bindDeployerProperties() throws Exception {
	YamlPropertiesFactoryBean properties = new YamlPropertiesFactoryBean();
	properties.setResources(new ClassPathResource("dataflow-server.yml"),
			new ClassPathResource("dataflow-server-tolerations.yml"),
			new ClassPathResource("dataflow-server-secretKeyRef.yml"),
			new ClassPathResource("dataflow-server-configMapKeyRef.yml"),
			new ClassPathResource("dataflow-server-podsecuritycontext.yml"),
			new ClassPathResource("dataflow-server-nodeAffinity.yml"),
			new ClassPathResource("dataflow-server-podAffinity.yml"),
			new ClassPathResource("dataflow-server-podAntiAffinity.yml"));
	Properties yaml = properties.getObject();
	MapConfigurationPropertySource source = new MapConfigurationPropertySource(yaml);
	return new Binder(source).bind("", Bindable.of(KubernetesDeployerProperties.class)).get();
}