List of usage examples for org.springframework.core.io Resource isReadable
default boolean isReadable()
From source file:com.haulmont.cuba.client.testsupport.CubaClientTestCase.java
protected List<String> getClasses(Resource[] resources) { List<String> classNames = new ArrayList<>(); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader; try { metadataReader = metadataReaderFactory.getMetadataReader(resource); } catch (IOException e) { throw new RuntimeException("Unable to read metadata resource", e); }//from w w w. j a va 2 s. c om AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName()) || annotationMetadata.isAnnotated(MappedSuperclass.class.getName()) || annotationMetadata.isAnnotated(Entity.class.getName())) { ClassMetadata classMetadata = metadataReader.getClassMetadata(); classNames.add(classMetadata.getClassName()); } } } return classNames; }
From source file:org.brekka.stillingar.spring.resource.ScanningResourceSelector.java
/** * Search the specified base directory for files with names matching those in <code>names</code>. If the location * gets rejected then it should be added to the list of rejected locations. * //from w w w . j a v a 2s . co m * @param locationBase * the location to search * @param names * the names of files to find within the base location * @param rejected * collects failed locations. * @return the resource or null if one cannot be found. */ protected Resource findInBaseDir(BaseDirectory locationBase, Set<String> names, List<RejectedSnapshotLocation> rejected) { Resource dir = locationBase.getDirResource(); if (dir instanceof UnresolvableResource) { UnresolvableResource res = (UnresolvableResource) dir; rejected.add(new Rejected(locationBase.getDisposition(), null, res.getMessage())); } else { String dirPath = null; try { URI uri = dir.getURI(); if (uri != null) { dirPath = uri.toString(); } } catch (IOException e) { if (log.isWarnEnabled()) { log.warn(format("Resource dir '%s' has a bad uri", locationBase), e); } } String message; if (dir.exists()) { StringBuilder messageBuilder = new StringBuilder(); for (String name : names) { try { Resource location = dir.createRelative(name); if (location.exists()) { if (location.isReadable()) { // We have found a file return location; } if (messageBuilder.length() > 0) { messageBuilder.append(" "); } messageBuilder.append("File '%s' exists but cannot be read."); } else { // Fair enough, it does not exist } } catch (IOException e) { // Location could not be resolved, log as warning, then move on to the next one. if (log.isWarnEnabled()) { log.warn(format("Resource location '%s' encountered problem", locationBase), e); } } } if (messageBuilder.length() == 0) { message = "no configuration files found"; } else { message = messageBuilder.toString(); } } else { message = "Directory does not exist"; } rejected.add(new Rejected(locationBase.getDisposition(), dirPath, message)); } // No resource found return null; }
From source file:com.civilizer.web.handler.ResourceHttpRequestHandler.java
protected Resource getResource(HttpServletRequest request) { String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE); if (path == null) { throw new IllegalStateException("Required request attribute '" + HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE + "' is not set"); }/*from www . j ava 2s. c o m*/ // // For resources having UTF-8 encoded path; // path = FsUtil.toUtf8Path(path); if (!StringUtils.hasText(path) || isInvalidPath(path)) { if (logger.isDebugEnabled()) { logger.debug("Ignoring invalid resource path [" + path + "]"); } return null; } for (Resource location : this.locations) { try { if (logger.isDebugEnabled()) { logger.debug("Trying relative path [" + path + "] against base location: " + location); } Resource resource = location.createRelative(path); if (resource.exists() && resource.isReadable()) { if (logger.isDebugEnabled()) { logger.debug("Found matching resource: " + resource); } return resource; } else if (logger.isTraceEnabled()) { logger.trace("Relative resource doesn't exist or isn't readable: " + resource); } } catch (IOException ex) { logger.debug("Failed to create relative resource - trying next resource location", ex); } } return null; }
From source file:com.fortify.processrunner.RunProcessRunnerFromSpringConfig.java
/** * Check whether the given configuration file exists and is readable. * @param configFile//from www. jav a2 s . c o m */ protected final void checkConfigFile(String configFile) { Resource resource = new FileSystemResource(configFile); if (!resource.exists()) { throw new IllegalArgumentException("ERROR: Configuration file " + configFile + " does not exist"); } if (!resource.isReadable()) { throw new IllegalArgumentException("ERROR: Configuration file " + configFile + " is not readable"); } }
From source file:com.haulmont.cuba.core.config.AppPropertiesLocator.java
protected Set<Class> findConfigInterfaces() { if (interfacesCache == null) { synchronized (this) { if (interfacesCache == null) { log.trace("Locating config interfaces"); Set<String> cache = new HashSet<>(); for (String rootPackage : metadata.getRootPackages()) { String packagePrefix = rootPackage.replace(".", "/") + "/**/*.class"; String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packagePrefix; Resource[] resources; try { resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory .getMetadataReader(resource); ClassMetadata classMetadata = metadataReader.getClassMetadata(); if (classMetadata.isInterface()) { for (String intf : classMetadata.getInterfaceNames()) { if (Config.class.getName().equals(intf)) { cache.add(classMetadata.getClassName()); break; } }/* w w w.j a va 2 s .c o m*/ } } } } catch (IOException e) { throw new RuntimeException("Error searching for Config interfaces", e); } } log.trace("Found config interfaces: {}", cache); interfacesCache = cache; } } } return interfacesCache.stream().map(ReflectionHelper::getClass).collect(Collectors.toSet()); }
From source file:com.google.api.ads.adwords.awreporting.model.csv.CsvReportEntitiesMapping.java
/** * Adds the resource as a candidate if the resource matches the rules. * * @param resource the current resource. * @param metadataReaderFactory the meta data factory for the bean. * @param candidates the list of candidates. * @throws IOException in case the meta data could not be created. * @throws ClassNotFoundException in case the class is not present in the classpath *//*from w w w . j ava2 s . co m*/ @SuppressWarnings("unchecked") private void addCandidateIfApplicable(Resource resource, MetadataReaderFactory metadataReaderFactory, List<Class<? extends Report>> candidates) throws IOException, ClassNotFoundException { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (isAnnotationPresentAndReportSubclass(metadataReader)) { candidates.add( (Class<? extends Report>) Class.forName(metadataReader.getClassMetadata().getClassName())); } } }
From source file:com.baomidou.hibernateplus.HibernateSpringSessionFactoryBuilder.java
/** * Perform Spring-based scanning for entity classes, registering them * as annotated classes with this {@code Configuration}. * * @param packagesToScan one or more Java package names * @throws HibernateException if scanning fails for any reason *///from w w w . ja va 2 s.c o m @SuppressWarnings("unchecked") public HibernateSpringSessionFactoryBuilder scanPackages(String... packagesToScan) throws HibernateException { Set<String> entityClassNames = new TreeSet<String>(); Set<String> converterClassNames = new TreeSet<String>(); Set<String> packageNames = new TreeSet<String>(); try { for (String pkg : packagesToScan) { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + 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 (matchesEntityTypeFilter(reader, readerFactory)) { entityClassNames.add(className); } else if (CONVERTER_TYPE_FILTER.match(reader, readerFactory)) { converterClassNames.add(className); } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) { packageNames .add(className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length())); } } } } } catch (IOException ex) { throw new MappingException("Failed to scan classpath for unlisted classes", ex); } try { ClassLoader cl = this.resourcePatternResolver.getClassLoader(); for (String className : entityClassNames) { Class<?> cls = cl.loadClass(className); // TODO Caratacus ? EntityInfo EntityInfoUtils.initEntityInfo(cls); addAnnotatedClass(cls); } for (String className : converterClassNames) { addAttributeConverter((Class<? extends AttributeConverter<?, ?>>) cl.loadClass(className)); } for (String packageName : packageNames) { addPackage(packageName); } } catch (ClassNotFoundException ex) { throw new MappingException("Failed to load annotated classes from classpath", ex); } return this; }
From source file:org.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration.java
/** * Perform Spring-based scanning for entity classes, registering them * as annotated classes with this {@code Configuration}. * @param packagesToScan one or more Java package names * @throws HibernateException if scanning fails for any reason *//*from www . j a v a 2s.c o m*/ public void scanPackages(String... packagesToScan) throws HibernateException { try { for (String pkg : packagesToScan) { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + RESOURCE_PATTERN; Resource[] resources = resourcePatternResolver.getResources(pattern); MetadataReaderFactory readerFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader reader = readerFactory.getMetadataReader(resource); String className = reader.getClassMetadata().getClassName(); if (matchesFilter(reader, readerFactory)) { addAnnotatedClasses(resourcePatternResolver.getClassLoader().loadClass(className)); } } } } } catch (IOException ex) { throw new MappingException("Failed to scan classpath for unlisted classes", ex); } catch (ClassNotFoundException ex) { throw new MappingException("Failed to load annotated classes from classpath", ex); } }
From source file:com.qcadoo.model.internal.classconverter.ModelXmlToClassConverterImpl.java
@Override @SuppressWarnings("deprecation") public Collection<Class<?>> convert(final Resource... resources) { Map<String, CtClass> ctClasses = new HashMap<String, CtClass>(); Map<String, Class<?>> existingClasses = new HashMap<String, Class<?>>(); for (Resource resource : resources) { if (resource.isReadable()) { LOG.info("Getting existing classes from " + resource); try { existingClasses.putAll(findExistingClasses(resource.getInputStream())); } catch (XMLStreamException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } catch (IOException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); }//from ww w. j av a 2s .c om } } for (Resource resource : resources) { if (resource.isReadable()) { LOG.info("Creating classes from " + resource); try { ctClasses.putAll(createClasses(existingClasses, resource.getInputStream())); } catch (XMLStreamException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } catch (IOException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } } } for (Resource resource : resources) { if (resource.isReadable()) { LOG.info("Defining classes from " + resource + " to classes"); try { defineClasses(ctClasses, resource.getInputStream()); } catch (XMLStreamException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } catch (ModelXmlCompilingException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } catch (IOException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } catch (NotFoundException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } } } List<Class<?>> classes = new ArrayList<Class<?>>(); for (CtClass ctClass : ctClasses.values()) { try { classes.add(ctClass.toClass(classLoader)); } catch (CannotCompileException e) { throw new IllegalStateException(L_ERROR_WHILE_PARSING_MODEL_XML + e.getMessage(), e); } } classes.addAll(existingClasses.values()); return classes; }