org.springframework.boot.env.YamlPropertySourceLoader Java Examples

The following examples show how to use org.springframework.boot.env.YamlPropertySourceLoader. 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: YamlPropertyLoaderFactory.java    From magic-starter with GNU Lesser General Public License v3.0 8 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource encodedResource) throws IOException {
	if (encodedResource == null) {
		return emptyPropertySource(name);
	}
	Resource resource = encodedResource.getResource();
	String fileName = resource.getFilename();
	List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(fileName, resource);
	if (sources.isEmpty()) {
		return emptyPropertySource(fileName);
	}
	// yaml 数据存储,合成一个 PropertySource
	Map<String, Object> ymlDataMap = new HashMap<>(32);
	for (PropertySource<?> source : sources) {
		ymlDataMap.putAll(((MapPropertySource) source).getSource());
	}
	return new OriginTrackedMapPropertySource(getSourceName(fileName, name), ymlDataMap);
}
 
Example #2
Source File: Deployer.java    From spring-cloud-cli with Apache License 2.0 6 votes vote down vote up
private PropertySource<?> loadPropertySource(Resource resource, String path) {
	if (resource.exists()) {
		try {
			List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(path,
					resource);
			if (sources != null) {
				logger.info("Loaded YAML properties from: " + resource);
			} else if (sources == null || sources.isEmpty()){
			    return null;
               }

			CompositePropertySource composite = new CompositePropertySource("cli-sources");

			for (PropertySource propertySource : sources) {
				composite.addPropertySource(propertySource);
			}

			return composite;
		}
		catch (IOException e) {
		}
	}
	return null;
}
 
Example #3
Source File: SyndesisCommand.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private AbstractApplicationContext createContext() {
    final AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();

    final YamlPropertySourceLoader propertySourceLoader = new YamlPropertySourceLoader();
    final List<PropertySource<?>> yamlPropertySources;
    try {
        yamlPropertySources = propertySourceLoader.load(name, context.getResource("classpath:" + name + ".yml"));
    } catch (final IOException e) {
        throw new IllegalStateException(e);
    }

    final StandardEnvironment environment = new StandardEnvironment();
    final MutablePropertySources propertySources = environment.getPropertySources();
    propertySources.addFirst(new MapPropertySource("parameters", parameters));
    yamlPropertySources.forEach(propertySources::addLast);

    context.setEnvironment(environment);

    final String packageName = getClass().getPackage().getName();
    context.scan(packageName);

    context.refresh();

    return context;
}
 
Example #4
Source File: SimpleConfigLoader.java    From Cleanstone with MIT License 6 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {
        Path fileSystemConfig = Paths.get(SIMPLE_CONFIG);
        boolean exists = Files.exists(fileSystemConfig);
        if (!exists) {
            InputStream classPathConfig = new ClassPathResource(SIMPLE_CONFIG).getInputStream();

            Files.copy(classPathConfig, fileSystemConfig);
        }

        Resource resource = applicationContext.getResource("file:./" + SIMPLE_CONFIG);
        YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
        List<PropertySource<?>> propertySources = sourceLoader.load("simpleConfig", resource);
        propertySources.forEach(propertySource -> applicationContext.getEnvironment().getPropertySources().addFirst(propertySource));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: ApplicationPropertiesTests.java    From github-release-notes-generator with Apache License 2.0 6 votes vote down vote up
@Test
public void loadYaml() throws Exception {
	YamlPropertySourceLoader yamlLoader = new YamlPropertySourceLoader();
	List<PropertySource<?>> yaml = yamlLoader.load("application",
			new ClassPathResource("test-application.yml", getClass()));
	Binder binder = new Binder(ConfigurationPropertySources.from(yaml));
	ApplicationProperties properties = binder.bind("releasenotes", ApplicationProperties.class).get();
	Github github = properties.getGithub();
	assertThat(github.getUsername()).isEqualTo("testuser");
	assertThat(github.getPassword()).isEqualTo("testpass");
	assertThat(github.getOrganization()).isEqualTo("testorg");
	assertThat(github.getRepository()).isEqualTo("testrepo");
	List<Section> sections = properties.getSections();
	assertThat(sections.get(0).getTitle()).isEqualTo("New Features");
	assertThat(sections.get(0).getEmoji()).isEqualTo(":star:");
	assertThat(sections.get(0).getLabels()).containsExactly("enhancement");
}
 
Example #6
Source File: YamlPropertyLoaderFactory.java    From Aooms with Apache License 2.0 5 votes vote down vote up
public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
    /*if (resource == null) {
        super.createPropertySource(name, resource);
    }*/

    List<PropertySource<?>> propertySourceList = new YamlPropertySourceLoader().load(resource.getResource().getFilename(),resource.getResource());
    return propertySourceList.get(0);
}
 
