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

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

Introduction

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

Prototype

default boolean isReadable() 

Source Link

Document

Indicate whether non-empty contents of this resource can be read via #getInputStream() .

Usage

From source file:org.springframework.cloud.config.server.resource.GenericResourceRepository.java

@Override
public synchronized Resource findOne(String application, String profile, String label, String path) {

    if (StringUtils.hasText(path)) {
        String[] locations = this.service.getLocations(application, profile, label).getLocations();
        try {/*from w ww .  ja va 2  s  .c  om*/
            for (int i = locations.length; i-- > 0;) {
                String location = locations[i];
                for (String local : getProfilePaths(profile, path)) {
                    if (!isInvalidPath(local) && !isInvalidEncodedPath(local)) {
                        Resource file = this.resourceLoader.getResource(location).createRelative(local);
                        if (file.exists() && file.isReadable()) {
                            return file;
                        }
                    }
                }
            }
        } catch (IOException e) {
            throw new NoSuchResourceException("Error : " + path + ". (" + e.getMessage() + ")");
        }
    }
    throw new NoSuchResourceException("Not found: " + path);
}

From source file:org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.java

private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
    Set<BeanDefinition> candidates = new LinkedHashSet<>();
    try {/* ww  w. j a  v  a 2 s  .c  o m*/
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + resolveBasePackage(basePackage) + '/' + this.resourcePattern;
        Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
        boolean traceEnabled = logger.isTraceEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        for (Resource resource : resources) {
            if (traceEnabled) {
                logger.trace("Scanning " + resource);
            }
            if (resource.isReadable()) {
                try {
                    MetadataReader metadataReader = getMetadataReaderFactory().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 (debugEnabled) {
                                logger.debug("Ignored because not a concrete top-level class: " + resource);
                            }
                        }
                    } else {
                        if (traceEnabled) {
                            logger.trace("Ignored because not matching any filter: " + resource);
                        }
                    }
                } catch (Throwable ex) {
                    throw new BeanDefinitionStoreException(
                            "Failed to read candidate component class: " + resource, ex);
                }
            } else {
                if (traceEnabled) {
                    logger.trace("Ignored because not readable: " + resource);
                }
            }
        }
    } catch (IOException ex) {
        throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
    }
    return candidates;
}

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
 *//* w w w.  j a  v a2 s. 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.orm.jpa.persistenceunit.DefaultPersistenceUnitManager.java

private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
    if (this.componentsIndex != null) {
        Set<String> candidates = new HashSet<>();
        for (AnnotationTypeFilter filter : entityTypeFilters) {
            candidates/*w  w  w. j  a v a2 s. c o m*/
                    .addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
        }
        candidates.forEach(scannedUnit::addManagedClassName);
        Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
        managedPackages.forEach(scannedUnit::addManagedPackage);
        return;
    }

    try {
        String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(pattern);
        MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver);
        for (Resource resource : resources) {
            if (resource.isReadable()) {
                MetadataReader reader = readerFactory.getMetadataReader(resource);
                String className = reader.getClassMetadata().getClassName();
                if (matchesFilter(reader, readerFactory)) {
                    scannedUnit.addManagedClassName(className);
                    if (scannedUnit.getPersistenceUnitRootUrl() == null) {
                        URL url = resource.getURL();
                        if (ResourceUtils.isJarURL(url)) {
                            scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
                        }
                    }
                } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
                    scannedUnit.addManagedPackage(
                            className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
                }
            }
        }
    } catch (IOException ex) {
        throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
    }
}

From source file:org.springframework.web.servlet.resource.PathResourceResolver.java

private Resource getResource(String path, List<? extends Resource> locations) {
    for (Resource location : locations) {
        try {//  w  ww.  ja v a  2  s  .c o m
            if (logger.isTraceEnabled()) {
                logger.trace("Checking location=[" + location + "]");
            }
            Resource resource = location.createRelative(path);
            if (resource.exists() && resource.isReadable()) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Found match");
                }
                return resource;
            } else if (logger.isTraceEnabled()) {
                logger.trace("No match");
            }
        } catch (IOException ex) {
            logger.trace("Failure checking for relative resource. Trying next location.", ex);
        }
    }
    return null;
}

From source file:ru.kwanza.dbtool.orm.impl.mapping.SpringEntityMappingRegistryImpl.java

private void scanPackage(String basePackage) {
    try {//ww  w . j  a v a 2  s .  co m
        final String packageSearchPath = createPackageSearchPath(basePackage);
        final Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        for (Resource resource : resources) {
            if (log.isTraceEnabled()) {
                log.trace("Scanning " + resource);
            }
            if (resource.isReadable()) {
                try {
                    final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
                    final ClassMetadata classMetadata = metadataReader.getClassMetadata();
                    final String className = classMetadata.getClassName();
                    if (!classMetadata.isAbstract()
                            && !Enum.class.getName().equals(classMetadata.getSuperClassName())) {
                        log.trace(className);
                        final ClassLoader classLoader = resourcePatternResolver.getClassLoader();
                        Class<?> entityClass = classLoader.loadClass(className);
                        if (entityClass.isAnnotationPresent(Entity.class)
                                || entityClass.isAnnotationPresent(AbstractEntity.class)) {
                            delegate.registerEntityClass(entityClass);
                        }
                    }
                } catch (Throwable e) {
                    throw new RuntimeException("Error while registering entity mapping: " + resource, e);
                }
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Ignored because not readable: " + resource);
                }
            }
        }
    } catch (IOException e) {
        throw new RuntimeException("I/O failure during classpath scanning", e);
    }
}

From source file:software.coolstuff.springframework.owncloud.service.impl.local.OwncloudLocalUserDataServiceImpl.java

@Override
public void afterPropertiesSet() throws Exception {
    log.debug("Load Resource from Location {}", properties.getLocation());
    Resource resource = resourceLoader.getResource(properties.getLocation());
    Validate.notNull(resource);//from w w w.  ja  va2s  .  c  o m
    Validate.isTrue(resource.exists());
    Validate.isTrue(resource.isReadable());

    log.debug("Read the Resource {} to the Class {}", resource.getFilename(),
            OwncloudLocalUserData.class.getName());
    OwncloudLocalUserData resourceData = xmlMapper.readValue(resource.getInputStream(),
            OwncloudLocalUserData.class);
    checkGroupReferences(resourceData);

    log.trace("Clear the Users Map");
    users.clear();

    log.debug("Read the Users as a Map");
    if (CollectionUtils.isNotEmpty(resourceData.getUsers())) {
        for (OwncloudLocalUserData.User user : resourceData.getUsers()) {
            users.put(user.getUsername(), user);
        }
    }

    log.trace("Clear the Groups Map");
    groups.clear();
    log.debug("Read the Groups as a Map");
    if (CollectionUtils.isNotEmpty(resourceData.getGroups())) {
        groups.addAll(resourceData.getGroups());
    }

    log.info("User Information from Resource Location {} successfully loaded", properties.getLocation());
}