blob: cd18cf5e84dd56b3a4805e885c43aef32acc578a [file] [log] [blame]
Stuart McCulloch39cc9ac2012-07-16 13:43:38 +00001package aQute.bnd.osgi;
Stuart McCullochbb014372012-06-07 21:57:32 +00002
3import java.io.*;
4import java.util.regex.*;
5
6public class FileResource implements Resource {
7 File file;
8 String extra;
Stuart McCulloch2286f232012-06-15 13:27:53 +00009
Stuart McCullochbb014372012-06-07 21:57:32 +000010 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) {
Stuart McCulloch2286f232012-06-15 13:27:53 +000019 traverse(jar, directory.getAbsolutePath().length(), directory, doNotCopy);
Stuart McCullochbb014372012-06-07 21:57:32 +000020 }
21
22 public String toString() {
23 return ":" + file.getName() + ":";
24 }
25
26 public void write(OutputStream out) throws Exception {
27 copy(this, out);
28 }
29
Stuart McCulloch2286f232012-06-15 13:27:53 +000030 static synchronized void copy(Resource resource, OutputStream out) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000031 InputStream in = resource.openInputStream();
32 try {
33 byte buffer[] = new byte[20000];
34 int size = in.read(buffer);
35 while (size > 0) {
36 out.write(buffer, 0, size);
37 size = in.read(buffer);
38 }
39 }
40 finally {
41 in.close();
42 }
43 }
44
Stuart McCulloch2286f232012-06-15 13:27:53 +000045 static void traverse(Jar jar, int rootlength, File directory, Pattern doNotCopy) {
Stuart McCullochbb014372012-06-07 21:57:32 +000046 if (doNotCopy != null && doNotCopy.matcher(directory.getName()).matches())
47 return;
48 jar.updateModified(directory.lastModified(), "Dir change");
Stuart McCulloch2286f232012-06-15 13:27:53 +000049
Stuart McCullochbb014372012-06-07 21:57:32 +000050 File files[] = directory.listFiles();
51 for (int i = 0; i < files.length; i++) {
52 if (files[i].isDirectory())
53 traverse(jar, rootlength, files[i], doNotCopy);
54 else {
Stuart McCulloch2286f232012-06-15 13:27:53 +000055 String path = files[i].getAbsolutePath().substring(rootlength + 1);
Stuart McCullochbb014372012-06-07 21:57:32 +000056 if (File.separatorChar != '/')
57 path = path.replace(File.separatorChar, '/');
58 jar.putResource(path, new FileResource(files[i]), true);
59 }
60 }
61 }
62
63 public long lastModified() {
64 return file.lastModified();
65 }
66
67 public String getExtra() {
68 return extra;
69 }
70
71 public void setExtra(String extra) {
72 this.extra = extra;
73 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000074
Stuart McCullochbb014372012-06-07 21:57:32 +000075 public long size() {
Stuart McCulloch2286f232012-06-15 13:27:53 +000076 return (int) file.length();
Stuart McCullochbb014372012-06-07 21:57:32 +000077 }
78}