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