Java Code Examples for org.springframework.util.ClassUtils#convertClassNameToResourcePath()

The following examples show how to use org.springframework.util.ClassUtils#convertClassNameToResourcePath() . 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
Source File: AbstractDataBaseBean.java    From spring-boot-starter-dao with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 2
Source File: SimpleMetadataReaderFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public MetadataReader getMetadataReader(String className) throws IOException {
	String resourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
			ClassUtils.convertClassNameToResourcePath(className) + ClassUtils.CLASS_FILE_SUFFIX;
	Resource resource = this.resourceLoader.getResource(resourcePath);
	if (!resource.exists()) {
		// Maybe an inner class name using the dot name syntax? Need to use the dollar syntax here...
		// ClassUtils.forName has an equivalent check for resolution into Class references later on.
		int lastDotIndex = className.lastIndexOf('.');
		if (lastDotIndex != -1) {
			String innerClassName =
					className.substring(0, lastDotIndex) + '$' + className.substring(lastDotIndex + 1);
			String innerClassResourcePath = ResourceLoader.CLASSPATH_URL_PREFIX +
					ClassUtils.convertClassNameToResourcePath(innerClassName) + ClassUtils.CLASS_FILE_SUFFIX;
			Resource innerClassResource = this.resourceLoader.getResource(innerClassResourcePath);
			if (innerClassResource.exists()) {
				resource = innerClassResource;
			}
		}
	}
	return getMetadataReader(resource);
}
 
Example 3
Source File: AnnotationMetadataReadingVisitorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
protected AnnotationMetadata get(Class<?> source) {
	try {
		ClassLoader classLoader = source.getClassLoader();
		String className = source.getName();
		String resourcePath = ResourceLoader.CLASSPATH_URL_PREFIX
				+ ClassUtils.convertClassNameToResourcePath(className)
				+ ClassUtils.CLASS_FILE_SUFFIX;
		Resource resource = new DefaultResourceLoader().getResource(resourcePath);
		try (InputStream inputStream = new BufferedInputStream(
				resource.getInputStream())) {
			ClassReader classReader = new ClassReader(inputStream);
			AnnotationMetadataReadingVisitor metadata = new AnnotationMetadataReadingVisitor(
					classLoader);
			classReader.accept(metadata, ClassReader.SKIP_DEBUG);
			return metadata;
		}
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 4
Source File: ClassPathTestScanner.java    From COLA with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Set<Class<?>> findTestComponents(String... basePackages) throws Exception {
    Set<Class<?>> testClzzList = new HashSet<>();
    for(String basePackage : basePackages){
        if(StringUtils.isBlank(basePackage)){
            continue;
        }
        String resourcePath = ClassUtils.convertClassNameToResourcePath(this.environment.resolveRequiredPlaceholders(basePackage));

        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            resourcePath + '/' + DEFAULT_RESOURCE_PATTERN;
        Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);
        for(Resource res : resources){
            Class testClass = Thread.currentThread().getContextClassLoader().loadClass(getClassName(res));
            if(!isColaTestClass(testClass)){
                continue;
            }
            testClzzList.add(testClass);
        }
    }

    return testClzzList;
}
 
Example 5
Source File: HandlerAnnotationFactoryBean.java    From MultimediaDesktop with Apache License 2.0 6 votes vote down vote up
private void beforeHandlerResource(
		ConcurrentHashMap<String, ConcurrentHashMap<HandlerScope, LinkedList<String>>> handlersMap) {
	try {

		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);

				onHandlerResource(resources, readerFactory, handlersMap);

			}
		}
	} catch (IOException e) {
		log.fatal("扫描业务处理异常", e);
	}
}
 
Example 6
Source File: MongoXmlParser.java    From jstarcraft-core with 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 7
Source File: CommunicationXmlParser.java    From jstarcraft-core with 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 name = CommunicationModule.class.getName();
        for (Resource resource : resources) {
            if (!resource.isReadable()) {
                continue;
            }
            // 判断是否静态资源
            MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
            AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
            if (!annotationMetadata.hasAnnotation(name)) {
                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 CommunicationConfigurationException(message, exception);
    }
}
 
Example 8
Source File: SqlScriptsTestExecutionListener.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]", prefixedResourcePath,
				elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: "
				+ "%s does not exist. Either declare statements or scripts via @Sql or make the "
				+ "default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 9
Source File: SqlScriptsTestExecutionListener.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
					prefixedResourcePath, elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
				"%s does not exist. Either declare statements or scripts via @Sql or make the " +
				"default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 10
Source File: EnumDictHandlerRegister.java    From hsweb-framework with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("all")
public static void register(String[] packages) {
    if (typeHandlerRegistry == null) {
        log.error("请在spring容器初始化后再调用此方法!");
        return;
    }
    for (String basePackage : packages) {
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                ClassUtils.convertClassNameToResourcePath(basePackage) + "/**/*.class";
        try {
            Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
            for (Resource resource : resources) {
                try {
                    MetadataReader reader = metadataReaderFactory.getMetadataReader(resource);
                    Class enumType = Class.forName(reader.getClassMetadata().getClassName());
                    if (enumType.isEnum() && EnumDict.class.isAssignableFrom(enumType)) {
                        log.debug("register enum dict:{}", enumType);
                        DefaultDictDefineRepository.registerDefine(DefaultDictDefineRepository.parseEnumDict(enumType));
                        //注册枚举类型
                        typeHandlerRegistry.register(enumType, new EnumDictHandler(enumType));

                        //注册枚举数组类型
                        typeHandlerRegistry.register(Array.newInstance(enumType, 0).getClass(), new EnumDictArrayHandler(enumType));
                    }
                } catch (Exception | Error ignore) {

                }
            }
        } catch (IOException e) {
            log.warn("register enum dict error", e);
        }
    }
}
 
