Example usage for org.springframework.core.io Resource exists

List of usage examples for org.springframework.core.io Resource exists

Introduction

In this page you can find the example usage for org.springframework.core.io Resource exists.

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:com.wavemaker.commons.classloader.ClassLoaderUtils.java

/**
 * Returns the File object associated with the given classpath-based path.
 * //from www . j  ava  2s .  co m
 * Note that this method won't work as expected if the file exists in a jar. This method will throw an IOException
 * in that case.
 * 
 * @param path The path to search for.
 * @return The File object associated with the given path.
 * @throws IOException
 */
public static Resource getClasspathFile(String path) throws IOException {
    Resource ret = new ClassPathResource(path);
    if (!ret.exists()) {
        // must have come from a jar or some other obscure location
        // that we didn't expect
        throw new IOException("Cannot access " + ret.toString());
    }
    return ret;
}

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
 *///w w w.j a  v  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:ch.algotrader.config.spring.ConfigLoader.java

/**
 * Loads system parameters.//w  w w.j  a v  a 2 s . c o m
 * <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:com.opengamma.elsql.ElSqlBundle.java

private static ElSqlBundle parseResource(Resource[] resources, ElSqlConfig config) {
    List<List<String>> files = new ArrayList<List<String>>();
    for (Resource resource : resources) {
        if (resource.exists()) {
            List<String> lines = loadResource(resource);
            files.add(lines);/*from  w  ww .ja  va 2 s .  c o  m*/
        }
    }
    return parse(files, config);
}

From source file:com.scf.core.context.app.cfg.module.ModuleConfigHandler.java

/**
 *
 * @param classPackage//from w  w w  . j  a v a2s  .  c  o  m
 * @param marges
 */
private static void loadModuleConfigs(String classPackage, Properties marges) {
    Resource[] resources = ClassScanner.scan(classPackage, "config.properties");
    for (Resource resource : resources) {
        try {
            if (!resource.exists()) {
                continue;
            }
            Properties props = new Properties();
            // ?file??
            String moduleName = resource.createRelative("/").getFilename();
            PropertiesLoaderUtils.fillProperties(props, new EncodedResource(resource, "utf-8"));
            ConfigParams cp = loadModuleConfig(marges, moduleName, props);
            _logger.info("Loaded module config for " + moduleName + " has " + cp.getParams().keySet().size()
                    + " properties.");
            map.put(moduleName, cp);
        } catch (IOException ex) {
            _logger.warn("Can not load module config for " + resource, ex);
        }
    }
}

From source file:com.hmsinc.epicenter.classifier.ClassifierFactory.java

/**
 * Creates a classifier using the given resource.
 * //from w w  w.  ja v a2  s .  co m
 * @param resource
 * @return classificationEngine
 */
public static ClassificationEngine createClassifier(final Resource resource) throws IOException {

    Validate.notNull(resource, "Resource was null!");
    if (!resource.exists()) {
        throw new IOException("Resource " + resource.toString() + " does not exist.");
    }

    ClassificationEngine engine = null;

    try {

        engine = instantiateClassifier(resource);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return engine;

}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * //from w w  w .j  a  v a 2s .c o  m
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * @param resources Array of String resources (filenames) to be copied
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 */
public static void copyResources(String[] resources, ClassPathResource cpr, String webAppDestPath)
        throws IOException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();
    for (int i = 0; i < resources.length; i++) {
        File dstFile = new File(dstPath, resources[i]); //    (StringUtils.applyRelativePath(dstPath, images[i]));
        Resource fileRes = cpr.createRelative(resources[i]);
        if (!dstFile.exists() && fileRes.exists()) {
            FileOutputStream fos = new FileOutputStream(dstFile);
            FileCopyUtils.copy(fileRes.getInputStream(), fos);
            logger.info("Successfully copied file " + fileRes.getFilename() + " from " + cpr.getPath() + " to "
                    + dstFile.getPath());
        }
    }
}

From source file:org.dspace.servicemanager.spring.ResourceFinder.java

