blob: ae3c449355283e3ab0875e97abc10a63571cebc1 [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.zip.*;
5
6import aQute.lib.io.*;
7
8public class EmbeddedResource implements Resource {
9 byte data[];
10 long lastModified;
11 String extra;
12
13 public EmbeddedResource(byte data[], long lastModified) {
14 this.data = data;
15 this.lastModified = lastModified;
16 }
17
18 public InputStream openInputStream() throws FileNotFoundException {
19 return new ByteArrayInputStream(data);
20 }
21
22 public void write(OutputStream out) throws IOException {
23 out.write(data);
24 }
25
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000026 @Override
Stuart McCullochbb014372012-06-07 21:57:32 +000027 public String toString() {
28 return ":" + data.length + ":";
29 }
30
31 public static void build(Jar jar, InputStream in, long lastModified) throws IOException {
32 ZipInputStream jin = new ZipInputStream(in);
33 ZipEntry entry = jin.getNextEntry();
34 while (entry != null) {
35 if (!entry.isDirectory()) {
36 byte data[] = collect(jin);
37 jar.putResource(entry.getName(), new EmbeddedResource(data, lastModified), true);
38 }
39 entry = jin.getNextEntry();
40 }
41 IO.drain(in);
42 jin.close();
43 }
44
45 /**
46 * Convenience method to turn an inputstream into a byte array. The method
47 * uses a recursive algorithm to minimize memory usage.
48 *
49 * @param in
50 * stream with data
51 * @param offset
52 * where we are in the stream
53 * @returns byte array filled with data
54 */
55 static byte[] collect(InputStream in) throws IOException {
56 ByteArrayOutputStream out = new ByteArrayOutputStream();
57 copy(in, out);
58 return out.toByteArray();
59 }
60
61 static void copy(InputStream in, OutputStream out) throws IOException {
62 int available = in.available();
63 if (available <= 10000)
64 available = 64000;
65 byte[] buffer = new byte[available];
66 int size;
67 while ((size = in.read(buffer)) > 0)
68 out.write(buffer, 0, size);
69 }
70
71 public long lastModified() {
72 return lastModified;
73 }
74
75 public static void build(Jar sub, Resource resource) throws Exception {
76 InputStream in = resource.openInputStream();
77 try {
78 build(sub, in, resource.lastModified());
Stuart McCulloch2286f232012-06-15 13:27:53 +000079 }
80 catch (Exception e) {
Stuart McCullochbb014372012-06-07 21:57:32 +000081 e.printStackTrace();
82 }
83 finally {
84 in.close();
85 }
86 }
87
88 public String getExtra() {
89 return extra;
90 }
91
92 public void setExtra(String extra) {
93 this.extra = extra;
94 }
95
96 public long size() {
97 return data.length;
98 }
99
100}