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