blob: ed72c41e5a78255c9607c22bbc47f1adfc2cb7cc [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.*;
4
5public abstract class WriteResource implements Resource {
Stuart McCulloch2286f232012-06-15 13:27:53 +00006 String extra;
7 volatile long size = -1;
8
Stuart McCullochbb014372012-06-07 21:57:32 +00009 public InputStream openInputStream() throws Exception {
Stuart McCulloch2286f232012-06-15 13:27:53 +000010 PipedInputStream pin = new PipedInputStream();
11 final PipedOutputStream pout = new PipedOutputStream(pin);
12 Thread t = new Thread() {
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000013 @Override
Stuart McCulloch2286f232012-06-15 13:27:53 +000014 public void run() {
15 try {
16 write(pout);
17 pout.flush();
18 }
19 catch (Exception e) {
20 e.printStackTrace();
21 }
22 finally {
23 try {
24 pout.close();
25 }
26 catch (IOException e) {
27 // Ignore
28 }
29 }
30 }
31 };
32 t.start();
33 return pin;
Stuart McCullochbb014372012-06-07 21:57:32 +000034 }
35
36 public abstract void write(OutputStream out) throws IOException, Exception;
Stuart McCulloch2286f232012-06-15 13:27:53 +000037
Stuart McCullochbb014372012-06-07 21:57:32 +000038 public abstract long lastModified();
39
40 public String getExtra() {
41 return extra;
42 }
43
44 public void setExtra(String extra) {
45 this.extra = extra;
46 }
Stuart McCullochbb014372012-06-07 21:57:32 +000047
Stuart McCulloch2286f232012-06-15 13:27:53 +000048 static class CountingOutputStream extends OutputStream {
49 long size;
50
51 @Override
52 public void write(int var0) throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000053 size++;
54 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000055
56 @Override
57 public void write(byte[] buffer) throws IOException {
58 size += buffer.length;
Stuart McCullochbb014372012-06-07 21:57:32 +000059 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000060
61 @Override
62 public void write(byte[] buffer, int start, int length) throws IOException {
63 size += length;
Stuart McCullochbb014372012-06-07 21:57:32 +000064 }
65 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000066
Stuart McCullochbb014372012-06-07 21:57:32 +000067 public long size() throws IOException, Exception {
Stuart McCulloch2286f232012-06-15 13:27:53 +000068 if (size == -1) {
Stuart McCullochbb014372012-06-07 21:57:32 +000069 CountingOutputStream cout = new CountingOutputStream();
70 write(cout);
71 size = cout.size;
72 }
73 return size;
74 }
75}