private static Resource makeResource(String path) {
    if (path.startsWith("/")) {
        path = path.substring(1);//  www. j a  va  2s  .  c o  m
    }
    Resource r = findResource(path);
    if (!r.exists()) {
        // try to find just the fileName
        // get the fileName from the path
        int fileStart = path.lastIndexOf('/') + 1;
        String fileName = path.substring(fileStart);
        r = findResource(fileName);
    }
    // try the environment path first
    if (!r.exists()) {
        throw new IllegalArgumentException(
                "Could not find this resource (" + path + ") in any of the checked locations");
    }
    return r;
}

From source file:org.shept.util.JarUtils.java

/**
 * Copy resources from a classPath, typically within a jar file 
 * to a specified destination, typically a resource directory in
 * the projects webApp directory (images, sounds, e.t.c. )
 * //from  ww  w .  j av  a 2s  . c  o  m
 * Copies resources only if the destination file does not exist and
 * the specified resource is available.
 * 
 * The ClassPathResource will be scanned for all resources in the path specified by the resource.
 * For example  a path like:
 *    new ClassPathResource("resource/images/pager/", SheptBaseController.class);
 * takes all the resources in the path 'resource/images/pager' (but not in sub-path)
 * from the specified clazz 'SheptBaseController'
 * 
 * @param cpr ClassPathResource specifying the source location on the classPath (maybe within a jar)
 * @param webAppDestPath Full path String to the fileSystem destination directory   
 * @throws IOException when copying on copy error
 * @throws URISyntaxException 
 */
public static void copyResources(ClassPathResource cpr, String webAppDestPath)
        throws IOException, URISyntaxException {
    String dstPath = webAppDestPath; //  + "/" + jarPathInternal(cpr.getURL());
    File dir = new File(dstPath);
    dir.mkdirs();

    URL url = cpr.getURL();
    // jarUrl is the URL of the containing lib, e.g. shept.org in this case
    URL jarUrl = ResourceUtils.extractJarFileURL(url);
    String urlFile = url.getFile();
    String resPath = "";
    int separatorIndex = urlFile.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
    if (separatorIndex != -1) {
        // just copy the the location path inside the jar without leading separators !/
        resPath = urlFile.substring(separatorIndex + ResourceUtils.JAR_URL_SEPARATOR.length());
    } else {
        return; // no resource within jar to copy
    }

    File f = new File(ResourceUtils.toURI(jarUrl));
    JarFile jf = new JarFile(f);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        String path = entry.getName();
        if (path.startsWith(resPath) && entry.getSize() > 0) {
            String fileName = path.substring(path.lastIndexOf("/"));
            File dstFile = new File(dstPath, fileName); //  (StringUtils.applyRelativePath(dstPath, fileName));
            Resource fileRes = cpr.createRelative(fileName);
            if (!dstFile.exists() && fileRes.exists()) {
                FileOutputStream fos = new FileOutputStream(dstFile);
                FileCopyUtils.copy(fileRes.getInputStream(), fos);
                logger.info("Successfully copied file " + fileName + " from " + cpr.getPath() + " to "
                        + dstFile.getPath());
            }
        }
    }

    if (jf != null) {
        jf.close();
    }

}

From source file:com.google.api.ads.adwords.jaxws.extensions.kratu.KratuMain.java

/**
 * Initialize the application context, adding the properties configuration file depending on the
 * specified path.//from w w  w  .j ava  2  s .c o m
 *
 * @param propertiesPath the path to the file.
 * @return the resource loaded from the properties file.
 * @throws IOException error opening the properties file.
 */
private static Properties initApplicationContextAndProperties(String propertiesPath) throws IOException {

    Resource resource = new ClassPathResource(propertiesPath);
    if (!resource.exists()) {
        resource = new FileSystemResource(propertiesPath);
    }
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);

    Properties properties = PropertiesLoaderUtils.loadProperties(resource);
    String dbType = (String) properties.get(AW_REPORT_MODEL_DB_TYPE);
    if (dbType != null && dbType.equals(DataBaseType.MONGODB.name())) {
        appCtx = new ClassPathXmlApplicationContext("classpath:kratubackend-mongodb-beans.xml");
    } else {
        appCtx = new ClassPathXmlApplicationContext("classpath:kratubackend-sql-beans.xml");
    }

    return properties;
}