类org.springframework.boot.context.properties.source.MapConfigurationPropertySource源码实例Demo

下面列出了怎么用org.springframework.boot.context.properties.source.MapConfigurationPropertySource的API类实例代码及写法,或者点击链接到github查看源代码。

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();
	});
}
 
/**
 * 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;
}
 
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);
}
 
@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);
  }
}
 
@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);
  }
}
 
源代码6 项目: synopsys-detect   文件: DetectCustomFieldParser.java
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);
    }
}
 
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);
    }
 
源代码8 项目: teiid-spring-boot   文件: XADataSourceBuilder.java
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);
}
 
/**
 * 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;
}
 
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();
}
 
/**
 * 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);
}
 
/**
 * 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);
}
 
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;
}
 
源代码14 项目: spring-cloud-stream   文件: BindingServiceTests.java
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;
}
 
源代码15 项目: ByteJTA   文件: DataSourceSpiBuilder.java
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));
}
 
源代码16 项目: genie   文件: ConfigureAgentStage.java
@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)
        );
}
 
源代码17 项目: Milkomeda   文件: DataSourceFactory.java
@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));
}
 
private CloudFoundryDeploymentProperties bindDeployerProperties(Map<String,String> env) {
	MapConfigurationPropertySource source = new MapConfigurationPropertySource(env);
	return new Binder(source).bind("", Bindable.of(CloudFoundryDeploymentProperties.class)).get();
}
 
源代码19 项目: ByteJTA   文件: DataSourceCciBuilder.java
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));
}
 
private static InitializrProperties load(Resource resource) {
	ConfigurationPropertySource source = new MapConfigurationPropertySource(loadProperties(resource));
	Binder binder = new Binder(source);
	return binder.bind("initializr", InitializrProperties.class).get();
}
 
 类所在包
 同包方法