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