001: package liquibase;
002:
003: import java.io.File;
004: import java.io.FileInputStream;
005: import java.io.IOException;
006: import java.io.InputStream;
007: import java.net.MalformedURLException;
008: import java.net.URL;
009: import java.net.URLClassLoader;
010: import java.util.ArrayList;
011: import java.util.Enumeration;
012: import java.util.Iterator;
013: import java.util.List;
014:
015: /**
016: * A FileOpener implementation which finds Files in the
017: * File System.
018: * <p/>
019: * FileSystemFileOpeners can use a BaseDirectory to determine
020: * where relative paths should be resolved from.
021: *
022: * @author <a href="mailto:csuml@yahoo.co.uk>Paul Keeble</a>
023: */
024: public class FileSystemFileOpener implements FileOpener {
025: String baseDirectory;
026:
027: /**
028: * Creates using a Base directory of null, all files will be
029: * resolved exactly as they are given.
030: */
031: public FileSystemFileOpener() {
032: baseDirectory = null;
033: }
034:
035: /**
036: * Creates using a supplied base directory.
037: *
038: * @param base The path to use to resolve relative paths
039: */
040: public FileSystemFileOpener(String base) {
041: if (new File(base).isFile())
042: throw new IllegalArgumentException(
043: "base must be a directory");
044: baseDirectory = base;
045: }
046:
047: /**
048: * Opens a stream on a file, resolving to the baseDirectory if the
049: * file is relative.
050: */
051: public InputStream getResourceAsStream(String file)
052: throws IOException {
053: File absoluteFile = new File(file);
054: File relativeFile = (baseDirectory == null) ? new File(file)
055: : new File(baseDirectory, file);
056:
057: if (absoluteFile.exists() && absoluteFile.isFile()
058: && absoluteFile.isAbsolute()) {
059: return new FileInputStream(absoluteFile);
060: } else if (relativeFile.exists() && relativeFile.isFile()) {
061: return new FileInputStream(relativeFile);
062: } else {
063: return null;
064:
065: }
066: }
067:
068: public Enumeration<URL> getResources(String packageName)
069: throws IOException {
070: String directoryPath = (new File(packageName).isAbsolute() || baseDirectory == null) ? packageName
071: : baseDirectory + File.separator + packageName;
072:
073: File[] files = new File(directoryPath).listFiles();
074:
075: List<URL> results = new ArrayList<URL>();
076:
077: for (File f : files) {
078: results.add(new URL("file://" + f.getCanonicalPath()));
079: }
080:
081: final Iterator<URL> it = results.iterator();
082: return new Enumeration<URL>() {
083:
084: public boolean hasMoreElements() {
085: return it.hasNext();
086: }
087:
088: public URL nextElement() {
089: return it.next();
090: }
091:
092: };
093: }
094:
095: public ClassLoader toClassLoader() {
096: try {
097: return new URLClassLoader(new URL[] { new URL("file://"
098: + baseDirectory) });
099: } catch (MalformedURLException e) {
100: throw new RuntimeException(e);
101: }
102: }
103: }
|