类org.springframework.beans.factory.config.YamlPropertiesFactoryBean源码实例Demo

下面列出了怎么用org.springframework.beans.factory.config.YamlPropertiesFactoryBean的API类实例代码及写法,或者点击链接到github查看源代码。

protected Properties generateProperties(String value,
                                        Format format) {
    final Properties props = new Properties();

    if (format == Format.PROPERTIES) {
        try {
            // Must use the ISO-8859-1 encoding because Properties.load(stream)
            // expects it.
            props.load(new ByteArrayInputStream(value.getBytes(StandardCharsets.ISO_8859_1)));
        } catch (IOException e) {
            logger.error("Can't be encoded with exception: ", e);
            throw new IllegalArgumentException(
                    value + " can't be encoded using ISO-8859-1");
        }
        return props;
    } else if (format == Format.YAML) {
        final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ByteArrayResource(value.getBytes(StandardCharsets.UTF_8)));
        return yaml.getObject();
    } else {
        return props;
    }
}
 
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();
	});
}
 
源代码3 项目: apollo   文件: ItemController.java
private void doSyntaxCheck(NamespaceTextModel model) {
  if (StringUtils.isBlank(model.getConfigText())) {
    return;
  }

  // only support yaml syntax check
  if (model.getFormat() != ConfigFileFormat.YAML && model.getFormat() != ConfigFileFormat.YML) {
    return;
  }

  // use YamlPropertiesFactoryBean to check the yaml syntax
  YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
  yamlPropertiesFactoryBean.setResources(new ByteArrayResource(model.getConfigText().getBytes()));
  // this call converts yaml to properties and will throw exception if the conversion fails
  yamlPropertiesFactoryBean.getObject();
}
 
static Function<String, Properties> yamlParserGenerator(Environment environment) {
	return s -> {
		YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
		yamlFactory.setDocumentMatchers(properties -> {
			String profiles = properties.getProperty("spring.profiles");
			if (environment != null && StringUtils.hasText(profiles)) {
				return environment.acceptsProfiles(Profiles.of(profiles)) ? FOUND
						: NOT_FOUND;
			}
			else {
				return ABSTAIN;
			}
		});
		yamlFactory.setResources(new ByteArrayResource(s.getBytes()));
		return yamlFactory.getObject();
	};
}
 
