List of usage examples for org.springframework.core.io Resource isReadable
default boolean isReadable()
From source file:com.fantasy.Application.java
private static List<Class> findTypes(String basePackage) throws IOException, ClassNotFoundException { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); List<Class> candidates = new ArrayList(); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage) + "/" + "**/*.class"; Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (isCandidate(metadataReader)) { candidates.add(Class.forName(metadataReader.getClassMetadata().getClassName())); }/* www . j a v a 2 s . c om*/ } } return candidates; }
From source file:com.baomidou.mybatisplus.toolkit.PackageHelper.java
/** * <p>//from ww w . j a v a2 s .c om * ??? * </p> * <p> * <property name="typeAliasesPackage" value="com.baomidou.*.entity"/> * </p> * * @param typeAliasesPackage * ?? * @return */ public static String[] convertTypeAliasesPackage(String typeAliasesPackage) { ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(typeAliasesPackage) + "/*.class"; /* * ??Resource * ClassLoader.getResource("META-INF")????????? */ try { Set<String> set = new HashSet<String>(); Resource[] resources = resolver.getResources(pkg); if (resources != null && resources.length > 0) { MetadataReader metadataReader = null; for (Resource resource : resources) { if (resource.isReadable()) { metadataReader = metadataReaderFactory.getMetadataReader(resource); set.add(Class.forName(metadataReader.getClassMetadata().getClassName()).getPackage() .getName()); } } } if (!set.isEmpty()) { return set.toArray(new String[] {}); } else { throw new MybatisPlusException("not find typeAliasesPackage:" + pkg); } } catch (Exception e) { throw new MybatisPlusException("not find typeAliasesPackage:" + pkg, e); } }
From source file:com.intuit.cto.selfservice.service.Util.java
/** * Extract files from a package on the classpath into a directory. * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot) * @param toDir directory to extract to/*from w ww . j a v a 2 s .c o m*/ * @return int the number of files copied * @throws java.io.IOException if something goes wrong, including if nothing was found on classpath */ public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException { String locationPattern = "classpath*:" + packagePath + "/**"; ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resourcePatternResolver.getResources(locationPattern); if (resources.length == 0) { throw new IOException("Nothing found at " + locationPattern); } int counter = 0; for (Resource resource : resources) { if (resource.isReadable()) { // Skip hidden or system files URL url = resource.getURL(); String path = url.toString(); if (!path.endsWith("/")) { // Skip directories int p = path.lastIndexOf(packagePath) + packagePath.length(); path = path.substring(p); File targetFile = new File(toDir, path); long len = resource.contentLength(); if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files FileUtils.copyURLToFile(url, targetFile); counter++; } } } } logger.info("Unpacked {} files from {} to {}", new Object[] { counter, locationPattern, toDir }); return counter; }
From source file:com.baomidou.framework.spring.SpringScanPackage.java
/** * <p>/*from www. j a va 2 s.c o m*/ * ???,? * </p> * * @param scanPackages * ??package * @return */ public static Set<String> findPackageClass(String scanPackages) { Set<String> clazzSet = new HashSet<String>(); ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resolver); String pkg = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(scanPackages) + "/**/*.class"; /* * ??Resource * ClassLoader.getResource("META-INF")????????? */ try { Resource[] resources = resolver.getResources(pkg); if (resources != null && resources.length > 0) { for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); if (metadataReader != null) { clazzSet.add(metadataReader.getClassMetadata().getClassName()); } } } } } catch (Exception e) { e.printStackTrace(); } return clazzSet; }
From source file:ch.vorburger.mariadb4j.Util.java
/** * Extract files from a package on the classpath into a directory. * /*from ww w . j a v a 2 s .c o m*/ * @param packagePath e.g. "com/stuff" (always forward slash not backslash, never dot) * @param toDir directory to extract to * @return int the number of files copied * @throws java.io.IOException if something goes wrong, including if nothing was found on * classpath */ public static int extractFromClasspathToFile(String packagePath, File toDir) throws IOException { String locationPattern = "classpath*:" + packagePath + "/**"; ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resourcePatternResolver.getResources(locationPattern); if (resources.length == 0) { throw new IOException("Nothing found at " + locationPattern); } int counter = 0; for (Resource resource : resources) { if (resource.isReadable()) { // Skip hidden or system files final URL url = resource.getURL(); String path = url.toString(); if (!path.endsWith("/")) { // Skip directories int p = path.lastIndexOf(packagePath) + packagePath.length(); path = path.substring(p); final File targetFile = new File(toDir, path); long len = resource.contentLength(); if (!targetFile.exists() || targetFile.length() != len) { // Only copy new files tryN(5, 500, new Procedure<IOException>() { @Override public void apply() throws IOException { FileUtils.copyURLToFile(url, targetFile); } }); counter++; } } } } if (counter > 0) { Object[] info = new Object[] { counter, locationPattern, toDir }; logger.info("Unpacked {} files from {} to {}", info); } return counter; }
From source file:com.crudetech.junit.categories.Categories.java
static Class<?>[] allTestClassesInClassPathMatchingPattern(String pattern) throws InitializationError { List<Class<?>> classes = new ArrayList<Class<?>>(); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metaDataReaderFactory = new CachingMetadataReaderFactory(); try {/*from www . j av a2 s . c o m*/ String classPattern = "classpath:" + pattern.replace('.', '/') + ".class"; Resource[] res = resolver.getResources(classPattern); for (Resource r : res) { if (!r.isReadable()) { continue; } MetadataReader reader = metaDataReaderFactory.getMetadataReader(r); Class<?> c = Class.forName(reader.getClassMetadata().getClassName()); if (Modifier.isAbstract(c.getModifiers())) { continue; } classes.add(c); } return classes.toArray(new Class<?>[classes.size()]); } catch (Exception e) { throw new InitializationError(e); } }
From source file:com.foilen.smalltools.tools.Hibernate4Tools.java
/** * Generate the SQL file. This is based on the code in {@link LocalSessionFactoryBuilder#scanPackages(String...)} * * @param dialect// ww w . ja v a 2 s.co m * the dialect (e.g: org.hibernate.dialect.MySQL5InnoDBDialect ) * @param outputSqlFile * where to put the generated SQL file * @param useUnderscore * true: to have tables names like "employe_manager" ; false: to have tables names like "employeManager" * @param packagesToScan * the packages where your entities are */ @SuppressWarnings("deprecation") public static void generateSqlSchema(Class<? extends Dialect> dialect, String outputSqlFile, boolean useUnderscore, String... packagesToScan) { // Configuration Configuration configuration = new Configuration(); if (useUnderscore) { configuration.setNamingStrategy(new ImprovedNamingStrategy()); } Properties properties = new Properties(); properties.setProperty(AvailableSettings.DIALECT, dialect.getName()); // Scan packages Set<String> classNames = 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 = 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 (matchesEntityTypeFilter(reader, readerFactory)) { classNames.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 { for (String className : classNames) { configuration.addAnnotatedClass(resourcePatternResolver.getClassLoader().loadClass(className)); } for (String packageName : packageNames) { configuration.addPackage(packageName); } } catch (ClassNotFoundException ex) { throw new MappingException("Failed to load annotated classes from classpath", ex); } // Exportation SchemaExport schemaExport = new SchemaExport(configuration, properties); schemaExport.setOutputFile(outputSqlFile); schemaExport.setDelimiter(";"); schemaExport.setFormat(true); schemaExport.execute(true, false, false, true); }
From source file:de.tudarmstadt.ukp.dkpro.core.api.resources.ResourceUtils.java
/** * Make a given classpath location available as a folder. A temporary folder is created and * deleted upon a regular shutdown of the JVM. This method must not be used for creating * executable binaries. For this purpose, getUrlAsExecutable should be used. * * @param aClasspathBase// ww w . j a va2s. co m * a classpath location as used by * {@link PathMatchingResourcePatternResolver#getResources(String)} * @param aCache * use the cache or not. * @see PathMatchingResourcePatternResolver */ public static File getClasspathAsFolder(String aClasspathBase, boolean aCache) throws IOException { synchronized (classpathFolderCache) { File folder = classpathFolderCache.get(aClasspathBase); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); if (!aCache || (folder == null) || !folder.exists()) { folder = File.createTempFile("dkpro-package", ""); folder.delete(); FileUtils.forceMkdir(folder); Resource[] roots = resolver.getResources(aClasspathBase); for (Resource root : roots) { String base = root.getURL().toString(); Resource[] resources = resolver.getResources(base + "/**/*"); for (Resource resource : resources) { if (!resource.isReadable()) { // This is true for folders/packages continue; } // Relativize String res = resource.getURL().toString(); if (!res.startsWith(base)) { throw new IOException("Resource location does not start with base location"); } String relative = resource.getURL().toString().substring(base.length()); // Make sure the target folder exists File target = new File(folder, relative).getAbsoluteFile(); if (target.getParentFile() != null) { FileUtils.forceMkdir(target.getParentFile()); } // Copy data InputStream is = null; OutputStream os = null; try { is = resource.getInputStream(); os = new FileOutputStream(target); IOUtils.copyLarge(is, os); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } // WORKAROUND: folders get written as files if inside jars // delete files of size zero if (target.length() == 0) { FileUtils.deleteQuietly(target); } } } if (aCache) { classpathFolderCache.put(aClasspathBase, folder); } } return folder; } }
From source file:com.hp.application.automation.tools.octane.tests.CopyResourceSCM.java
@Override public boolean checkout(AbstractBuild<?, ?> build, Launcher launcher, FilePath workspace, BuildListener listener, File changeLogFile) throws IOException, InterruptedException { if (workspace.exists()) { listener.getLogger().println("Deleting existing workspace " + workspace.getRemote()); workspace.deleteRecursive();//from w ww . j a v a2 s . c o m } Resource[] resources = new PathMatchingResourcePatternResolver().getResources("classpath*:" + path + "/**"); for (Resource resource : resources) { if (resource.exists() && resource.isReadable()) { String urlString = resource.getURL().toExternalForm(); String targetName = urlString.substring(urlString.indexOf(path) + path.length()); byte[] fileContent = IOUtils.toByteArray(resource.getInputStream()); FileUtils.writeByteArrayToFile(new File(new File(workspace.getRemote(), targetPath), targetName), fileContent); } } return true; }
From source file:org.fenixedu.start.service.ProjectService.java
private Map<String, byte[]> build(ProjectRequest request, String type) throws PebbleException, IOException { List<Resource> resources = resourcesByType.get(type); Map<String, byte[]> project = new HashMap<>(); for (Resource resource : resources) { if (resource.isReadable()) { String fileData = process(new String(ByteStreams.toByteArray(resource.getInputStream())), request); if (fileData != null) { String filePath = getFilePath(resource, type); project.put(process(filePath, request), fileData.getBytes()); }//from w w w. j a va 2 s. c o m } } return project; }