Example usage for org.springframework.core.io ResourceLoader getResource

List of usage examples for org.springframework.core.io ResourceLoader getResource

Introduction

In this page you can find the example usage for org.springframework.core.io ResourceLoader getResource.

Prototype

Resource getResource(String location);

Source Link

Document

Return a Resource handle for the specified resource location.

Usage

From source file:com.zekke.webapp.config.TestConfig.java

@Bean
public static PropertiesFactoryBean configProperties(ResourceLoader resourceLoader) throws IOException {
    PropertiesFactoryBean props = new PropertiesFactoryBean();
    props.setLocation(resourceLoader.getResource(CONFIG_PROPERTIES_URI));
    props.afterPropertiesSet();//from   ww w.  ja v a2  s  .c om
    return props;
}

From source file:com.trigonic.utils.spring.beans.ImportHelper.java

private static void importSingleAbsoluteResource(XmlBeanDefinitionReader reader, String location,
        Set<Resource> actualResources, ResourceLoader resourceLoader) {
    Resource resource = resourceLoader.getResource(location);
    if (resource.exists()) {
        int loadCount = reader.loadBeanDefinitions(resource);
        if (actualResources != null) {
            actualResources.add(resource);
        }//  w ww. j ava  2 s .c  om
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
        }
    }
}

From source file:com.zekke.webapp.config.MainConfig.java

