Java Code Examples for org.springframework.core.io.ResourceLoader#getResource()

The following examples show how to use org.springframework.core.io.ResourceLoader#getResource() . 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: ConfigPrinter.java    From Qualitis with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void printConfig() throws UnSupportConfigFileSuffixException {
    LOGGER.info("Start to print config");
    addPropertiesFile();
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    LOGGER.info("Prepared to print config in file: {}", propertiesFiles);

    for (String fileName : propertiesFiles) {
        LOGGER.info("======================== Config in {} ========================", fileName);
        PropertySourceLoader propertySourceLoader = getPropertySourceLoader(fileName);
        Resource resource = resourceLoader.getResource(fileName);
        try {
            List<PropertySource<?>> propertySources = propertySourceLoader.load(fileName, resource);
            for (PropertySource p : propertySources) {
                Map<String, Object> map = (Map<String, Object>) p.getSource();
                for (String key : map.keySet()) {
                    LOGGER.info("Name: [{}]=[{}]", key, map.get(key));
                }
            }
        } catch (IOException e) {
            LOGGER.info("Failed to open file: {}, caused by: {}, it does not matter", fileName, e.getMessage());
        }
        LOGGER.info("=======================================================================================\n");
    }
    LOGGER.info("Succeed to print all configs");
}
 
Example 2
Source File: HelpAction.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public String execute()
    throws Exception
{
    List<Locale> locales = localeManager.getLocalesOrderedByPriority();

    ResourceLoader resourceLoader = new DefaultResourceLoader();

    for ( Locale locale : locales )
    {
        String helpPage = helpPagePreLocale + locale.toString() + helpPagePostLocale;

        if ( resourceLoader.getResource( helpPage ) != null )
        {
            this.helpPage = helpPage;

            return SUCCESS;
        }
    }

    return SUCCESS;
}
 
Example 3
Source File: DelegatingResourceLoader.java    From spring-cloud-deployer with Apache License 2.0 6 votes vote down vote up
@Override
public Resource getResource(String location) {
	try {
		URI uri = new URI(location);
		String scheme = uri.getScheme();
		Assert.notNull(scheme, "a scheme (prefix) is required");
		ResourceLoader loader = this.loaders.get(scheme);
		if (loader == null) {
			if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) {
				loader = new DownloadingUrlResourceLoader();
			}
			else {
				loader = this.defaultResourceLoader;
			}
		}
		return loader.getResource(location);
	}
	catch (Exception e) {
		throw new ResourceNotResolvedException(e.getMessage(), e);
	}

}
 
Example 4
Source File: PropertiesBeanDefinitionReaderDemo.java    From geekbang-lessons with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    // 创建 IoC 底层容器
    DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
    // 创建面向 Properties 资源的 BeanDefinitionReader 示例
    PropertiesBeanDefinitionReader beanDefinitionReader = new PropertiesBeanDefinitionReader(beanFactory);
    // Properties 资源加载默认通过 ISO-8859-1,实际存储 UTF-8
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    // 通过指定的 ClassPath 获取 Resource 对象
    Resource resource = resourceLoader.getResource("classpath:/META-INF/user-bean-definitions.properties");
    // 转换成带有字符编码 EncodedResource 对象
    EncodedResource encodedResource = new EncodedResource(resource, "UTF-8");
    int beanDefinitionsCount = beanDefinitionReader.loadBeanDefinitions(encodedResource);
    System.out.println(String.format("已记载 %d 个 BeanDefinition\n", beanDefinitionsCount));
    // 通过依赖查找获取 User Bean
    User user = beanFactory.getBean("user", User.class);
    System.out.println(user);
}
 
