2003/09/30 21:30:49
[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 import java.util.*;
6 import java.util.zip.*;
7 import org.xwt.js.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10
11 /** base class for XWT resources */
12 public abstract class Res extends JS {
13
14     public String getDescriptiveName() { return ""; }
15
16     /** cache of subresources so that the equality operator works on them */
17     private Hash refCache = null;
18
19     public Template t = null;
20
21     public Res getParent() { return null; }
22
23     /** returns an InputStream containing the Resource's contents */
24     public InputStream getInputStream() throws IOException { return getInputStream(""); }
25     public abstract InputStream getInputStream(String path) throws IOException;
26
27     /** graft newResource in place of this resource on its parent */
28     public Res graft(Object newResource) { throw new JS.Exn("cannot graft onto this resource"); }
29
30     /** if the path of this resource does not end with extension, return a new one wit it appended */
31     public Res addExtension(String extension) { return new Ref(this, extension); }
32
33     public Object[] keys() { throw new JS.Exn("cannot enumerate a resource"); } 
34     public void put(Object key, Object val) { throw new JS.Exn("cannot put to a resource"); } 
35     public Object get(Object key) {
36         if ("".equals(key)) {
37             Template t = Template.getTemplate(addExtension(".xwt"));
38             return t == null ? null : t.getStatic();
39         }
40         Object ret = refCache == null ? null : refCache.get(key);
41         if (ret != null) return ret;
42         ret = new Ref(this, key);
43         if (refCache == null) refCache = new Hash();
44         refCache.put(key, ret);
45         return ret;
46     }
47
48     public static Res stringToRes(String url) { return stringToRes(url, false); }
49     public static Res stringToRes(String url, boolean permitLocalFilesystem) {
50         if (url.indexOf('!') != -1)
51             return (Res)(new Zip(stringToRes(url.substring(0, url.lastIndexOf('!')))).
52                          get(url.substring(url.lastIndexOf('!') + 1)));
53         if (url.startsWith("http://")) return new HTTP(url);
54         if (url.startsWith("https://")) return new HTTP(url);
55         if (url.startsWith("file:") && permitLocalFilesystem) return new File(url.substring(5));
56         if (url.startsWith("cab:")) return new CAB(stringToRes(url.substring(4)));
57         if (url.startsWith("data:")) return new ByteArray(Base64.decode(url.substring(5)));
58         if (url.startsWith("utf8:")) return new ByteArray(url.substring(5).getBytes());
59         throw new JS.Exn("invalid resource specifier " + url);
60     }
61
62     /** subclass from this if you want a CachedInputStream for each path */
63     public static abstract class CachedRes extends Res {
64         private Hash cachedInputStreams = new Hash();
65         abstract InputStream _getInputStream(String path) throws IOException;
66         public final InputStream getInputStream(String path) throws IOException {
67             CachedInputStream cis = (CachedInputStream)cachedInputStreams.get(path);
68             if (cis == null) {
69                 cis = new CachedInputStream(_getInputStream(path));
70                 cachedInputStreams.put(path, cis);
71             }
72             return cis.getInputStream();
73         }
74     }
75
76     /** HTTP or HTTPS resource */
77     public static class HTTP extends CachedRes {
78         private String url;
79         HTTP(String url) { this.url = url; }
80         public InputStream _getInputStream(String path) throws IOException {
81             return new org.xwt.HTTP(url + path).GET(); }
82     }
83
84     /** byte arrays */
85     public static class ByteArray extends Res {
86         private byte[] bytes;
87         ByteArray(byte[] bytes) { this.bytes = bytes; }
88         public InputStream getInputStream(String path) throws IOException {
89             if (!"".equals(path)) throw new JS.Exn("can't get subresources of a byte[] resource");
90             return new ByteArrayInputStream(bytes);
91         }
92     }
93
94     /** a file */
95     public static class File extends Res {
96         private String path;
97         File(String path) { this.path = path; }
98         public InputStream getInputStream(String rest) throws IOException {
99             return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
100     }
101
102     /** wrap a Res around a preexisting InputStream */
103     public static class IS extends Res {
104         InputStream parent;
105         IS(InputStream parent) { this.parent = parent; }
106         public InputStream getInputStream(String path) {
107             if (!"".equals(path)) throw new JS.Exn("can't access subresources of IS");
108             return parent;
109         }
110     }
111
112     /** "unwrap" a Zip archive */
113     public static class Zip extends Res {
114         private Res parent;
115         Zip(Res parent) { this.parent = parent; }
116         public InputStream getInputStream(String path) throws IOException {
117             if (path.startsWith("/")) path = path.substring(1);
118             ZipInputStream zis = new ZipInputStream(parent.getInputStream());
119             ZipEntry ze = zis.getNextEntry();
120             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
121             if (ze == null) throw new JS.Exn("requested file not found in archive");
122             return zis;
123         }
124     }
125
126     /** what you get when you reference a subresource */
127     public static class Ref extends Res {
128         Res parent;
129         Object key;
130         Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
131         public String getDescriptiveName() {
132             String pdn = parent.getDescriptiveName();
133             return pdn.equals("") ? key.toString() : (pdn + "." + key.toString());
134         }
135         public Res addExtension(String extension) {
136             return (key instanceof String && ((String)key).endsWith(extension)) ? this : new Ref(parent, key + extension);
137         }
138         public InputStream getInputStream(String path) throws IOException {
139             return parent.getInputStream("/" + key + path);
140         }
141         public Res getParent() { return parent; }
142         public Res graft(Object newResource) { return new Graft(parent, key, newResource); }
143     }
144
145     /** shadow resource which replaces the graft */
146     public static class Graft extends Res {
147         Res graftee;
148         Object replaced_key;
149         Object replaced_val;
150         Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
151         public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
152         public int hashCode() { return graftee.hashCode(); }
153         public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
154         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
155         public String getDescriptiveName() { return graftee.getDescriptiveName(); }
156         public Res getParent() { return graftee.getParent(); }
157     }
158
159     /** shadow resource which replaces the graft */
160     public static class ProgressWatcher extends Res {
161         Res watchee;
162         JS.Callable callback;
163         ProgressWatcher(Res watchee, JS.Callable callback) { this.watchee = watchee; this.callback = callback; }
164         public InputStream getInputStream(String s) throws IOException {
165             return new FilterInputStream(watchee.getInputStream(s)) {
166                     int bytesDownloaded = 0;
167                     public int read() throws IOException {
168                         int ret = super.read();
169                         if (ret != -1) bytesDownloaded++;
170                         return ret;
171                     }
172                     public int read(byte[] b, int off, int len) throws IOException {
173                         int ret = super.read(b, off, len);
174                         if (ret != 1) bytesDownloaded += ret;
175                         ThreadMessage.newthread(new JS.Callable() { public Object call(JS.Array a) {
176                             JS.Array args = new JS.Array();
177                             args.addElement(new Integer(bytesDownloaded));
178                             callback.call(args);
179                             return null;
180                         } });
181                         return ret;
182                     }
183                 };
184         }
185     }
186
187     /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
188     public static class CAB extends Res {
189         private Res parent;
190         CAB(Res parent) { this.parent = parent; }
191         private int swap_endian(int i) {
192             return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
193         }
194         public InputStream getInputStream(String path) throws IOException {
195             try {
196                return org.xwt.util.CAB.getFileInputStream(parent.getInputStream(), 2, path);
197             } catch (EOFException eof) {
198                throw new JS.Exn("MSCF header tag not found in file");
199             } catch (IOException ioe) {
200                throw new JS.Exn("IOException while reading file");
201             }
202         }
203     }
204
205     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
206         if (method.equals("getUTF")) {
207             if (checkOnly) return Boolean.TRUE;
208             if (args.length() != 0) return null;
209             try {
210                 CharArrayWriter caw = new CharArrayWriter();
211                 InputStream is = getInputStream();
212                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
213                 char[] buf = new char[1024];
214                 while(true) {
215                     int numread = r.read(buf, 0, 1024);
216                     if (numread == -1) break;
217                     caw.write(buf, 0, numread);
218                 }
219                 return caw.toString();
220             } catch (IOException e) {
221                 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
222                 if (Log.on) Log.log(Res.class, e);
223                 throw new JS.Exn("error while reading from Resource");
224             }
225         } else if (method.equals("getDOM")) {
226             if (checkOnly) return Boolean.TRUE;
227             if (args.length() != 0) return null;
228             return new XMLHelper().doParse();
229         }
230         if (checkOnly) return Boolean.FALSE;
231         return null;
232     }
233
234     private class XMLHelper extends XML {
235         Vector obStack = new Vector();
236         public XMLHelper() { super(BUFFER_SIZE); }
237         public void startElement(XML.Element c) throws XML.SchemaException {
238             JS o = new JS.Obj();
239             o.put("$name", c.localName);
240             for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
241             o.put("$numchildren", new Integer(0));
242             obStack.addElement(o);
243         }
244         public void endElement(XML.Element c) throws XML.SchemaException {
245             if (obStack.size() == 1) return;
246             JS me = (JS)obStack.lastElement();
247             obStack.setSize(obStack.size() - 1);
248             JS parent = (JS)obStack.lastElement();
249             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
250             parent.put("$numchildren", new Integer(numchildren + 1));
251             parent.put(new Integer(numchildren), me);
252         }
253         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
254             String s = new String(ch, start, length);
255             JS parent = (JS)obStack.lastElement();
256             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
257             Object lastChild = parent.get(new Integer(numchildren - 1));
258             if (lastChild instanceof String) {
259                 parent.put(new Integer(numchildren - 1), lastChild + s);
260             } else {
261                 parent.put("$numchildren", new Integer(numchildren + 1));
262                 parent.put(new Integer(numchildren), s);
263             }
264         }
265         public void whitespace(char[] ch, int start, int length) {}
266         public JS doParse() throws JS.Exn {
267             try { 
268                 InputStream is = getInputStream();
269                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
270                 parse(r);
271             } catch (XML.XMLException e) {
272                 throw new JS.Exn("error parsing XML: " + e.toString());
273             } catch (IOException e) {
274                 if (Log.on) Log.log(this, "IO Exception while reading from file");
275                 if (Log.on) Log.log(this, e);
276                 throw new JS.Exn("error reading from Resource");
277             }
278             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
279         }
280     }
281
282     public void writeTo(OutputStream os) throws IOException {
283         InputStream is = getInputStream();
284         byte[] buf = new byte[1024];
285         while(true) {
286             int numread = is.read(buf, 0, 1024);
287             if (numread == -1) break;
288             if (Log.on) Log.log(this, "wrote " + numread + " bytes");
289             os.write(buf, 0, numread);
290         }
291         os.flush();
292
293         // we have to close this because flush() doesn't work on Win32-GCJ
294         os.close();
295     }
296 }