Example #7
Source File: ExtConfigEnvironmentPostProcessor.java    From Jpom with MIT License 5 votes vote down vote up
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
    YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
    Resource resource = ExtConfigBean.getResource();
    try {
        List<PropertySource<?>> propertySources = yamlPropertySourceLoader.load(ExtConfigBean.FILE_NAME, resource);
        propertySources.forEach(propertySource -> environment.getPropertySources().addLast(propertySource));
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example #8
Source File: SystemConfigController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "save_config.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@OptLog(UserOperateLogV1.OptType.EditSysConfig)
@SystemPermission
public String saveConfig(String nodeId, String content, String restart) {
    if (StrUtil.isNotEmpty(nodeId)) {
        return NodeForward.request(getNode(), getRequest(), NodeUrl.SystemSaveConfig).toString();
    }
    if (StrUtil.isEmpty(content)) {
        return JsonMessage.getString(405, "内容不能为空");
    }
    try {
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        ByteArrayResource resource = new ByteArrayResource(content.getBytes(StandardCharsets.UTF_8));
        yamlPropertySourceLoader.load("test", resource);
    } catch (Exception e) {
        DefaultSystemLog.getLog().warn("内容格式错误,请检查修正", e);
        return JsonMessage.getString(500, "内容格式错误,请检查修正:" + e.getMessage());
    }
    if (JpomManifest.getInstance().isDebug()) {
        return JsonMessage.getString(405, "调试模式不支持在线修改,请到resource目录下");
    }
    File resourceFile = ExtConfigBean.getResourceFile();
    FileUtil.writeString(content, resourceFile, CharsetUtil.CHARSET_UTF_8);

    if (Convert.toBool(restart, false)) {
        // 重启
        ThreadUtil.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ignored) {
            }
            JpomApplication.restart();
        });
    }
    return JsonMessage.getString(200, "修改成功");
}
 
Example #9
Source File: SystemConfigController.java    From Jpom with MIT License 5 votes vote down vote up
@RequestMapping(value = "save_config.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public String saveConfig(String content, String restart) {
    if (StrUtil.isEmpty(content)) {
        return JsonMessage.getString(405, "内容不能为空");
    }
    try {
        YamlPropertySourceLoader yamlPropertySourceLoader = new YamlPropertySourceLoader();
        ByteArrayResource resource = new ByteArrayResource(content.getBytes());
        yamlPropertySourceLoader.load("test", resource);
    } catch (Exception e) {
        DefaultSystemLog.getLog().warn("内容格式错误,请检查修正", e);
        return JsonMessage.getString(500, "内容格式错误,请检查修正:" + e.getMessage());
    }
    if (JpomManifest.getInstance().isDebug()) {
        return JsonMessage.getString(405, "调试模式不支持在线修改,请到resource目录下");
    }
    File resourceFile = ExtConfigBean.getResourceFile();
    FileUtil.writeString(content, resourceFile, CharsetUtil.CHARSET_UTF_8);

    if (Convert.toBool(restart, false)) {
        // 重启
        ThreadUtil.execute(() -> {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ignored) {
            }
            JpomApplication.restart();
        });
    }
    return JsonMessage.getString(200, "修改成功");
}
 
Example #10
Source File: CustomContextInitializer.java    From Auth-service with MIT License 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
    try {
        Resource resource = applicationContext.getResource("classpath:application-test.yml");
        YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
        List<PropertySource<?>> yamlTestProperties = sourceLoader.load("test-properties", resource);
        applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties.get(0));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #11
Source File: YamlFileApplicationContextInitializer.java    From fiat with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
  try {
    Resource resource = applicationContext.getResource("classpath:application.yml");
    YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
    List<PropertySource<?>> yamlTestProperties =
        sourceLoader.load("yamlTestProperties", resource);
    for (PropertySource<?> ps : yamlTestProperties) {
      applicationContext.getEnvironment().getPropertySources().addLast(ps);
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #12
Source File: BootUtils.java    From onetwo with Apache License 2.0 5 votes vote down vote up
public static PropertySource<?> loadYaml(String classpath){
	YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
	try {
        PropertySource<?> props = loader.load(classpath, SpringUtils.newClassPathResource(classpath), null);
        return props;
       } catch (IOException e) {
        throw new BaseException("load yaml file error: " + classpath);
       }
}
 
Example #13
Source File: YamlPropertySourceLoaderTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void test() throws Exception{
	YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
	PropertySource<?> props = loader.load("application", SpringUtils.newClassPathResource("application.yaml"), null);
	Object env = props.getProperty("spring.profiles.active");
	System.out.println("env: " + env);
	env = props.getProperty("server.port");
	System.out.println("port: " + env);
}
 
Example #14
Source File: ServiceBrokerPropertiesBindingTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
void bindMinimumValidYaml() throws Exception {
	this.context.register(ServiceBrokerPropertiesConfiguration.class);
	Resource resource = context.getResource("classpath:catalog-minimal.yml");
	YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
	List<PropertySource<?>> properties = sourceLoader.load("catalog", resource);
	context.getEnvironment().getPropertySources().addFirst(properties.get(0));
	validateMinimumCatalog();
}
 
Example #15
Source File: ServiceBrokerPropertiesBindingTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
@Test
void bindFullValidYaml() throws Exception {
	this.context.register(ServiceBrokerPropertiesConfiguration.class);
	Resource resource = context.getResource("classpath:catalog-full.yml");
	YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
	List<PropertySource<?>> properties = sourceLoader.load("catalog", resource);
	context.getEnvironment().getPropertySources().addFirst(properties.get(0));
	validateFullCatalog();
}
 
Example #16
Source File: ConfigPrinter.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
private PropertySourceLoader getPropertySourceLoader(String fileName) throws UnSupportConfigFileSuffixException {
    if (fileName.contains(PROPERTIES_FILE_EXTENSION)) {
        return new PropertiesPropertySourceLoader();
    } else if (fileName.contains(YAML_FILE_EXTENSION)) {
        return new YamlPropertySourceLoader();
    }
    LOGGER.error("Failed to recognize file: {}", fileName);
    throw new UnSupportConfigFileSuffixException();
}
 
Example #17
Source File: YamlSourceFactory.java    From spring-boot-examples with Apache License 2.0 4 votes vote down vote up
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
    return new YamlPropertySourceLoader().load(resource.getResource().getFilename()
            , resource.getResource()).get(0);
}