Java Code Examples for org.springframework.boot.context.properties.source.MapConfigurationPropertySource

The following examples show how to use org.springframework.boot.context.properties.source.MapConfigurationPropertySource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
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 2
/**
 * 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 3
Source Project: spring-cloud-gateway   Source File: ConfigurationService.java    License: 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 4
@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 5
@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 6
Source Project: synopsys-detect   Source File: DetectCustomFieldParser.java    License: Apache License 2.0 5 votes vote down vote up
public CustomFieldDocument parseCustomFieldDocument(final Map<String, String> currentProperties) throws DetectUserFriendlyException {
    try {
        final ConfigurationPropertySource source = new MapConfigurationPropertySource(currentProperties);
        final Binder objectBinder = new Binder(source);
        final BindResult<CustomFieldDocument> fieldDocumentBinding = objectBinder.bind("detect.custom.fields", CustomFieldDocument.class);
        final CustomFieldDocument fieldDocument = fieldDocumentBinding.orElse(new CustomFieldDocument());
        fieldDocument.getProject().forEach(this::filterEmptyQuotes);
        fieldDocument.getVersion().forEach(this::filterEmptyQuotes);
        return fieldDocument;
    } catch (final Exception e) {
        throw new DetectUserFriendlyException("Unable to parse custom fields.", e, ExitCodeType.FAILURE_CONFIGURATION);
    }
}
 
Example 7
public static void main(String[] args) {

        MapConfigurationPropertySource propertySource = new MapConfigurationPropertySource();

        propertySource.put("userName", "Mercy");
        propertySource.put("user-id", 1);
        propertySource.put("user_id", 1);

        propertySource.stream().map(name -> name.getLastElement(ConfigurationPropertyName.Form.UNIFORM))
                .forEach(System.out::println);
    }
 
Example 8
Source Project: teiid-spring-boot   Source File: XADataSourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private void bindXaProperties(Bindable<XADataSource> target) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(
            this.properties);
    ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
    aliases.addAliases("url", "jdbc-url");
    aliases.addAliases("username", "user");
    aliases.addAliases("portNumber", "port");
    aliases.addAliases("serverName", "server");
    aliases.addAliases("databaseName", "database");

    Binder binder = new Binder(source.withAliases(aliases));
    binder.bind(ConfigurationPropertyName.EMPTY, target);
}
 
Example 9
/**
 * Volume mount deployment properties are specified in YAML format:
 * <p>
 * <code>
 * spring.cloud.deployer.kubernetes.volumeMounts=[{name: 'testhostpath', mountPath: '/test/hostPath'},
 * {name: 'testpvc', mountPath: '/test/pvc'}, {name: 'testnfs', mountPath: '/test/nfs'}]
 * </code>
 * <p>
 * Volume mounts can be specified as deployer properties as well as app deployment properties.
 * Deployment properties override deployer properties.
 *
 * @param deploymentProperties the deployment properties from {@link AppDeploymentRequest}
 * @return the configured volume mounts
 */
List<VolumeMount> getVolumeMounts(Map<String, String> deploymentProperties) {
	List<VolumeMount> volumeMounts = new ArrayList<>();
	String volumeMountDeploymentProperty = PropertyParserUtils.getDeploymentPropertyValue(deploymentProperties,
			this.propertyPrefix + ".volumeMounts");

	if (!StringUtils.isEmpty(volumeMountDeploymentProperty)) {
		try {
			YamlPropertiesFactoryBean properties = new YamlPropertiesFactoryBean();
			String tmpYaml = "{ volume-mounts: " + volumeMountDeploymentProperty + " }";
			properties.setResources(new ByteArrayResource(tmpYaml.getBytes()));
			Properties yaml = properties.getObject();
			MapConfigurationPropertySource source = new MapConfigurationPropertySource(yaml);
			KubernetesDeployerProperties deployerProperties = new Binder(source)
					.bind("", Bindable.of(KubernetesDeployerProperties.class)).get();
			volumeMounts.addAll(deployerProperties.getVolumeMounts());
		} catch (Exception e) {
			throw new IllegalArgumentException(
					String.format("Invalid volume mount '%s'", volumeMountDeploymentProperty), e);
		}
	}

	// only add volume mounts that have not already been added, based on the volume mount's name
	// i.e. allow provided deployment volume mounts to override deployer defined volume mounts
	volumeMounts.addAll(this.properties.getVolumeMounts().stream().filter(volumeMount -> volumeMounts.stream()
			.noneMatch(existingVolumeMount -> existingVolumeMount.getName().equals(volumeMount.getName())))
			.collect(Collectors.toList()));

	return volumeMounts;
}
 
Example 10
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();
}
 
Example 11
/**
 * 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 12
/**
 * 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 13
private ServiceBrokerProperties bindProperties() {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.map);
	Binder binder = new Binder(source);
	ServiceBrokerProperties serviceBrokerProperties = new ServiceBrokerProperties();
	binder.bind(PREFIX, Bindable.ofInstance(serviceBrokerProperties));
	return serviceBrokerProperties;
}
 
Example 14
Source Project: spring-cloud-stream   Source File: BindingServiceTests.java    License: Apache License 2.0 5 votes vote down vote up
private BindingServiceProperties createBindingServiceProperties(
		HashMap<String, String> properties) {
	BindingServiceProperties bindingServiceProperties = new BindingServiceProperties();
	org.springframework.boot.context.properties.bind.Binder propertiesBinder;
	propertiesBinder = new org.springframework.boot.context.properties.bind.Binder(
			new MapConfigurationPropertySource(properties));
	propertiesBinder.bind("spring.cloud.stream",
			org.springframework.boot.context.properties.bind.Bindable
					.ofInstance(bindingServiceProperties));
	return bindingServiceProperties;
}
 
Example 15
private void bind(XADataSource result) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
	ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
	aliases.addAliases("url", "jdbc-url");
	aliases.addAliases("username", "user");
	Binder binder = new Binder(source.withAliases(aliases));
	binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
 
Example 16
Source Project: genie   Source File: ConfigureAgentStage.java    License: 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 17
Source Project: Milkomeda   Source File: DataSourceFactory.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("rawtypes")
private void bind(DataSource result, Map properties) {
    ConfigurationPropertySource source = new MapConfigurationPropertySource(properties);
    Binder binder = new Binder(source.withAliases(ALIASES));
    binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(result));
}
 
Example 18
private CloudFoundryDeploymentProperties bindDeployerProperties(Map<String,String> env) {
	MapConfigurationPropertySource source = new MapConfigurationPropertySource(env);
	return new Binder(source).bind("", Bindable.of(CloudFoundryDeploymentProperties.class)).get();
}
 
Example 19
private void bind(DataSource dataSource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(this.properties);
	ConfigurationPropertyNameAliases aliases = new ConfigurationPropertyNameAliases();
	Binder binder = new Binder(source.withAliases(aliases));
	binder.bind(ConfigurationPropertyName.EMPTY, Bindable.ofInstance(dataSource));
}
 
Example 20
Source Project: initializr   Source File: InitializrMetadataBuilderTests.java    License: Apache License 2.0 4 votes vote down vote up
private static InitializrProperties load(Resource resource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(loadProperties(resource));
	Binder binder = new Binder(source);
	return binder.bind("initializr", InitializrProperties.class).get();
}