下面列出了org.springframework.core.io.support.PathMatchingResourcePatternResolver#getResources ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Populate the database with the available bootstrap themes found in the jar. This enables the
* release of the application with a set of predefined bootstrap themes.
*
* <p>If a given bootstrap 3 theme is located a matching bootstrap 4 theme is added the the
* styleSheet row is present.
*/
public void populate() {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
Resource[] bootstrap3Themes = resolver.getResources(LOCAL_CSS_BOOTSTRAP_3_THEME_LOCATION);
Resource[] bootstrap4Themes = resolver.getResources(LOCAL_CSS_BOOTSTRAP_4_THEME_LOCATION);
// filter out themes already stored in the database
List<Resource> newThemes =
Arrays.stream(bootstrap3Themes)
.filter(
theme ->
dataService.getRepository(STYLE_SHEET).findOneById(theme.getFilename())
== null)
.collect(Collectors.toList());
newThemes.forEach(nt -> addNewTheme(nt, bootstrap4Themes));
} catch (Exception e) {
LOG.error("error populating bootstrap themes", e);
}
}
File generate(List<Project> projects,
List<ConfigurationProperty> configurationProperties) {
PathMatchingResourcePatternResolver resourceLoader = new PathMatchingResourcePatternResolver();
try {
Resource[] resources = resourceLoader
.getResources("templates/spring-cloud/*.hbs");
List<TemplateProject> templateProjects = templateProjects(projects);
for (Resource resource : resources) {
File templateFile = resource.getFile();
File outputFile = new File(outputFolder, renameTemplate(templateFile));
Template template = template(templateFile.getName().replace(".hbs", ""));
Map<String, Object> map = new HashMap<>();
map.put("projects", projects);
map.put("springCloudProjects", templateProjects);
map.put("properties", configurationProperties);
String applied = template.apply(map);
Files.write(outputFile.toPath(), applied.getBytes());
info("Successfully rendered [" + outputFile.getAbsolutePath() + "]");
}
}
catch (IOException e) {
throw new IllegalStateException(e);
}
return outputFolder;
}
public List<TemplatePackInfo> resolveTopLevelPacks() {
List<TemplatePackInfo> packInfos = newArrayList();
PathMatchingResourcePatternResolver o = new PathMatchingResourcePatternResolver();
try {
Resource packInfosAsResource[] = o.getResources(CLASSPATH_CELERIO_PACK);
for (Resource r : packInfosAsResource) {
CelerioPack celerioPack = celerioPackConfigLoader.load(r.getInputStream());
packInfos.add(new TemplatePackInfo(celerioPack));
}
return packInfos;
} catch (IOException ioe) {
throw new RuntimeException("Error while searching for Celerio template pack having a META-INF/celerio-pack.xml file!", ioe);
}
}
/**
* Scan the classpath for SQL configurations.
*/
protected List<SqlConfInfo> getSqlConfInfos() {
List<SqlConfInfo> packInfos = newArrayList();
PathMatchingResourcePatternResolver o = new PathMatchingResourcePatternResolver();
try {
Resource packInfosAsResource[] = o.getResources("classpath*:sqlconf/*/00-info.txt");
for (Resource r : packInfosAsResource) {
packInfos.add(new SqlConfInfo(r));
}
Collections.sort(packInfos);
return packInfos;
} catch (IOException ioe) {
throw new RuntimeException("Error while searching for SQL CONF having a sqlconf/*/00-info.txt file!", ioe);
}
}
protected void initMessageSource(String namesPackage) {
Set<String> fileNames = new HashSet<String>();
try {
PathMatchingResourcePatternResolver r = new PathMatchingResourcePatternResolver();
String pack = (!namesPackage.endsWith("/") ? namesPackage + "/" : namesPackage);
Resource[] resources = r.getResources("classpath*:" + pack + "*.properties");
for (Resource resource : resources) {
int endIdx = resource.getFilename().indexOf('_');
if (endIdx < 0) {
endIdx = resource.getFilename().indexOf(".properties");
}
fileNames.add(pack + resource.getFilename().substring(0, endIdx));
}
} catch (IOException e) {
throw new RuntimeException(e);
}
setBasenames(fileNames.toArray(new String[fileNames.size()]));
}
/**
* Let typeAliasesPackage alias bean support wildcards.
*
* @return
*/
private Class<?>[] getTypeAliases(PathMatchingResourcePatternResolver resolver) throws Exception {
List<Class<?>> typeAliases = new ArrayList<>();
// Define metadataReader
MetadataReaderFactory metadataReaderFty = new CachingMetadataReaderFactory(resolver);
for (String pkg : typeAliasesPackage.split(",")) {
// Get location
String location = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath(pkg)
+ "**/*.class";
// Get resources.
Resource[] resources = resolver.getResources(location);
if (resources != null) {
for (Resource resource : resources) {
if (resource.isReadable()) {
MetadataReader metadataReader = metadataReaderFty.getMetadataReader(resource);
typeAliases.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
}
}
}
}
return typeAliases.toArray(new Class<?>[] {});
}
protected void testLabelsTranslations(String propertiesFolder, String properties1, String properties2) throws Throwable {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources1 = resolver.getResources(propertiesFolder + properties1);
Resource[] resources2 = resolver.getResources(propertiesFolder + properties2);
Properties props1 = new Properties();
Properties props2 = new Properties();
props1.load(resources1[0].getInputStream());
props2.load(resources2[0].getInputStream());
Set<String> stringPropertyNames1 = props1.stringPropertyNames();
Set<String> stringPropertyNames2 = props2.stringPropertyNames();
stringPropertyNames1.removeAll(stringPropertyNames2);
stringPropertyNames1.forEach((v) -> {
logger.error("{}{} -> found error for the key {} check this or {} file to fix this error", propertiesFolder, properties1, v, properties2);
});
assertEquals(0, stringPropertyNames1.size());
stringPropertyNames1 = props1.stringPropertyNames();
stringPropertyNames2 = props2.stringPropertyNames();
stringPropertyNames2.removeAll(stringPropertyNames1);
stringPropertyNames2.forEach((v) -> {
logger.error("{}{} found error for the key {} check this or {} file to fix this error", propertiesFolder, properties2, v, properties1);
});
assertEquals(0, stringPropertyNames2.size());
}
private List<String> getJarList(String path) {
List<String> list = new ArrayList<>();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
Resource[] res = resolver.getResources(path);
for (Resource r : res) {
String name = r.getFilename();
if (name != null) {
list.add(name.endsWith(JAR) ? name.substring(0, name.length() - JAR.length()) : name);
}
}
} catch (IOException e) {
// ok to ignore
}
return list;
}
@Bean(name = "sqlSessionFactory")
@Primary
public SqlSessionFactoryBean createSqlSessionFactoryBean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
/** 设置datasource */
sqlSessionFactoryBean.setDataSource(dataSource1);
VFS.addImplClass(SpringBootVFS.class);
/** 设置mybatis configuration 扫描路径 */
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("Configuration.xml"));
/** 设置typeAlias 包扫描路径 */
sqlSessionFactoryBean.setTypeAliasesPackage("indi.mybatis.flying");
/** 添加mapper 扫描路径 */
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] ra1 = resolver.getResources("classpath*:indi/mybatis/flying/mapper*/*.xml");
sqlSessionFactoryBean.setMapperLocations(ra1); // 扫描映射文件
return sqlSessionFactoryBean;
}
@Bean(name = "sqlSessionFactory2")
@Primary
public SqlSessionFactoryBean createSqlSessionFactory2Bean() throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
/** 设置datasource */
sqlSessionFactoryBean.setDataSource(dataSource2);
VFS.addImplClass(SpringBootVFS.class);
/** 设置mybatis configuration 扫描路径 */
sqlSessionFactoryBean.setConfigLocation(new ClassPathResource("Configuration.xml"));
/** 设置typeAlias 包扫描路径 */
sqlSessionFactoryBean.setTypeAliasesPackage("indi.mybatis.flying");
/** 添加mapper 扫描路径 */
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] ra1 = resolver.getResources("classpath*:indi/mybatis/flying/mapper*/*.xml");
sqlSessionFactoryBean.setMapperLocations(ra1); // 扫描映射文件
return sqlSessionFactoryBean;
}
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//mybatis配置
Properties prop = new Properties();
prop.setProperty("mapUnderscoreToCamelCase", "true");
sqlSessionFactoryBean.setConfigurationProperties(prop);
sqlSessionFactoryBean.setTypeAliasesPackage("com.tc.ly.bean");
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:mapper/*.xml");
sqlSessionFactoryBean.setMapperLocations(resources);
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean;
}
@Override
public void execute() {
try {
sourceDirectory = makeAbsolute(sourceDirectory);
outputDirectory = makeAbsolute(outputDirectory);
if ( ! sourceDirectory.exists() ) return;
getLog().debug("Running ApiGen\n\tsourceDirectory=" + sourceDirectory +
"\n\toutputDirectory=" + outputDirectory);
ClassLoader cp = getCompileClassLoader();
ApiGen apiGen = new ApiGen.Builder()
.withOutputDirectory(outputDirectory.toPath())
.withGuiceModuleName(guiceModuleName)
.withDefaultPackageName(defaultPackageName)
.build();
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cp);
for ( org.springframework.core.io.Resource resource : resolver.getResources("classpath*:graphql-apigen-schema/*.graphql{,s}") ) {
URL url = resource.getURL();
getLog().debug("Processing "+url);
apiGen.addForReference(url);
}
findGraphql(sourceDirectory, apiGen::addForGeneration);
apiGen.generate();
Resource schemaResource = new Resource();
schemaResource.setTargetPath("graphql-apigen-schema");
schemaResource.setFiltering(false);
schemaResource.setIncludes(Arrays.asList("*.graphqls","*.graphql"));
schemaResource.setDirectory(sourceDirectory.toString());
project.addResource(schemaResource);
project.addCompileSourceRoot(outputDirectory.getAbsolutePath());
} catch (Exception e) {
String msg = e.getMessage();
if ( null == msg ) msg = e.getClass().getName();
getLog().error(msg + " when trying to build sources from graphql.", e);
}
}
/**
*/
public void setLocations(List<String> fileNames) {
List<Resource> resources = new ArrayList<Resource>();
for (String filename : fileNames) {
// trim
filename = filename.trim();
String realFileName = getFileName(filename);
//
// register to disconf
//
DisconfMgr.getInstance().reloadableScan(realFileName);
//
// only properties will reload
//
String ext = FilenameUtils.getExtension(filename);
if (ext.equals("properties")) {
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver =
new PathMatchingResourcePatternResolver();
try {
Resource[] resourceList = pathMatchingResourcePatternResolver.getResources(filename);
for (Resource resource : resourceList) {
resources.add(resource);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
this.locations = resources.toArray(new Resource[resources.size()]);
lastModified = new long[locations.length];
super.setLocations(locations);
}
private Map<String, List<PropertyInfo>> calculate() throws IOException {
Map<String, List<PropertiesInfoCollector.PropertyInfo>> propertyMap = new HashMap<>();
PathMatchingResourcePatternResolver pathPatternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources = pathPatternResolver.getResources(locationPattern);
if (resources == null || resources.length == 0) {
return Collections.unmodifiableMap(new HashMap<>());
}
Arrays.stream(resources).map(this::retrieve)
.forEach(file -> {
final String[] group = {""};
final String[] name = {null};
final String[] description = {""};
file.forEach(str -> {
for (String line : str.split("\n")) {
line = clean(line);
if (!line.isEmpty()) {
if (isGroup(line)) {
group[0] = line.replaceFirst("##", "").trim();
} else if (name[0] == null && isNameOrDescription(line)) {
name[0] = line;
} else if (name[0] != null && isNameOrDescription(line)) {
description[0] = description[0].concat(line).concat("\n");
} else { //is val
propertyMap.computeIfAbsent(group[0], key -> new ArrayList<>())
.add(new PropertiesInfoCollector.PropertyInfo(getKey(line), group[0], name[0], description[0]));
name[0] = null;
description[0] = "";
}
}
}
});
});
Map<String, List<PropertiesInfoCollector.PropertyInfo>> propertyMapNotModified = new ConcurrentHashMap<>();
propertyMap.forEach((k, v) -> propertyMapNotModified.put(k, Collections.unmodifiableList(v)));
return Collections.unmodifiableMap(propertyMapNotModified);
}
private void loadApiResources(String locationPattern) throws Exception {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(locationPattern);
ApiResourcesDefDOM dom = null;
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
InputStream is = null;
String path = resource.getURL().getPath();
try {
is = resource.getInputStream();
String xml = FileTextReader.getText(is);
dom = new ApiResourcesDefDOM(xml, path);
Map<String, ApiResource> extractedResources = dom.getResources();
if (null != extractedResources) {
Iterator<ApiResource> extractedResourcesIter = extractedResources.values().iterator();
while (extractedResourcesIter.hasNext()) {
ApiResource apiResource = extractedResourcesIter.next();
if (null != this.getResources().get(apiResource.getCode())) {
_logger.info("Into definition file '{}' there is an API with namespace '{}', resource '{}' and there is just one already present - The old definition will be overrided!!!", path, apiResource.getNamespace(), apiResource.getResourceName());
}
this.getResources().put(apiResource.getCode(), apiResource);
}
}
_logger.debug("Loaded Api Resources definition by file {}", path);
} catch (Throwable t) {
_logger.error("Error loading Api Resources definition by location Pattern '{}'",path, t);
//ApsSystemUtils.logThrowable(t, this, "loadApiResources", "Error loading Api Resources definition by location Pattern '" + path + "'");
} finally {
if (null != is) {
is.close();
}
}
}
}
public static void main(String[] args) throws Exception {
String locationPattern = "classpath:/org/wallride/domain/*";
final BootstrapServiceRegistry registry = new BootstrapServiceRegistryBuilder().build();
final MetadataSources metadataSources = new MetadataSources(registry);
final StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(registry);
registryBuilder.applySetting(AvailableSettings.DIALECT, ExtendedMySQL5InnoDBDialect.class.getCanonicalName());
registryBuilder.applySetting(AvailableSettings.GLOBALLY_QUOTED_IDENTIFIERS, true);
registryBuilder.applySetting(AvailableSettings.PHYSICAL_NAMING_STRATEGY, PhysicalNamingStrategySnakeCaseImpl.class);
final PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
final Resource[] resources = resourcePatternResolver.getResources(locationPattern);
final SimpleMetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
for (Resource resource : resources) {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
if (metadata.hasAnnotation(Entity.class.getName())) {
metadataSources.addAnnotatedClass(Class.forName(metadata.getClassName()));
}
}
final StandardServiceRegistryImpl registryImpl = (StandardServiceRegistryImpl) registryBuilder.build();
final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder(registryImpl);
new SchemaExport()
.setHaltOnError(true)
.setDelimiter(";")
.create(EnumSet.of(TargetType.STDOUT), metadataBuilder.build());
}
private List<String> readFolderContent(String path) {
List<String> files = new ArrayList<String>();
try {
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources("classpath:" + path + "/*");
assertThat(resources.length, greaterThan(0));
for (Resource res : resources) {
files.add(res.getFilename());
}
} catch (IOException e) {
fail("unable to load resources from " + path);
}
return files;
}
private void setupRepo() throws Exception
{
AuthenticationUtil.clearCurrentSecurityContext();
AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getSystemUserName());
// Create a test workspace
this.testStoreRef = this.nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "Test_" + System.currentTimeMillis());
// Get a reference to the root node
NodeRef rootNodeRef = this.nodeService.getRootNode(this.testStoreRef);
// Create and authenticate the user
if(!authenticationService.authenticationExists(AuthenticationUtil.getAdminUserName()))
{
authenticationService.createAuthentication(AuthenticationUtil.getAdminUserName(), PWD.toCharArray());
}
// Authenticate - as admin
authenticationService.authenticate(AuthenticationUtil.getAdminUserName(), PWD.toCharArray());
// Store test messages in repo
String pattern = "classpath*:" + BASE_RESOURCE_CLASSPATH + BASE_BUNDLE_NAME + "*";
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
Resource[] resources = resolver.getResources(pattern);
if (resources != null)
{
for (int i = 0; i < resources.length; i++)
{
String filename = resources[i].getFilename();
addMessageResource(rootNodeRef, filename, resources[i].getInputStream());
}
}
}
/**
* Create permission set for jira project
*
* @param project the project
* @return the number of created permission sets
*/
public int createSpecialPermissions(OpenProjectData project) {
if (!isSpecialPermissionSchemeEnabled()) {
logger.info(
"Do not create special permission set for project {}, "
+ "since property jira.specialpermissionschema.enabled=false",
project.projectKey);
return 0;
}
PathMatchingResourcePatternResolver pmrl =
new PathMatchingResourcePatternResolver(Thread.currentThread().getContextClassLoader());
int updatedPermissions = 0;
try {
Resource[] permissionFiles = pmrl.getResources(jiraPermissionFilePattern);
logger.debug("Found permissionsets: {}", permissionFiles.length);
for (Resource permissionFile : permissionFiles) {
PermissionScheme singleScheme =
new ObjectMapper().readValue(permissionFile.getInputStream(), PermissionScheme.class);
String permissionSchemeName = project.projectKey + " PERMISSION SCHEME";
singleScheme.setName(permissionSchemeName);
String description = project.description;
if (description != null && description.length() > 0) {
singleScheme.setDescription(description);
} else {
singleScheme.setDescription(permissionSchemeName);
}
// replace group with real group
for (Permission permission : singleScheme.getPermissions()) {
String group = permission.getHolder().getParameter();
if ("adminGroup".equals(group)) {
permission.getHolder().setParameter(project.projectAdminGroup);
} else if ("userGroup".equals(group)) {
permission.getHolder().setParameter(project.projectUserGroup);
} else if ("readonlyGroup".equals(group)) {
permission.getHolder().setParameter(project.projectReadonlyGroup);
} else if ("keyuserGroup".equals(group)) {
permission.getHolder().setParameter(globalKeyuserRoleName);
}
}
logger.debug(
"Update permissionScheme {} location: {}",
permissionSchemeName,
permissionFile.getFilename());
String path = String.format("%s%s/permissionscheme", jiraUri, jiraApiPath);
RestClientCall call =
httpPost()
.url(path)
.body(singleScheme)
.returnTypeReference(new TypeReference<PermissionScheme>() {});
singleScheme = getRestClient().execute(call);
// update jira project
path =
String.format(
"%s%s/project/%s/permissionscheme", jiraUri, jiraApiPath, project.projectKey);
PermissionScheme small = new PermissionScheme();
small.setId(singleScheme.getId());
getRestClient().execute(httpPut().body(small).url(path).returnType(null));
updatedPermissions++;
}
} catch (Exception createPermissions) {
// continue - we are ok if permissions fail, because the admin has access, and
// can create / link the set
logger.error(
"Could not update jira project permissionset: {} Exception: {} ",
project.projectKey,
createPermissions.getMessage());
}
return updatedPermissions;
}
/**
* Figure out which resource to start with in case of restart, open the delegate and restore delegate's position in
* the resource.
*/
@Override
public void open(ExecutionContext executionContext) throws ItemStreamException {
super.open(executionContext);
Assert.notNull(resourcesLocationPattern, "ResourcesLocationPattern must be set");
PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
try {
//新增:动态读取资源文件列表
resources = patternResolver.getResources(resourcesLocationPattern);
} catch (IOException e) {
e.printStackTrace();
}
noInput = false;
if (resources.length == 0) {
if (strict) {
throw new IllegalStateException(
"No resources to read. Set strict=false if this is not an error condition.");
}
else {
logger.warn("No resources to read. Set strict=true if this should be an error condition.");
noInput = true;
return;
}
}
Arrays.sort(resources, comparator);
if (executionContext.containsKey(getExecutionContextKey(RESOURCE_KEY))) {
currentResource = executionContext.getInt(getExecutionContextKey(RESOURCE_KEY));
// context could have been saved before reading anything
if (currentResource == -1) {
currentResource = 0;
}
delegate.setResource(resources[currentResource]);
delegate.open(executionContext);
}
else {
currentResource = -1;
}
}