Java Code Examples for org.springframework.core.io.Resource#isReadable()

The following examples show how to use org.springframework.core.io.Resource#isReadable() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory(applicationContext);
	DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) beanFactory;
	String resolvedPath = resolvePackageToScan();
	logger.debug("Scanning '{}' for JSON-RPC service interfaces.", resolvedPath);
	try {
		for (Resource resource : applicationContext.getResources(resolvedPath)) {
			if (resource.isReadable()) {
				MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
				ClassMetadata classMetadata = metadataReader.getClassMetadata();
				AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
				String jsonRpcPathAnnotation = JsonRpcService.class.getName();
				if (annotationMetadata.isAnnotated(jsonRpcPathAnnotation)) {
					String className = classMetadata.getClassName();
					String path = (String) annotationMetadata.getAnnotationAttributes(jsonRpcPathAnnotation).get("value");
					logger.debug("Found JSON-RPC service to proxy [{}] on path '{}'.", className, path);
					registerJsonProxyBean(defaultListableBeanFactory, className, path);
				}
			}
		}
	} catch (IOException e) {
		throw new IllegalStateException(format("Cannot scan package '%s' for classes.", resolvedPath), e);
	}
}
 
Example 2
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new StorageFileNotFoundException(
                    "Could not read file: " + filename);

        }
    }
    catch (MalformedURLException e) {
        throw new StorageFileNotFoundException("Could not read file: " + filename, e);
    }
}
 
Example 3
Source Project: code-examples   File: FileSystemStorageService.java    License: MIT License 6 votes vote down vote up
@Override
public Resource loadAsResource(String filename) {
    try {
        Path file = load(filename);
        Resource resource = new UrlResource(file.toUri());
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
        else {
            throw new FileNotFoundException(
                    "Could not read file: " + filename);
        }
    }
    catch (MalformedURLException e) {
        throw new FileNotFoundException("Could not read file: " + filename, e);
    }
}
 
Example 4
/**
 * Find the resource under the given location.
 * <p>The default implementation checks if there is a readable
 * {@code Resource} for the given path relative to the location.
 * @param resourcePath the path to the resource
 * @param location the location to check
 * @return the resource, or {@code null} if none found
 */
protected Resource getResource(String resourcePath, Resource location) throws IOException {
	Resource resource = location.createRelative(resourcePath);
	if (resource.exists() && resource.isReadable()) {
		if (checkResource(resource, location)) {
			return resource;
		}
		else if (logger.isTraceEnabled()) {
			logger.trace("Resource path=\"" + resourcePath + "\" was successfully resolved " +
					"but resource=\"" +	resource.getURL() + "\" is neither under the " +
					"current location=\"" + location.getURL() + "\" nor under any of the " +
					"allowed locations=" + Arrays.asList(getAllowedLocations()));
		}
	}
	return null;
}
 
Example 5
/**
 * Find the resource under the given location.
 * <p>The default implementation checks if there is a readable
 * {@code Resource} for the given path relative to the location.
 * @param resourcePath the path to the resource
 * @param location the location to check
 * @return the resource, or {@code null} if none found
 */
protected Resource getResource(String resourcePath, Resource location) throws IOException {
	Resource resource = location.createRelative(resourcePath);
	if (resource.exists() && resource.isReadable()) {
		if (checkResource(resource, location)) {
			return resource;
		}
		else if (logger.isTraceEnabled()) {
			logger.trace("Resource path=\"" + resourcePath + "\" was successfully resolved " +
					"but resource=\"" +	resource.getURL() + "\" is neither under the " +
					"current location=\"" + location.getURL() + "\" nor under any of the " +
					"allowed locations=" + Arrays.asList(getAllowedLocations()));
		}
	}
	return null;
}
 
Example 6
Source Project: herd   File: ModelClassFinder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds all the model classes and the model error class.
 *
 * @throws MojoExecutionException if a class couldn't be instantiated or an I/O error occurred.
 */
private void findModelClasses() throws MojoExecutionException
{
    try
    {
        log.debug("Finding model classes.");

        // Get the model classes as resources.
        modelClasses = new HashSet<>();

        // Loop through each model resource and add each one to the set of model classes.
        for (Resource resource : ResourceUtils.getResources(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(modelJavaPackage)) +
            "/**/*.class"))
        {
            if (resource.isReadable())
            {
                MetadataReader metadataReader = new CachingMetadataReaderFactory(new PathMatchingResourcePatternResolver()).getMetadataReader(resource);
                Class<?> clazz = Class.forName(metadataReader.getClassMetadata().getClassName());
                modelClasses.add(clazz);
                log.debug("Found model class \"" + clazz.getName() + "\".");

                // If the model error class name is configured and matches this class, then hold onto it.
                if (clazz.getSimpleName().equals(modelErrorClassName))
                {
                    log.debug("Found model error class \"" + clazz.getName() + "\".");
                    modelErrorClass = clazz;
                }
            }
        }
    }
    catch (IOException | ClassNotFoundException e)
    {
        throw new MojoExecutionException("Error finding model classes. Reason: " + e.getMessage(), e);
    }
}
 
