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.jpoweredcart.common.mock.servlet.MockServletContext.java

public InputStream getResourceAsStream(String path) {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }/*from   w ww  . j a  v  a  2 s. c o m*/
    try {
        return resource.getInputStream();
    } catch (IOException ex) {
        logger.warn("Couldn't open InputStream for " + resource, ex);
        return null;
    }
}

From source file:com.jpoweredcart.common.mock.servlet.MockServletContext.java

public URL getResource(String path) throws MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }//  w  ww .j  a  va2 s  . com
    try {
        return resource.getURL();
    } catch (MalformedURLException ex) {
        throw ex;
    } catch (IOException ex) {
        logger.warn("Couldn't get URL for " + resource, ex);
        return null;
    }
}

From source file:com.gzj.tulip.jade.context.spring.JadeComponentProvider.java

/**
 * jar?JadeDAO?//from   w  ww. j a  v a2 s .  c  o  m
 * <p>
 * ?BeanDefinition?DAO??
 * {@link BeanDefinition#getBeanClassName()} DAO???
 * <p>
 * BeanDefinition??Spring???
 */
public Set<BeanDefinition> findCandidateComponents(String uriPrefix) {
    if (!uriPrefix.endsWith("/")) {
        uriPrefix = uriPrefix + "/";
    }
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = uriPrefix + this.resourcePattern;
        boolean traceEnabled = logger.isDebugEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        if (debugEnabled) {
            logger.debug("[jade/find] find " + resources.length + " resources for " + packageSearchPath);
        }
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (traceEnabled) {
                logger.trace("[jade/find] scanning " + resource);
            }
            // resourcePatternResolver.getResources?classPathResourcesmetadataReadergetInputStreamnull
            // ???exists
            if (!resource.exists()) {
                if (debugEnabled) {
                    logger.debug("Ignored because not exists:" + resource);
                }
            } else if (resource.isReadable()) {
                MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                if (isCandidateComponent(metadataReader)) {
                    ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                    sbd.setResource(resource);
                    sbd.setSource(resource);
                    if (sbd.getMetadata().isInterface() && sbd.getMetadata().isIndependent()) {
                        if (debugEnabled) {
                            logger.debug("Identified candidate component class: " + resource);
                        }
                        candidates.add(sbd);
                    } else {
                        if (traceEnabled) {
                            logger.trace("Ignored because not a interface top-level class: " + resource);
                        }
                    }
                } else {
                    if (traceEnabled) {
                        logger.trace("Ignored because not matching any filter: " + resource);
                    }
                }
            } else {
                if (traceEnabled) {
                    logger.trace("Ignored because not readable: " + resource);
                }
            }
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during jade scanning", ex);
    }
    return candidates;
}

From source file:net.solarnetwork.node.dao.jdbc.AbstractJdbcDao.java

