blob: 0aad6054cf29b7481dfdb0a5d2578eddd18b1edd [file] [log] [blame]
Stuart McCulloch42151ee2012-07-16 13:43:38 +00001package aQute.bnd.osgi;
Stuart McCullochf3173222012-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
26 public String toString() {
27 return ":" + data.length + ":";
28 }
29
30 public static void build(Jar jar, InputStream in, long lastModified) throws IOException {
31 ZipInputStream jin = new ZipInputStream(in);
32 ZipEntry entry = jin.getNextEntry();
33 while (entry != null) {
34 if (!entry.isDirectory()) {
35 byte data[] = collect(jin);
36 jar.putResource(entry.getName(), new EmbeddedResource(data, lastModified), true);
37 }
38 entry = jin.getNextEntry();
39 }
40 IO.drain(in);
41 jin.close();
42 }
43
44 /**
45 * Convenience method to turn an inputstream into a byte array. The method
46 * uses a recursive algorithm to minimize memory usage.
47 *
48 * @param in
49 * stream with data
50 * @param offset
51 * where we are in the stream
52 * @returns byte array filled with data
53 */
54 static byte[] collect(InputStream in) throws IOException {
55 ByteArrayOutputStream out = new ByteArrayOutputStream();
56 copy(in, out);
57 return out.toByteArray();
58 }
59
60 static void copy(InputStream in, OutputStream out) throws IOException {
61 int available = in.available();
62 if (available <= 10000)
63 available = 64000;
64 byte[] buffer = new byte[available];
65 int size;
66 while ((size = in.read(buffer)) > 0)
67 out.write(buffer, 0, size);
68 }
69
70 public long lastModified() {
71 return lastModified;
72 }
73
74 public static void build(Jar sub, Resource resource) throws Exception {
75 InputStream in = resource.openInputStream();
76 try {
77 build(sub, in, resource.lastModified());
Stuart McCulloch4482c702012-06-15 13:27:53 +000078 }
79 catch (Exception e) {
Stuart McCullochf3173222012-06-07 21:57:32 +000080 e.printStackTrace();
81 }
82 finally {
83 in.close();
84 }
85 }
86
87 public String getExtra() {
88 return extra;
89 }
90
91 public void setExtra(String extra) {
92 this.extra = extra;
93 }
94
95 public long size() {
96 return data.length;
97 }
98
99}