Example 7
Source Project: mall   File: QiniuStorage.java    License: MIT License 5 votes vote down vote up
@Override
public Resource loadAsResource(String keyName) {
    try {
        URL url = new URL(generateUrl(keyName));
        Resource resource = new UrlResource(url);
        if (resource.exists() || resource.isReadable()) {
            return resource;
        } else {
            return null;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 8
Source Project: jstarcraft-core   File: CodecXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定包下的静态资源对象
 * 
 * @param packageName 包名
 * @return
 * @throws IOException
 */
private String[] getResources(String packageName) {
    try {
        // 搜索资源
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)) + "/" + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        // 提取资源
        Set<String> names = new HashSet<String>();
        String name = ProtocolConfiguration.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (annotationMetadata.hasAnnotation(name)) {
                names.add(classMetadata.getClassName());
            } else {
                String[] interfaceNames = classMetadata.getInterfaceNames();
                for (String interfaceName : interfaceNames) {
                    metadataReader = this.metadataReaderFactory.getMetadataReader(interfaceName);
                    annotationMetadata = metadataReader.getAnnotationMetadata();
                    if (annotationMetadata.hasAnnotation(name)) {
                        names.add(classMetadata.getClassName());
                        break;
                    }
                }
            }
        }
        return names.toArray(new String[0]);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}
 
Example 9
@Override
public Resource loadAsResource(String keyName) {
    try {
        URL url = new URL(generateUrl(keyName));
        Resource resource = new UrlResource(url);
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 10
Source Project: jstarcraft-core   File: LuceneXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
private String[] getResources(String packageName) {
    try {
        // 搜索资源
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)) + "/" + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        // 提取资源
        Set<String> names = new HashSet<String>();
        String document = LuceneConfiguration.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (!annotationMetadata.hasAnnotation(document)) {
                continue;
            }
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            names.add(classMetadata.getClassName());
        }
        return names.toArray(new String[0]);
    } catch (IOException exception) {
        String message = "无法获取资源";
        LOGGER.error(message, exception);
        throw new StorageConfigurationException(message, exception);
    }
}
 
Example 11
private void onHandlerResource(
		Resource[] resources,
		MetadataReaderFactory readerFactory,
		ConcurrentHashMap<String, ConcurrentHashMap<HandlerScope, LinkedList<String>>> handlersMap)
		throws IOException {

	if (resources == null || readerFactory == null) {
		return;
	}

	for (Resource resource : resources) {
		if (resource.isReadable()) {
			MetadataReader reader = readerFactory
					.getMetadataReader(resource);
			// 这儿可以抽象出来,但是因为本项目只需要一个注解扫描
			if (matchesEntityTypeFilter(reader, readerFactory)) {
				Map<String, Object> map = reader.getAnnotationMetadata()
						.getAnnotationAttributes(
								"com.wms.studio.annotations.Handler");
				if (map != null) {
					String handlerName = (String) map.get("handlerName");
					String beanName = (String) map.get("beanName");
					HandlerScope scope = (HandlerScope) map.get("scope");
					if (scope == HandlerScope.None) {
						continue;
					}

					addHandler(handlerName, beanName, scope, handlersMap);
				}
			}
		}
	}
}
 
Example 12
private String[] getResources(String packageName) {
    try {
        // 搜索资源
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)) + "/" + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        // 提取资源
        Set<String> names = new HashSet<String>();
        String entity = Entity.class.getName();
        String persistent = Persistent.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (!annotationMetadata.hasAnnotation(entity) && !annotationMetadata.hasAnnotation(persistent)) {
                continue;
            }
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            names.add(classMetadata.getClassName());
        }
        return names.toArray(new String[0]);
    } catch (IOException exception) {
        String message = "无法获取资源";
        LOGGER.error(message, exception);
        throw new StorageConfigurationException(message, exception);
    }
}
 
Example 13
Source Project: cuba   File: WindowConfig.java    License: Apache License 2.0 5 votes vote down vote up
protected MetadataReader loadClassMetadata(String className) {
    Resource resource = getResourceLoader().getResource("/" + className.replace(".", "/") + ".class");
    if (!resource.isReadable()) {
        throw new RuntimeException(String.format("Resource %s is not readable for class %s", resource, className));
    }
    try {
        return getMetadataReaderFactory().getMetadataReader(resource);
    } catch (IOException e) {
        throw new RuntimeException("Unable to read resource " + resource, e);
    }
}
 