/**
 * Load a classpath SQL resource into a String.
 * /*from  w  w  w .  j a v  a2  s . co m*/
 * <p>
 * The classpath resource is taken as the {@link #getSqlResourcePrefix()}
 * value and {@code -} and the {@code classPathResource} combined with a
 * {@code .sql} suffix. If that resoruce is not found, then the prefix is
 * split into components separated by a {@code -} character, and the last
 * component is dropped and then combined with {@code -} and
 * {@code classPathResource} again to try to find a match, until there is no
 * prefix left and just the {@code classPathResource} itself is tried.
 * </p>
 * 
 * <p>
 * This method will cache the SQL resource in-memory for quick future
 * access.
 * </p>
 * 
 * @param string
 *        the classpath resource to load as a SQL string
 * @return the String
 */
protected String getSqlResource(String classPathResource) {
    Class<?> myClass = getClass();
    String resourceName = getSqlResourcePrefix() + "-" + classPathResource + ".sql";
    String key = myClass.getName() + ";" + classPathResource;
    if (sqlResourceCache.containsKey(key)) {
        return sqlResourceCache.get(key);
    }
    String[] prefixes = getSqlResourcePrefix().split("-");
    int prefixEndIndex = prefixes.length - 1;
    try {
        Resource r = new ClassPathResource(resourceName, myClass);
        while (!r.exists() && prefixEndIndex >= 0) {
            // try by chopping down prefix, which we split on a dash character
            String subName;
            if (prefixEndIndex > 0) {
                String[] subPrefixes = new String[prefixEndIndex];
                System.arraycopy(prefixes, prefixEndIndex, subPrefixes, 0, prefixEndIndex);
                subName = StringUtils.arrayToDelimitedString(subPrefixes, "-") + "-" + classPathResource;
            } else {
                subName = classPathResource;
            }
            subName += ".sql";
            r = new ClassPathResource(subName, myClass);
            prefixEndIndex--;
        }
        if (!r.exists()) {
            throw new RuntimeException("SQL resource " + resourceName + " not found");
        }
        String result = FileCopyUtils.copyToString(new InputStreamReader(r.getInputStream()));
        if (result != null && result.length() > 0) {
            sqlResourceCache.put(key, result);
        }
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wavemaker.tools.project.LocalStudioFileSystem.java

@Override
public Resource createPath(Resource resource, String path) {
    Assert.isInstanceOf(FileSystemResource.class, resource, "Expected a FileSystemResource");
    try {/*  w  w  w .ja va2s. co  m*/
        if (!resource.exists()) {
            File rootFile = resource.getFile();
            while (rootFile.getAbsolutePath().length() > 1 && !rootFile.exists()) {
                rootFile = rootFile.getParentFile();
            }
            IOUtils.makeDirectories(resource.getFile(), rootFile);
        }
        FileSystemResource relativeResource = (FileSystemResource) resource.createRelative(path);
        if (!relativeResource.exists()) {
            if (relativeResource.getPath().endsWith("/")) {
                IOUtils.makeDirectories(relativeResource.getFile(), resource.getFile());
            } else {
                IOUtils.makeDirectories(relativeResource.getFile().getParentFile(), resource.getFile());
            }
        }
        return relativeResource;
    } catch (IOException ex) {
        throw new WMRuntimeException(ex);
    }
}

From source file:org.cloudfoundry.identity.uaa.config.YamlServletProfileInitializer.java

private Resource getResource(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext, String locations) {
    Resource resource = null;
    String[] configFileLocations = locations == null ? DEFAULT_PROFILE_CONFIG_FILE_LOCATIONS
            : StringUtils.commaDelimitedListToStringArray(locations);
    for (String location : configFileLocations) {
        location = applicationContext.getEnvironment().resolvePlaceholders(location);
        servletContext.log("Testing for YAML resources at: " + location);
        resource = applicationContext.getResource(location);
        if (resource != null && resource.exists()) {
            break;
        }/* www.  ja  va 2 s.  c  o m*/
    }
    return resource;
}

From source file:com.wantscart.jade.core.JadeDaoComponentProvider.java

/**
 * Scan the class path for candidate components.
 * //from   www  .  j  av a2  s . c  om
 *  basePackage the package to check for annotated classes
 *  a corresponding Set of autodetected bean definitions
 */
public Set<BeanDefinition> findCandidateComponents(String uriPrefix) {
    if (!uriPrefix.endsWith("/")) {
        uriPrefix = uriPrefix + "/";
    }
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = uriPrefix + this.resourcePattern;
        boolean traceEnabled = logger.isDebugEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        if (debugEnabled) {
            logger.debug("[jade/find] find " + resources.length + " resources for " + packageSearchPath);
        }
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (traceEnabled) {
                logger.trace("[jade/find] scanning " + resource);
            }
            // resourcePatternResolver.getResources?classPathResourcesmetadataReadergetInputStreamnull
            // ???exists
            if (!resource.exists()) {
                if (debugEnabled) {
                    logger.debug("Ignored because not exists:" + resource);
                }
            } else if (resource.isReadable()) {
                MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
                if (isCandidateComponent(metadataReader)) {
                    ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                    sbd.setResource(resource);
                    sbd.setSource(resource);
                    if (isCandidateComponent(sbd)) {
                        if (debugEnabled) {
                            logger.debug("Identified candidate component class: " + resource);
                        }
                        candidates.add(sbd);
                    } else {
                        if (traceEnabled) {
                            logger.trace("Ignored because not a interface top-level class: " + resource);
                        }
                    }
                } else {
                    if (traceEnabled) {
                        logger.trace("Ignored because not matching any filter: " + resource);
                    }
                }
            } else {
                if (traceEnabled) {
                    logger.trace("Ignored because not readable: " + resource);
                }
            }
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during jade scanning", ex);
    }
    return candidates;
}

From source file:org.paxml.table.csv.CsvTable.java

public CsvTable(Resource res, CsvOptions opt, ITableRange range) {
    if (opt == null) {
        opt = new CsvOptions();
    }/*from  w  w  w.j a  va  2  s .com*/
    this.res = res;
    this.opt = opt;

    CsvPreference pref = opt.toPreference();

    if (res.exists()) {
        try {
            reader = new CsvListReader(
                    new InputStreamReader(new BOMInputStream(res.getInputStream()), opt.getEncoding()), pref);
        } catch (IOException e) {
            throw new PaxmlRuntimeException("Cannot read csv file: " + PaxmlUtils.getResourceFile(res), e);
        }
    } else {
        reader = null;
    }
    List<String> cols = opt.getColumns();
    if (cols == null) {
        // detect headers from file
        headers = new LinkedHashMap<String, IColumn>();
        if (reader != null) {
            String[] h;
            try {
                h = reader.getHeader(true);
            } catch (IOException e) {
                throw new PaxmlRuntimeException(
                        "Cannot read csv file header: " + PaxmlUtils.getResourceFile(res), e);
            }
            if (h != null) {
                for (String s : h) {
                    addColumn(s);
                }
            }
        }
    } else if (cols.isEmpty()) {
        headers = null;
    } else {
        // given header, skip existing header too
        if (reader != null) {
            try {
                reader.getHeader(true);
            } catch (IOException e) {
                throw new PaxmlRuntimeException(
                        "Cannot read csv file header: " + PaxmlUtils.getResourceFile(res), e);
            }
        }
        headers = new LinkedHashMap<String, IColumn>();
        for (String col : cols) {
            addColumn(col);
        }
    }
    CsvListWriter w = null;
    if (!opt.isReadOnly()) {
        writerFile = getWriterFile(res);
        if (writerFile != null) {

            try {
                w = new CsvListWriter(new FileWriter(reader == null ? res.getFile() : writerFile), pref);
                if (headers != null && !headers.isEmpty()) {
                    w.writeHeader(headers.keySet().toArray(new String[headers.size()]));
                }
            } catch (IOException e) {
                // do nothing, because this means writer cannot write to the
                // file.
            }

        }
    } else {
        writerFile = null;
    }
    writer = w;

    if (reader == null && writer == null) {
        throw new PaxmlRuntimeException(
                "Can neither read from nor write to csv file: " + PaxmlUtils.getResourceFile(res));
    }

    setRange(range);
}

From source file:com.wavemaker.runtime.WMAppContext.java

private WMAppContext(ServletContextEvent event) {
    this.context = event.getServletContext();
    this.appName = this.context.getServletContextName();
    if (this.appName == null) {
        this.appName = "Project Name";
    }//from  w  w w. ja v a2s  .  c o m

    // In Studio, the tenant field and def tenant ID is injected by ProjectManager when a project opens
    if (!this.appName.equals(DataServiceConstants.WAVEMAKER_STUDIO)) {
        // Store types.js contents in memory
        try {
            Resource typesResource = new ServletContextResource(this.context, "/types.js");
            String s = IOUtils.toString(typesResource.getInputStream());
            this.typesObj = new JSONObject(s.substring(11));
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Set up multi-tenant info
        Resource appPropsResource = null;
        try {
            appPropsResource = new ServletContextResource(this.context,
                    "/WEB-INF/" + CommonConstants.APP_PROPERTY_FILE);
        } catch (WMRuntimeException re) {
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        if (!appPropsResource.exists()) {
            return;
        }

        Properties props;

        try {
            props = new Properties();
            InputStream is = appPropsResource.getInputStream();
            props.load(is);
            is.close();
        } catch (IOException ioe) {
            ioe.printStackTrace();
            return;
        }

        this.tenantFieldName = props.getProperty(DataServiceConstants.TENANT_FIELD_PROPERTY_NAME);
        this.tenantColumnName = props.getProperty(DataServiceConstants.TENANT_COLUMN_PROPERTY_NAME);
        this.defaultTenantID = Integer
                .parseInt(props.getProperty(DataServiceConstants.DEFAULT_TENANT_ID_PROPERTY_NAME));
    }
}

From source file:com.cloudseal.spring.client.namespace.CloudSealBeanDefinitionParserInstance.java

private Resource getResourceFromLocation(String location) {
    Resource resource = parserContext.getReaderContext().getResourceLoader().getResource(location);
    if (!resource.exists()) {
        throw new IllegalStateException("Cannot find resource: " + location);
    }//from w  w w.ja va 2s . co m
    return resource;
}