Example 5
Source File: SiteContextFactory.java    From engine with GNU General Public License v3.0 6 votes vote down vote up
protected HierarchicalConfiguration getConfig(SiteContext siteContext, String[] configPaths,
                                              ResourceLoader resourceLoader) {
    String siteName = siteContext.getSiteName();

    logger.info("--------------------------------------------------");
    logger.info("<Loading configuration for site: " + siteName + ">");
    logger.info("--------------------------------------------------");

    try {
        for (int i = configPaths.length - 1; i >= 0; i--) {
            Resource config = resourceLoader.getResource(configPaths[i]);
            if (config.exists()) {
                return configurationReader.readXmlConfiguration(config);
            }
        }
        return null;
    } catch (ConfigurationException e) {
        throw new SiteContextCreationException("Unable to load configuration for site '" + siteName + "'", e);
    } finally {
        logger.info("--------------------------------------------------");
        logger.info("</Loading configuration for site: " + siteName + ">");
        logger.info("--------------------------------------------------");
    }
}
 
Example 6
Source File: ScriptFactoryPostProcessor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Convert the given script source locator to a ScriptSource instance.
 * <p>By default, supported locators are Spring resource locations
 * (such as "file:C:/myScript.bsh" or "classpath:myPackage/myScript.bsh")
 * and inline scripts ("inline:myScriptText...").
 * @param beanName the name of the scripted bean
 * @param scriptSourceLocator the script source locator
 * @param resourceLoader the ResourceLoader to use (if necessary)
 * @return the ScriptSource instance
 */
protected ScriptSource convertToScriptSource(String beanName, String scriptSourceLocator,
		ResourceLoader resourceLoader) {

	if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
		return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()), beanName);
	}
	else {
		return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
	}
}
 
Example 7
Source File: MyAwareService.java    From journaldev with MIT License 5 votes vote down vote up
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
	System.out.println("setResourceLoader called");
	Resource resource = resourceLoader.getResource("classpath:spring.xml");
	System.out.println("setResourceLoader:: Resource File Name="
			+ resource.getFilename());
}
 
Example 8
Source File: ApisAutoConfiguration.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get the jobs dir as a Spring Resource. Will create if it doesn't exist.
 *
 * @param resourceLoader The resource loader to use
 * @param jobsProperties The jobs properties to use
 * @return The job dir as a resource
 * @throws IOException on error reading or creating the directory
 */
@Bean
@ConditionalOnMissingBean(name = "jobsDir", value = Resource.class)
public Resource jobsDir(
    final ResourceLoader resourceLoader,
    final JobsProperties jobsProperties
) throws IOException {
    final String jobsDirLocation = jobsProperties.getLocations().getJobs().toString();
    final Resource tmpJobsDirResource = resourceLoader.getResource(jobsDirLocation);
    if (tmpJobsDirResource.exists() && !tmpJobsDirResource.getFile().isDirectory()) {
        throw new IllegalStateException(jobsDirLocation + " exists but isn't a directory. Unable to continue");
    }

    // We want the resource to end in a slash for use later in the generation of URL's
    final String slash = "/";
    String localJobsDir = jobsDirLocation;
    if (!jobsDirLocation.endsWith(slash)) {
        localJobsDir = localJobsDir + slash;
    }
    final Resource jobsDirResource = resourceLoader.getResource(localJobsDir);

    if (!jobsDirResource.exists()) {
        final File file = jobsDirResource.getFile();
        if (!file.mkdirs()) {
            throw new IllegalStateException(
                "Unable to create jobs directory " + jobsDirLocation + " and it doesn't exist."
            );
        }
    }

    return jobsDirResource;
}
 
Example 9
Source File: SiteContextFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected void configureScriptSandbox(SiteContext siteContext, ResourceLoader resourceLoader) {
    if (enableScriptSandbox) {
        Resource sandboxBlacklist = resourceLoader.getResource(this.sandboxBlacklist);
        try(InputStream is = sandboxBlacklist.getInputStream()) {
            Blacklist blacklist = new Blacklist(new InputStreamReader(is));
            siteContext.scriptSandbox = new SandboxInterceptor(blacklist, singletonList(Dom4jExtension.class));
        } catch (IOException e) {
            throw new SiteContextCreationException("Unable to load sandbox blacklist for site '" +
                    siteContext.getSiteName() + "'", e);
        }
    }
}
 
