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