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