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 /** an InputStream that makes sure it is not in the MessageQueue when blocked on a read */
25 private static class BackgroundInputStream extends FilterInputStream {
26 BackgroundInputStream(InputStream i) { super(i); }
27 private void suspend() throws IOException {
28 if (!ThreadMessage.suspendThread())
29 throw new IOException("attempt to perform background-only operation in a foreground thread");
31 private void resume() {
32 ThreadMessage.resumeThread();
34 public int read() throws IOException {
36 try { return super.read(); }
39 public int read(byte[] b, int off, int len) throws IOException {
41 try { return super.read(b, off, len); }
46 /** returns an InputStream containing the Resource's contents */
47 public final InputStream getInputStream() throws IOException { return new BackgroundInputStream(getInputStream("")); }
48 public abstract InputStream getInputStream(String path) throws IOException;
50 /** graft newResource in place of this resource on its parent */
51 public Res graft(Object newResource) { throw new JS.Exn("cannot graft onto this resource"); }
53 /** if the path of this resource does not end with extension, return a new one wit it appended */
54 public Res addExtension(String extension) { return new Ref(this, extension); }
56 public Object[] keys() { throw new JS.Exn("cannot enumerate a resource"); }
57 public void put(Object key, Object val) { throw new JS.Exn("cannot put to a resource"); }
58 public Object get(Object key) {
60 Template t = Template.getTemplate(addExtension(".xwt"));
61 return t == null ? null : t.getStatic();
63 Object ret = refCache == null ? null : refCache.get(key);
64 if (ret != null) return ret;
65 ret = new Ref(this, key);
66 if (refCache == null) refCache = new Hash();
67 refCache.put(key, ret);
71 public static Res stringToRes(String url) {
72 if (url.indexOf('!') != -1)
73 return (Res)(new Zip(stringToRes(url.substring(0, url.lastIndexOf('!')))).
74 get(url.substring(url.lastIndexOf('!') + 1)));
75 if (url.startsWith("http://")) return new HTTP(url);
76 if (url.startsWith("https://")) return new HTTP(url);
77 if (url.startsWith("cab:")) return new CAB(stringToRes(url.substring(4)));
78 if (url.startsWith("data:")) return new ByteArray(Base64.decode(url.substring(5)));
79 if (url.startsWith("utf8:")) return new ByteArray(url.substring(5).getBytes());
80 throw new JS.Exn("invalid resource specifier " + url);
83 /** subclass from this if you want a CachedInputStream for each path */
84 public static abstract class CachedRes extends Res {
85 private Hash cachedInputStreams = new Hash();
86 abstract InputStream _getInputStream(String path) throws IOException;
87 public final InputStream getInputStream(String path) throws IOException {
88 CachedInputStream cis = (CachedInputStream)cachedInputStreams.get(path);
90 cis = new CachedInputStream(_getInputStream(path));
91 cachedInputStreams.put(path, cis);
93 return cis.getInputStream();
97 /** HTTP or HTTPS resource */
98 public static class HTTP extends CachedRes {
100 HTTP(String url) { this.url = url; }
101 public InputStream _getInputStream(String path) throws IOException {
102 return new org.xwt.HTTP(url + path).GET(); }
106 public static class ByteArray extends Res {
107 private byte[] bytes;
108 ByteArray(byte[] bytes) { this.bytes = bytes; }
109 public InputStream getInputStream(String path) throws IOException {
110 if (!"".equals(path)) throw new JS.Exn("can't get subresources of a byte[] resource");
111 return new ByteArrayInputStream(bytes);
116 public static class File extends Res {
118 File(String path) { this.path = path; }
119 public InputStream getInputStream(String rest) throws IOException {
120 return new FileInputStream((path + rest).replace('/', java.io.File.separatorChar)); }
123 /** "unwrap" a Zip archive */
124 public static class Zip extends Res {
126 Zip(Res parent) { this.parent = parent; }
127 public InputStream getInputStream(String path) throws IOException {
128 if (path.startsWith("/")) path = path.substring(1);
129 ZipInputStream zis = new ZipInputStream(parent.getInputStream());
130 ZipEntry ze = zis.getNextEntry();
131 while(ze != null && !ze.getName().equals(path)) ze = zis.getNextEntry();
132 if (ze == null) throw new JS.Exn("requested file (" + path + ") not found in archive");
137 /** what you get when you reference a subresource */
138 public static class Ref extends Res {
141 Ref(Res parent, Object key) { this.parent = parent; this.key = key; }
142 public String getDescriptiveName() {
143 String pdn = parent.getDescriptiveName();
144 return pdn.equals("") ? key.toString() : (pdn + "." + key.toString());
146 public Res addExtension(String extension) {
147 return (key instanceof String && ((String)key).endsWith(extension)) ? this : new Ref(parent, key + extension);
149 public InputStream getInputStream(String path) throws IOException {
150 return parent.getInputStream("/" + key + path);
152 public Res getParent() { return parent; }
153 public Res graft(Object newResource) { return new Graft(parent, key, newResource); }
156 // FEATURE: eliminate code duplication with JS.Graft
157 /** shadow resource which replaces the graft */
158 public static class Graft extends Res {
162 Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
163 public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
164 public int hashCode() { return graftee.hashCode(); }
165 public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
166 public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
167 public String getDescriptiveName() { return graftee.getDescriptiveName(); }
168 public Res getParent() { return graftee.getParent(); }
169 public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
170 if (!replaced_key.equals(method)) return graftee.callMethod(method, args, checkOnly);
171 if (replaced_val instanceof Callable) return checkOnly ? Boolean.TRUE : ((Callable)replaced_val).call(args);
172 if (checkOnly) return Boolean.FALSE;
173 throw new JS.Exn("attempt to call non-function");
175 public Number coerceToNumber() { return graftee.coerceToNumber(); }
176 public String coerceToString() { return graftee.coerceToString(); }
177 public boolean coerceToBoolean() { return graftee.coerceToBoolean(); }
178 public String typeName() { return graftee.typeName(); }
181 /** shadow resource which replaces the graft */
182 public static class ProgressWatcher extends Res {
184 JS.Callable callback;
185 ProgressWatcher(Res watchee, JS.Callable callback) { this.watchee = watchee; this.callback = callback; }
186 public InputStream getInputStream(String s) throws IOException {
187 return new FilterInputStream(watchee.getInputStream(s)) {
188 int bytesDownloaded = 0;
189 public int read() throws IOException {
190 int ret = super.read();
191 if (ret != -1) bytesDownloaded++;
194 public int read(byte[] b, int off, int len) throws IOException {
195 int ret = super.read(b, off, len);
196 if (ret != 1) bytesDownloaded += ret;
197 ThreadMessage.newthread(new JS.Callable() { public Object call(JS.Array a) {
198 JS.Array args = new JS.Array();
199 args.addElement(new Integer(bytesDownloaded));
209 /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
210 public static class CAB extends Res {
212 CAB(Res parent) { this.parent = parent; }
213 private int swap_endian(int i) {
214 return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
216 public InputStream getInputStream(String path) throws IOException {
218 return org.xwt.util.CAB.getFileInputStream(parent.getInputStream(), 2, path);
219 } catch (EOFException eof) {
220 throw new JS.Exn("MSCF header tag not found in file");
221 } catch (IOException ioe) {
222 throw new JS.Exn("IOException while reading file");
227 public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
228 if (method.equals("getUTF")) {
229 if (checkOnly) return Boolean.TRUE;
230 if (args.length() != 0) return null;
232 CharArrayWriter caw = new CharArrayWriter();
233 InputStream is = getInputStream();
234 BufferedReader r = new BufferedReader(new InputStreamReader(is));
235 char[] buf = new char[1024];
237 int numread = r.read(buf, 0, 1024);
238 if (numread == -1) break;
239 caw.write(buf, 0, numread);
241 return caw.toString();
242 } catch (IOException e) {
243 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
244 if (Log.on) Log.log(Res.class, e);
245 throw new JS.Exn("error while reading from Resource");
247 } else if (method.equals("getDOM")) {
248 if (checkOnly) return Boolean.TRUE;
249 if (args.length() != 0) return null;
250 return new XMLHelper().doParse();
252 if (checkOnly) return Boolean.FALSE;
256 private class XMLHelper extends XML {
257 Vector obStack = new Vector();
258 public XMLHelper() { super(BUFFER_SIZE); }
259 public void startElement(XML.Element c) throws XML.SchemaException {
261 o.put("$name", c.localName);
262 for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
263 o.put("$numchildren", new Integer(0));
264 obStack.addElement(o);
266 public void endElement(XML.Element c) throws XML.SchemaException {
267 if (obStack.size() == 1) return;
268 JS me = (JS)obStack.lastElement();
269 obStack.setSize(obStack.size() - 1);
270 JS parent = (JS)obStack.lastElement();
271 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
272 parent.put("$numchildren", new Integer(numchildren + 1));
273 parent.put(new Integer(numchildren), me);
275 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
276 String s = new String(ch, start, length);
277 JS parent = (JS)obStack.lastElement();
278 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
279 Object lastChild = parent.get(new Integer(numchildren - 1));
280 if (lastChild instanceof String) {
281 parent.put(new Integer(numchildren - 1), lastChild + s);
283 parent.put("$numchildren", new Integer(numchildren + 1));
284 parent.put(new Integer(numchildren), s);
287 public void whitespace(char[] ch, int start, int length) {}
288 public JS doParse() throws JS.Exn {
290 InputStream is = getInputStream();
291 BufferedReader r = new BufferedReader(new InputStreamReader(is));
293 } catch (XML.XMLException e) {
294 throw new JS.Exn("error parsing XML: " + e.toString());
295 } catch (IOException e) {
296 if (Log.on) Log.log(this, "IO Exception while reading from file");
297 if (Log.on) Log.log(this, e);
298 throw new JS.Exn("error reading from Resource");
300 return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
304 public void writeTo(OutputStream os) throws IOException {
305 InputStream is = getInputStream();
306 byte[] buf = new byte[1024];
308 int numread = is.read(buf, 0, 1024);
309 if (numread == -1) break;
310 if (Log.on) Log.log(this, "wrote " + numread + " bytes");
311 os.write(buf, 0, numread);
315 // we have to close this because flush() doesn't work on Win32-GCJ