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

The following examples show how to use org.springframework.boot.context.properties.bind.Bindable. 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: 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 #2
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 #3
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 #4
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 #5
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 #6
Source File: BindingHandlerAdvise.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Override
public BindHandler apply(BindHandler bindHandler) {


	BindHandler handler = new AbstractBindHandler(bindHandler) {
		@Override
		public <T> Bindable<T> onStart(ConfigurationPropertyName name,
				Bindable<T> target, BindContext context) {
			ConfigurationPropertyName defaultName = getDefaultName(name);
			if (defaultName != null) {
				BindResult<T> result = context.getBinder().bind(defaultName, target);
				if (result.isBound()) {
					return target.withExistingValue(result.get());
				}
			}
			return bindHandler.onStart(name, target, context);
		}
	};
	return handler;
}
 
Example #7
Source File: JasyptEncryptorConfigurationProperties.java    From jasypt-spring-boot with MIT License 6 votes vote down vote up
public static JasyptEncryptorConfigurationProperties bindConfigProps(ConfigurableEnvironment environment) {
    final BindHandler handler = new IgnoreErrorsBindHandler(BindHandler.DEFAULT);
    final MutablePropertySources propertySources = environment.getPropertySources();
    final Binder binder = new Binder(ConfigurationPropertySources.from(propertySources),
            new PropertySourcesPlaceholdersResolver(propertySources),
            ApplicationConversionService.getSharedInstance());
    final JasyptEncryptorConfigurationProperties config = new JasyptEncryptorConfigurationProperties();

    final ResolvableType type = ResolvableType.forClass(JasyptEncryptorConfigurationProperties.class);
    final Annotation annotation = AnnotationUtils.findAnnotation(JasyptEncryptorConfigurationProperties.class,
            ConfigurationProperties.class);
    final Annotation[] annotations = new Annotation[]{annotation};
    final Bindable<?> target = Bindable.of(type).withExistingValue(config).withAnnotations(annotations);

    binder.bind("jasypt.encryptor", target, handler);
    return config;
}
 
Example #8
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 #9
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 #10
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 #11
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 #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: 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 #14
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 #15
Source File: EncodingDecodingBindAdviceHandler.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public BindHandler apply(BindHandler bindHandler) {
	BindHandler handler = new AbstractBindHandler(bindHandler) {
		@Override
		public <T> Bindable<T> onStart(ConfigurationPropertyName name,
									Bindable<T> target, BindContext context) {
			final String configName = name.toString();
			if (configName.contains("use") && configName.contains("native") &&
					(configName.contains("encoding") || configName.contains("decoding"))) {
				BindResult<T> result = context.getBinder().bind(name, target);
				if (result.isBound()) {
					if (configName.contains("encoding")) {
						EncodingDecodingBindAdviceHandler.this.encodingSettingProvided = true;
					}
					else {
						EncodingDecodingBindAdviceHandler.this.decodingSettingProvided = true;
					}
					return target.withExistingValue(result.get());
				}
			}
			return bindHandler.onStart(name, target, context);
		}
	};
	return handler;
}
 
Example #16
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 #17
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 #18
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 #19
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 #20
Source File: Front50PluginsConfiguration.java    From kork with Apache License 2.0 5 votes vote down vote up
@Bean
public static PluginOkHttpClientProvider pluginsOkHttpClient(Environment environment) {
  OkHttpClientConfigurationProperties okHttpClientProperties =
      Binder.get(environment)
          .bind("ok-http-client", Bindable.of(OkHttpClientConfigurationProperties.class))
          .orElse(new OkHttpClientConfigurationProperties());

  OkHttpClient okHttpClient =
      new OkHttp3ClientConfiguration(okHttpClientProperties)
          .create()
          .retryOnConnectionFailure(okHttpClientProperties.isRetryOnConnectionFailure())
          .build();

  return new PluginOkHttpClientProvider(okHttpClient);
}
 
Example #21
Source File: HttpClientSdkConfiguration.java    From kork with Apache License 2.0 5 votes vote down vote up
@Bean
public static SdkFactory httpClientSdkFactory(
    List<OkHttp3ClientFactory> okHttpClientFactories,
    Environment environment,
    Provider<Registry> registry) {

  OkHttpClientConfigurationProperties okHttpClientProperties =
      Binder.get(environment)
          .bind("ok-http-client", Bindable.of(OkHttpClientConfigurationProperties.class))
          .orElse(new OkHttpClientConfigurationProperties());

  OkHttpMetricsInterceptorProperties okHttpMetricsInterceptorProperties =
      Binder.get(environment)
          .bind(
              "ok-http-client.interceptor", Bindable.of(OkHttpMetricsInterceptorProperties.class))
          .orElse(new OkHttpMetricsInterceptorProperties());

  List<OkHttp3ClientFactory> factories = new ArrayList<>(okHttpClientFactories);
  OkHttp3MetricsInterceptor okHttp3MetricsInterceptor =
      new OkHttp3MetricsInterceptor(registry, okHttpMetricsInterceptorProperties.skipHeaderCheck);
  factories.add(new DefaultOkHttp3ClientFactory(okHttp3MetricsInterceptor));

  OkHttp3ClientConfiguration config =
      new OkHttp3ClientConfiguration(okHttpClientProperties, okHttp3MetricsInterceptor);

  // TODO(rz): It'd be nice to make this customizable, but I'm not sure how to do that without
  //  bringing Jackson into the Plugin SDK (quite undesirable).
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.registerModule(new Jdk8Module());
  objectMapper.registerModule(new JavaTimeModule());
  objectMapper.registerModule(new KotlinModule());
  objectMapper.disable(READ_DATE_TIMESTAMPS_AS_NANOSECONDS);
  objectMapper.disable(WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS);
  objectMapper.disable(FAIL_ON_UNKNOWN_PROPERTIES);
  objectMapper.disable(FAIL_ON_EMPTY_BEANS);
  objectMapper.setSerializationInclusion(NON_NULL);

  return new HttpClientSdkFactory(
      new CompositeOkHttpClientFactory(factories), environment, objectMapper, config);
}
 
