Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame^] | 1 | package aQute.lib.osgi; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.util.regex.*; |
| 5 | |
| 6 | public class FileResource implements Resource { |
| 7 | File file; |
| 8 | String extra; |
| 9 | |
| 10 | public FileResource(File file) { |
| 11 | this.file = file; |
| 12 | } |
| 13 | |
| 14 | public InputStream openInputStream() throws FileNotFoundException { |
| 15 | return new FileInputStream(file); |
| 16 | } |
| 17 | |
| 18 | public static void build(Jar jar, File directory, Pattern doNotCopy) { |
| 19 | traverse( |
| 20 | jar, |
| 21 | directory.getAbsolutePath().length(), |
| 22 | directory, |
| 23 | doNotCopy); |
| 24 | } |
| 25 | |
| 26 | public String toString() { |
| 27 | return ":" + file.getName() + ":"; |
| 28 | } |
| 29 | |
| 30 | public void write(OutputStream out) throws Exception { |
| 31 | copy(this, out); |
| 32 | } |
| 33 | |
| 34 | static synchronized void copy(Resource resource, OutputStream out) |
| 35 | throws Exception { |
| 36 | InputStream in = resource.openInputStream(); |
| 37 | try { |
| 38 | byte buffer[] = new byte[20000]; |
| 39 | int size = in.read(buffer); |
| 40 | while (size > 0) { |
| 41 | out.write(buffer, 0, size); |
| 42 | size = in.read(buffer); |
| 43 | } |
| 44 | } |
| 45 | finally { |
| 46 | in.close(); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | static void traverse(Jar jar, int rootlength, File directory, |
| 51 | Pattern doNotCopy) { |
| 52 | if (doNotCopy != null && doNotCopy.matcher(directory.getName()).matches()) |
| 53 | return; |
| 54 | jar.updateModified(directory.lastModified(), "Dir change"); |
| 55 | |
| 56 | File files[] = directory.listFiles(); |
| 57 | for (int i = 0; i < files.length; i++) { |
| 58 | if (files[i].isDirectory()) |
| 59 | traverse(jar, rootlength, files[i], doNotCopy); |
| 60 | else { |
| 61 | String path = files[i].getAbsolutePath().substring( |
| 62 | rootlength + 1); |
| 63 | if (File.separatorChar != '/') |
| 64 | path = path.replace(File.separatorChar, '/'); |
| 65 | jar.putResource(path, new FileResource(files[i]), true); |
| 66 | } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | public long lastModified() { |
| 71 | return file.lastModified(); |
| 72 | } |
| 73 | |
| 74 | public String getExtra() { |
| 75 | return extra; |
| 76 | } |
| 77 | |
| 78 | public void setExtra(String extra) { |
| 79 | this.extra = extra; |
| 80 | } |
| 81 | |
| 82 | public long size() { |
| 83 | return (int) file.length(); |
| 84 | } |
| 85 | } |