public static List<String> getMaps() { List<String> maps = new ArrayList<>(); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); try { Resource[] resources = resolver.getResources("maps/*.yaml"); Arrays.stream(resources).map(Resource::getFilename).map(f -> f.replace(".yaml", "")) .filter(s -> !s.equals("defaults")) .forEach(maps::add); } catch (IOException e) { e.printStackTrace(); } File[] localYamls = new File(".").listFiles( (dir, name) -> name.toLowerCase().endsWith(".yaml") ); Arrays.stream(localYamls).forEach(f -> maps.add(f.getName().replace(".yaml", ""))); return maps; }
public static void validateResource(String resourcePath,Logger log) { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); try { if (resourceResolver.getResources("classpath*:/GameData" +resourcePath+"*").length==0) log.error("INEXISTENT RESOURCE "+"/GameData" +resourcePath+"*"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** * <p>根据多个包名搜索class * 例如: ScanClassUtils.scanPakcages("javacommon.**.*");</p> * * @param basePackages 各个包名使用逗号分隔,各个包名可以有通配符 * @return 类名的集合 */ @SuppressWarnings("all") public static List<String> scanPackages(String basePackages) { Assert.notNull(basePackages,"'basePakcages' must be not null"); ResourcePatternResolver rl = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(rl); List<String> result = new ArrayList<String>(); String[] arrayPackages = basePackages.split(","); try { for(int j = 0; j < arrayPackages.length; j++) { String packageToScan = arrayPackages[j]; String packagePart = packageToScan.replace('.', '/'); String classPattern = "classpath*:/" + packagePart + "/**/*.class"; Resource[] resources = rl.getResources(classPattern); for (int i = 0; i < resources.length; i++) { Resource resource = resources[i]; MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource); String className = metadataReader.getClassMetadata().getClassName(); result.add(className); } } } catch(Exception e) { throw new RuntimeException(String.format("Scanning package[%s] class occurred an error!", basePackages), e); } return result; }
protected List<Class<?>> findMyTypes(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(forName(metadataReader.getClassMetadata().getClassName())); } } } return candidates; }
private List<Class<?>> findMangoDaoClasses(String packages) { try { List<Class<?>> daos = new ArrayList<Class<?>>(); ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(resourcePatternResolver); for (String locationPattern : getLocationPattern(packages)) { Resource[] rs = resourcePatternResolver.getResources(locationPattern); for (Resource r : rs) { MetadataReader reader = metadataReaderFactory.getMetadataReader(r); AnnotationMetadata annotationMD = reader.getAnnotationMetadata(); if (annotationMD.hasAnnotation(DB.class.getName())) { ClassMetadata clazzMD = reader.getClassMetadata(); daos.add(Class.forName(clazzMD.getClassName())); } } } return daos; } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } }
/** * 将符合条件的Bean以Class集合的形式返回 * * @return * @throws IOException * @throws ClassNotFoundException */ public Set<Class<?>> getClassSet() throws IOException, ClassNotFoundException { this.classSet.clear(); if (!this.packagesList.isEmpty()) { for (String pkg : this.packagesList) { 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)) { this.classSet.add(Class.forName(className)); } } } } } return this.classSet; }
public void testAppContextClassHierarchy() { Class<?>[] clazz = ClassUtils.getClassHierarchy(OsgiBundleXmlApplicationContext.class, ClassUtils.ClassSet.ALL_CLASSES); //Closeable.class, Class<?>[] expected = new Class<?>[] { OsgiBundleXmlApplicationContext.class, AbstractDelegatedExecutionApplicationContext.class, AbstractOsgiBundleApplicationContext.class, AbstractRefreshableApplicationContext.class, AbstractApplicationContext.class, DefaultResourceLoader.class, ResourceLoader.class, AutoCloseable.class, DelegatedExecutionOsgiBundleApplicationContext.class, ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, MessageSource.class, BeanFactory.class, DisposableBean.class }; assertTrue(compareArrays(expected, clazz)); }
/** * Return the search type to be used for the give string based on the * prefix. * * @param path * @return */ public static int getSearchType(String path) { Assert.notNull(path); int type = PREFIX_TYPE_NOT_SPECIFIED; String prefix = getPrefix(path); // no prefix is treated just like osgibundle: if (!StringUtils.hasText(prefix)) type = PREFIX_TYPE_NOT_SPECIFIED; else if (prefix.startsWith(OsgiBundleResource.BUNDLE_URL_PREFIX)) type = PREFIX_TYPE_BUNDLE_SPACE; else if (prefix.startsWith(OsgiBundleResource.BUNDLE_JAR_URL_PREFIX)) type = PREFIX_TYPE_BUNDLE_JAR; else if (prefix.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) type = PREFIX_TYPE_CLASS_SPACE; else if (prefix.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)) type = PREFIX_TYPE_CLASS_ALL_SPACE; else type = PREFIX_TYPE_UNKNOWN; return type; }
@Bean public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(env.getProperty("mybatis.config-location"))); PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver(); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + env.getProperty("mybatis.mapper-locations"); sqlSessionFactoryBean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath)); sqlSessionFactoryBean.setDataSource(dataSource()); PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("reasonable", env.getProperty("pageHelper.reasonable")); properties.setProperty("supportMethodsArguments", env.getProperty("pageHelper.supportMethodsArguments")); properties.setProperty("returnPageInfo", env.getProperty("pageHelper.returnPageInfo")); properties.setProperty("params", env.getProperty("pageHelper.params")); pageHelper.setProperties(properties); sqlSessionFactoryBean.setPlugins(new Interceptor[]{pageHelper}); return sqlSessionFactoryBean; }
@Before public void setUp() throws IOException { resourceLoader = mock(ResourceLoader.class, withSettings().extraInterfaces(ResourcePatternResolver.class)); elmoConfigurationResource = mock(Resource.class); when(elmoConfigurationResource.getFilename()).thenReturn("elmo.trig"); elmoShapesResource = mock(Resource.class); // when(elmoShapesResource.getFilename()).thenReturn("elmo-shapes.trig"); when(elmoShapesResource.getInputStream()).thenReturn(new ByteArrayInputStream( "@prefix dbeerpedia: <http://dbeerpedia.org#> .".getBytes(Charsets.UTF_8))); shaclValidator = mock(ShaclValidator.class); when(elmoConfigurationResource.getInputStream()).thenReturn( new ByteArrayInputStream("@prefix dbeerpedia: <http://dbeerpedia.org#> .".getBytes())); report = mock(ValidationReport.class); when(report.isValid()).thenReturn(true); when(shaclValidator.validate(any(), any())).thenReturn(report); backend = new FileConfigurationBackend(elmoConfigurationResource, repository, "file:config", elmoShapesResource, shaclValidator); backend.setResourceLoader(resourceLoader); backend.setEnvironment(environment); when(repository.getConnection()).thenReturn(repositoryConnection); }
@Test public void configurateBackend_validationFailed_throwShaclValdiationException() throws Exception { // Arrange Resource resource = mock(Resource.class); when(resource.getInputStream()).thenReturn(new ByteArrayInputStream( "@prefix dbeerpedia: <http://dbeerpedia.org#> .".getBytes(Charsets.UTF_8))); when(resource.getFilename()).thenReturn("config.trig"); when(((ResourcePatternResolver) resourceLoader).getResources(anyString())).thenReturn( new Resource[] {resource}); when(report.isValid()).thenReturn(false); // Assert thrown.expect(ShaclValidationException.class); // Act backend.loadResources(); }
@Test public void loadResources_LoadsRepository_WithConfigTrigFile() throws Exception { // Arrange Resource resource = mock(Resource.class); when(resource.getInputStream()).thenReturn(new ByteArrayInputStream( "@prefix dbeerpedia: <http://dbeerpedia.org#> .".getBytes(Charsets.UTF_8))); when(resource.getFilename()).thenReturn("config.trig"); when(((ResourcePatternResolver) resourceLoader).getResources(anyString())).thenReturn( new Resource[] {resource}); // Act backend.loadResources(); // Assert assertThat(backend.getRepository(), equalTo(repository)); verify(repository).initialize(); verify(repositoryConnection).close(); }
@Test public void loadResources_ThrowsException_WhenRdfDataLoadError() throws Exception { // Arrange Resource resource = mock(Resource.class); when(resource.getInputStream()).thenThrow(new RDFParseException("message")); when(resource.getFilename()).thenReturn("config.trig"); when(((ResourcePatternResolver) resourceLoader).getResources(anyString())).thenReturn( new Resource[] {resource}); // Assert thrown.expect(ConfigurationException.class); thrown.expectMessage("Error while loading RDF data."); // Act backend.loadResources(); }
@Test public void loadPrefixes_ThrowConfigurationException_FoundMultiplePrefixesDeclaration() throws Exception { // Arrange Resource resource = mock(Resource.class); when(resource.getInputStream()).thenReturn( new ByteArrayInputStream(new String("@prefix dbeerpedia: <http://dbeerpedia.org#> .\n" + "@prefix elmo: <http://dotwebstack.org/def/elmo#> .\n" + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n" + "@prefix rdfs: <http://www.have-a-nice-day.com/rdf-schema#> .").getBytes( Charsets.UTF_8))); when(resource.getFilename()).thenReturn("_prefixes.trig"); when(((ResourcePatternResolver) resourceLoader).getResources(any())).thenReturn( new Resource[] {resource}); // Assert thrown.expect(ConfigurationException.class); thrown.expectMessage( "Found multiple declaration <@prefix rdfs: <http://www.have-a-nice-day.com/rdf-schema#> .> at line <5>"); // Act backend.loadResources(); }
@Test public void loadPrefixes_ThrowConfigurationException_FoundUnknownPrefix() throws Exception { // Arrange Resource resource = mock(Resource.class); when(resource.getInputStream()).thenReturn( new ByteArrayInputStream(new String("@prefix dbeerpedia: <http://dbeerpedia.org#> .\n" + "@prefix elmo: <http://dotwebstack.org/def/elmo#> .\n" + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .\n" + "this is not a valid prefix").getBytes(Charsets.UTF_8))); when(resource.getFilename()).thenReturn("_prefixes.trig"); when(((ResourcePatternResolver) resourceLoader).getResources(any())).thenReturn( new Resource[] {resource}); // Assert thrown.expect(ConfigurationException.class); thrown.expectMessage("Found unknown prefix format <this is not a valid prefix> at line <5>"); // Act backend.loadResources(); }
@Test public void loadConfiguration_ThrowConfigurationException_IoException() throws Exception { // Arrange Resource prefixes = mock(Resource.class); when(prefixes.getInputStream()).thenReturn( new ByteArrayInputStream(new String("@prefix dbeerpedia: <http://dbeerpedia.org#> .\n" + "@prefix elmo: <http://dotwebstack.org/def/elmo#> .\n" + "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n" + "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .").getBytes(Charsets.UTF_8))); when(prefixes.getFilename()).thenReturn("_prefixes.trig"); Resource config = mock(Resource.class); when(config.getInputStream()).thenThrow(IOException.class); when(config.getFilename()).thenReturn("config.trig"); when(((ResourcePatternResolver) resourceLoader).getResources(any())).thenReturn( new Resource[] {prefixes, config}); // Assert thrown.expect(ConfigurationException.class); thrown.expectMessage("Configuration file <config.trig> could not be read"); // Act backend.loadResources(); }
/** * Returns an instance which uses the the specified selector, as the name of the * definition file(s). In the case of a name with a Spring "classpath*:" prefix, * or with no prefix, which is treated the same, the current thread's context class * loader's {@code getResources} method will be called with this value to get * all resources having that name. These resources will then be combined to form a * definition. In the case where the name uses a Spring "classpath:" prefix, or * a standard URL prefix, then only one resource file will be loaded as the * definition. * @param selector the location of the resource(s) which will be read and * combined to form the definition for the BeanFactoryLocator instance. * Any such files must form a valid ApplicationContext definition. * @return the corresponding BeanFactoryLocator instance * @throws BeansException in case of factory loading failure */ public static BeanFactoryLocator getInstance(String selector) throws BeansException { String resourceLocation = selector; if (resourceLocation == null) { resourceLocation = DEFAULT_RESOURCE_LOCATION; } // For backwards compatibility, we prepend "classpath*:" to the selector name if there // is no other prefix (i.e. "classpath*:", "classpath:", or some URL prefix). if (!ResourcePatternUtils.isUrl(resourceLocation)) { resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation; } synchronized (instances) { if (logger.isTraceEnabled()) { logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + instances.hashCode() + ", instances=" + instances); } BeanFactoryLocator bfl = instances.get(resourceLocation); if (bfl == null) { bfl = new ContextSingletonBeanFactoryLocator(resourceLocation); instances.put(resourceLocation, bfl); } return bfl; } }
/** * Returns an instance which uses the the specified selector, as the name of the * definition file(s). In the case of a name with a Spring 'classpath*:' prefix, * or with no prefix, which is treated the same, the current thread context * ClassLoader's {@code getResources} method will be called with this value * to get all resources having that name. These resources will then be combined to * form a definition. In the case where the name uses a Spring 'classpath:' prefix, * or a standard URL prefix, then only one resource file will be loaded as the * definition. * @param selector the name of the resource(s) which will be read and * combined to form the definition for the BeanFactoryLocator instance. * Any such files must form a valid BeanFactory definition. * @return the corresponding BeanFactoryLocator instance * @throws BeansException in case of factory loading failure */ public static BeanFactoryLocator getInstance(String selector) throws BeansException { String resourceLocation = selector; if (resourceLocation == null) { resourceLocation = DEFAULT_RESOURCE_LOCATION; } // For backwards compatibility, we prepend 'classpath*:' to the selector name if there // is no other prefix (i.e. classpath*:, classpath:, or some URL prefix. if (!ResourcePatternUtils.isUrl(resourceLocation)) { resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation; } synchronized (instances) { if (logger.isTraceEnabled()) { logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + instances.hashCode() + ", instances=" + instances); } BeanFactoryLocator bfl = instances.get(resourceLocation); if (bfl == null) { bfl = new SingletonBeanFactoryLocator(resourceLocation); instances.put(resourceLocation, bfl); } return bfl; } }
/** * Populate the given {@code registry} with the following resource editors: * ResourceEditor, InputStreamEditor, InputSourceEditor, FileEditor, URLEditor, * URIEditor, ClassEditor, ClassArrayEditor. * <p>If this registrar has been configured with a {@link ResourcePatternResolver}, * a ResourceArrayPropertyEditor will be registered as well. * @see org.springframework.core.io.ResourceEditor * @see org.springframework.beans.propertyeditors.InputStreamEditor * @see org.springframework.beans.propertyeditors.InputSourceEditor * @see org.springframework.beans.propertyeditors.FileEditor * @see org.springframework.beans.propertyeditors.URLEditor * @see org.springframework.beans.propertyeditors.URIEditor * @see org.springframework.beans.propertyeditors.ClassEditor * @see org.springframework.beans.propertyeditors.ClassArrayEditor * @see org.springframework.core.io.support.ResourceArrayPropertyEditor */ @Override public void registerCustomEditors(PropertyEditorRegistry registry) { ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver); doRegisterEditor(registry, Resource.class, baseEditor); doRegisterEditor(registry, ContextResource.class, baseEditor); doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor)); doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor)); doRegisterEditor(registry, File.class, new FileEditor(baseEditor)); doRegisterEditor(registry, URL.class, new URLEditor(baseEditor)); ClassLoader classLoader = this.resourceLoader.getClassLoader(); doRegisterEditor(registry, URI.class, new URIEditor(classLoader)); doRegisterEditor(registry, Class.class, new ClassEditor(classLoader)); doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader)); if (this.resourceLoader instanceof ResourcePatternResolver) { doRegisterEditor(registry, Resource[].class, new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver)); } }
/** * 将符合条件的Bean以Class集合的形式返回 * @throws Exception 异常 * @return 类集合 */ public Set<Class<?>> scan() throws Exception { Set<Class<?>> classSet = new HashSet<Class<?>>(); if (!this.packagesList.isEmpty()) { for (String pkg : this.packagesList) { 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)) { classSet.add(Class.forName(className)); } } } } } return classSet; }
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage, String typeAliasesPackage, Dialect dialect, Configuration configuration) { configuration.setDatabaseId(dataSourceName); BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class); bdb.addPropertyValue("configuration", configuration); bdb.addPropertyValue("failFast", true); bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage)); bdb.addPropertyReference("dataSource", dataSourceName); bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) }); if (!StringUtils.isEmpty(mapperPackage)) { try { mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage); String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage); String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml"; Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath); bdb.addPropertyValue("mapperLocations", resources); } catch (Exception e) { log.error("初始化失败", e); throw new RuntimeException( String.format("SqlSessionFactory 初始化失败 mapperPackage=%s", mapperPackage + "")); } } return bdb.getBeanDefinition(); }
@Bean public static SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception { SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); factory.setDataSource(dataSource); factory.setTypeAliasesPackage(MODEL_PACKAGE); //配置分页插件,详情请查阅官方文档 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("pageSizeZero", "true");//分页尺寸为0时查询所有纪录不再执行分页 properties.setProperty("reasonable", "true");//页码<=0 查询第一页,页码>=总页数查询最后一页 properties.setProperty("supportMethodsArguments", "true");//支持通过 Mapper 接口参数来传递分页参数 pageHelper.setProperties(properties); //添加插件 factory.setPlugins(new Interceptor[]{pageHelper}); //添加XML目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); factory.setMapperLocations(resolver.getResources("classpath:mapper/*.xml")); return factory.getObject(); }
@Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource, DataSourceProperties properties) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //分页插件 // PageHelper pageHelper = new PageHelper(); // Properties properties = new Properties(); // properties.setProperty("reasonable", "true"); // properties.setProperty("supportMethodsArguments", "true"); // properties.setProperty("returnPageInfo", "check"); // properties.setProperty("params", "count=countSql"); // pageHelper.setProperties(properties); //添加插件 // bean.setPlugins(new Interceptor[]{pageHelper}); ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setMapperLocations(resolver.getResources(properties.getMybatisMapperLocations())); return bean.getObject(); }
public List<Resource> findInterestResources(String basePackage) { String[] packages = StringUtils.tokenizeToStringArray(basePackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); List<Resource> allResource = new LinkedList<Resource>(); try { for (String pack : packages) { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(pack) + "/" + this.resourcePattern; Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath); allResource.addAll(Arrays.asList(resources)); } } catch (IOException ex) { throw new BeanDefinitionStoreException("扫描ClassPath的时候I/O资源错误", ex); } return allResource; }
public static void init() { ResourcePatternResolver resolver = new LodsvePathMatchingResourcePatternResolver(); List<Resource> resources = new ArrayList<>(); try { resources.addAll(Arrays.asList(resolver.getResources(ParamsHome.getInstance().getParamsRoot() + "/*.properties"))); resources.addAll(Arrays.asList(resolver.getResources(ParamsHome.getInstance().getParamsRoot() + "/framework/*.properties"))); } catch (IOException e) { return; } loadProperties(env, resources); // 获取覆盖的值 ParamsHome.getInstance().coveredWithExtResource(env); env.put("params.root", ParamsHome.getInstance().getParamsRoot()); }
public ModuleService(SpinnakerConfiguration spinnakerConfiguration, CloudFoundryAppDeployerFactory appDeployerFactory, ResourcePatternResolver ctx, CounterService counterService, TempFileManager fileManager, MavenProperties mavenProperties, ResourceLoader resourceLoader) { this.spinnakerConfiguration = spinnakerConfiguration; this.appDeployerFactory = appDeployerFactory; this.ctx = ctx; this.counterService = counterService; this.fileManager = fileManager; this.mavenProperties = mavenProperties; this.resourceLoader = resourceLoader; }
/** * Populate the given {@code registry} with the following resource editors: * ResourceEditor, InputStreamEditor, InputSourceEditor, FileEditor, URLEditor, * URIEditor, ClassEditor, ClassArrayEditor. * <p>If this registrar has been configured with a {@link ResourcePatternResolver}, * a ResourceArrayPropertyEditor will be registered as well. * @see org.springframework.core.io.ResourceEditor * @see org.springframework.beans.propertyeditors.InputStreamEditor * @see org.springframework.beans.propertyeditors.InputSourceEditor * @see org.springframework.beans.propertyeditors.FileEditor * @see org.springframework.beans.propertyeditors.URLEditor * @see org.springframework.beans.propertyeditors.URIEditor * @see org.springframework.beans.propertyeditors.ClassEditor * @see org.springframework.beans.propertyeditors.ClassArrayEditor * @see org.springframework.core.io.support.ResourceArrayPropertyEditor */ @Override public void registerCustomEditors(PropertyEditorRegistry registry) { ResourceEditor baseEditor = new ResourceEditor(this.resourceLoader, this.propertyResolver); doRegisterEditor(registry, Resource.class, baseEditor); doRegisterEditor(registry, ContextResource.class, baseEditor); doRegisterEditor(registry, InputStream.class, new InputStreamEditor(baseEditor)); doRegisterEditor(registry, InputSource.class, new InputSourceEditor(baseEditor)); doRegisterEditor(registry, File.class, new FileEditor(baseEditor)); doRegisterEditor(registry, Reader.class, new ReaderEditor(baseEditor)); doRegisterEditor(registry, URL.class, new URLEditor(baseEditor)); ClassLoader classLoader = this.resourceLoader.getClassLoader(); doRegisterEditor(registry, URI.class, new URIEditor(classLoader)); doRegisterEditor(registry, Class.class, new ClassEditor(classLoader)); doRegisterEditor(registry, Class[].class, new ClassArrayEditor(classLoader)); if (this.resourceLoader instanceof ResourcePatternResolver) { doRegisterEditor(registry, Resource[].class, new ResourceArrayPropertyEditor((ResourcePatternResolver) this.resourceLoader, this.propertyResolver)); } }
public synchronized void doScanExtension() { if(SCANNED){ return; } SCANNED = true; try { String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/META-INF/venus.exception.xml"; Resource[] resources = resourcePatternResolver.getResources(packageSearchPath); for (Resource resource : resources) { if (logger.isInfoEnabled()) { logger.info("Scanning " + resource); } if (resource.isReadable()) { load(resource); } else { if (logger.isInfoEnabled()) { logger.info("Ignored because not readable: " + resource); } } } } catch (IOException ex) { logger.error("read venus exception xml error", ex); } }
private Package findPackage(CharSequence source) { Package pkg = Package.getPackage(source.toString()); if (pkg != null) { return pkg; } try { // Attempt to find a class in this package ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver( getClass().getClassLoader()); Resource[] resources = resolver.getResources( ClassUtils.convertClassNameToResourcePath(source.toString()) + "/*.class"); for (Resource resource : resources) { String className = StringUtils .stripFilenameExtension(resource.getFilename()); load(Class.forName(source.toString() + "." + className)); break; } } catch (Exception ex) { // swallow exception and continue } return Package.getPackage(source.toString()); }
private boolean anyExists(ResourcePatternResolver resolver) throws IOException { String searchPath = this.path; if (searchPath.startsWith(ResourceLoader.CLASSPATH_URL_PREFIX)) { searchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + searchPath.substring(ResourceLoader.CLASSPATH_URL_PREFIX.length()); } if (searchPath.startsWith(ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX)) { Resource[] resources = resolver.getResources(searchPath); for (Resource resource : resources) { if (resource.exists()) { return true; } } } return false; }
/** * Returns an instance which uses the specified selector, as the name of the * definition file(s). In the case of a name with a Spring "classpath*:" prefix, * or with no prefix, which is treated the same, the current thread's context class * loader's {@code getResources} method will be called with this value to get * all resources having that name. These resources will then be combined to form a * definition. In the case where the name uses a Spring "classpath:" prefix, or * a standard URL prefix, then only one resource file will be loaded as the * definition. * @param selector the location of the resource(s) which will be read and * combined to form the definition for the BeanFactoryLocator instance. * Any such files must form a valid ApplicationContext definition. * @return the corresponding BeanFactoryLocator instance * @throws BeansException in case of factory loading failure */ public static BeanFactoryLocator getInstance(String selector) throws BeansException { String resourceLocation = selector; if (resourceLocation == null) { resourceLocation = DEFAULT_RESOURCE_LOCATION; } // For backwards compatibility, we prepend "classpath*:" to the selector name if there // is no other prefix (i.e. "classpath*:", "classpath:", or some URL prefix). if (!ResourcePatternUtils.isUrl(resourceLocation)) { resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation; } synchronized (instances) { if (logger.isTraceEnabled()) { logger.trace("ContextSingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + instances.hashCode() + ", instances=" + instances); } BeanFactoryLocator bfl = instances.get(resourceLocation); if (bfl == null) { bfl = new ContextSingletonBeanFactoryLocator(resourceLocation); instances.put(resourceLocation, bfl); } return bfl; } }
/** * Returns an instance which uses the specified selector, as the name of the * definition file(s). In the case of a name with a Spring 'classpath*:' prefix, * or with no prefix, which is treated the same, the current thread context * ClassLoader's {@code getResources} method will be called with this value * to get all resources having that name. These resources will then be combined to * form a definition. In the case where the name uses a Spring 'classpath:' prefix, * or a standard URL prefix, then only one resource file will be loaded as the * definition. * @param selector the name of the resource(s) which will be read and * combined to form the definition for the BeanFactoryLocator instance. * Any such files must form a valid BeanFactory definition. * @return the corresponding BeanFactoryLocator instance * @throws BeansException in case of factory loading failure */ public static BeanFactoryLocator getInstance(String selector) throws BeansException { String resourceLocation = selector; if (resourceLocation == null) { resourceLocation = DEFAULT_RESOURCE_LOCATION; } // For backwards compatibility, we prepend 'classpath*:' to the selector name if there // is no other prefix (i.e. classpath*:, classpath:, or some URL prefix. if (!ResourcePatternUtils.isUrl(resourceLocation)) { resourceLocation = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resourceLocation; } synchronized (instances) { if (logger.isTraceEnabled()) { logger.trace("SingletonBeanFactoryLocator.getInstance(): instances.hashCode=" + instances.hashCode() + ", instances=" + instances); } BeanFactoryLocator bfl = instances.get(resourceLocation); if (bfl == null) { bfl = new SingletonBeanFactoryLocator(resourceLocation); instances.put(resourceLocation, bfl); } return bfl; } }
/** Merge array. */ @Test public void mergeArray() { try { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); Resource resource1 = resourceResolver.getResource("classpath:jsonLever/src1.json"); Resource resource2 = resourceResolver.getResource("classpath:jsonLever/src2.json"); Resource resultResource = resourceResolver.getResource("classpath:jsonLever/resultArray.json"); JsonParser jsonParser = jsonLever.getJsonParser(); JsonElement src1 = jsonParser.parse(new InputStreamReader(resource1.getInputStream())); JsonElement src2 = jsonParser.parse(new InputStreamReader(resource2.getInputStream())); JsonElement result = jsonParser.parse(new InputStreamReader(resultResource.getInputStream())); JsonElement merge = jsonLever.merge(src1, src2, Boolean.TRUE); Assert.assertTrue(merge.isJsonObject()); Assert.assertEquals(result, merge); } catch (Exception e) { Assert.assertFalse(e.getMessage(), true); } }
/** * Gets the field equals. * * @return the field equals */ @Test public void getFieldEquals() { try { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); Resource samres = resourceResolver.getResource("classpath:jsonQuery/sample1.json"); Resource qres = resourceResolver.getResource("classpath:jsonQuery/query1.json"); JsonParser jsonParser = jsonLever.getJsonParser(); JsonElement sample = jsonParser.parse(new InputStreamReader(samres.getInputStream())); JsonElement query = jsonParser.parse(new InputStreamReader(qres.getInputStream())); jsonLever.asJsonObject(query).add("from", sample); JsonElement result = jq.query(query.getAsJsonObject()); Assert.assertTrue(jsonLever.isArray(result)); Assert.assertEquals(1, result.getAsJsonArray().size()); Assert.assertEquals("prajwal", jsonLever.asString(result.getAsJsonArray().get(0))); } catch (Exception e) { Assert.assertFalse(e.getMessage(), true); } }
/** * Gets the field equals or. * * @return the field equals or */ @Test public void getFieldEqualsOr() { try { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); Resource samres = resourceResolver.getResource("classpath:jsonQuery/sample1.json"); Resource qres = resourceResolver.getResource("classpath:jsonQuery/query5.json"); JsonParser jsonParser = jsonLever.getJsonParser(); JsonElement sample = jsonParser.parse(new InputStreamReader(samres.getInputStream())); JsonElement query = jsonParser.parse(new InputStreamReader(qres.getInputStream())); jsonLever.asJsonObject(query).add("from", sample); JsonElement result = jq.query(query.getAsJsonObject()); Assert.assertTrue(jsonLever.isArray(result)); Assert.assertEquals(2, result.getAsJsonArray().size()); Assert.assertEquals("prajwal", jsonLever.asString(result.getAsJsonArray().get(0))); Assert.assertEquals("paneesh", jsonLever.asString(result.getAsJsonArray().get(1))); } catch (Exception e) { Assert.assertFalse(e.getMessage(), true); } }
/** * Gets the field equals and. * * @return the field equals and */ @Test public void getFieldEqualsAnd() { try { ResourcePatternResolver resourceResolver = new PathMatchingResourcePatternResolver(); Resource samres = resourceResolver.getResource("classpath:jsonQuery/sample1.json"); Resource qres = resourceResolver.getResource("classpath:jsonQuery/query6.json"); JsonParser jsonParser = jsonLever.getJsonParser(); JsonElement sample = jsonParser.parse(new InputStreamReader(samres.getInputStream())); JsonElement query = jsonParser.parse(new InputStreamReader(qres.getInputStream())); jsonLever.asJsonObject(query).add("from", sample); JsonElement result = jq.query(query.getAsJsonObject()); Assert.assertTrue(jsonLever.isArray(result)); Assert.assertEquals(1, result.getAsJsonArray().size()); Assert.assertEquals("prajwal", jsonLever.asString(result.getAsJsonArray().get(0))); } catch (Exception e) { Assert.assertFalse(e.getMessage(), true); } }