public void testClasspathPrefix() throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 只加载一个绝对匹配Resource,且通过ResourceLoader.getResource进行加载 Resource[] resources = resolver.getResources("classpath:META-INF/INDEX.LIST"); Assert.assertEquals(1, resources.length); // 只加载一个匹配的Resource,且通过ResourceLoader.getResource进行加载 resources = resolver.getResources("classpath:META-INF/*.LIST"); Assert.assertTrue(resources.length == 1); }
public void testClasspathAsteriskPrefix() throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 将加载多个绝对匹配 的所有Resource // 将首先通过ClassLoader.getResource("META-INF")加载非模式路径部分 // 然后进行遍历模式匹配 Resource[] resources = resolver.getResources("classpath*:META-INF/INDEX.LIST"); Assert.assertTrue(resources.length > 1); // 将加载多个模式匹配的Resource resources = resolver.getResources("classpath*:META-INF/*.LIST"); Assert.assertTrue(resources.length > 1); }
@Test public void testClasspathAsteriskPrefixLimit() throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); // 将首先通过ClassLoader.getResource()加载目录 // 将只返回文件系统的类路径不返回jar的根路径 // 然后进行遍历模式匹配 Resource[] resources = resolver.getResources("classpath*:asm-*.txt"); Assert.assertTrue(resources.length == 0); // 将通过ClassLoader.getResource("asm-license.txt")加载 // asm-license.txt存在于com.spring.net.sf.cglib-2.2.0.jar resources = resolver.getResources("classpath*:asm-license.txt"); Assert.assertTrue(resources.length > 0); // 将只加载文件系统类路径匹配 的Resource resources = resolver.getResources("classpath*:LICENS*"); Assert.assertTrue(resources.length == 1); }
/** * 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 */ 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); } }
private Resource[] getResources() throws IOException { String paramsRoot = InitConfigPath.getParamsRoot(); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] propertiesResources = resolver.getResources("file:" + paramsRoot + "/i18n/**/*.properties"); Resource[] htmlResources = resolver.getResources("file:" + paramsRoot + "/i18n/**/*.html"); Resource[] txtResources = resolver.getResources("file:" + paramsRoot + "/i18n/**/*.txt"); List<Resource> resources = new ArrayList<Resource>(); resources.addAll(Arrays.asList(propertiesResources)); resources.addAll(Arrays.asList(htmlResources)); resources.addAll(Arrays.asList(txtResources)); return resources.toArray(new Resource[] {}); }
/** method adds all the method names to map with annotation attribute value as key */ private static void findAnnotationMethods( final Class<? extends Annotation> annotationClass, final String attributeName) throws IOException { final String basePackagePath = ClassUtils.convertClassNameToResourcePath( new StandardEnvironment().resolveRequiredPlaceholders(SEARCH_PACKAGE)); final String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePath + "/" + RESOURCE_PATTERN; final Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (final Resource resource : resources) { if (resource.isReadable()) { final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); final Set<MethodMetadata> metadataSet = metadataReader.getAnnotationMetadata().getAnnotatedMethods(annotationClass.getName()); if (metadataSet != null && metadataSet.size() > 0) { for (final MethodMetadata metadata : metadataSet) { final Map<String, Object> attributes = metadata.getAnnotationAttributes(annotationClass.getName()); final JobName attributeValue = (JobName) attributes.get(attributeName); final String className = metadata.getDeclaringClassName(); final String[] mapVal = {className, metadata.getMethodName()}; targetMethosMap.put(attributeValue.toString(), mapVal); } } } } }
public static void main(String[] args) throws Throwable { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource resources[] = resolver.getResources("classpath*:com/baobaotao/**/*.xml"); for (Resource resource : resources) { System.out.println(resource.getDescription()); } }
@Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception { final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations( patternResolver.getResources(ResourceLoader.CLASSPATH_URL_PREFIX + "mapper/**/*.xml")); return sqlSessionFactoryBean.getObject(); }
public static void init() throws Exception { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources("file:" + InitConfigPath.getParamsRoot() + "/*.properties"); loadProperties(prop, resources); prop.put("params.root", InitConfigPath.getParamsRoot()); }
private Resource[] scan(ClassLoader loader, String packageName) throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(loader); String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(packageName) + "/**/*.class"; Resource[] resources = resolver.getResources(pattern); return resources; }
private Properties loadProperties() throws Exception { if (StringUtils.hasText(propertiesLocation)) { PropertiesFactoryBean propsFactory = new PropertiesFactoryBean(); propsFactory.setLocations(resourceResolver.getResources(propertiesLocation)); propsFactory.afterPropertiesSet(); return propsFactory.getObject(); } return null; }
public List<IDataSet> loadMultiple(DataSetFormatOptions options, String[] locations) throws DataSetException, IOException { List<IDataSet> dataSets = new ArrayList<IDataSet>(locations.length); for (String location : locations) { Resource[] resources = RESOURCE_LOADER.getResources(location); for (Resource resource : resources) { dataSets.add(fromResource(resource, options)); } } return dataSets; }
static { String resourcePattern = "classpath*:META-INF/spring.integration.default.properties"; try { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(IntegrationProperties.class.getClassLoader()); Resource[] defaultResources = resourceResolver.getResources(resourcePattern); PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocations(defaultResources); propertiesFactoryBean.afterPropertiesSet(); defaults = propertiesFactoryBean.getObject(); } catch (IOException e) { throw new IllegalStateException("Can't load '" + resourcePattern + "' resources.", e); } }
public static void addLocation(String locationPattern) { try { Resource[] resources = resourcePatternResolver.getResources(locationPattern); for (int i = 0; i < resources.length; i++) { String url = resources[i].getURL().toString(); int lastIndex = url.lastIndexOf("/"); String prefix = url.substring(0, lastIndex + 1); String suffix = url.substring(lastIndex + 1); suffix = suffix.split("\\.")[0].split("_")[0]; set.add(prefix + suffix); } } catch (IOException e) { throw new RuntimeException(e); } initMessageSourceAccessor(); }
@Override public Map<Resource, NodeRef> deployResources( String resourcePattern, RepositoryLocation targetLocation, UpdateStrategy updateStrategy, String encoding, String mimetype, QName nodeType) throws IOException { final Map<Resource, NodeRef> nodeReferences = new HashMap<Resource, NodeRef>(); final Resource[] resources = resourcePatternResolver.getResources(resourcePattern); for (Resource resource : resources) { final NodeRef result = deployResource(targetLocation, updateStrategy, encoding, mimetype, resource, nodeType); nodeReferences.put(resource, result); } return nodeReferences; }
private Transform() { try { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(TEMPLATES_PATH); for (Resource resource : resources) { templates.put( getName(resource), transformerFactory.newTemplates(new StreamSource(resource.getURL().openStream()))); } } catch (IOException e) { throw new RuntimeException( "Failed to discover XSLT resources in '" + TEMPLATES_PATH + "'", e); } catch (TransformerConfigurationException e) { throw new RuntimeException("Error loading XSLT stylesheets", e); } if (log.isDebugEnabled()) { log.debug("templates=" + new TreeSet<String>(templates.keySet())); } }
/** * Scans the configured base package for files matching the configured mapping file name pattern. * Will simply return an empty {@link Set} in case no {@link ResourceLoader} or mapping file name * pattern was configured. Resulting paths are resource-loadable from the application classpath * according to the JPA spec. * * @see javax.persistence.spi.PersistenceUnitInfo.PersistenceUnitInfo#getMappingFileNames() * @return */ private Set<String> scanForMappingFileLocations() { if (resolver == null || !StringUtils.hasText(mappingFileNamePattern)) { return Collections.emptySet(); } /* * Note that we cannot use File.pathSeparator here since resourcePath uses a forward slash path ('/') separator * being an URI, while basePackagePathComponent has system dependent separator (on windows it's the backslash separator). * * @see DATAJPA-407 */ char slash = '/'; String basePackagePathComponent = basePackage.replace('.', slash); String path = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePathComponent + slash + mappingFileNamePattern; Set<String> mappingFileUris = new HashSet<String>(); Resource[] scannedResources = new Resource[0]; try { scannedResources = resolver.getResources(path); } catch (IOException e) { throw new IllegalStateException( String.format("Cannot load mapping files from path %s!", path), e); } for (Resource resource : scannedResources) { try { String resourcePath = getResourcePath(resource.getURI()); String resourcePathInClasspath = resourcePath.substring(resourcePath.indexOf(basePackagePathComponent)); mappingFileUris.add(resourcePathInClasspath); } catch (IOException e) { throw new IllegalStateException( String.format("Couldn't get URI for %s!", resource.toString()), e); } } return mappingFileUris; }
public void afterPropertiesSet() throws Exception { resourceLoader = GrailsResourceLoaderHolder.getResourceLoader(); if (resourceLoader != null) { return; } if (Environment.getCurrent().isReloadEnabled()) { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { Resource[] resources = resolver.getResources( "file:" + Environment.getCurrent().getReloadLocation() + "/grails-app/**/*.groovy"); resourceLoader = new GrailsResourceLoader(resources); } catch (IOException e) { createDefaultInternal(); } } else { createDefaultInternal(); } GrailsResourceLoaderHolder.setResourceLoader(resourceLoader); }
@Bean @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) public SqlSessionFactory getMybatisSqlSessionFactoryBean(DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); ResourcePatternResolver resolver = (ResourcePatternResolver) new PathMatchingResourcePatternResolver(); factoryBean.setTypeAliasesPackage("com.xb.persistent"); Resource[] resources = resolver.getResources("classpath:/com/xb/persistent/mapper/*.xml"); factoryBean.setMapperLocations(resources); factoryBean.setCache(null); PageHelper pageHelper = new com.github.pagehelper.PageHelper(); Properties p = new Properties(); p.setProperty("dialect", "mysql"); pageHelper.setProperties(p); factoryBean.setPlugins(new Interceptor[] {pageHelper}); MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); configuration.setJdbcTypeForNull(JdbcType.NULL); factoryBean.setConfiguration(configuration); return factoryBean.getObject(); }
/** * Scans the configured base package for files matching the configured mapping file name pattern. * Will simply return an empty {@link Set} in case no {@link ResourceLoader} or mapping file name * pattern was configured. Resulting paths are resource-loadable from the application classpath * according to the JPA spec. * * @see javax.persistence.spi.PersistenceUnitInfo.PersistenceUnitInfo#getMappingFileNames() * @return */ private Set<String> scanForMappingFileLocations() { if (resolver == null || !StringUtils.hasText(mappingFileNamePattern)) { return Collections.emptySet(); } String basePackagePathComponent = basePackage.replace('.', File.separatorChar); String path = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePathComponent + File.separator + mappingFileNamePattern; Set<String> mappingFileUris = new HashSet<String>(); Resource[] scannedResources = new Resource[0]; try { scannedResources = resolver.getResources(path); } catch (IOException e) { throw new IllegalStateException( String.format("Cannot load mapping files from path %s!", path), e); } for (Resource resource : scannedResources) { try { String resourcePath = resource.getURI().getPath(); String resourcePathInClasspath = resourcePath.substring(resourcePath.indexOf(basePackagePathComponent)); mappingFileUris.add(resourcePathInClasspath); } catch (IOException e) { throw new IllegalStateException( String.format("Couldn't get URI for %s!", resource.toString()), e); } } return mappingFileUris; }
public static void main(String[] args) throws Exception { try { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); AnnotationConfiguration config = new AnnotationConfiguration() .configure(new File("D:/gjxt/source/news/config/hibernate/hibernate.cfg.xml")); config.setProperty("output", "C:\\ddl.txt"); String[] packagesToScan = {"com.team.cmc.domain.model"}; for (String pkg : packagesToScan) { String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg) + "/**/*.class"; 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)) { config.addAnnotatedClass( resourcePatternResolver.getClassLoader().loadClass(className)); } } } } SessionFactory sessionFactory = config.buildSessionFactory(); session = sessionFactory.openSession(); tx = session.beginTransaction(); SchemaExport schemaExport = new SchemaExport(config); schemaExport.setOutputFile("c:\\a.txt"); schemaExport.create(true, true); System.out.println("Table created."); tx.commit(); // // config = new Configuration().configure(new File( // "src/hibernate.cfg.xml")); // // System.out.println("Creating tables..."); // // SessionFactory sessionFactory = config.configure() // .buildSessionFactory(); // session = sessionFactory.openSession(); // tx = session.beginTransaction(); // // SchemaExport schemaExport = new SchemaExport(config); // schemaExport.create(true, true); // // System.out.println("Table created."); // // tx.commit(); } catch (HibernateException e) { e.printStackTrace(); try { tx.rollback(); } catch (HibernateException e1) { e1.printStackTrace(); } } finally { } }
public Resource[] getResources(String locationPattern) throws IOException { ResourcePatternResolver pResolver = resolvePatternResolver(locationPattern); return pResolver.getResources(locationPattern); }
@Override protected void doParse( Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { Map<String, ParsingModuleInfo> scripts = parseSpecificBeans(element, parserContext, builder.getRawBeanDefinition(), ns(LANG_URI)); ElementSelector searchFolders = and(sameNs(element), name("search-folders")); ElementSelector searchFiles = and(sameNs(element), name("search-files")); for (Element subElement : subElements(element)) { String prefix = null; String typeName = null; String moduleName = null; Pattern scriptNamePattern = null; String scriptResourceName = null; String language = null; if (searchFolders.accept(subElement)) { String folderName = assertNotNull( normalizePathName(subElement.getAttribute("folders")), "no folder name provided for search-folders"); // 取prefix prefix = getPrefix(folderName); if (prefix != null) { folderName = folderName.substring(prefix.length() + 1); } // folderName不以/开始 if (folderName.startsWith("/")) { folderName = folderName.substring(1); } scriptNamePattern = compilePathName(folderName); typeName = assertNotNull(trimToNull(subElement.getAttribute("type")), "no type name provided"); language = trimToNull(subElement.getAttribute("language")); scriptResourceName = folderName + "/**/*.*"; log.trace( "Searching in folders: {}, moduleType={}, language={}", new Object[] {folderName, typeName, language == null ? "auto" : language}); } else if (searchFiles.accept(subElement)) { String fileName = assertNotNull( normalizePathName(subElement.getAttribute("files")), "no script file name provided for search-files"); // fileName不以/结尾 assertTrue(!fileName.endsWith("/"), "invalid script file name: %s", fileName); // 取prefix prefix = getPrefix(fileName); if (prefix != null) { fileName = fileName.substring(prefix.length() + 1); } // fileName不以/开始 if (fileName.startsWith("/")) { fileName = fileName.substring(1); } scriptNamePattern = compilePathName(fileName); typeName = assertNotNull(trimToNull(subElement.getAttribute("type")), "no type name provided"); moduleName = assertNotNull(trimToNull(subElement.getAttribute("name")), "no module name provided"); language = trimToNull(subElement.getAttribute("language")); scriptResourceName = fileName; log.trace( "Searching for script files: {}, moduleType={}, moduleName={}, language={}", new Object[] {fileName, typeName, moduleName, language == null ? "auto" : language}); } if (scriptResourceName != null) { scriptResourceName = prefix == null ? scriptResourceName : prefix + ":" + scriptResourceName; // 扫描scripts ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( parserContext.getReaderContext().getResourceLoader()); int found = 0; try { Resource[] resources = resolver.getResources(scriptResourceName.replace('?', '*')); BeanDefinitionDefaults defaults = getBeanDefinitionDefaults(subElement, parserContext); ParsingModuleMatcher matcher = new ParsingModuleMatcher(scripts, scriptNamePattern, typeName, moduleName) { @Override protected String getName(String name, String itemName) { String ext = getExt(itemName); if (ext != null && name.endsWith("." + ext)) { return name.substring(0, name.length() - ext.length() - 1); } return name; } }; for (Resource resource : resources) { if (resource.isReadable()) { URI uri = resource.getURI(); if (uri == null) { continue; } String resourceName = uri.normalize().toString(); if (matcher.doMatch(resourceName)) { BeanDefinition scriptBean = createScriptBean(subElement, parserContext, resourceName, language, defaults); String beanName = matcher.generateBeanName(resourceName, parserContext.getRegistry()); parserContext.getRegistry().registerBeanDefinition(beanName, scriptBean); found++; } } } } catch (IOException e) { parserContext .getReaderContext() .error("Failed to scan resources: " + scriptResourceName, subElement, e); return; } log.debug("Found {} module scripts with pattern: {}", found, scriptResourceName); } } postProcessItems(element, parserContext, builder, scripts, "search-folders or search-files"); }
private static Resource[] getResources(String pattern) throws IOException { ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); Resource[] resources = resolver.getResources(pattern); return resources; }