/**
 * Creates a new Properties./*from   ww  w .  ja  v  a  2 s.  com*/
 *
 * @param resourceLoader any ResourceLoader.
 * @return a Properties.
 * @throws IOException if the properties file is not found in
 * {@link #CONFIG_PROPERTIES_URI}.
 */
@Bean
public static PropertiesFactoryBean configProperties(ResourceLoader resourceLoader) throws IOException {
    PropertiesFactoryBean props = new PropertiesFactoryBean();
    props.setLocation(resourceLoader.getResource(CONFIG_PROPERTIES_URI));
    props.afterPropertiesSet();
    return props;
}

From source file:com.netflix.genie.agent.cli.UserConsole.java

/**
 * Load and print the Spring banner (if one is configured) to UserConsole.
 *
 * @param environment the Spring environment
 *///from   w  w  w .  j av a 2s. c  o m
static void printBanner(final Environment environment) {
    try {
        final String bannerLocation = environment.getProperty(BANNER_LOCATION_SPRING_PROPERTY_KEY);
        if (StringUtils.isNotBlank(bannerLocation)) {
            final ResourceLoader resourceLoader = new DefaultResourceLoader();
            final Resource resource = resourceLoader.getResource(bannerLocation);
            if (resource.exists()) {
                final String banner = StreamUtils.copyToString(resource.getInputStream(),
                        environment.getProperty(BANNER_CHARSET_SPRING_PROPERTY_KEY, Charset.class,
                                StandardCharsets.UTF_8));
                UserConsole.getLogger().info(banner);
            }
        }
    } catch (final Throwable t) {
        System.err.println("Failed to print banner: " + t.getMessage());
        t.printStackTrace(System.err);
    }
}

From source file:lichen.orm.LichenOrmModule.java

public static DataSource buildDataSource(@Symbol(LichenOrmSymbols.DATABASE_CFG_FILE) String dbCfgFile,
        RegistryShutdownHub shutdownHub) throws IOException, ProxoolException {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    Resource resource = resourceLoader.getResource(dbCfgFile);
    Properties info = new Properties();
    info.load(resource.getInputStream());
    PropertyConfigurator.configure(info);

    String poolNameKey = F.flow(info.keySet()).filter(new Predicate<Object>() {
        public boolean accept(Object element) {
            return element.toString().contains("alias");
        }//from   w  w w. j a  v a 2s  .c  o  m
    }).first().toString();

    if (poolNameKey == null) {
        throw new RuntimeException("?poolName");
    }
    final String poolName = info.getProperty(poolNameKey);

    //new datasource
    ProxoolDataSource ds = new ProxoolDataSource(poolName);
    //register to shutdown
    shutdownHub.addRegistryShutdownListener(new RegistryShutdownListener() {
        public void registryDidShutdown() {
            Flow<?> flow = F.flow(ProxoolFacade.getAliases()).filter(new Predicate<String>() {
                public boolean accept(String element) {
                    return element.equals(poolName);
                }
            });
            if (flow.count() == 1) {
                try {
                    ProxoolFacade.removeConnectionPool(poolName);
                } catch (ProxoolException e) {
                    //do nothing
                }
            }
        }
    });
    return ds;
}

From source file:io.spring.initializr.util.TemplateRenderer.java

private static TemplateLoader mustacheTemplateLoader() {
    ResourceLoader resourceLoader = new DefaultResourceLoader();
    String prefix = "classpath:/templates/";
    Charset charset = Charset.forName("UTF-8");
    return (name) -> new InputStreamReader(resourceLoader.getResource(prefix + name).getInputStream(), charset);
}

From source file:sf.wicklet.gwt.site.server.db.H2Configurator.java

/** @param dbpath Absolute path relative to web application context root. */
public static EmbeddedDatabase createDatabase(final String dbpath, final String... initscripts)
        throws ClassNotFoundException {
    final EmbeddedDatabaseFactory f = new EmbeddedDatabaseFactory();
    final ResourceDatabasePopulator p = new ResourceDatabasePopulator();
    final ResourceLoader l = new DefaultResourceLoader();
    final IWickletSupport support = Config.get().getSupport();
    final File dbfile = support.getContextFile(dbpath + ".h2.db");
    if (!dbfile.exists()) {
        for (final String s : initscripts) {
            p.addScript(l.getResource("file:" + support.getContextFile(s).getAbsolutePath()));
        }/*w w w . j  av a 2s.  com*/
    }
    f.setDatabasePopulator(p);
    f.setDatabaseConfigurer(H2Configurator.getInstance(support.getContextFile(dbpath).getAbsolutePath()));
    // Database name is actually a don't care.
    f.setDatabaseName(TextUtil.fileName(dbpath));
    return f.getDatabase();
}

From source file:ar.com.zauber.commons.spring.configurers.JndiInitialContextHelper.java

/** dado paths jndi retorna archivos de propiedades */
public static Resource[] getJndiLocations(final String[] filePathJndiNames) {

    final ResourceLoader resourceLoader = new DefaultResourceLoader();

    try {//from  w  w  w .  j a va 2 s .com
        final InitialContext initCtx = new InitialContext();
        final Resource[] locations = new Resource[filePathJndiNames.length];
        boolean found = false;

        try {
            final Context envCtx = (Context) initCtx.lookup("java:comp/env");
            for (int i = 0; i < filePathJndiNames.length; i++) {
                locations[i] = resourceLoader.getResource((String) envCtx.lookup(filePathJndiNames[i]));
            }
            found = true;
        } catch (final NamingException e) {
            LOGGER.warn("Error JNDI looking up 'java:comp/env':" + e.getExplanation());
            // void
        }

        if (!found) {
            // Para Jetty 7 Server
            try {
                for (int i = 0; i < filePathJndiNames.length; i++) {
                    locations[i] = resourceLoader.getResource((String) initCtx.lookup(filePathJndiNames[i]));
                }
            } catch (final NamingException e) {
                LOGGER.warn("Hubo un error en el lookup de JNDI. Se usaran " + "properties del classpath: "
                        + e.getExplanation());
                return null;
            }
        }

        return locations;
    } catch (final NamingException e) {
        LOGGER.warn("Hubo un error en el lookup de JNDI. Se usaran " + "properties del classpath: "
                + e.getExplanation());
        return null;
    }
}

From source file:ch.algotrader.config.spring.ConfigLoader.java

/**
 * Loads system parameters.//from  w ww.  jav  a 2  s  .  c  om
 * <ul>
 * <li>conf.properties</li>
 * <li>conf-core.properties</li>
 * <li>conf-fix.properties</li>
 * <li>conf-ib.properties</li>
 * <li>conf-bb.properties</li>
 * </ul>
 */
public static Map<String, String> load(final ResourceLoader resourceResolver) throws IOException {

    Assert.notNull(resourceResolver, "ResourcePatternResolver is null");

    Map<String, String> paramMap = new LinkedHashMap<>();
    String[] resourceNames = new String[] { "conf.properties", "conf-core.properties", "conf-fix.properties",
            "conf-ib.properties", "conf-bb.properties" };
    for (String resourceName : resourceNames) {
        Resource resource = resourceResolver.getResource("classpath:/" + resourceName);
        if (resource != null && resource.exists()) {
            ConfigLoader.loadResource(paramMap, resource);
        }
    }

    String strategyName = System.getProperty("strategyName");
    if (strategyName != null) {

        Resource resource = resourceResolver
                .getResource("classpath:/conf-" + strategyName.toLowerCase(Locale.ROOT) + ".properties");
        if (resource != null && resource.exists()) {
            ConfigLoader.loadResource(paramMap, resource);
        }
    }

    return paramMap;
}

From source file:org.springextensions.db4o.io.ResourceStorageTest.java

@Test
public void testExists() {
    String uri = "resource";

    Resource resource = mock(Resource.class);
    when(resource.exists()).thenReturn(true);

    ResourceLoader resourceLoader = mock(ResourceLoader.class);
    when(resourceLoader.getResource(uri)).thenReturn(resource);

    ResourceStorage resourceStorage = new ResourceStorage();
    resourceStorage.setResourceLoader(resourceLoader);

    Assert.assertTrue(resourceStorage.exists(uri));
}