/**
 * 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;
}
 
@Bean(name = "graviteeProperties")
public static Properties graviteeProperties() throws IOException {
    LOGGER.info("Loading Gravitee Management configuration.");

    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

    String yamlConfiguration = System.getProperty(GRAVITEE_CONFIGURATION);
    Resource yamlResource = new FileSystemResource(yamlConfiguration);

    LOGGER.info("\tGravitee Management configuration loaded from {}", yamlResource.getURL().getPath());

    yaml.setResources(yamlResource);
    Properties properties = yaml.getObject();
    LOGGER.info("Loading Gravitee Management configuration. DONE");

    return properties;
}
 
@Bean(name = "graviteeProperties")
public static Properties graviteeProperties() throws IOException {
    LOGGER.info("Loading Gravitee Management configuration.");

    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();

    String yamlConfiguration = System.getProperty(GRAVITEE_CONFIGURATION);
    Resource yamlResource = new FileSystemResource(yamlConfiguration);

    LOGGER.info("\tGravitee Management configuration loaded from {}", yamlResource.getURL().getPath());

    yaml.setResources(yamlResource);
    Properties properties = yaml.getObject();
    LOGGER.info("Loading Gravitee Management configuration. DONE");

    return properties;
}
 
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
    yamlPropertiesFactoryBean.setResources(resource.getResource());
    Properties yamlProperties = yamlPropertiesFactoryBean.getObject();
    return new PropertiesPropertySource(name, yamlProperties);
}
 
源代码9 项目: mutual-tls-ssl   文件: PropertyResolver.java
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
    PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource(CLIENT_PROPERTY_FILE));
    propertySourcesPlaceholderConfigurer.setProperties(Objects.requireNonNull(yaml.getObject()));
    return propertySourcesPlaceholderConfigurer;
}
 
源代码10 项目: mutual-tls-ssl   文件: PropertyResolverShould.java
@Test
@SuppressWarnings("AccessStaticViaInstance")
public void loadProperties() {
    LogCaptor<YamlPropertiesFactoryBean> logCaptor = LogCaptor.forClass(YamlPropertiesFactoryBean.class);
    PropertySourcesPlaceholderConfigurer properties = new PropertyResolver().properties();

    assertThat(properties).isNotNull();

    List<String> debugLogs = logCaptor.getDebugLogs();

    assertThat(debugLogs).hasSize(3);
    assertThat(debugLogs.get(0)).isEqualTo("Loading from YAML: class path resource [application.yml]");
    assertThat(debugLogs.get(1)).containsSubsequence("Merging document (no matchers set): {spring={main={banner-mode=off, web-application-type=none}}, ");
    assertThat(debugLogs.get(2)).isEqualTo("Loaded 1 document from YAML resource: class path resource [application.yml]");
}
 
源代码11 项目: super-cloudops   文件: PropertySources.java
@Override
public Map<String, Object> resolve(String content) {
	YamlPropertiesFactoryBean ymlFb = new YamlPropertiesFactoryBean();

	ymlFb.setResources(new ByteArrayResource(content.getBytes(Charsets.UTF_8)));
	ymlFb.afterPropertiesSet();
	// Properties to map
	Map<String, Object> map = new HashMap<>();
	if (ymlFb.getObject() != null) {
		ymlFb.getObject().forEach((k, v) -> map.put(String.valueOf(k), v));
	}
	return map;
}
 
private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
    try {
        final YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    } catch (IllegalStateException e) {
        // for ignoreResourceNotFound
        final Throwable cause = e.getCause();
        if (cause instanceof FileNotFoundException) {
            throw (FileNotFoundException) cause;
        }
        throw e;
    }
}
 
源代码13 项目: servicecomb-java-chassis   文件: KieUtil.java
public static Map<String, String> processValueType(KVDoc kvDoc) {
  ValueType valueType = parseValueType(kvDoc.getValueType());

  Properties properties = new Properties();
  Map<String, String> kvMap = new HashMap<>();
  try {
    if (valueType == (ValueType.YAML) || valueType == (ValueType.YML)) {
      YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
      yamlFactory.setResources(new ByteArrayResource(kvDoc.getValue().getBytes()));
      properties = yamlFactory.getObject();
    } else if (valueType == (ValueType.PROPERTIES)) {
      properties.load(new StringReader(kvDoc.getValue()));
    } else if (valueType == (ValueType.TEXT) || valueType == (ValueType.STRING)) {
      kvMap.put(kvDoc.getKey(), kvDoc.getValue());
      return kvMap;
    } else {
      // ValueType.JSON
      kvMap.put(kvDoc.getKey(), kvDoc.getValue());
      return kvMap;
    }
    kvMap = toMap(kvDoc.getKey(), properties);
    return kvMap;
  } catch (Exception e) {
    LOGGER.error("read config failed", e);
  }
  return Collections.emptyMap();
}
 
源代码14 项目: jeesuite-config   文件: CCPropertySourceLoader.java
private Properties loadProperties(String name, Resource resource) throws IOException{
	Properties properties = null;
	if(name.contains("properties")){
		properties = PropertiesLoaderUtils.loadProperties(resource);
	}else{
		YamlPropertiesFactoryBean bean = new YamlPropertiesFactoryBean();
		bean.setResources(resource);
		properties = bean.getObject();
	}
	return properties;
}
 
private static void contributeDefaults(Map<String, Object> defaults, Resource resource) {
	if (resource.exists()) {
		YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
		yamlPropertiesFactoryBean.setResources(resource);
		yamlPropertiesFactoryBean.afterPropertiesSet();
		Properties p = yamlPropertiesFactoryBean.getObject();
		for (Object k : p.keySet()) {
			String key = k.toString();
			defaults.put(key, p.get(key));
		}
	}
}
 
源代码16 项目: klask-io   文件: DefaultProfileUtil.java
/**
 * Load application.yml from classpath.
 */
private static Properties readProperties() {
    try {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(new ClassPathResource("config/application.yml"));
        return factory.getObject();
    } catch (Exception e) {
        log.error("Failed to read application.yml to get default profile");
    }
    return null;
}
 
源代码17 项目: apollo   文件: YamlParserTest.java
private void check(String yamlContent) {
  YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
  yamlPropertiesFactoryBean.setResources(new ByteArrayResource(yamlContent.getBytes()));
  Properties expected = yamlPropertiesFactoryBean.getObject();

  Properties actual = parser.yamlToProperties(yamlContent);

  assertTrue("expected: " + expected + " actual: " + actual, checkPropertiesEquals(expected, actual));
}
 
/**
 * 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();
}
 
源代码20 项目: OpenIoE   文件: DefaultProfileUtil.java
/**
 * Load application.yml from classpath.
 */
private static Properties readProperties() {
    try {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(new ClassPathResource("config/application.yml"));
        return factory.getObject();
    } catch (Exception e) {
        log.error("Failed to read application.yml to get default profile");
    }
    return null;
}
 
private static void contributeDefaults(Map<String, Object> defaults, Resource resource) {
	if (resource.exists()) {
		YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
		yamlPropertiesFactoryBean.setResources(resource);
		yamlPropertiesFactoryBean.afterPropertiesSet();
		Properties p = yamlPropertiesFactoryBean.getObject();
		for (Object k : p.keySet()) {
			String key = k.toString();
			defaults.put(key, p.get(key));
		}
	}
}
 