Example 11
Source File: PluginClassLoader.java    From springboot-plugin-framework-parent with Apache License 2.0 5 votes vote down vote up
@Override
public ResourceWrapper load(BasePlugin basePlugin) throws Exception{
    String scanPackage = basePlugin.scanPackage();
    String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
            ClassUtils.convertClassNameToResourcePath(scanPackage) +
            "/**/*.class";
    ResourcePatternResolver resourcePatternResolver =
            new PathMatchingResourcePatternResolver(basePlugin.getWrapper().getPluginClassLoader());
    Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
    if(resources == null){
        return new ResourceWrapper();
    }
    return new ResourceWrapper(resources);
}
 
Example 12
Source File: SqlScriptsTestExecutionListener.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Detect a default SQL script by implementing the algorithm defined in
 * {@link Sql#scripts}.
 */
private String detectDefaultScript(TestContext testContext, boolean classLevel) {
	Class<?> clazz = testContext.getTestClass();
	Method method = testContext.getTestMethod();
	String elementType = (classLevel ? "class" : "method");
	String elementName = (classLevel ? clazz.getName() : method.toString());

	String resourcePath = ClassUtils.convertClassNameToResourcePath(clazz.getName());
	if (!classLevel) {
		resourcePath += "." + method.getName();
	}
	resourcePath += ".sql";

	String prefixedResourcePath = ResourceUtils.CLASSPATH_URL_PREFIX + resourcePath;
	ClassPathResource classPathResource = new ClassPathResource(resourcePath);

	if (classPathResource.exists()) {
		if (logger.isInfoEnabled()) {
			logger.info(String.format("Detected default SQL script \"%s\" for test %s [%s]",
					prefixedResourcePath, elementType, elementName));
		}
		return prefixedResourcePath;
	}
	else {
		String msg = String.format("Could not detect default SQL script for test %s [%s]: " +
				"%s does not exist. Either declare statements or scripts via @Sql or make the " +
				"default SQL script available.", elementType, elementName, classPathResource);
		logger.error(msg);
		throw new IllegalStateException(msg);
	}
}
 
Example 13
Source File: LuceneXmlParser.java    From jstarcraft-core with 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 14
Source File: ClassScanner.java    From kaif with Apache License 2.0 4 votes vote down vote up
private static String resolveBasePackage(String basePackage) {
  return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(
      basePackage));
}
 
Example 15
Source File: DefaultPersistenceUnitManager.java    From java-technology-stack with MIT License 4 votes vote down vote up
private void scanPackage(SpringPersistenceUnitInfo scannedUnit, String pkg) {
	if (this.componentsIndex != null) {
		Set<String> candidates = new HashSet<>();
		for (AnnotationTypeFilter filter : entityTypeFilters) {
			candidates.addAll(this.componentsIndex.getCandidateTypes(pkg, filter.getAnnotationType().getName()));
		}
		candidates.forEach(scannedUnit::addManagedClassName);
		Set<String> managedPackages = this.componentsIndex.getCandidateTypes(pkg, "package-info");
		managedPackages.forEach(scannedUnit::addManagedPackage);
		return;
	}

	try {
		String pattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
				ClassUtils.convertClassNameToResourcePath(pkg) + CLASS_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 (matchesFilter(reader, readerFactory)) {
					scannedUnit.addManagedClassName(className);
					if (scannedUnit.getPersistenceUnitRootUrl() == null) {
						URL url = resource.getURL();
						if (ResourceUtils.isJarURL(url)) {
							scannedUnit.setPersistenceUnitRootUrl(ResourceUtils.extractJarFileURL(url));
						}
					}
				}
				else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
					scannedUnit.addManagedPackage(
							className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
				}
			}
		}
	}
	catch (IOException ex) {
		throw new PersistenceException("Failed to scan classpath for unlisted entity classes", ex);
	}
}
 
Example 16
Source File: JFishResourcesScanner.java    From onetwo with Apache License 2.0 4 votes vote down vote up
protected String resolveBasePackage(String basePackage) {
	return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
 
Example 17
Source File: AbstractScanConfiguration.java    From cuba with Apache License 2.0 4 votes vote down vote up
protected String resolveBasePackage(String basePackage) {
    Environment environment = getEnvironment();
    return ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(basePackage));
}
 
Example 18
Source File: AutomaticJobRegistrarConfiguration.java    From spring-boot-starter-batch-web with Apache License 2.0 4 votes vote down vote up
private String resolveBasePackage(String basePackage) {
	return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils.resolvePlaceholders(basePackage));
}
 
Example 19
Source File: ClassPathScanningCandidateComponentProvider.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Resolve the specified base package into a pattern specification for
 * the package search path.
 * <p>The default implementation resolves placeholders against system properties,
 * and converts a "."-based package path to a "/"-based resource path.
 * @param basePackage the base package as specified by the user
 * @return the pattern specification to be used for package searching
 */
protected String resolveBasePackage(String basePackage) {
	return ClassUtils.convertClassNameToResourcePath(this.environment.resolveRequiredPlaceholders(basePackage));
}
 
Example 20
Source File: AbstractRefactoringTests.java    From Refactoring-Bot with MIT License 2 votes vote down vote up
/**
 * Returns the test resource file that was determined based on the test
 * resources class
 * 
 * @param clazz
 * @return
 */
private File getTestResourcesFile(Class<?> clazz) {
	String pathToTestResources = TestUtils.TEST_FOLDER_PATH + ClassUtils.convertClassNameToResourcePath(clazz.getName())
			+ JAVA_FILE_EXTENSION;
	return new File(pathToTestResources);
}