Java Code Examples for org.springframework.beans.factory.config.YamlPropertiesFactoryBean#getObject()

The following examples show how to use org.springframework.beans.factory.config.YamlPropertiesFactoryBean#getObject() . 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: PropertiesConfiguration.java    From gravitee-management-rest-api with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 2
Source File: PropertySourceUtils.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
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();
	};
}
 
Example 3
Source File: ItemController.java    From apollo with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 4
Source File: ConsulPropertySource.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 5
Source File: YamlParserTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 6
Source File: AbstractVaultEnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 7
Source File: DefaultEnvironmentPostProcessor.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
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));
		}
	}
}
 
Example 8
Source File: DefaultProfileUtil.java    From OpenIoE with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 9
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();
}
 
Example 10
Source File: AwsS3EnvironmentRepository.java    From spring-cloud-config with Apache License 2.0 5 votes vote down vote up
@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);
	}
}
 
Example 11
Source File: YamlPropertySourceFactory.java    From tutorials with MIT License 5 votes vote down vote up
@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);
}
 
Example 12
Source File: DefaultProfileUtil.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 13
Source File: DefaultEnvironmentPostProcessor.java    From spring-cloud-dashboard with Apache License 2.0 5 votes vote down vote up
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));
		}
	}
}
 
Example 14
Source File: KieUtil.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 15
Source File: YamlPropertySourceFactory.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
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;
    }
}
 
Example 16
Source File: PropertySources.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 17
Source File: NoBootTest.java    From zuihou-admin-cloud with Apache License 2.0 4 votes vote down vote up
@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);
}
 
Example 18
Source File: AwsIntegrationTestStackRule.java    From spring-cloud-stream-app-starters with Apache License 2.0 4 votes vote down vote up
@Override
protected void before() throws Throwable {
	try {
		String awsCredentialsDir = System.getProperty("aws.credentials.path");
		File awsCredentialsFile = new File(awsCredentialsDir, "aws.credentials.properties");
		Properties awsCredentials = new Properties();
		awsCredentials.load(new FileReader(awsCredentialsFile));
		String accessKey = awsCredentials.getProperty("cloud.aws.credentials.accessKey");
		String secretKey = awsCredentials.getProperty("cloud.aws.credentials.secretKey");
		this.cloudFormation = new AmazonCloudFormationClient(new BasicAWSCredentials(accessKey, secretKey));

		YamlPropertiesFactoryBean yamlPropertiesFactoryBean = new YamlPropertiesFactoryBean();
		yamlPropertiesFactoryBean.setResources(new ClassPathResource("application.yml"));
		Properties applicationProperties = yamlPropertiesFactoryBean.getObject();

		this.stackName = applicationProperties.getProperty("cloud.aws.stack.name");

		after();

		ClassPathResource stackTemplate = new ClassPathResource("AwsIntegrationTestTemplate.json");
		String templateBody = FileCopyUtils.copyToString(new InputStreamReader(stackTemplate.getInputStream()));

		this.cloudFormation.createStack(
				new CreateStackRequest()
						.withTemplateBody(templateBody)
						.withOnFailure(OnFailure.DELETE)
						.withStackName(this.stackName));

		waitForCompletion();

		System.setProperty("cloud.aws.credentials.accessKey", accessKey);
		System.setProperty("cloud.aws.credentials.secretKey", secretKey);
	}
	catch (Exception e) {
		if (!(e instanceof AssumptionViolatedException)) {
			Assume.assumeTrue("Can't perform AWS integration test because of: " + e.getMessage(), false);
		}
		else {
			throw e;
		}
	}
}
 
Example 19
Source File: YamlPropertySourceFactory.java    From spring-cloud with Apache License 2.0 4 votes vote down vote up
private Properties loadYamlIntoProperties(EncodedResource resource) {
    YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
    factory.setResources(resource.getResource());
    factory.afterPropertiesSet();
    return factory.getObject();
}
 
Example 20
Source File: InitializrMetadataBuilderTests.java    From initializr with Apache License 2.0 4 votes vote down vote up
private static Properties loadProperties(Resource resource) {
	YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
	yamlFactory.setResources(resource);
	yamlFactory.afterPropertiesSet();
	return yamlFactory.getObject();
}