Example 10
Source File: ScriptFactoryPostProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Convert the given script source locator to a ScriptSource instance.
 * <p>By default, supported locators are Spring resource locations
 * (such as "file:C:/myScript.bsh" or "classpath:myPackage/myScript.bsh")
 * and inline scripts ("inline:myScriptText...").
 * @param beanName the name of the scripted bean
 * @param scriptSourceLocator the script source locator
 * @param resourceLoader the ResourceLoader to use (if necessary)
 * @return the ScriptSource instance
 */
protected ScriptSource convertToScriptSource(String beanName, String scriptSourceLocator,
		ResourceLoader resourceLoader) {

	if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
		return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()), beanName);
	}
	else {
		return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
	}
}
 
Example 11
Source File: IndexController.java    From wetech-admin with MIT License 5 votes vote down vote up
@GetMapping("datasource/initialize")
public Result initializeDatasource() {
    DataSource dataSource = SpringUtils.getBean(DataSource.class);
    ResourceLoader loader = new DefaultResourceLoader();
    Resource schema = loader.getResource("classpath:schema.sql");
    Resource data = loader.getResource("classpath:data.sql");
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator(schema, data);
    populator.execute(dataSource);
    return Result.success();
}
 
Example 12
Source File: ScriptFactoryPostProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Convert the given script source locator to a ScriptSource instance.
 * <p>By default, supported locators are Spring resource locations
 * (such as "file:C:/myScript.bsh" or "classpath:myPackage/myScript.bsh")
 * and inline scripts ("inline:myScriptText...").
 * @param beanName the name of the scripted bean
 * @param scriptSourceLocator the script source locator
 * @param resourceLoader the ResourceLoader to use (if necessary)
 * @return the ScriptSource instance
 */
protected ScriptSource convertToScriptSource(String beanName, String scriptSourceLocator,
		ResourceLoader resourceLoader) {

	if (scriptSourceLocator.startsWith(INLINE_SCRIPT_PREFIX)) {
		return new StaticScriptSource(scriptSourceLocator.substring(INLINE_SCRIPT_PREFIX.length()), beanName);
	}
	else {
		return new ResourceScriptSource(resourceLoader.getResource(scriptSourceLocator));
	}
}
 
Example 13
Source File: LauncherApplication.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner commandLineRunner(DependencyProcessor dependencyProcessor, ResourceLoader resourceLoader) {
    return args -> {
        if (launcherProperties.getApplicationPath() == null) {
            throw new LaunchingException("application path can not be null");
        }

        if (originalMBeanDomain != null) {
            System.setProperty(LiveBeansView.MBEAN_DOMAIN_PROPERTY_NAME, originalMBeanDomain);
        }
        if (originalAdminEnabled != null) {
            System.setProperty("spring.application.admin.enabled", originalAdminEnabled);
        }

        Resource gitResource = resourceLoader.getResource("classpath:/git.properties");

        try (InputStream in = gitResource.getInputStream()) {
            Properties props = new Properties();
            props.load(in);

            props.forEach((key, value) -> {
                System.setProperty("formula.launcher." + key, (String) value);
            });
        } catch (FileNotFoundException e) {
            // do nothing
        }

        new FormulaLauncher(launcherProperties, dependencyProcessor).launch(args);
    };
}
 
Example 14
Source File: TestAttestationUtil.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
public static PrivateKey loadPrivateKeyFromResourcePath(String resourcePath) {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource(resourcePath);
    return loadPrivateKeyFromResource(resource);
}
 
Example 15
Source File: TestAttestationUtil.java    From webauthn4j with Apache License 2.0 4 votes vote down vote up
public static X509Certificate loadCertificateFromResourcePath(String resourcePath) {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource(resourcePath);
    return loadCertificateFromResource(resource);
}
 
Example 16
Source File: ResourceReader.java    From tutorials with MIT License 4 votes vote down vote up
public static String readFileToString(String path) {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource(path);
    return asString(resource);
}
 
