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