org.springframework.core.io.support.PropertiesLoaderUtils Java Examples
The following examples show how to use
org.springframework.core.io.support.PropertiesLoaderUtils.
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: ExternalizedConfigurationBinderBootstrap.java From thinking-in-spring-boot-samples with Apache License 2.0 | 7 votes |
public static void main(String[] args) throws IOException { // application.properties 文件资源 classpath 路径 String location = "application.properties"; // 编码化的 Resource 对象(解决乱码问题) EncodedResource resource = new EncodedResource(new ClassPathResource(location), "UTF-8"); // 加载 application.properties 文件,转化为 Properties 对象 Properties properties = PropertiesLoaderUtils.loadProperties(resource); // 创建 Properties 类型的 PropertySource PropertiesPropertySource propertySource = new PropertiesPropertySource("map", properties); // 转化为 Spring Boot 2 外部化配置源 ConfigurationPropertySource 集合 Iterable<ConfigurationPropertySource> propertySources = ConfigurationPropertySources.from(propertySource); // 创建 Spring Boot 2 Binder 对象(设置 ConversionService ,扩展类型转换能力) Binder binder = new Binder(propertySources, null, conversionService()); // 执行绑定,返回绑定结果 BindResult<User> bindResult = binder.bind("user", User.class); // 获取绑定对象 User user = bindResult.get(); // 输出结果 System.out.println(user); }
Example #2
Source File: I18nUtil.java From microservices-platform with Apache License 2.0 | 6 votes |
public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); i18n = StringUtils.isNotBlank(i18n)?("_"+i18n):i18n; String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #3
Source File: DefaultHealthInfoContributor.java From datawave with Apache License 2.0 | 6 votes |
@Override public VersionInfo versionInfo() { String buildTime = null; GitInfo gitInfo = null; try { ClassPathResource cpr = new ClassPathResource("/git.properties", getClass()); Properties gitProps = PropertiesLoaderUtils.loadProperties(cpr); CommitInfo ci = new CommitInfo(gitProps.getProperty("git.commit.time"), gitProps.getProperty("git.commit.id.abbrev")); gitInfo = new GitInfo(ci, gitProps.getProperty("git.branch")); buildTime = gitProps.getProperty("git.build.time"); } catch (IOException e) { // Ignore -- we just won't have git info. } String version = getClass().getPackage().getImplementationVersion(); BuildInfo buildInfo = new BuildInfo(version, buildTime); return new VersionInfo("default", buildInfo, gitInfo); }
Example #4
Source File: PropertiesUtil.java From DataLink with Apache License 2.0 | 6 votes |
/** * 获取properties文件内容 * * @param propertiesPath :绝对路径 * @return */ public static Properties getProperties(String propertiesPath) throws IOException { Properties resultProperties = propertiesMap.get(propertiesPath); if (resultProperties == null) { Resource resource = new PathResource(propertiesPath); try { resultProperties = PropertiesLoaderUtils.loadProperties(resource); } catch (FileNotFoundException e) { resultProperties = null; } if (resultProperties != null) propertiesMap.put(propertiesPath, resultProperties); } return resultProperties; }
Example #5
Source File: DefaultDhisConfigurationProvider.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 6 votes |
private Properties loadDhisConf() throws IllegalStateException { try ( InputStream in = locationManager.getInputStream( CONF_FILENAME ) ) { Properties conf = PropertiesLoaderUtils.loadProperties( new InputStreamResource( in ) ); substituteEnvironmentVariables( conf ); return conf; } catch ( LocationManagerException | IOException | SecurityException ex ) { log.debug( String.format( "Could not load %s", CONF_FILENAME ), ex ); throw new IllegalStateException( "Properties could not be loaded", ex ); } }
Example #6
Source File: DLockGenerator.java From dlock with Apache License 2.0 | 6 votes |
/** * Load the lease config from properties, and init the lockConfigMap. */ @PostConstruct public void init() { try { // Using default path if no specified confPath = StringUtils.isBlank(confPath) ? DEFAULT_CONF_PATH : confPath; // Load lock config from properties Properties properties = PropertiesLoaderUtils.loadAllProperties(confPath); // Build the lockConfigMap for (Entry<Object, Object> propEntry : properties.entrySet()) { DLockType lockType = EnumUtils.valueOf(DLockType.class, propEntry.getKey().toString()); Integer lease = Integer.valueOf(propEntry.getValue().toString()); if (lockType != null && lease != null) { lockConfigMap.put(lockType, lease); } } } catch (Exception e) { throw new RuntimeException("Load distributed lock config fail", e); } }
Example #7
Source File: AwAlerting.java From adwords-alerting with Apache License 2.0 | 6 votes |
/** * Initialize the application context, adding the properties configuration file depending on the * specified path. * * @param propertiesResource the properties resource * @return the resource loaded from the properties file * @throws IOException error opening the properties file */ private static Properties initApplicationContextAndProperties(Resource propertiesResource) throws IOException { LOGGER.trace("Innitializing Spring application context."); DynamicPropertyPlaceholderConfigurer.setDynamicResource(propertiesResource); Properties properties = PropertiesLoaderUtils.loadProperties(propertiesResource); // Selecting the XMLs to choose the Spring Beans to load. List<String> listOfClassPathXml = new ArrayList<String>(); listOfClassPathXml.add("classpath:aw-alerting-processor-beans.xml"); appCtx = new ClassPathXmlApplicationContext( listOfClassPathXml.toArray(new String[listOfClassPathXml.size()])); return properties; }
Example #8
Source File: Config.java From awesome-delay-queue with MIT License | 6 votes |
@Bean public AwesomeURL awesomeUrl() throws IOException { String configPath = storage+".properties"; Resource resource = new ClassPathResource(configPath); Properties props = PropertiesLoaderUtils.loadProperties(resource); Set<String> keySet = props.stringPropertyNames(); String host = props.getProperty("host"); int port = Integer.parseInt(props.getProperty("port")); String username = props.getProperty("username"); String password = props.getProperty("password"); Map<String,String> paramMap = new HashMap<>(); for (String key:keySet){ paramMap.put(key, (String) props.get(key)); } AwesomeURL awesomeURL = new AwesomeURL(storage,username,password,host,port,null,paramMap); return awesomeURL; }
Example #9
Source File: I18nUtil.java From xxl-job with GNU General Public License v3.0 | 6 votes |
public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); String i18nFile = MessageFormat.format("i18n/message_{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #10
Source File: I18nUtil.java From xmfcn-spring-cloud with Apache License 2.0 | 6 votes |
public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); i18n = StringUtils.isNotBlank(i18n)?("_"+i18n):i18n; String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #11
Source File: I18nUtil.java From zuihou-admin-boot with Apache License 2.0 | 6 votes |
public static Properties loadI18nProp() { if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); i18n = StringUtils.isNotBlank(i18n) ? ("_" + i18n) : i18n; String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource, "UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #12
Source File: BinderFactoryAutoConfiguration.java From spring-cloud-stream with Apache License 2.0 | 6 votes |
static Collection<BinderType> parseBinderConfigurations(ClassLoader classLoader, Resource resource) throws IOException, ClassNotFoundException { Properties properties = PropertiesLoaderUtils.loadProperties(resource); Collection<BinderType> parsedBinderConfigurations = new ArrayList<>(); for (Map.Entry<?, ?> entry : properties.entrySet()) { String binderType = (String) entry.getKey(); String[] binderConfigurationClassNames = StringUtils .commaDelimitedListToStringArray((String) entry.getValue()); Class<?>[] binderConfigurationClasses = new Class[binderConfigurationClassNames.length]; int i = 0; for (String binderConfigurationClassName : binderConfigurationClassNames) { binderConfigurationClasses[i++] = ClassUtils .forName(binderConfigurationClassName, classLoader); } parsedBinderConfigurations .add(new BinderType(binderType, binderConfigurationClasses)); } return parsedBinderConfigurations; }
Example #13
Source File: I18nUtil.java From zuihou-admin-cloud with Apache License 2.0 | 6 votes |
public static Properties loadI18nProp() { if (prop != null) { return prop; } try { // build i18n prop String i18n = XxlJobAdminConfig.getAdminConfig().getI18n(); i18n = StringUtils.isNotBlank(i18n) ? ("_" + i18n) : i18n; String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource, "UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #14
Source File: InitPropConfigFactory.java From mPass with Apache License 2.0 | 6 votes |
/** * 配置文件信息获取 * * @return */ @Override public Map<String, Object> defaultConfig() { Map<String, Object> rtnMap = new HashMap<>(1); try { ClassLoader classLoader = this.getClass().getClassLoader(); Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(getPropFilePath()) : ClassLoader.getSystemResources(getPropFilePath())); while (urls.hasMoreElements()) { URL url = urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); for (Map.Entry<?, ?> entry : properties.entrySet()) { rtnMap.put((String) entry.getKey(), entry.getValue()); } } } catch (IOException e) { log.error("加载初始配置错误.", e); } return rtnMap; }
Example #15
Source File: I18nUtil.java From open-capacity-platform with Apache License 2.0 | 6 votes |
public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18nFile = "i18n/message.properties"; // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #16
Source File: ExtInfoEndpointConfiguration.java From booties with Apache License 2.0 | 6 votes |
@Bean public InfoEndpoint infoEndpoint() throws Exception { LinkedHashMap<String, Object> info = new LinkedHashMap<String, Object>(); for (String filename : getAllPropertiesFiles()) { Resource resource = new ClassPathResource("/" + filename); Properties properties = new Properties(); if (resource.exists()) { properties = PropertiesLoaderUtils.loadProperties(resource); String name = resource.getFilename(); info.put(name.replace(PROPERTIES_SUFFIX, PROPERTIES_SUFFIX_REPLACEMENT), Maps.fromProperties(properties)); } else { if (failWhenResourceNotExists()) { throw new RuntimeException("Resource : " + filename + " does not exist"); } else { log.info("Resource {} does not exist", filename); } } } return new InfoEndpoint(info); }
Example #17
Source File: InitPropConfigFactory.java From mPaaS with Apache License 2.0 | 6 votes |
/** * 配置文件信息获取 * * @return */ @Override public Map<String, Object> defaultConfig() { Map<String, Object> rtnMap = new HashMap<>(1); try { ClassLoader classLoader = this.getClass().getClassLoader(); Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(getPropFilePath()) : ClassLoader.getSystemResources(getPropFilePath())); while (urls.hasMoreElements()) { URL url = urls.nextElement(); UrlResource resource = new UrlResource(url); Properties properties = PropertiesLoaderUtils.loadProperties(resource); for (Map.Entry<?, ?> entry : properties.entrySet()) { rtnMap.put((String) entry.getKey(), entry.getValue()); } } } catch (IOException e) { log.error("加载初始配置错误.", e); } return rtnMap; }
Example #18
Source File: I18nUtil.java From datax-web with MIT License | 6 votes |
public static Properties loadI18nProp(){ if (prop != null) { return prop; } try { // build i18n prop String i18n = JobAdminConfig.getAdminConfig().getI18n(); i18n = (i18n!=null && i18n.trim().length()>0)?("_"+i18n):i18n; String i18nFile = MessageFormat.format("i18n/message{0}.properties", i18n); // load prop Resource resource = new ClassPathResource(i18nFile); EncodedResource encodedResource = new EncodedResource(resource,"UTF-8"); prop = PropertiesLoaderUtils.loadProperties(encodedResource); } catch (IOException e) { logger.error(e.getMessage(), e); } return prop; }
Example #19
Source File: XMLContentLoader.java From syncope with Apache License 2.0 | 6 votes |
private void createViews(final String domain, final DataSource dataSource) throws IOException { LOG.debug("[{}] Creating views", domain); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); Properties views = PropertiesLoaderUtils.loadProperties(viewsXML.getResource()); views.stringPropertyNames().stream().sorted().forEachOrdered(idx -> { LOG.debug("[{}] Creating view {}", domain, views.get(idx).toString()); try { jdbcTemplate.execute(views.getProperty(idx).replaceAll("\\n", " ")); } catch (DataAccessException e) { LOG.error("[{}] Could not create view", domain, e); } }); LOG.debug("Views created"); }
Example #20
Source File: XMLContentLoader.java From syncope with Apache License 2.0 | 6 votes |
private void createIndexes(final String domain, final DataSource dataSource) throws IOException { LOG.debug("[{}] Creating indexes", domain); JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); Properties indexes = PropertiesLoaderUtils.loadProperties(indexesXML.getResource()); indexes.stringPropertyNames().stream().sorted().forEachOrdered(idx -> { LOG.debug("[{}] Creating index {}", domain, indexes.get(idx).toString()); try { jdbcTemplate.execute(indexes.getProperty(idx)); } catch (DataAccessException e) { LOG.error("[{}] Could not create index", domain, e); } }); LOG.debug("Indexes created"); }
Example #21
Source File: SmtpMailer.java From alf.io with GNU General Public License v3.0 | 6 votes |
private static JavaMailSender toMailSender(Map<ConfigurationKeys, ConfigurationManager.MaybeConfiguration> conf) { JavaMailSenderImpl r = new CustomJavaMailSenderImpl(); r.setDefaultEncoding("UTF-8"); r.setHost(conf.get(SMTP_HOST).getRequiredValue()); r.setPort(Integer.parseInt(conf.get(SMTP_PORT).getRequiredValue())); r.setProtocol(conf.get(SMTP_PROTOCOL).getRequiredValue()); r.setUsername(conf.get(SMTP_USERNAME).getValueOrDefault(null)); r.setPassword(conf.get(SMTP_PASSWORD).getValueOrDefault(null)); String properties = conf.get(SMTP_PROPERTIES).getValueOrDefault(null); if (properties != null) { try { Properties prop = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ByteArrayResource( properties.getBytes(StandardCharsets.UTF_8)), "UTF-8")); r.setJavaMailProperties(prop); } catch (IOException e) { log.warn("error while setting the mail sender properties", e); } } return r; }
Example #22
Source File: KeyNamingStrategy.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Merges the {@code Properties} configured in the {@code mappings} and * {@code mappingLocations} into the final {@code Properties} instance * used for {@code ObjectName} resolution. * @throws IOException */ @Override public void afterPropertiesSet() throws IOException { this.mergedMappings = new Properties(); CollectionUtils.mergePropertiesIntoMap(this.mappings, this.mergedMappings); if (this.mappingLocations != null) { for (int i = 0; i < this.mappingLocations.length; i++) { Resource location = this.mappingLocations[i]; if (logger.isInfoEnabled()) { logger.info("Loading JMX object name mappings file from " + location); } PropertiesLoaderUtils.fillProperties(this.mergedMappings, location); } } }
Example #23
Source File: ApplicationProperties.java From wangmarket with Apache License 2.0 | 5 votes |
public ApplicationProperties() { try { Resource resource = new ClassPathResource("/application.properties");// properties = PropertiesLoaderUtils.loadProperties(resource); } catch (IOException e) { e.printStackTrace(); } }
Example #24
Source File: H2DhisConfigurationProvider.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
private Properties getPropertiesFromFile( String fileName ) { try { return PropertiesLoaderUtils.loadProperties( new ClassPathResource( fileName ) ); } catch ( IOException ex ) { log.warn( String.format( "Could not load %s from classpath", fileName ), ex ); return new Properties(); } }
Example #25
Source File: LocalPersistenceManagerFactoryBean.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Initialize the PersistenceManagerFactory for the given location. * @throws IllegalArgumentException in case of illegal property values * @throws IOException if the properties could not be loaded from the given location * @throws JDOException in case of JDO initialization errors */ @Override public void afterPropertiesSet() throws IllegalArgumentException, IOException, JDOException { if (this.persistenceManagerFactoryName != null) { if (this.configLocation != null || !this.jdoPropertyMap.isEmpty()) { throw new IllegalStateException("'configLocation'/'jdoProperties' not supported in " + "combination with 'persistenceManagerFactoryName' - specify one or the other, not both"); } if (logger.isInfoEnabled()) { logger.info("Building new JDO PersistenceManagerFactory for name '" + this.persistenceManagerFactoryName + "'"); } this.persistenceManagerFactory = newPersistenceManagerFactory(this.persistenceManagerFactoryName); } else { Map<String, Object> mergedProps = new HashMap<String, Object>(); if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading JDO config from [" + this.configLocation + "]"); } CollectionUtils.mergePropertiesIntoMap( PropertiesLoaderUtils.loadProperties(this.configLocation), mergedProps); } mergedProps.putAll(this.jdoPropertyMap); logger.info("Building new JDO PersistenceManagerFactory"); this.persistenceManagerFactory = newPersistenceManagerFactory(mergedProps); } // Build default JdoDialect if none explicitly specified. if (this.jdoDialect == null) { this.jdoDialect = new DefaultJdoDialect(this.persistenceManagerFactory.getConnectionFactory()); } }
Example #26
Source File: VelocityEngineFactory.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Prepare the VelocityEngine instance and return it. * @return the VelocityEngine instance * @throws IOException if the config file wasn't found * @throws VelocityException on Velocity initialization failure */ public VelocityEngine createVelocityEngine() throws IOException, VelocityException { VelocityEngine velocityEngine = newVelocityEngine(); Map<String, Object> props = new HashMap<String, Object>(); // Load config file if set. if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading Velocity config from [" + this.configLocation + "]"); } CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); } // Merge local properties if set. if (!this.velocityProperties.isEmpty()) { props.putAll(this.velocityProperties); } // Set a resource loader path, if required. if (this.resourceLoaderPath != null) { initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath); } // Log via Commons Logging? if (this.overrideLogging) { velocityEngine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM, new CommonsLogLogChute()); } // Apply properties to VelocityEngine. for (Map.Entry<String, Object> entry : props.entrySet()) { velocityEngine.setProperty(entry.getKey(), entry.getValue()); } postProcessVelocityEngine(velocityEngine); // Perform actual initialization. velocityEngine.init(); return velocityEngine; }
Example #27
Source File: VelocityEngineFactory.java From scoold with Apache License 2.0 | 5 votes |
/** * Prepare the VelocityEngine instance and return it. * * @return the VelocityEngine instance * @throws IOException if the config file wasn't found * @throws VelocityException on Velocity initialization failure */ public VelocityEngine createVelocityEngine() throws IOException, VelocityException { VelocityEngine velocityEngine = newVelocityEngine(); Map<String, Object> props = new HashMap<String, Object>(); // Load config file if set. if (this.configLocation != null) { if (logger.isInfoEnabled()) { logger.info("Loading Velocity config from [" + this.configLocation + "]"); } CollectionUtils.mergePropertiesIntoMap(PropertiesLoaderUtils.loadProperties(this.configLocation), props); } // Merge local properties if set. if (!this.velocityProperties.isEmpty()) { props.putAll(this.velocityProperties); } // Set a resource loader path, if required. if (this.resourceLoaderPath != null) { initVelocityResourceLoader(velocityEngine, this.resourceLoaderPath); } // Apply properties to VelocityEngine. for (Map.Entry<String, Object> entry : props.entrySet()) { velocityEngine.setProperty(entry.getKey(), entry.getValue()); } postProcessVelocityEngine(velocityEngine); // Perform actual initialization. velocityEngine.init(); return velocityEngine; }
Example #28
Source File: SystemProps.java From MultimediaDesktop with Apache License 2.0 | 5 votes |
public static boolean InitProps() { try { props = PropertiesLoaderUtils.loadAllProperties(SERVER_FILE); } catch (IOException e) { log.fatal("读取配置文件失败", e); return false; } return props != null; }
Example #29
Source File: ScriptVariableGeneratorConfiguration.java From spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
@Bean(name = "variableGenerator") public ScriptVariableGenerator scriptVariableGenerator() throws IOException { Map<String, Object> variables = new HashMap<>(); CollectionUtils.mergePropertiesIntoMap(properties.getVariables(), variables); if (properties.getVariablesLocation() != null) { CollectionUtils.mergePropertiesIntoMap( PropertiesLoaderUtils.loadProperties(properties.getVariablesLocation()), variables); } return new DefaultScriptVariableGenerator(variables); }
Example #30
Source File: ScriptVariableGeneratorConfiguration.java From spring-cloud-stream-app-starters with Apache License 2.0 | 5 votes |
@Bean(name = "variableGenerator") public ScriptVariableGenerator scriptVariableGenerator() throws IOException { Map<String, Object> variables = new HashMap<>(); CollectionUtils.mergePropertiesIntoMap(properties.getVariables(), variables); if (properties.getVariablesLocation() != null) { CollectionUtils.mergePropertiesIntoMap( PropertiesLoaderUtils.loadProperties(properties.getVariablesLocation()), variables); } return new DefaultScriptVariableGenerator(variables); }