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