@Override
public Environment findOne(String application, String profile, String label) {
	String[] profiles = StringUtils.commaDelimitedListToStringArray(profile);
	List<String> scrubbedProfiles = scrubProfiles(profiles);

	List<String> keys = findKeys(application, scrubbedProfiles);

	Environment environment = new Environment(application, profiles, label, null,
			getWatchState());

	for (String key : keys) {
		// read raw 'data' key from vault
		String data = read(key);
		if (data != null) {
			// data is in json format of which, yaml is a superset, so parse
			final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
			yaml.setResources(new ByteArrayResource(data.getBytes()));
			Properties properties = yaml.getObject();

			if (!properties.isEmpty()) {
				environment.add(new PropertySource("vault:" + key, properties));
			}
		}
	}

	return environment;
}
 
@Override
public Properties read() {
	final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
	try (InputStream in = inputStream) {
		yaml.setResources(new InputStreamResource(in));
		return yaml.getObject();
	}
	catch (IOException e) {
		throw new IllegalStateException("Cannot load environment", e);
	}
}
 
源代码24 项目: spring-cloud-consul   文件: ConsulPropertySource.java
protected Properties generateProperties(String value,
		ConsulConfigProperties.Format format) {
	final Properties props = new Properties();

	if (format == PROPERTIES) {
		try {
			// Must use the ISO-8859-1 encoding because Properties.load(stream)
			// expects it.
			props.load(new ByteArrayInputStream(value.getBytes("ISO-8859-1")));
		}
		catch (IOException e) {
			throw new IllegalArgumentException(
					value + " can't be encoded using ISO-8859-1");
		}

		return props;
	}
	else if (format == YAML) {
		final YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
		yaml.setResources(
				new ByteArrayResource(value.getBytes(Charset.forName("UTF-8"))));

		return yaml.getObject();
	}

	return props;
}
 
源代码25 项目: tutorials   文件: YamlPropertySourceFactory.java
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) throws IOException {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(encodedResource.getResource());

    Properties properties = factory.getObject();

    return new PropertiesPropertySource(encodedResource.getResource().getFilename(), properties);
}
 
源代码26 项目: spring-cloud   文件: YamlPropertySourceFactory.java
private Properties loadYamlIntoProperties(EncodedResource resource) {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(resource.getResource());
    factory.afterPropertiesSet();
    return factory.getObject();
}
 
源代码27 项目: zuihou-admin-cloud   文件: NoBootTest.java
@Test
public void test2() {
    String data = "zuihou:\n" +
            "  swagger:\n" +
            "    enabled: true\n" +
            "    title: 网关模块\n" +
            "    base-package: com.github.zuihou.zuul.controller\n" +
            "\n" +
            "zuul:\n" +
            "  retryable: false\n" +
            "  servlet-path: /\n" +
            "  ignored-services: \"*\"\n" +
            "  sensitive-headers:\n" +
            "  ratelimit:\n" +
            "    key-prefix: gate_rate\n" +
            "    enabled: true\n" +
            "    repository: REDIS\n" +
            "    behind-proxy: true\n" +
            "    default-policy:\n" +
            "      cycle-type: 1\n" +
            "      limit: 10\n" +
            "      refresh-interval: 60\n" +
            "      type:\n" +
            "        - APP\n" +
            "        - URL\n" +
            "  routes:\n" +
            "    authority:\n" +
            "      path: /authority/**\n" +
            "      serviceId: zuihou-authority-server\n" +
            "    file:\n" +
            "      path: /file/**\n" +
            "      serviceId: zuihou-file-server\n" +
            "    msgs:\n" +
            "      path: /msgs/**\n" +
            "      serviceId: zuihou-msgs-server\n" +
            "    order:\n" +
            "      path: /order/**\n" +
            "      serviceId: zuihou-order-server\n" +
            "    demo:\n" +
            "      path: /demo/**\n" +
            "      serviceId: zuihou-demo-server\n" +
            "\n" +
            "authentication:\n" +
            "  user:\n" +
            "    header-name: token\n" +
            "    pub-key: client/pub.key";

    YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
    yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
    Properties object = yamlFactory.getObject();
    System.out.println(object);
}
 
源代码28 项目: Spring-Security-Third-Edition   文件: JavaConfig.java
@Bean
public static YamlPropertiesFactoryBean yamlPropertiesFactoryBean() {
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource("application.yml"));
    return yaml;
}
 
源代码29 项目: Spring-Security-Third-Edition   文件: JavaConfig.java
@Bean
public static YamlPropertiesFactoryBean yamlPropertiesFactoryBean() {
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource("application.yml"));
    return yaml;
}
 
源代码30 项目: Spring-Security-Third-Edition   文件: JavaConfig.java
@Bean
public static YamlPropertiesFactoryBean yamlPropertiesFactoryBean() {
    YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
    yaml.setResources(new ClassPathResource("application.yml"));
    return yaml;
}
 
 同包方法