tô com o seguinte problema: estou querendo implementar a facilidade de busca de arquivos xml que o Spring tem (usando regras como ‘classpath*’, ‘file’) sem poder usar o Spring. Ou seja, preciso daquela inteligência bem out-of-a-box.
Eu tentei bastante aqui com o
getResourceAsStream("file.name")
tanto do Classloader da classe que chama, quanto da thread corrente, mas passando wildcards (como o do maven: ‘**/*.xml’) o getResourceAsStream não acha.
Ou seja, quero passar um pattern (como ‘**.teste.xml’) e o sistema for capaz de buscar arquivos nesse padrão utilizando todo o classpath corrente (inclusive de bibliotecas importadas).
resolvei a parada! E acho que nem era lá java avançado! :D
publicCollection<String>withName(StringresourceName){// TODO necessita refactoring pesado.URLClassLoaderc=(URLClassLoader)Thread.currentThread().getContextClassLoader();ArrayList<String>ryans=newArrayList<String>();for(URLurl:c.getURLs()){ryans.addAll((ArrayList<String>)getResources(url.getPath(),Pattern.compile(resourceName)));}returnryans;}privateCollection<String>getResourcesFromDirectory(Filedirectory,Patternpattern){ArrayList<String>retval=newArrayList<String>();File[]fileList=directory.listFiles();for(Filefile:fileList){if(file.isDirectory()){retval.addAll(getResourcesFromDirectory(file,pattern));}else{try{StringfileName=file.getCanonicalPath();booleanaccept=pattern.matcher(fileName).matches();if(accept){retval.add(fileName);}}catch(IOExceptione){thrownewError(e);}}}returnretval;}privateCollection<String>getResourcesFromJarFile(Filefile,Patternpattern){ArrayList<String>retval=newArrayList<String>();ZipFilezf;try{zf=newZipFile(file);}catch(ZipExceptione){thrownewError(e);}catch(IOExceptione){thrownewError(e);}Enumeration<?extendsZipEntry>e=zf.entries();while(e.hasMoreElements()){ZipEntryze=(ZipEntry)e.nextElement();StringfileName=ze.getName();booleanaccept=pattern.matcher(fileName).matches();if(accept){retval.add(fileName);}}try{zf.close();}catch(IOExceptione1){thrownewError(e1);}returnretval;}privateCollection<String>getResources(Stringelement,Patternpattern){ArrayList<String>retval=newArrayList<String>();Filefile=newFile(element);if(file.isDirectory()){retval.addAll(getResourcesFromDirectory(file,pattern));}else{retval.addAll(getResourcesFromJarFile(file,pattern));}returnretval;}
Eu achei isso em um fórum, mas não me lembro aonde.
Outra coisa: usa bastante conceitos básicos (ex.: pega o arquivo utilizando o path absoluto), deve ter alguma implementação mais alto-nível.