Leitura de resources de configuração [RESOLVIDO]

1 resposta
dondiego

Galera!

Boa tarde!

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

Alguém conhece alguma solução sem ser o Spring?

Abraços!

1 Resposta

dondiego

Galera,

resolvei a parada! E acho que nem era lá java avançado! :D

public Collection<String> withName(String resourceName) {

		// TODO necessita refactoring pesado.

		URLClassLoader c = (URLClassLoader) Thread.currentThread().getContextClassLoader();
		ArrayList<String> ryans = new ArrayList<String>();
		for (URL url : c.getURLs()) {
			ryans.addAll((ArrayList<String>) getResources(url.getPath(), Pattern.compile(resourceName)));
		}

		return ryans;
	}

	private Collection<String> getResourcesFromDirectory(File directory, Pattern pattern) {
		ArrayList<String> retval = new ArrayList<String>();
		File[] fileList = directory.listFiles();
		for (File file : fileList) {
			if (file.isDirectory()) {
				retval.addAll(getResourcesFromDirectory(file, pattern));
			} else {
				try {
					String fileName = file.getCanonicalPath();
					boolean accept = pattern.matcher(fileName).matches();
					if (accept) {
						retval.add(fileName);
					}
				} catch (IOException e) {
					throw new Error(e);
				}
			}
		}
		return retval;
	}

	private Collection<String> getResourcesFromJarFile(File file, Pattern pattern) {
		ArrayList<String> retval = new ArrayList<String>();
		ZipFile zf;
		try {
			zf = new ZipFile(file);
		} catch (ZipException e) {
			throw new Error(e);
		} catch (IOException e) {
			throw new Error(e);
		}
		Enumeration<? extends ZipEntry> e = zf.entries();
		while (e.hasMoreElements()) {
			ZipEntry ze = (ZipEntry) e.nextElement();
			String fileName = ze.getName();
			boolean accept = pattern.matcher(fileName).matches();
			if (accept) {
				retval.add(fileName);
			}
		}
		try {
			zf.close();
		} catch (IOException e1) {
			throw new Error(e1);
		}
		return retval;
	}

	private Collection<String> getResources(String element, Pattern pattern) {
		ArrayList<String> retval = new ArrayList<String>();
		File file = new File(element);
		if (file.isDirectory()) {
			retval.addAll(getResourcesFromDirectory(file, pattern));
		} else {
			retval.addAll(getResourcesFromJarFile(file, pattern));
		}
		return retval;
	}

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.

Abraços!

Criado 3 de fevereiro de 2011
Ultima resposta 8 de fev. de 2011
Respostas 1
Participantes 1