1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
6 import java.util.zip.*;
9 import org.bouncycastle.util.encoders.Base64;
11 /** base class for XWT resources */
12 public abstract class Res extends JS {
14 public String getDescriptiveName() { return ""; }
15 public String typeName() { return "resource"; }
17 /** cache of subresources so that the equality operator works on them */
18 private Hash refCache = null;
20 public Template t = null;
22 public Res getParent() { return null; }
24 /** returns an InputStream containing the Resource's contents */
25 public InputStream getInputStream() throws IOException { return getInputStream(""); }
26 public abstract InputStream getInputStream(String path) throws IOException;
28 /** graft newResource in place of this resource on its parent */
29 public Res graft(Object newResource) { throw new JS.Exn("cannot graft onto this resource"); }
31 /** if the path of this resource does not end with extension, return a new one wit it appended */
32 public Res addExtension(String extension) { return new Ref(this, extension); }
34 public Object[] keys() { throw new JS.Exn("cannot enumerate a resource"); }
35 public void put(Object key, Object val) { throw new JS.Exn("cannot put to a resource"); }
36 public Object get(Object key) {
38 Template t = Template.getTemplate(addExtension(".xwt"));
39 return t == null ? null : t.getStatic();
41 Object ret = refCache == null ? null : refCache.get(key);
42 if (ret != null) return ret;
43 ret = new Ref(this, key);
44 if (refCache == null) refCache = new Hash();
45 refCache.put(key, ret);
49 public static Res stringToRes(String url) { return stringToRes(url, false); }
50 public static Res stringToRes(String url, boolean permitLocalFilesystem) {
51 if (url.indexOf('!') != -1)
52 return (Res)(new Zip(stringToRes(url.substring(0, url.lastIndexOf('!')))).
53 get(url.substring(url.lastIndexOf('!') + 1)));
54 if (url.startsWith("http://")) return new HTTP(url);
55 if (url.startsWith("https://")) return new HTTP(url);
56 if (url.startsWith("file:") && permitLocalFilesystem) return new File(url.substring(5));
57 if (url.startsWith("cab:")) return new CAB(stringToRes(url.substring(4)));
58 if (url.startsWith("data:")) return new ByteArray(Base64.decode(url.substring(5)));
59 if (url.startsWith("utf8:")) return new ByteArray(url.substring(5).getBytes());
60 throw new JS.Exn("invalid resource specifier " + url);
63 /** subclass from this if you want a CachedInputStream for each path */
64 public static abstract class CachedRes extends Res {
65 private Hash cachedInputStreams = new Hash();
66 abstract InputStream _getInputStream(String path) throws IOException;
67 public final InputStream getInputStream(String path) throws IOException {
68 CachedInputStream cis = (CachedInputStream)cachedInputStreams.get(path);
70 cis = new CachedInputStream(_getInputStream(path));
71 cachedInputStreams.put(path, cis);
73 return cis.getInputStream();
77 /** HTTP or HTTPS resource */
78 public static class HTTP extends CachedRes {
80 HTTP(String url) { this.url = url; }
81 public InputStream _getInputStream(String path) throws IOException {
82 return new org.xwt.HTTP(url + path).GET(); }
86 public static class ByteArray extends Res {
88 ByteArray(byte[] bytes) { this.bytes = bytes; }
89 public InputStream getInputStream(String path) throws IOException {
90 if (!"".equals(path)) throw new JS.Exn("can't get subresources of a byte[] resource");
91 return new ByteArrayInputStream(bytes);
96 public static class File extends Res {
98 File(String path) { this.path = path; }
99 public InputStream getInputStream(String rest) throws IOException {
100 return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
103 /** wrap a Res around a preexisting InputStream */
104 public static class IS extends Res {
106 IS(InputStream parent) { this.parent = parent; }
107 public InputStream getInputStream(String path) {
108 if (!"".equals(path)) throw new JS.Exn("can't access subresources of IS");
113 /** "unwrap" a Zip archive */
114 public static class Zip extends Res {
116 Zip(Res parent) { this.parent = parent; }
117 public InputStream getInputStream(String path) throws IOException {
118 if (path.startsWith("/")) path = path.substring(1);
119 ZipInputStream zis = new ZipInputStream(parent.getInputStream());
120 ZipEntry ze = zis.getNextEntry();
121 while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
122 if (ze == null) throw new JS.Exn("requested file not found in archive");
127 /** what you get when you reference a subresource */
128 public static class Ref extends Res {
131 Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
132 public String getDescriptiveName() {
133 String pdn = parent.getDescriptiveName();
134 return pdn.equals("") ? key.toString() : (pdn + "." + key.toString());
136 public Res addExtension(String extension) {
137 return (key instanceof String && ((String)key).endsWith(extension)) ? this : new Ref(parent, key + extension);
139 public InputStream getInputStream(String path) throws IOException {
140 return parent.getInputStream("/" + key + path);
142 public Res getParent() { return parent; }
143 public Res graft(Object newResource) { return new Graft(parent, key, newResource); }
146 // FEATURE: eliminate code duplication with JS.Graft
147 /** shadow resource which replaces the graft */
148 public static class Graft extends Res {
152 Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
153 public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
154 public int hashCode() { return graftee.hashCode(); }
155 public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
156 public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
157 public String getDescriptiveName() { return graftee.getDescriptiveName(); }
158 public Res getParent() { return graftee.getParent(); }
159 public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
160 if (!replaced_key.equals(method)) return graftee.callMethod(method, args, checkOnly);
161 if (replaced_val instanceof Callable) return checkOnly ? Boolean.TRUE : ((Callable)replaced_val).call(args);
162 if (checkOnly) return Boolean.FALSE;
163 throw new JS.Exn("attempt to call non-function");
165 public Number coerceToNumber() { return graftee.coerceToNumber(); }
166 public String coerceToString() { return graftee.coerceToString(); }
167 public boolean coerceToBoolean() { return graftee.coerceToBoolean(); }
168 public String typeName() { return graftee.typeName(); }
171 /** shadow resource which replaces the graft */
172 public static class ProgressWatcher extends Res {
174 JS.Callable callback;
175 ProgressWatcher(Res watchee, JS.Callable callback) { this.watchee = watchee; this.callback = callback; }
176 public InputStream getInputStream(String s) throws IOException {
177 return new FilterInputStream(watchee.getInputStream(s)) {
178 int bytesDownloaded = 0;
179 public int read() throws IOException {
180 int ret = super.read();
181 if (ret != -1) bytesDownloaded++;
184 public int read(byte[] b, int off, int len) throws IOException {
185 int ret = super.read(b, off, len);
186 if (ret != 1) bytesDownloaded += ret;
187 ThreadMessage.newthread(new JS.Callable() { public Object call(JS.Array a) {
188 JS.Array args = new JS.Array();
189 args.addElement(new Integer(bytesDownloaded));
199 /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
200 public static class CAB extends Res {
202 CAB(Res parent) { this.parent = parent; }
203 private int swap_endian(int i) {
204 return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
206 public InputStream getInputStream(String path) throws IOException {
208 return org.xwt.util.CAB.getFileInputStream(parent.getInputStream(), 2, path);
209 } catch (EOFException eof) {
210 throw new JS.Exn("MSCF header tag not found in file");
211 } catch (IOException ioe) {
212 throw new JS.Exn("IOException while reading file");
217 public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
218 if (method.equals("getUTF")) {
219 if (checkOnly) return Boolean.TRUE;
220 if (args.length() != 0) return null;
222 CharArrayWriter caw = new CharArrayWriter();
223 InputStream is = getInputStream();
224 BufferedReader r = new BufferedReader(new InputStreamReader(is));
225 char[] buf = new char[1024];
227 int numread = r.read(buf, 0, 1024);
228 if (numread == -1) break;
229 caw.write(buf, 0, numread);
231 return caw.toString();
232 } catch (IOException e) {
233 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
234 if (Log.on) Log.log(Res.class, e);
235 throw new JS.Exn("error while reading from Resource");
237 } else if (method.equals("getDOM")) {
238 if (checkOnly) return Boolean.TRUE;
239 if (args.length() != 0) return null;
240 return new XMLHelper().doParse();
242 if (checkOnly) return Boolean.FALSE;
246 private class XMLHelper extends XML {
247 Vector obStack = new Vector();
248 public XMLHelper() { super(BUFFER_SIZE); }
249 public void startElement(XML.Element c) throws XML.SchemaException {
251 o.put("$name", c.localName);
252 for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
253 o.put("$numchildren", new Integer(0));
254 obStack.addElement(o);
256 public void endElement(XML.Element c) throws XML.SchemaException {
257 if (obStack.size() == 1) return;
258 JS me = (JS)obStack.lastElement();
259 obStack.setSize(obStack.size() - 1);
260 JS parent = (JS)obStack.lastElement();
261 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
262 parent.put("$numchildren", new Integer(numchildren + 1));
263 parent.put(new Integer(numchildren), me);
265 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
266 String s = new String(ch, start, length);
267 JS parent = (JS)obStack.lastElement();
268 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
269 Object lastChild = parent.get(new Integer(numchildren - 1));
270 if (lastChild instanceof String) {
271 parent.put(new Integer(numchildren - 1), lastChild + s);
273 parent.put("$numchildren", new Integer(numchildren + 1));
274 parent.put(new Integer(numchildren), s);
277 public void whitespace(char[] ch, int start, int length) {}
278 public JS doParse() throws JS.Exn {
280 InputStream is = getInputStream();
281 BufferedReader r = new BufferedReader(new InputStreamReader(is));
283 } catch (XML.XMLException e) {
284 throw new JS.Exn("error parsing XML: " + e.toString());
285 } catch (IOException e) {
286 if (Log.on) Log.log(this, "IO Exception while reading from file");
287 if (Log.on) Log.log(this, e);
288 throw new JS.Exn("error reading from Resource");
290 return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
294 public void writeTo(OutputStream os) throws IOException {
295 InputStream is = getInputStream();
296 byte[] buf = new byte[1024];
298 int numread = is.read(buf, 0, 1024);
299 if (numread == -1) break;
300 if (Log.on) Log.log(this, "wrote " + numread + " bytes");
301 os.write(buf, 0, numread);
305 // we have to close this because flush() doesn't work on Win32-GCJ