blob: 5d470675408d76d910df41216ccd37057bbe26ff [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.*;
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
Stuart McCulloch55d4dfe2012-08-07 10:57:21 +000021 @Override
Stuart McCullochbb014372012-06-07 21:57:32 +000022 public String toString() {
23 return ":" + url.getPath() + ":";
24 }
25
26 public void write(OutputStream out) throws Exception {
27 IO.copy(this.openInputStream(), out);
28 }
29
30 public long lastModified() {
31 return -1;
32 }
33
34 public String getExtra() {
35 return extra;
36 }
37
38 public void setExtra(String extra) {
39 this.extra = extra;
40 }
41
42 public long size() throws Exception {
43 if (size >= 0)
44 return size;
45
46 try {
47 if (url.getProtocol().equals("file:")) {
48 File file = new File(url.getPath());
Stuart McCulloch2286f232012-06-15 13:27:53 +000049 if (file.isFile())
Stuart McCullochbb014372012-06-07 21:57:32 +000050 return size = file.length();
51 } else {
52 URLConnection con = url.openConnection();
53 if (con instanceof HttpURLConnection) {
54 HttpURLConnection http = (HttpURLConnection) con;
55 http.setRequestMethod("HEAD");
56 http.connect();
57 String l = http.getHeaderField("Content-Length");
58 if (l != null) {
59 return size = Long.parseLong(l);
60 }
61 }
62 }
Stuart McCulloch2286f232012-06-15 13:27:53 +000063 }
64 catch (Exception e) {
Stuart McCullochbb014372012-06-07 21:57:32 +000065 // Forget this exception, we do it the hard way
66 }
67 InputStream in = openInputStream();
68 DataInputStream din = null;
69 try {
70 din = new DataInputStream(in);
71 long result = din.skipBytes(Integer.MAX_VALUE);
Stuart McCulloch2286f232012-06-15 13:27:53 +000072 while (in.read() >= 0) {
Stuart McCullochbb014372012-06-07 21:57:32 +000073 result += din.skipBytes(Integer.MAX_VALUE);
74 }
75 size = result;
Stuart McCulloch2286f232012-06-15 13:27:53 +000076 }
77 finally {
Stuart McCullochbb014372012-06-07 21:57:32 +000078 if (din != null) {
79 din.close();
80 }
81 }
82 return size;
83 }
84
85}