2003/10/01 03:10:00
[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     /** shadow resource which replaces the graft */
147     public static class Graft extends Res {
148         Res graftee;
149         Object replaced_key;
150         Object replaced_val;
151         Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
152         public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
153         public int hashCode() { return graftee.hashCode(); }
154         public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
155         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
156         public String getDescriptiveName() { return graftee.getDescriptiveName(); }
157         public Res getParent() { return graftee.getParent(); }
158     }
159
160     /** shadow resource which replaces the graft */
161     public static class ProgressWatcher extends Res {
162         Res watchee;
163         JS.Callable callback;
164         ProgressWatcher(Res watchee, JS.Callable callback) { this.watchee = watchee; this.callback = callback; }
165         public InputStream getInputStream(String s) throws IOException {
166             return new FilterInputStream(watchee.getInputStream(s)) {
167                     int bytesDownloaded = 0;
168                     public int read() throws IOException {
169                         int ret = super.read();
170                         if (ret != -1) bytesDownloaded++;
171                         return ret;
172                     }
173                     public int read(byte[] b, int off, int len) throws IOException {
174                         int ret = super.read(b, off, len);
175                         if (ret != 1) bytesDownloaded += ret;
176                         ThreadMessage.newthread(new JS.Callable() { public Object call(JS.Array a) {
177                             JS.Array args = new JS.Array();
178                             args.addElement(new Integer(bytesDownloaded));
179                             callback.call(args);
180                             return null;
181                         } });
182                         return ret;
183                     }
184                 };
185         }
186     }
187
188     /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
189     public static class CAB extends Res {
190         private Res parent;
191         CAB(Res parent) { this.parent = parent; }
192         private int swap_endian(int i) {
193             return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
194         }
195         public InputStream getInputStream(String path) throws IOException {
196             try {
197                return org.xwt.util.CAB.getFileInputStream(parent.getInputStream(), 2, path);
198             } catch (EOFException eof) {
199                throw new JS.Exn("MSCF header tag not found in file");
200             } catch (IOException ioe) {
201                throw new JS.Exn("IOException while reading file");
202             }
203         }
204     }
205
206     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
207         if (method.equals("getUTF")) {
208             if (checkOnly) return Boolean.TRUE;
209             if (args.length() != 0) return null;
210             try {
211                 CharArrayWriter caw = new CharArrayWriter();
212                 InputStream is = getInputStream();
213                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
214                 char[] buf = new char[1024];
215                 while(true) {
216                     int numread = r.read(buf, 0, 1024);
217                     if (numread == -1) break;
218                     caw.write(buf, 0, numread);
219                 }
220                 return caw.toString();
221             } catch (IOException e) {
222                 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
223                 if (Log.on) Log.log(Res.class, e);
224                 throw new JS.Exn("error while reading from Resource");
225             }
226         } else if (method.equals("getDOM")) {
227             if (checkOnly) return Boolean.TRUE;
228             if (args.length() != 0) return null;
229             return new XMLHelper().doParse();
230         }
231         if (checkOnly) return Boolean.FALSE;
232         return null;
233     }
234
235     private class XMLHelper extends XML {
236         Vector obStack = new Vector();
237         public XMLHelper() { super(BUFFER_SIZE); }
238         public void startElement(XML.Element c) throws XML.SchemaException {
239             JS o = new JS.Obj();
240             o.put("$name", c.localName);
241             for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
242             o.put("$numchildren", new Integer(0));
243             obStack.addElement(o);
244         }
245         public void endElement(XML.Element c) throws XML.SchemaException {
246             if (obStack.size() == 1) return;
247             JS me = (JS)obStack.lastElement();
248             obStack.setSize(obStack.size() - 1);
249             JS parent = (JS)obStack.lastElement();
250             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
251             parent.put("$numchildren", new Integer(numchildren + 1));
252             parent.put(new Integer(numchildren), me);
253         }
254         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
255             String s = new String(ch, start, length);
256             JS parent = (JS)obStack.lastElement();
257             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
258             Object lastChild = parent.get(new Integer(numchildren - 1));
259             if (lastChild instanceof String) {
260                 parent.put(new Integer(numchildren - 1), lastChild + s);
261             } else {
262                 parent.put("$numchildren", new Integer(numchildren + 1));
263                 parent.put(new Integer(numchildren), s);
264             }
265         }
266         public void whitespace(char[] ch, int start, int length) {}
267         public JS doParse() throws JS.Exn {
268             try { 
269                 InputStream is = getInputStream();
270                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
271                 parse(r);
272             } catch (XML.XMLException e) {
273                 throw new JS.Exn("error parsing XML: " + e.toString());
274             } catch (IOException e) {
275                 if (Log.on) Log.log(this, "IO Exception while reading from file");
276                 if (Log.on) Log.log(this, e);
277                 throw new JS.Exn("error reading from Resource");
278             }
279             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
280         }
281     }
282
283     public void writeTo(OutputStream os) throws IOException {
284         InputStream is = getInputStream();
285         byte[] buf = new byte[1024];
286         while(true) {
287             int numread = is.read(buf, 0, 1024);
288             if (numread == -1) break;
289             if (Log.on) Log.log(this, "wrote " + numread + " bytes");
290             os.write(buf, 0, numread);
291         }
292         os.flush();
293
294         // we have to close this because flush() doesn't work on Win32-GCJ
295         os.close();
296     }
297 }