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:org.springframework.integration.xquery.support.XQueryUtils.java

/**
 * Reads the XQuery string from the resource file specified
 *
 * @param resource the {@link Resource} instance of the file that contains the XQuery
 *          currently only classpath and file resources are supported
 *
 * @return the XQuery string from the resource specified
 *//*from  w  ww  .  ja  v a  2s . co  m*/
public static String readXQueryFromResource(Resource resource) {
    Assert.notNull(resource, "null resource provided");
    Assert.isTrue(resource.exists(), "Provided XQuery resource does not exist");
    Assert.isTrue(resource.isReadable(), "Provided XQuery resource is not readable");
    BufferedReader reader = null;
    try {
        URL url = resource.getURL();
        InputStream inStream = url.openStream();
        reader = new BufferedReader(new InputStreamReader(inStream));
        String line = reader.readLine();
        StringBuilder builder = new StringBuilder();
        while (line != null) {
            builder.append(line).append("\n");
            line = reader.readLine();
        }
        String xQuery = builder.toString();
        reader.close();
        return xQuery;
    } catch (IOException e) {
        throw new MessagingException("Error while reading the xQuery resource", e);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                logger.error("Exception while closing reader", e);
            }
        }
    }
}

From source file:org.springframework.jdbc.support.SQLErrorCodesFactory.java

/**
 * Create a new instance of the {@link SQLErrorCodesFactory} class.
 * <p>Not public to enforce Singleton design pattern. Would be private
 * except to allow testing via overriding the
 * {@link #loadResource(String)} method.
 * <p><b>Do not subclass in application code.</b>
 * @see #loadResource(String)/*  w  w  w  .java  2 s  .  c  o  m*/
 */
protected SQLErrorCodesFactory() {
    Map<String, SQLErrorCodes> errorCodes;

    try {
        DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
        lbf.setBeanClassLoader(getClass().getClassLoader());
        XmlBeanDefinitionReader bdr = new XmlBeanDefinitionReader(lbf);

        // Load default SQL error codes.
        Resource resource = loadResource(SQL_ERROR_CODE_DEFAULT_PATH);
        if (resource != null && resource.exists()) {
            bdr.loadBeanDefinitions(resource);
        } else {
            logger.warn("Default sql-error-codes.xml not found (should be included in spring.jar)");
        }

        // Load custom SQL error codes, overriding defaults.
        resource = loadResource(SQL_ERROR_CODE_OVERRIDE_PATH);
        if (resource != null && resource.exists()) {
            bdr.loadBeanDefinitions(resource);
            logger.info("Found custom sql-error-codes.xml file at the root of the classpath");
        }

        // Check all beans of type SQLErrorCodes.
        errorCodes = lbf.getBeansOfType(SQLErrorCodes.class, true, false);
        if (logger.isInfoEnabled()) {
            logger.info("SQLErrorCodes loaded: " + errorCodes.keySet());
        }
    } catch (BeansException ex) {
        logger.warn("Error loading SQL error codes from config file", ex);
        errorCodes = Collections.emptyMap();
    }

    this.errorCodesMap = errorCodes;
}

From source file:org.springframework.mock.web.MockServletContext.java