Example 17
Source File: SiteContextFactory.java    From engine with GNU General Public License v3.0 4 votes vote down vote up
protected UrlRewriter getUrlRewriter(SiteContext siteContext, String[] urlRewriteConfPaths,
                                     ResourceLoader resourceLoader) {
    String siteName = siteContext.getSiteName();
    String confPath = null;
    Resource confResource = null;
    Conf conf = null;
    UrlRewriter urlRewriter = null;

    logger.info("--------------------------------------------------");
    logger.info("<Loading URL rewrite engine for site: " + siteName + ">");
    logger.info("--------------------------------------------------");

    try {
        for (int i = urlRewriteConfPaths.length - 1; i >= 0; i--) {
            Resource resource = resourceLoader.getResource(urlRewriteConfPaths[i]);
            if (resource.exists()) {
                confPath = urlRewriteConfPaths[i];
                confResource = resource;
                break;
            }
        }

        if (confResource != null) {
            // By convention, if it ends in .xml, it's an XML-style url rewrite config, else it's a mod_rewrite-style
            // url rewrite config
            boolean modRewriteStyleConf = !confPath.endsWith(".xml");

            try (InputStream is = confResource.getInputStream()) {
                conf = new Conf(servletContext, is, confPath, "", modRewriteStyleConf);

                logger.info("URL rewrite configuration loaded @ " + confResource);
            }
        }

        if (conf != null) {
            if (conf.isOk() && conf.isEngineEnabled()) {
                urlRewriter = new UrlRewriter(conf);

                logger.info("URL rewrite engine loaded for site " + siteName + " (conf ok)");
            } else {
                logger.error("URL rewrite engine not loaded, there might have been conf errors");
            }
        }

        return urlRewriter;
    } catch (Exception e) {
        throw new SiteContextCreationException("Unable to load URL rewrite conf for site '" + siteName + "'", e);
    } finally {
        logger.info("--------------------------------------------------");
        logger.info("</Loading URL rewrite engine for site: " + siteName + ">");
        logger.info("--------------------------------------------------");
    }
}
 
Example 18
Source File: DynamicResourceMessageSource.java    From geekbang-lessons with Apache License 2.0 4 votes vote down vote up
private Resource getMessagePropertiesResource() {
    ResourceLoader resourceLoader = getResourceLoader();
    Resource resource = resourceLoader.getResource(resourcePath);
    return resource;
}
 
Example 19
Source File: TestPropertySourceUtils.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * Add the {@link Properties} files from the given resource {@code locations}
 * to the supplied {@link ConfigurableEnvironment environment}.
 * <p>Property placeholders in resource locations (i.e., <code>${...}</code>)
 * will be {@linkplain Environment#resolveRequiredPlaceholders(String) resolved}
 * against the {@code Environment}.
 * <p>Each properties file will be converted to a {@link ResourcePropertySource}
 * that will be added to the {@link PropertySources} of the environment with
 * highest precedence.
 * @param environment the environment to update; never {@code null}
 * @param resourceLoader the {@code ResourceLoader} to use to load each resource;
 * never {@code null}
 * @param locations the resource locations of {@code Properties} files to add
 * to the environment; potentially empty but never {@code null}
 * @throws IllegalStateException if an error occurs while processing a properties file
 * @since 4.3
 * @see ResourcePropertySource
 * @see TestPropertySource#locations
 * @see #addPropertiesFilesToEnvironment(ConfigurableApplicationContext, String...)
 */
public static void addPropertiesFilesToEnvironment(ConfigurableEnvironment environment,
		ResourceLoader resourceLoader, String... locations) {

	Assert.notNull(environment, "'environment' must not be null");
	Assert.notNull(resourceLoader, "'resourceLoader' must not be null");
	Assert.notNull(locations, "'locations' must not be null");
	try {
		for (String location : locations) {
			String resolvedLocation = environment.resolveRequiredPlaceholders(location);
			Resource resource = resourceLoader.getResource(resolvedLocation);
			environment.getPropertySources().addFirst(new ResourcePropertySource(resource));
		}
	}
	catch (IOException ex) {
		throw new IllegalStateException("Failed to add PropertySource to Environment", ex);
	}
}
 
Example 20
Source File: ResourceUtil.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
public static byte[] readResource(ResourceLoader applicationContext, String resourceLocation) throws IOException {
    Resource resource = applicationContext.getResource(resourceLocation);
    return StreamUtils.copyToByteArray(resource.getInputStream());
}