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 /** shadow resource which replaces the graft */
147 public static class Graft extends Res {
151 Graft(Res graftee, Object key, Object val) { this.graftee = graftee; replaced_key = key; replaced_val = val; }
152 public boolean equals(Object o) { return (this == o || graftee.equals(o)); }
153 public int hashCode() { return graftee.hashCode(); }
154 public InputStream getInputStream(String s) throws IOException { return graftee.getInputStream(s); }
155 public Object get(Object key) { return replaced_key.equals(key) ? replaced_val : graftee.get(key); }
156 public String getDescriptiveName() { return graftee.getDescriptiveName(); }
157 public Res getParent() { return graftee.getParent(); }
160 /** shadow resource which replaces the graft */
161 public static class ProgressWatcher extends Res {
163 JS.Callable callback;
164 ProgressWatcher(Res watchee, JS.Callable callback) { this.watchee = watchee; this.callback = callback; }
165 public InputStream getInputStream(String s) throws IOException {
166 return new FilterInputStream(watchee.getInputStream(s)) {
167 int bytesDownloaded = 0;
168 public int read() throws IOException {
169 int ret = super.read();
170 if (ret != -1) bytesDownloaded++;
173 public int read(byte[] b, int off, int len) throws IOException {
174 int ret = super.read(b, off, len);
175 if (ret != 1) bytesDownloaded += ret;
176 ThreadMessage.newthread(new JS.Callable() { public Object call(JS.Array a) {
177 JS.Array args = new JS.Array();
178 args.addElement(new Integer(bytesDownloaded));
188 /** unpacks a Microsoft CAB file (possibly embedded in another file; we scan for 'MSCF' */
189 public static class CAB extends Res {
191 CAB(Res parent) { this.parent = parent; }
192 private int swap_endian(int i) {
193 return ((i & 0xff) << 24) | ((i & 0xff00) << 8) | ((i & 0xff0000) >>> 8) | (i >>> 24);
195 public InputStream getInputStream(String path) throws IOException {
197 return org.xwt.util.CAB.getFileInputStream(parent.getInputStream(), 2, path);
198 } catch (EOFException eof) {
199 throw new JS.Exn("MSCF header tag not found in file");
200 } catch (IOException ioe) {
201 throw new JS.Exn("IOException while reading file");
206 public Object callMethod(Object method, Array args, boolean checkOnly) throws JS.Exn {
207 if (method.equals("getUTF")) {
208 if (checkOnly) return Boolean.TRUE;
209 if (args.length() != 0) return null;
211 CharArrayWriter caw = new CharArrayWriter();
212 InputStream is = getInputStream();
213 BufferedReader r = new BufferedReader(new InputStreamReader(is));
214 char[] buf = new char[1024];
216 int numread = r.read(buf, 0, 1024);
217 if (numread == -1) break;
218 caw.write(buf, 0, numread);
220 return caw.toString();
221 } catch (IOException e) {
222 if (Log.on) Log.log(Res.class, "IO Exception while reading from file");
223 if (Log.on) Log.log(Res.class, e);
224 throw new JS.Exn("error while reading from Resource");
226 } else if (method.equals("getDOM")) {
227 if (checkOnly) return Boolean.TRUE;
228 if (args.length() != 0) return null;
229 return new XMLHelper().doParse();
231 if (checkOnly) return Boolean.FALSE;
235 private class XMLHelper extends XML {
236 Vector obStack = new Vector();
237 public XMLHelper() { super(BUFFER_SIZE); }
238 public void startElement(XML.Element c) throws XML.SchemaException {
240 o.put("$name", c.localName);
241 for(int i=0; i<c.len; i++) o.put(c.keys[i], c.vals[i]);
242 o.put("$numchildren", new Integer(0));
243 obStack.addElement(o);
245 public void endElement(XML.Element c) throws XML.SchemaException {
246 if (obStack.size() == 1) return;
247 JS me = (JS)obStack.lastElement();
248 obStack.setSize(obStack.size() - 1);
249 JS parent = (JS)obStack.lastElement();
250 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
251 parent.put("$numchildren", new Integer(numchildren + 1));
252 parent.put(new Integer(numchildren), me);
254 public void characters(char[] ch, int start, int length) throws XML.SchemaException {
255 String s = new String(ch, start, length);
256 JS parent = (JS)obStack.lastElement();
257 int numchildren = ((Integer)parent.get("$numchildren")).intValue();
258 Object lastChild = parent.get(new Integer(numchildren - 1));
259 if (lastChild instanceof String) {
260 parent.put(new Integer(numchildren - 1), lastChild + s);
262 parent.put("$numchildren", new Integer(numchildren + 1));
263 parent.put(new Integer(numchildren), s);
266 public void whitespace(char[] ch, int start, int length) {}
267 public JS doParse() throws JS.Exn {
269 InputStream is = getInputStream();
270 BufferedReader r = new BufferedReader(new InputStreamReader(is));
272 } catch (XML.XMLException e) {
273 throw new JS.Exn("error parsing XML: " + e.toString());
274 } catch (IOException e) {
275 if (Log.on) Log.log(this, "IO Exception while reading from file");
276 if (Log.on) Log.log(this, e);
277 throw new JS.Exn("error reading from Resource");
279 return obStack.size() >= 1 ? (JS)obStack.elementAt(0) : null;
283 public void writeTo(OutputStream os) throws IOException {
284 InputStream is = getInputStream();
285 byte[] buf = new byte[1024];
287 int numread = is.read(buf, 0, 1024);
288 if (numread == -1) break;
289 if (Log.on) Log.log(this, "wrote " + numread + " bytes");
290 os.write(buf, 0, numread);
294 // we have to close this because flush() doesn't work on Win32-GCJ