blob: 5cc522907b6fbf1eb96f5e25d2106bd7b1a6c65c [file] [log] [blame]
Stuart McCullochbb014372012-06-07 21:57:32 +00001package aQute.lib.osgi;
2
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() {
13 public void run() {
14 try {
15 write(pout);
16 pout.flush();
17 }
18 catch (Exception e) {
19 e.printStackTrace();
20 }
21 finally {
22 try {
23 pout.close();
24 }
25 catch (IOException e) {
26 // Ignore
27 }
28 }
29 }
30 };
31 t.start();
32 return pin;
Stuart McCullochbb014372012-06-07 21:57:32 +000033 }
34
35 public abstract void write(OutputStream out) throws IOException, Exception;
Stuart McCulloch2286f232012-06-15 13:27:53 +000036
Stuart McCullochbb014372012-06-07 21:57:32 +000037 public abstract long lastModified();
38
39 public String getExtra() {
40 return extra;
41 }
42
43 public void setExtra(String extra) {
44 this.extra = extra;
45 }
Stuart McCullochbb014372012-06-07 21:57:32 +000046
Stuart McCulloch2286f232012-06-15 13:27:53 +000047 static class CountingOutputStream extends OutputStream {
48 long size;
49
50 @Override
51 public void write(int var0) throws IOException {
Stuart McCullochbb014372012-06-07 21:57:32 +000052 size++;
53 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000054
55 @Override
56 public void write(byte[] buffer) throws IOException {
57 size += buffer.length;
Stuart McCullochbb014372012-06-07 21:57:32 +000058 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000059
60 @Override
61 public void write(byte[] buffer, int start, int length) throws IOException {
62 size += length;
Stuart McCullochbb014372012-06-07 21:57:32 +000063 }
64 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000065
Stuart McCullochbb014372012-06-07 21:57:32 +000066 public long size() throws IOException, Exception {
Stuart McCulloch2286f232012-06-15 13:27:53 +000067 if (size == -1) {
Stuart McCullochbb014372012-06-07 21:57:32 +000068 CountingOutputStream cout = new CountingOutputStream();
69 write(cout);
70 size = cout.size;
71 }
72 return size;
73 }
74}