001 package com.ochafik.net;
002
003 import java.io.File;
004 import java.io.IOException;
005 import java.io.InputStream;
006 import java.net.URL;
007 import java.util.ArrayList;
008 import java.util.List;
009 import java.util.jar.JarEntry;
010 import java.util.jar.JarInputStream;
011
012 import com.ochafik.util.listenable.Filter;
013
014 public class URLUtils {
015
016 public static URL getResource(Class<?> cl, String path) throws IOException {
017 String clp = cl.getName().replace('.', '/') + ".class";
018 URL clu = cl.getClassLoader().getResource(clp);
019 String s = clu.toString();
020 if (s.endsWith(clp))
021 return new URL(s.substring(0, s.length() - clp.length()) + path);
022
023 if (s.startsWith("jar:")) {
024 String[] ss = s.split("!");
025 return new URL(ss[1] + "!/" + path);
026 }
027 return null;
028 }
029
030 public static List<URL> listFiles(URL directory, Filter<String> pathAccepter) throws IOException {
031 List<URL> ret = new ArrayList<URL>();
032 String s = directory.toString();
033 if (s.startsWith("jar:")) {
034 String[] ss = s.substring("jar:".length()).split("!");
035 String path = ss[1];
036 URL target = new URL(ss[0]);
037 InputStream tin = target.openStream();
038 try {
039 JarInputStream jin = new JarInputStream(tin);
040 JarEntry je;
041 while ((je = jin.getNextJarEntry()) != null) {
042 String p = "/" + je.getName();
043 if (p.startsWith(path) && p.indexOf('/', path.length() + 1) < 0)
044 if (pathAccepter == null || pathAccepter.accept(path))
045 ret.add(new URL("jar:" + target + "!" + p));
046 }
047 } finally {
048 tin.close();
049 }
050 } else if (s.startsWith("file:")) {
051 File f = new File(directory.getFile());
052 File[] ffs = f.listFiles();
053 if (ffs != null)
054 for (File ff : ffs)
055 if (pathAccepter == null || pathAccepter.accept(ff.toString()))
056 ret.add(ff.toURI().toURL());
057 } else
058 throw new IOException("Cannot list contents of " + directory);
059
060 return ret;
061 }
062 }