Example #22
Source File: AmazonRdsDatabaseAutoConfiguration.java    From spring-cloud-aws with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Map<String, String>> getDbInstanceConfigurations() {
	Map<String, Object> subProperties = Binder.get(this.environment)
			.bind(PREFIX, Bindable.mapOf(String.class, Object.class))
			.orElseGet(Collections::emptyMap);
	Map<String, Map<String, String>> dbConfigurationMap = new HashMap<>(
			subProperties.keySet().size());
	for (Map.Entry<String, Object> subProperty : subProperties.entrySet()) {
		String instanceName = subProperty.getKey();
		if (!dbConfigurationMap.containsKey(instanceName)) {
			dbConfigurationMap.put(instanceName, new HashMap<>());
		}

		Object value = subProperty.getValue();

		if (value instanceof Map) {
			Map<String, String> map = (Map) value;
			for (Map.Entry<String, String> entry : map.entrySet()) {
				dbConfigurationMap.get(instanceName).put(entry.getKey(),
						entry.getValue());
			}
		}
		else if (value instanceof String) {
			String subPropertyName = extractConfigurationSubPropertyName(
					subProperty.getKey());
			if (StringUtils.hasText(subPropertyName)) {
				dbConfigurationMap.get(instanceName).put(subPropertyName,
						(String) subProperty.getValue());
			}
		}
	}
	return dbConfigurationMap;
}
 
Example #23
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 #24
Source File: HostInfoEnvironmentPostProcessor.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private HostInfo getFirstNonLoopbackHostInfo(ConfigurableEnvironment environment) {
	InetUtilsProperties target = new InetUtilsProperties();
	ConfigurationPropertySources.attach(environment);
	Binder.get(environment).bind(InetUtilsProperties.PREFIX,
			Bindable.ofInstance(target));
	try (InetUtils utils = new InetUtils(target)) {
		return utils.findFirstNonLoopbackHostInfo();
	}
}
 
Example #25
Source File: ConfigurationServiceTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void createWorks() {
	Map<String, Object> map = Collections.singletonMap("config.value", 9);

	ValidatedConfig config = ConfigurationService.bindOrCreate(
			Bindable.of(ValidatedConfig.class), map, "config", getValidator(), null);

	assertThat(config).isNotNull().extracting(ValidatedConfig::getValue).isEqualTo(9);
}
 
Example #26
Source File: ConfigurationService.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Override
protected T doBind() {
	Bindable<T> bindable = Bindable.of(this.configurable.getConfigClass());
	T bound = bindOrCreate(bindable, this.normalizedProperties,
			this.configurable.shortcutFieldPrefix(),
			/* this.name, */this.service.validator.get(),
			this.service.conversionService.get());

	return bound;
}
 
Example #27
Source File: ConfigurationServiceTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void validationOnBindWorks() {
	thrown.expect(BindException.class);

	Map<String, Object> map = Collections.singletonMap("config.value", 11);

	ValidatedConfig config = new ValidatedConfig();
	ConfigurationService.bindOrCreate(Bindable.ofInstance(config), map, "config",
			getValidator(), null);
}
 
Example #28
Source File: ConfigurationServiceTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@Test
public void bindWorks() {
	Map<String, Object> map = Collections.singletonMap("config.value", 9);

	ValidatedConfig config = new ValidatedConfig();
	ConfigurationService.bindOrCreate(Bindable.ofInstance(config), map, "config",
			getValidator(), null);

	assertThat(config).isNotNull().extracting(ValidatedConfig::getValue).isEqualTo(9);
}
 
Example #29
Source File: AbstractLocalDeployerSupport.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.localDeployerProperties, copyOfDefaultProperties);
	return new Binder(new MapConfigurationPropertySource(runtimeDeploymentProperties))
			.bind(LocalDeployerProperties.PREFIX, Bindable.ofInstance(copyOfDefaultProperties))
			.orElse(copyOfDefaultProperties);
}
 
Example #30
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);
}