import java.awt.*; import java.awt.event.*; import java.applet.Applet; import java.net.*; import java.io.*; public class JSApplet extends Applet implements ActionListener { Socket socket = null; ObjectOutputStream os = null; ObjectInputStream is = null; Panel north, center; Button searchButton, clearButton; List searchResults; public void init() { // build the applet display setLayout(new BorderLayout()); north = new Panel(); north.setLayout(new FlowLayout()); searchButton = new Button("Begin Search"); searchButton.addActionListener(this); north.add(searchButton); clearButton = new Button("Clear Data"); clearButton.addActionListener(this); north.add(clearButton); add("North", north); searchResults = new List(); add("Center", searchResults); if (connectToServer()) { openDatabase(); } else { showStatus("Cannot open socket connection."); } } public boolean connectToServer() { try { socket = new Socket(getCodeBase().getHost(), 9000); os = new ObjectOutputStream(socket.getOutputStream()); is = new ObjectInputStream(socket.getInputStream()); } catch (Exception ex) { showStatus(ex.toString()); return false; } return true; } public void openDatabase() { String ack; send("open"); ack = (String)receive(); if (ack != null) showStatus(ack); } public void send(Object o) { try { os.writeObject(o); os.flush(); } catch (Exception ex) { showStatus(ex.toString()); } } public Object receive() { Object o = null; try { o = is.readObject(); } catch (Exception ex) { showStatus(ex.toString()); } return o; } public void finalize() { try { send("close"); os.close(); is.close(); socket.close(); } catch (Exception ex) {} super.destroy(); } public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("Begin Search")) { try { performSearch(); } catch (Exception ex) { showStatus(ex.toString() + ": Can't issue search"); } } else { clearListBox(); } return; } /** Clear the contents of the list box */ public void clearListBox() { searchResults.removeAll(); } /** Issue a SQL query with a WHERE clause */ public void performSearch() throws Exception { Object result; // Row retrieved from query clearListBox(); send("srch"); result = receive(); if (result.equals("ok")) { processResults(); } else { showStatus((String)result); } } public void processResults() { Object result; send("fetch"); result = receive(); if (result == null) { showStatus("No rows found using specified search criteria."); return; } while (result != null) { searchResults.addItem((String)result); send("fetch"); result = receive(); } } }