blob: 2cd2375cdb0b747d2b92d11de106e495533cbd2a [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.*;
4import java.net.*;
5
6import aQute.lib.io.*;
7
8public class URLResource implements Resource {
9 URL url;
10 String extra;
11 long size = -1;
12
13 public URLResource(URL url) {
14 this.url = url;
15 }
16
17 public InputStream openInputStream() throws IOException {
18 return url.openStream();
19 }
20
21 public String toString() {
22 return ":" + url.getPath() + ":";
23 }
24
25 public void write(OutputStream out) throws Exception {
26 IO.copy(this.openInputStream(), out);
27 }
28
29 public long lastModified() {
30 return -1;
31 }
32
33 public String getExtra() {
34 return extra;
35 }
36
37 public void setExtra(String extra) {
38 this.extra = extra;
39 }
40
41 public long size() throws Exception {
42 if (size >= 0)
43 return size;
44
45 try {
46 if (url.getProtocol().equals("file:")) {
47 File file = new File(url.getPath());
Stuart McCulloch4482c702012-06-15 13:27:53 +000048 if (file.isFile())
Stuart McCullochf3173222012-06-07 21:57:32 +000049 return size = file.length();
50 } else {
51 URLConnection con = url.openConnection();
52 if (con instanceof HttpURLConnection) {
53 HttpURLConnection http = (HttpURLConnection) con;
54 http.setRequestMethod("HEAD");
55 http.connect();
56 String l = http.getHeaderField("Content-Length");
57 if (l != null) {
58 return size = Long.parseLong(l);
59 }
60 }
61 }
Stuart McCulloch4482c702012-06-15 13:27:53 +000062 }
63 catch (Exception e) {
Stuart McCullochf3173222012-06-07 21:57:32 +000064 // Forget this exception, we do it the hard way
65 }
66 InputStream in = openInputStream();
67 DataInputStream din = null;
68 try {
69 din = new DataInputStream(in);
70 long result = din.skipBytes(Integer.MAX_VALUE);
Stuart McCulloch4482c702012-06-15 13:27:53 +000071 while (in.read() >= 0) {
Stuart McCullochf3173222012-06-07 21:57:32 +000072 result += din.skipBytes(Integer.MAX_VALUE);
73 }
74 size = result;
Stuart McCulloch4482c702012-06-15 13:27:53 +000075 }
76 finally {
Stuart McCullochf3173222012-06-07 21:57:32 +000077 if (din != null) {
78 din.close();
79 }
80 }
81 return size;
82 }
83
84}