@Override
@Nullable//  w  ww .  j  ava2s .co m
public URL getResource(String path) throws MalformedURLException {
    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
    if (!resource.exists()) {
        return null;
    }
    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:org.springframework.mock.web.MockServletContext.java

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

From source file:org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

/**
 * Determine JPA's default "META-INF/orm.xml" resource for use with Spring's default
 * persistence unit, if any./*from  w w w.java 2  s.co  m*/
 * <p>Checks whether a "META-INF/orm.xml" file exists in the classpath and uses it
 * if it is not co-located with a "META-INF/persistence.xml" file.
 */
@Nullable
private Resource getOrmXmlForDefaultPersistenceUnit() {
    Resource ormXml = this.resourcePatternResolver
            .getResource(this.defaultPersistenceUnitRootLocation + DEFAULT_ORM_XML_RESOURCE);
    if (ormXml.exists()) {
        try {
            Resource persistenceXml = ormXml.createRelative(PERSISTENCE_XML_FILENAME);
            if (!persistenceXml.exists()) {
                return ormXml;
            }
        } catch (IOException ex) {
            // Cannot resolve relative persistence.xml file - let's assume it's not there.
            return ormXml;
        }
    }
    return null;
}

From source file:org.springframework.orm.jpa.persistenceunit.PersistenceUnitReader.java

/**
 * Parse the {@code jar-file} XML elements.
 *///from w ww  .  ja v a  2s.co  m
protected void parseJarFiles(Element persistenceUnit, SpringPersistenceUnitInfo unitInfo) throws IOException {
    List<Element> jars = DomUtils.getChildElementsByTagName(persistenceUnit, JAR_FILE_URL);
    for (Element element : jars) {
        String value = DomUtils.getTextValue(element).trim();
        if (StringUtils.hasText(value)) {
            Resource[] resources = this.resourcePatternResolver.getResources(value);
            boolean found = false;
            for (Resource resource : resources) {
                if (resource.exists()) {
                    found = true;
                    unitInfo.addJarFileUrl(resource.getURL());
                }
            }
            if (!found) {
                // relative to the persistence unit root, according to the JPA spec
                URL rootUrl = unitInfo.getPersistenceUnitRootUrl();
                if (rootUrl != null) {
                    unitInfo.addJarFileUrl(new URL(rootUrl, value));
                } else {
                    logger.warn("Cannot resolve jar-file entry [" + value + "] in persistence unit '"
                            + unitInfo.getPersistenceUnitName() + "' without root URL");
                }
            }
        }
    }
}

From source file:org.springframework.osgi.test.internal.util.jar.JarCreator.java

/**
 * Resources' root path (the root path does not become part of the jar).
 * /*from  w w w  .  j a va  2 s . c om*/
 * @return the root path
 */
public String determineRootPath() {
    // load file using absolute path. This seems to be necessary in IntelliJ
    try {
        ResourceLoader fileLoader = new DefaultResourceLoader();
        Resource res = fileLoader.getResource(getClass().getName().replace('.', '/').concat(".class"));
        String fileLocation = "file://" + res.getFile().getAbsolutePath();
        fileLocation = fileLocation.substring(0, fileLocation.indexOf(TEST_CLASSES_DIR)) + TEST_CLASSES_DIR;
        if (res.exists()) {
            return fileLocation;
        }
    } catch (Exception e) {
    }

    return "file:./target/" + TEST_CLASSES_DIR;
}

From source file:org.springframework.scheduling.quartz.ResourceLoaderClassLoadHelper.java

@Override
@Nullable/*from   ww  w .j av a2 s.c  o  m*/
public URL getResource(String name) {
    Assert.state(this.resourceLoader != null, "ResourceLoaderClassLoadHelper not initialized");
    Resource resource = this.resourceLoader.getResource(name);
    if (resource.exists()) {
        try {
            return resource.getURL();
        } catch (IOException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Could not load " + resource);
            }
            return null;
        }
    } else {
        return getClassLoader().getResource(name);
    }
}

From source file:org.springframework.scheduling.quartz.ResourceLoaderClassLoadHelper.java

@Override
@Nullable//from  w  w w . ja  v a2  s .co  m
public InputStream getResourceAsStream(String name) {
    Assert.state(this.resourceLoader != null, "ResourceLoaderClassLoadHelper not initialized");
    Resource resource = this.resourceLoader.getResource(name);
    if (resource.exists()) {
        try {
            return resource.getInputStream();
        } catch (IOException ex) {
            if (logger.isWarnEnabled()) {
                logger.warn("Could not load " + resource);
            }
            return null;
        }
    } else {
        return getClassLoader().getResourceAsStream(name);
    }
}

From source file:org.springframework.ui.freemarker.SpringTemplateLoader.java

@Override
@Nullable/*from ww w. j  a v  a 2  s.  com*/
public Object findTemplateSource(String name) throws IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Looking for FreeMarker template with name [" + name + "]");
    }
    Resource resource = this.resourceLoader.getResource(this.templateLoaderPath + name);
    return (resource.exists() ? resource : null);
}