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