1 package org.ibex.xt.shell;
8 import org.ibex.util.*;
9 import org.ibex.util.Collections;
11 import org.ibex.xt.Prevalence;
12 import org.prevayler.*;
14 public class JSRemote extends JS {
15 public static final int VERSION = 1;
17 private final URL server;
18 private final String path;
20 private transient String cookie = null;
21 private transient Keys keys = null;
23 public JSRemote(URL s) { server = s; path = null; }
24 public JSRemote(URL s, String p) { server = s; path = p; }
26 /** Receives a Request object from a client on <tt>in</tt>
27 * and writes a response on <tt>out</tt> */
28 public static void receive(Prevayler p, JS root, ObjectInputStream in, ObjectOutputStream out)
30 out.writeInt(VERSION); if (in.readInt() != VERSION) return;
34 Object o = in.readObject();
35 if (o == null) throw new IOException("unexpected null request");
36 if (!(o instanceof Request)) throw new IOException(
37 "unexpected request object: "+o.getClass().getName());
39 } catch (ClassNotFoundException e) {
40 throw new IOException("unexpected class not found: " + e.getMessage());
43 r.execute(p, root, out);
46 /** Sends a request to the server. */
47 protected ObjectInputStream send(Request request) throws IOException {
48 URLConnection c = server.openConnection();
49 ((HttpURLConnection)c).setRequestMethod("POST");
51 if (cookie != null) c.setRequestProperty("Cookie", cookie);
55 ObjectOutputStream out = new ObjectOutputStream(c.getOutputStream());
56 out.writeInt(VERSION);
57 out.writeObject(request);
60 String cook = c.getHeaderField("Set-Cookie");
61 if (cook != null && cook.length() > 0) cookie = cook.substring(0, cook.indexOf(';'));
63 ObjectInputStream in = new ObjectInputStream(c.getInputStream());
64 int ver = in.readInt();
65 if (ver != VERSION) throw new IOException("server version "+ver+", expected "+VERSION);
69 /** FEATURE: It's questionable as to whether this belongs here. JSRemote shouldn't
70 * really know anything about prevayler, but that rquires another layer between
71 * this class and the http layer. Maybe not a bad idea. */
72 public void transaction(final JS t) {
75 resp = send(new Request(null) {
76 protected void execute() throws JSExn, IOException {
78 prevayler.execute(new Prevalence.JSTransaction(t));
79 out.writeObject(null);
80 } catch (Exception e) { e.printStackTrace(); out.writeObject(e); }
83 } catch (Exception e) {
84 throw new RuntimeException("transaction failed", e);
87 if (resp != null && resp instanceof Exception)
88 throw new RuntimeException("transaction failed", (Exception)resp);
91 public Collection keys() { return keys == null ? keys = new Keys() : keys.update(); }
93 public Object get(Object k) throws JSExn {
95 ObjectInputStream in = send(new Request(path, k) {
96 protected void execute() throws JSExn, IOException {
97 Object o = scope.get(key);
99 out.writeObject(null);
100 else if (o instanceof Number || o instanceof Boolean || o instanceof String)
102 else if (o instanceof JS)
103 out.writeObject(new JSRemote(server, (path == null ? "" : path + '.') + key));
104 else throw new JSExn("unexpected class type " + o + " ["+o.getClass()+"]");
107 Object o = in.readObject(); in.close();
109 if (o == null) return null;
110 else if (o instanceof JS) return new JSImmutable((JS)o);
111 else if (o instanceof Exception) throw (Exception)o;
113 } catch (JSExn e) { throw e;
114 } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
117 // FIXME: unroll JSRemote if it is a value
118 public Object put(Object k, final Object value) throws JSExn {
119 try { return send(new Request(path, k) {
120 protected void execute() throws JSExn, IOException {
121 out.writeObject(scope.put(key, value));
123 }).readObject(); } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
126 public Object remove(Object k) throws JSExn {
127 try { return send(new Request(path, k) {
128 protected void execute() throws JSExn, IOException {
129 out.writeObject(scope.remove(key));
131 }).readObject(); } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
134 public boolean containsKey(Object k) {
135 try { return send(new Request(path, k) {
136 protected void execute() throws JSExn, IOException {
137 out.writeBoolean(scope.containsKey(key));
139 }).readBoolean(); } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
142 public Object call(final Object a0, final Object a1, final Object a2,
143 final Object[] rest, final int nargs) throws JSExn {
144 try { return send(new Request(path) {
145 protected void execute() throws JSExn, IOException {
146 out.writeObject(scope.call(a0, a1, a2, rest, nargs));
148 }).readObject(); } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
151 public Object callMethod(final Object m, final Object a0, final Object a1, final Object a2,
152 final Object[] rest, final int nargs) throws JSExn {
153 try { return send(new Request(path) {
154 protected void execute() throws JSExn, IOException {
155 out.writeObject(scope.callMethod(m, a0, a1, a2, rest, nargs));
157 }).readObject(); } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
160 // FIXME: map trap functions to server
162 public static abstract class Request implements Serializable {
163 protected Prevayler prevayler;
164 protected ObjectOutputStream out;
166 protected String path;
167 protected Object key;
169 public Request(String path) { this.path = path; key = null; }
170 public Request(String path, Object key) {
171 if (key != null && key instanceof String) {
172 String k = (String)key;
173 if (k.length() > 0) {
174 if (k.charAt(0) == '.') k = k.substring(1);
175 if (k.charAt(k.length() - 1) == '.') k = k.substring(0, k.length() - 1);
177 int pos = k.lastIndexOf('.');
179 path += k.substring(0, pos);
180 k = k.substring(pos + 1);
183 } else this.key = key;
187 public void execute(Prevayler p, JS r, ObjectOutputStream o) throws IOException {
193 StringTokenizer st = new StringTokenizer(path, ".");
194 while (st.hasMoreTokens()) {
195 String s = st.nextToken().trim();
196 if (s.length() > 0 && !s.equals(".")) {
197 Object ob = scope.get(s);
198 if (ob == null || !(ob instanceof JS))
199 throw new JSExn("path not found");
205 } catch(JSExn e) { out.writeObject(e); }
210 protected abstract void execute() throws JSExn, IOException;
213 public static class JSImmutable extends JS {
214 private final JS wrapped;
215 public JSImmutable(JS toWrap) { wrapped = toWrap; }
217 public Collection keys() throws JSExn {
218 return Collections.unmodifiableCollection(wrapped.keys()); }
219 public Object get(Object key) throws JSExn { return wrapped.get(key); }
220 public boolean containsKey(Object key) { return wrapped.containsKey(key); }
221 public Object call(Object a0, Object a1, Object a2, Object[] r, int n)
222 throws JSExn { return wrapped.call(a0, a1, a2, r, n); }
224 public Object callMethod(Object m, Object a0, Object a1, Object a2, Object[] r, int n)
225 throws JSExn { throw new JSExn("immutable JS"); }
226 public Object put(Object k, Object v) throws JSExn {
227 throw new JSExn("immutable JS"); }
228 public Object remove(Object k) throws JSExn {
229 throw new JSExn("immutable JS"); }
230 public void putAndTriggerTraps(Object k, Object v) throws JSExn {
231 throw new JSExn("immutable JS"); }
232 public Object getAndTriggerTraps(Object k) throws JSExn {
233 throw new JSExn("immutable JS"); }
234 protected boolean isTrappable(Object n, boolean i) { return false; }
237 private class Keys extends AbstractCollection implements Serializable {
238 private transient boolean updating = false;
239 private transient final List items =
240 Collections.synchronizedList(new ArrayList());
241 private transient int modCount = 0;
243 private int size = -1;
245 public int size() { if (size == -1) update(); return size; }
246 public Iterator iterator() { updateList(); return new KeyIt(); }
248 private synchronized Keys update() {
249 if (updating) return this;
250 modCount++; items.clear();
252 final ObjectInputStream in = send(new Request(path) {
253 protected void execute() throws JSExn, IOException {
254 Collection c = scope.keys(); out.writeInt(c.size());
258 } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
263 private synchronized Keys updateList() {
264 if (updating) return this;
266 modCount++; items.clear();
268 final ObjectInputStream in = send(new Request(path) {
269 protected void execute() throws JSExn, IOException {
270 Collection c = scope.keys(); out.writeInt(c.size());
272 if (c.size() > 1000) { // FIXME: better way to unload server?
275 List l = new ArrayList(c);
277 i = l.listIterator();
279 while (i.hasNext()) out.writeObject(i.next());
283 new Thread() { public void run() {
285 for (int i=0; i < size; i++) items.add(in.readObject());
287 } catch (Exception e) {
288 size = -1; items.clear();
289 throw new RuntimeException("JSRemote", e);
291 synchronized (Keys.this) { Keys.this.updating = false; }
294 } catch (Exception e) { throw new RuntimeException("JSRemote", e); }
299 private class KeyIt implements Iterator {
300 private final int mod;
303 KeyIt() { mod = modCount; }
304 public boolean hasNext() {
305 if (modCount != mod) throw new ConcurrentModificationException();
308 public Object next() {
309 if (modCount != mod) throw new ConcurrentModificationException();
310 while (pos >= items.size()) {
311 if (pos >= size) throw new NoSuchElementException();
312 try { Thread.sleep(50); } catch (InterruptedException e) {}
314 return items.get(pos++);
316 public void remove() { throw new UnsupportedOperationException(); } // FIXME