blob: cb302da3bce6390f2c17d4aa036d6fcc642b75a1 [file] [log] [blame]
Stuart McCulloch26e7a5a2011-10-17 10:31:43 +00001package aQute.lib.osgi;
2
3import java.io.*;
4import java.util.zip.*;
5
6public class EmbeddedResource implements Resource {
7 byte data[];
8 long lastModified;
9 String extra;
10
11 public EmbeddedResource(byte data[], long lastModified) {
12 this.data = data;
13 this.lastModified = lastModified;
14 }
15
16 public InputStream openInputStream() throws FileNotFoundException {
17 return new ByteArrayInputStream(data);
18 }
19
20 public void write(OutputStream out) throws IOException {
21 out.write(data);
22 }
23
24 public String toString() {
25 return ":" + data.length + ":";
26 }
27
28 public static void build(Jar jar, InputStream in, long lastModified) throws IOException {
29 ZipInputStream jin = new ZipInputStream(in);
30 ZipEntry entry = jin.getNextEntry();
31 while (entry != null) {
32 if (!entry.isDirectory()) {
33 byte data[] = collect(jin);
34 jar.putResource(entry.getName(), new EmbeddedResource(data, lastModified), true);
35 }
36 entry = jin.getNextEntry();
37 }
38 jin.close();
39 }
40
41 /**
42 * Convenience method to turn an inputstream into a byte array. The method
43 * uses a recursive algorithm to minimize memory usage.
44 *
45 * @param in stream with data
46 * @param offset where we are in the stream
47 * @returns byte array filled with data
48 */
49 static byte[] collect(InputStream in) throws IOException {
50 ByteArrayOutputStream out = new ByteArrayOutputStream();
51 copy(in,out);
52 return out.toByteArray();
53 }
54
55 static void copy(InputStream in, OutputStream out) throws IOException {
56 int available = in.available();
57 if ( available <= 10000)
58 available = 64000;
59 byte [] buffer = new byte[available];
60 int size;
61 while ( (size=in.read(buffer))>0)
62 out.write(buffer,0,size);
63 }
64
65 public long lastModified() {
66 return lastModified;
67 }
68
69 public static void build(Jar sub, Resource resource) throws Exception {
70 InputStream in = resource.openInputStream();
71 build(sub,in, resource.lastModified());
72 in.close();
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 data.length;
85 }
86}