Stuart McCulloch | f317322 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.osgi; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.util.zip.*; |
| 5 | |
| 6 | import aQute.lib.io.*; |
| 7 | |
| 8 | public 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()); |
| 78 | } catch( Exception e ) { |
| 79 | e.printStackTrace(); |
| 80 | } |
| 81 | finally { |
| 82 | in.close(); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | public String getExtra() { |
| 87 | return extra; |
| 88 | } |
| 89 | |
| 90 | public void setExtra(String extra) { |
| 91 | this.extra = extra; |
| 92 | } |
| 93 | |
| 94 | public long size() { |
| 95 | return data.length; |
| 96 | } |
| 97 | |
| 98 | } |