Example 14
public List<String> scan(String... locations) throws IOException {
	List<String> routes = new ArrayList<>();
	for (String location : locations) {
		for (Resource resource : this.resolver.getResources(toPattern(location) + "**/routes.txt")) {
			if (resource.isReadable()) {
				routes.addAll(readLines(resource.getInputStream()));
			}
		}
	}
	return routes;
}
 
Example 15
Source Project: jstarcraft-core   File: MongoXmlParser.java    License: Apache License 2.0 5 votes vote down vote up
private String[] getResources(String packageName) {
    try {
        // 搜索资源
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(packageName)) + "/" + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
        // 提取资源
        Set<String> names = new HashSet<String>();
        String document = Document.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (!annotationMetadata.hasAnnotation(document)) {
                continue;
            }
            ClassMetadata classMetadata = metadataReader.getClassMetadata();
            names.add(classMetadata.getClassName());
        }
        return names.toArray(new String[0]);
    } catch (IOException exception) {
        String message = "无法获取资源";
        LOGGER.error(message, exception);
        throw new StorageConfigurationException(message, exception);
    }
}
 
Example 16
public UiExtensions scan(String... locations) throws IOException {
	List<UiExtension> extensions = new ArrayList<>();
	for (String location : locations) {
		for (Resource resource : resolveAssets(location)) {
			String resourcePath = this.getResourcePath(location, resource);
			if (resourcePath != null && resource.isReadable()) {
				UiExtension extension = new UiExtension(resourcePath, location + resourcePath);
				log.debug("Found UiExtension {}", extension);
				extensions.add(extension);
			}
		}
	}
	return new UiExtensions(extensions);
}
 
Example 17
Source Project: eclair   File: JaxbElementWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private Class<?>[] findWrapperClasses(Jaxb2Marshaller jaxb2Marshaller) {
    String contextPath = jaxb2Marshaller.getContextPath();
    if (!hasText(contextPath)) {
        return jaxb2Marshaller.getClassesToBeBound();
    }
    List<Class<?>> classes = new ArrayList<>();
    for (String path : contextPath.split(":")) {
        for (Resource resource : pathToResources(path)) {
            if (resource.isReadable()) {
                classes.add(forName(resource));
            }
        }
    }
    return classes.toArray(new Class[classes.size()]);
}
 
Example 18
/**
 * Find the resource under the given location.
 * <p>The default implementation checks if there is a readable
 * {@code Resource} for the given path relative to the location.
 * @param resourcePath the path to the resource
 * @param location the location to check
 * @return the resource, or empty {@link Mono} if none found
 */
protected Mono<Resource> getResource(String resourcePath, Resource location) {
	try {
		Resource resource = location.createRelative(resourcePath);
		if (resource.isReadable()) {
			if (checkResource(resource, location)) {
				return Mono.just(resource);
			}
			else if (logger.isWarnEnabled()) {
				Resource[] allowedLocations = getAllowedLocations();
				logger.warn("Resource path \"" + resourcePath + "\" was successfully resolved " +
						"but resource \"" + resource.getURL() + "\" is neither under the " +
						"current location \"" + location.getURL() + "\" nor under any of the " +
						"allowed locations " + (allowedLocations != null ? Arrays.asList(allowedLocations) : "[]"));
			}
		}
		return Mono.empty();
	}
	catch (IOException ex) {
		if (logger.isDebugEnabled()) {
			String error = "Skip location [" + location + "] due to error";
			if (logger.isTraceEnabled()) {
				logger.trace(error, ex);
			}
			else {
				logger.debug(error + ": " + ex.getMessage());
			}
		}
		return Mono.error(ex);
	}
}
 
Example 19
Source Project: litemall   File: TencentStorage.java    License: MIT License 5 votes vote down vote up
@Override
public Resource loadAsResource(String keyName) {
    try {
        URL url = new URL(getBaseUrl() + keyName);
        Resource resource = new UrlResource(url);
        if (resource.exists() || resource.isReadable()) {
            return resource;
        }
    } catch (MalformedURLException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 20
/**
 * Scan the class path for candidate components.
 * @param basePackage the package to check for annotated classes
 * @return a corresponding Set of autodetected bean definitions
 */
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
    Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>();
    try {
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                resolveBasePackage(basePackage) + "/" + this.resourcePattern;
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        boolean traceEnabled = logger.isTraceEnabled();
        boolean debugEnabled = logger.isDebugEnabled();
        for (int i = 0; i < resources.length; i++) {
            Resource resource = resources[i];
            if (traceEnabled) {
                logger.trace("Scanning " + resource);
            }
            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 (debugEnabled) {
                            logger.debug("Ignored because not a concrete 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 classpath scanning", ex);
    }
    return candidates;
}