2003/09/19 05:01:37
[org.ibex.core.git] / src / org / xwt / Res.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5
6 /** base class for XWT resources */
7 public abstract class Res {
8
9     public abstract InputStream getInputStream();
10     public Res getSubResource(String key) { return Null.singleton; }
11
12     public static Res stringToRes(String url) {
13         if (url.indexOf('!') == -1)
14             return new Zip(stringToRes(url.substring(0, url.lastIndexOf('!'))),
15                            url.substring(url.lastIndexOf('!') + 1));
16         if (url.startsWith("http://")) return new HTTP(url);
17         if (url.startsWith("https://")) return new HTTP(url);
18         throw new JS.Exn("invalid resource specifier");
19     }
20
21     /** the invalid resource; only causes an error if you actually try to use it */
22     public static class Null extends Res {
23         Null() { }
24         private static singleton = new Null();
25         public InputStream getInputStream() throws JS.Exn { throw new JS.Exn("invalid resource"); }
26     }
27
28     /** HTTP or HTTPS resource */
29     public static class HTTP extends Res {
30         private String url;
31         HTTP(String url) { this.url = url; }
32         public InputStream getInputStream() { return new HTTP(url).GET(); }
33         public Res getSubResource(String key) { return new HTTP(url + "/" + key); }
34     }
35
36     /** wrap a Res around a preexisting InputStream */
37     public static class IS extends Res {
38         InputStream parent;
39         IS(InputStream parent) { this.parent = parent; }
40         public InputStream getInputStream() { return parent; }
41     }
42
43     /** "unwrap" a Zip archive */
44     public static class Zip extends Res {
45         private Res parent;
46         private String path = "";
47         Zip(Res parent, String path) { this.parent = parent; this.path = path; }
48         public InputStream getInputStream() {
49             ZipInputStream zis = new ZipInputStream(parent.getInputStream());
50             ZipEntry ze = zis.getNextEntry();
51             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
52             if (ze == null) throw new JS.Exn("zip file not found in archive");
53             return zis;
54         }
55         public Res getSubResource(String key) { return new Zip(parent, path + '/' + key); }
56     }
57
58 }