blob: 66635d1bc209594694861cb413fa3d8b4ee74851 [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
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000022 @Override
Stuart McCullochbb014372012-06-07 21:57:32 +000023 public String toString() {
24 return ":" + file.getName() + ":";
25 }
26
27 public void write(OutputStream out) throws Exception {
28 copy(this, out);
29 }
30
Stuart McCulloch2286f232012-06-15 13:27:53 +000031 static synchronized void copy(Resource resource, OutputStream out) throws Exception {
Stuart McCullochbb014372012-06-07 21:57:32 +000032 InputStream in = resource.openInputStream();
33 try {
34 byte buffer[] = new byte[20000];
35 int size = in.read(buffer);
36 while (size > 0) {
37 out.write(buffer, 0, size);
38 size = in.read(buffer);
39 }
40 }
41 finally {
42 in.close();
43 }
44 }
45
Stuart McCulloch2286f232012-06-15 13:27:53 +000046 static void traverse(Jar jar, int rootlength, File directory, Pattern doNotCopy) {
Stuart McCullochbb014372012-06-07 21:57:32 +000047 if (doNotCopy != null && doNotCopy.matcher(directory.getName()).matches())
48 return;
49 jar.updateModified(directory.lastModified(), "Dir change");
Stuart McCulloch2286f232012-06-15 13:27:53 +000050
Stuart McCullochbb014372012-06-07 21:57:32 +000051 File files[] = directory.listFiles();
52 for (int i = 0; i < files.length; i++) {
53 if (files[i].isDirectory())
54 traverse(jar, rootlength, files[i], doNotCopy);
55 else {
Stuart McCulloch2286f232012-06-15 13:27:53 +000056 String path = files[i].getAbsolutePath().substring(rootlength + 1);
Stuart McCullochbb014372012-06-07 21:57:32 +000057 if (File.separatorChar != '/')
58 path = path.replace(File.separatorChar, '/');
59 jar.putResource(path, new FileResource(files[i]), true);
60 }
61 }
62 }
63
64 public long lastModified() {
65 return file.lastModified();
66 }
67
68 public String getExtra() {
69 return extra;
70 }
71
72 public void setExtra(String extra) {
73 this.extra = extra;
74 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000075
Stuart McCullochbb014372012-06-07 21:57:32 +000076 public long size() {
Stuart McCulloch2286f232012-06-15 13:27:53 +000077 return (int) file.length();
Stuart McCullochbb014372012-06-07 21:57:32 +000078 }
79}