blob: 494c678ec1b2443c5515b1be38d1795fc2dfe397 [file] [log] [blame]
Stuart McCulloch42151ee2012-07-16 13:43:38 +00001package aQute.bnd.osgi;
Stuart McCullochf3173222012-06-07 21:57:32 +00002
3import java.io.*;
4
5public abstract class WriteResource implements Resource {
Stuart McCulloch4482c702012-06-15 13:27:53 +00006 String extra;
7 volatile long size = -1;
8
Stuart McCullochf3173222012-06-07 21:57:32 +00009 public InputStream openInputStream() throws Exception {
Stuart McCulloch4482c702012-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 McCullochf3173222012-06-07 21:57:32 +000033 }
34
35 public abstract void write(OutputStream out) throws IOException, Exception;
Stuart McCulloch4482c702012-06-15 13:27:53 +000036
Stuart McCullochf3173222012-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 McCullochf3173222012-06-07 21:57:32 +000046
Stuart McCulloch4482c702012-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 McCullochf3173222012-06-07 21:57:32 +000052 size++;
53 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000054
55 @Override
56 public void write(byte[] buffer) throws IOException {
57 size += buffer.length;
Stuart McCullochf3173222012-06-07 21:57:32 +000058 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000059
60 @Override
61 public void write(byte[] buffer, int start, int length) throws IOException {
62 size += length;
Stuart McCullochf3173222012-06-07 21:57:32 +000063 }
64 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000065
Stuart McCullochf3173222012-06-07 21:57:32 +000066 public long size() throws IOException, Exception {
Stuart McCulloch4482c702012-06-15 13:27:53 +000067 if (size == -1) {
Stuart McCullochf3173222012-06-07 21:57:32 +000068 CountingOutputStream cout = new CountingOutputStream();
69 write(cout);
70 size = cout.size;
71 }
72 return size;
73 }
74}