blob: 771dbf7100df4e06dbcff41da3ee3d06b6b78cb9 [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.zip.*;
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 jin.close();
41 }
42
43 /**
44 * Convenience method to turn an inputstream into a byte array. The method
45 * uses a recursive algorithm to minimize memory usage.
46 *
47 * @param in stream with data
48 * @param offset where we are in the stream
49 * @returns byte array filled with data
50 */
51 static byte[] collect(InputStream in) throws IOException {
52 ByteArrayOutputStream out = new ByteArrayOutputStream();
53 copy(in,out);
54 return out.toByteArray();
55 }
56
57 static void copy(InputStream in, OutputStream out) throws IOException {
58 int available = in.available();
59 if ( available <= 10000)
60 available = 64000;
61 byte [] buffer = new byte[available];
62 int size;
63 while ( (size=in.read(buffer))>0)
64 out.write(buffer,0,size);
65 }
66
67 public long lastModified() {
68 return lastModified;
69 }
70
71 public static void build(Jar sub, Resource resource) throws IOException {
72 InputStream in = resource.openInputStream();
73 build(sub,in, resource.lastModified());
74 in.close();
75 }
76
77 public String getExtra() {
78 return extra;
79 }
80
81 public void setExtra(String extra) {
82 this.extra = extra;
83 }
84
85 public long size() {
86 return data.length;
87 }
88}