Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 1 | package aQute.lib.osgi; |
| 2 | |
| 3 | import java.io.*; |
| 4 | import java.net.*; |
| 5 | |
| 6 | import aQute.lib.io.*; |
| 7 | |
| 8 | public 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 48 | if (file.isFile()) |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 49 | 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 62 | } |
| 63 | catch (Exception e) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 64 | // 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 McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 71 | while (in.read() >= 0) { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 72 | result += din.skipBytes(Integer.MAX_VALUE); |
| 73 | } |
| 74 | size = result; |
Stuart McCulloch | 2286f23 | 2012-06-15 13:27:53 +0000 | [diff] [blame^] | 75 | } |
| 76 | finally { |
Stuart McCulloch | bb01437 | 2012-06-07 21:57:32 +0000 | [diff] [blame] | 77 | if (din != null) { |
| 78 | din.close(); |
| 79 | } |
| 80 | } |
| 81 | return size; |
| 82 | } |
| 83 | |
| 84 | } |