2003/09/27 06:42:26
[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('!')))).get(url.substring(url.lastIndexOf('!') + 1)));
52         if (url.startsWith("http://")) return new HTTP(url);
53         if (url.startsWith("https://")) return new HTTP(url);
54         if (url.startsWith("file:") && permitLocalFilesystem) return new File(url.substring(5));
55         if (url.startsWith("cab:")) return new CAB(stringToRes(url.substring(4)));
56         if (url.startsWith("data:")) return new ByteArray(Base64.decode(url.substring(5)));
57         throw new JS.Exn("invalid resource specifier " + url);
58     }
59
60     /** HTTP or HTTPS resource */
61     public static class HTTP extends Res {
62         private String url;
63         HTTP(String url) { this.url = url; }
64         public InputStream getInputStream(String path) throws IOException { return new org.xwt.HTTP(url + path).GET(); }
65     }
66
67     /** byte arrays */
68     public static class ByteArray extends Res {
69         private byte[] bytes;
70         ByteArray(byte[] bytes) { this.bytes = bytes; }
71         public InputStream getInputStream(String path) throws IOException {
72             if (!"".equals(path)) throw new JS.Exn("can't get subresources of a byte[] resource");
73             return new ByteArrayInputStream(bytes);
74         }
75     }
76
77     /** a file */
78     public static class File extends Res {
79         private String path;
80         File(String path) { this.path = path; }
81         public InputStream getInputStream(String rest) throws IOException {
82             return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
83     }
84
85     /** wrap a Res around a preexisting InputStream */
86     public static class IS extends Res {
87         InputStream parent;
88         IS(InputStream parent) { this.parent = parent; }
89         public InputStream getInputStream(String path) {
90             if (!"".equals(path)) throw new JS.Exn("can't access subresources of IS");
91             return parent;
92         }
93     }
94
95     /** "unwrap" a Zip archive */
96     public static class Zip extends Res {
97         private Res parent;
98         Zip(Res parent) { this.parent = parent; }
99         public InputStream getInputStream(String path) throws IOException {
100             if (path.startsWith("/")) path = path.substring(1);
101             ZipInputStream zis = new ZipInputStream(parent.getInputStream());
102             ZipEntry ze = zis.getNextEntry();
103             while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
104             if (ze == null) throw new JS.Exn("requested file not found in archive");
105             return zis;
106         }
107     }
108
109     /** what you get when you reference a subresource */
110     public static class Ref extends Res {
111         Res parent;
112         Object key;
113         Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
114         public String getDescriptiveName() {
115             String pdn = parent.getDescriptiveName();
116             return pdn.equals("") ? key.toString() : (pdn + "." + key.toString());
117         }
118         public Res addExtension(String extension) {
119             return (key instanceof String && ((String)key).endsWith(extension)) ? this : new Ref(parent, key + extension);
120         }
121         public InputStream getInputStream(String path) throws IOException {
122             return parent.getInputStream("/" + key + path);
123         }
124         public Res getParent() { return parent; }
125         public Res graft(Object newResource) { return new Graft(parent, key, newResource); }
126     }
127
128     /** shadow resource which replaces the graft */
129     public static class Graft extends Res {
130         Res graftee;
131         Object replaced_key;
132         Object replaced_val;
133         Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
134         public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
135         public int hashCode() { return graftee.hashCode(); }
136         public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
137         public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
138         public String getDescriptiveName() { return graftee.getDescriptiveName(); }
139         public Res getParent() { return graftee.getParent(); }
140     }
141
142     /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
143     public static class CAB extends Res {
144         private Res parent;
145         CAB(Res parent) { this.parent = parent; }
146         private int swap_endian(int i) {
147             return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
148         }
149         public InputStream getInputStream(String path) throws IOException {
150             InputStream is = parent.getInputStream();
151             byte[] scan = new byte[4];
152             int ofs = 0;
153             for(int i=0; i<2; i++)  {
154                 // wierdly, .exe files have three MSCF's
155                 while(scan[0] != 'M' || scan[1] != 'S' || scan[2] != 'C' || scan[3] != 'F') {
156                     System.arraycopy(scan, 1, scan, 0, 3);
157                     int read = is.read();
158                     if (read == -1) throw new JS.Exn("MSCF header tag not found in file");
159                     scan[3] = (byte)read;
160                     ofs++;
161                 }
162                 scan[0] = 0;
163             }
164             Log.log(this, "found MSCF header at offset " + ofs);
165             return org.xwt.util.CAB.getFileInputStream(is, path, true);
166         }
167     }
168
169     public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
170         if (method.equals("getUTF")) {
171             if (checkOnly) return Boolean.TRUE;
172             if (args.length() != 0) return null;
173             try {
174                 CharArrayWriter caw = new CharArrayWriter();
175                 InputStream is = getInputStream();
176                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
177                 char[] buf = new char[1024];
178                 while(true) {
179                     int numread = r.read(buf, 0, 1024);
180                     if (numread == -1) break;
181                     caw.write(buf, 0, numread);
182                 }
183                 return caw.toString();
184             } catch (IOException e) {
185                 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
186                 if (Log.on) Log.log(Res.class, e);
187                 throw new JS.Exn("error while reading from Resource");
188             }
189         } else if (method.equals("getDOM")) {
190             if (checkOnly) return Boolean.TRUE;
191             if (args.length() != 0) return null;
192             return new XMLHelper().doParse();
193         }
194         if (checkOnly) return Boolean.FALSE;
195         return null;
196     }
197
198     private class XMLHelper extends XML {
199         Vector obStack = new Vector();
200         public XMLHelper() { super(BUFFER_SIZE); }
201         public void startElement(XML.Element c) throws XML.SchemaException {
202             JS o = new JS.Obj();
203             o.put("$name", c.localName);
204             for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
205             o.put("$numchildren", new Integer(0));
206             obStack.addElement(o);
207         }
208         public void endElement(XML.Element c) throws XML.SchemaException {
209             if (obStack.size() == 1) return;
210             JS me = (JS)obStack.lastElement();
211             obStack.setSize(obStack.size() - 1);
212             JS parent = (JS)obStack.lastElement();
213             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
214             parent.put("$numchildren", new Integer(numchildren + 1));
215             parent.put(new Integer(numchildren), me);
216         }
217         public void characters(char[] ch, int start, int length) throws XML.SchemaException {
218             String s = new String(ch, start, length);
219             JS parent = (JS)obStack.lastElement();
220             int numchildren = ((Integer)parent.get("$numchildren")).intValue();
221             Object lastChild = parent.get(new Integer(numchildren - 1));
222             if (lastChild instanceof String) {
223                 parent.put(new Integer(numchildren - 1), lastChild + s);
224             } else {
225                 parent.put("$numchildren", new Integer(numchildren + 1));
226                 parent.put(new Integer(numchildren), s);
227             }
228         }
229         public void whitespace(char[] ch, int start, int length) {}
230         public JS doParse() throws JS.Exn {
231             try { 
232                 InputStream is = getInputStream();
233                 BufferedReader r = new BufferedReader(new InputStreamReader(is));
234                 parse(r);
235             } catch (XML.XMLException e) {
236                 throw new JS.Exn("error parsing XML: " + e.toString());
237             } catch (IOException e) {
238                 if (Log.on) Log.log(this, "IO Exception while reading from file");
239                 if (Log.on) Log.log(this, e);
240                 throw new JS.Exn("error reading from Resource");
241             }
242             return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
243         }
244     }
245
246     public void writeTo(OutputStream os) throws IOException {
247         InputStream is = getInputStream();
248         byte[] buf = new byte[1024];
249         while(true) {
250             int numread = is.read(buf, 0, 1024);
251             if (numread == -1) break;
252             if (Log.on) Log.log(this, "wrote " + numread + " bytes");
253             os.write(buf, 0, numread);
254         }
255         os.flush();
256
257         // we have to close this because flush() doesn't work on Win32-GCJ
258         os.close();
259     }
260 }