/** * ServletList.java 1.00 11.13.97 Michael Shoffner * * Copyright (c) 1997 Shoffner/Hughes. All Rights Reserved. * * Permission to use, copy, modify, and distribute this software * for non-commercial purposes and without fee is hereby granted * provided that this copyright notice appears in all copies. * * shoffner@prominence.com */ package shoffner.step.jan; import java.io.*; import java.util.*; import java.net.*; import org.merlin.step.dec.*; import org.merlin.step.dec.socket.*; public class ServletList extends ObservableList implements Runnable { public static final int UPDATE_DELAY = 10 * 1000; URL server; IDList list; Thread processor; public ServletList (String host, String loc) { try { server = new URL ("http://" + host + "/" + loc); } catch (MalformedURLException ex) { ex.printStackTrace (); } list = new IDList (); update (); processor = new Thread (this); processor.start (); } public Enumeration elements () { return list.elements (); } public void addElement (Object element) { Object id = queryServer (new AddElementMsg (element)); list.addElementWithID (id, element); } public void replaceElementAtEnd (Object oldE, Object newE) { Object oldID = list.getIDOfElement (oldE); Object id = queryServer (new ReplaceElementMsg (oldID, newE)); if (id != null) list.replaceElementWithID (oldID, id, newE); else System.out.println ("Unknown id:" + oldID); } public void run () { while (true) { try { Thread.sleep (UPDATE_DELAY); update (); } catch (Exception ignored) { ignored.printStackTrace (); } } } public void stop () { if (processor != null) { processor.stop (); processor = null; } } void update () { InitMsg i = (InitMsg) queryServer (new UpdateMsg (list.getUpdateCount ())); System.err.println ("ServletList.update (): i == " + i); IDList initList = i.getList (); if (initList != null) { list = initList; fireUpdate (); } } Object queryServer (Object arg) { URLConnection con; ObjectOutputStream req = null; ObjectInputStream res = null; Object result = null; try { con = server.openConnection (); con.setDoOutput (true); req = new ObjectOutputStream (new BufferedOutputStream (con.getOutputStream ())); req.writeObject (arg); req.flush (); req.close (); res = new ObjectInputStream (new BufferedInputStream (con.getInputStream ())); result = res.readObject (); } catch (IOException ignored) { ignored.printStackTrace (); } catch (ClassNotFoundException ex) { ex.printStackTrace (); } finally { try { res.close (); } catch (IOException ex) {} } return result; } }