chiark / gitweb /
style: change visibility of some members of MarketUploader
[jarrg-ian.git] / src / net / chiark / yarrg / MarketUploader.java
1 package net.chiark.yarrg;
2
3 import java.awt.*;
4 import java.awt.event.*;
5
6 import javax.accessibility.*;
7 import javax.swing.*;
8
9 import com.sun.java.accessibility.util.*;
10
11 import java.util.*;
12 import java.io.*;
13 import java.util.*;
14 import java.net.URL;
15 import org.w3c.dom.*;
16 import javax.xml.parsers.DocumentBuilderFactory;
17 import org.xml.sax.InputSource;
18 import java.util.zip.GZIPOutputStream;
19 import net.chiark.yarrg.ClientHttpRequest;
20 import java.util.regex.*;
21 import java.util.prefs.Preferences;
22 import java.beans.*;
23
24 /*
25  *      MarketUploader is a class that handles the uploading of market
26  *      data from Yohoho! Puzzle Pirates via the Java Accessibility
27  *      API.
28  *
29  *      MarketUploader initializes after the main YPP window has
30  *      initialized. It provides a simple window with a "Capture
31  *      Market Data" button displayed.  Upon clicking this button, a
32  *      progress dialog is displayed, and the data is processed and
33  *      submitted to the YARRG and PCTB servers. If any errors occur,
34  *      an error dialog is shown, and processing returns, the button
35  *      becoming re-enabled.
36  */
37 public class MarketUploader
38 implements Runnable, TopLevelWindowListener, GUIInitializedListener {
39   // UI object references which are set during startup
40   private JFrame frame = null;
41   private Window window = null;
42
43   // Genuinely global variables
44   private PrintStream dtxt = null;
45   public int uploadcounter = 0;
46
47   // UI objects which are enabled/disabled, cleared/set, created/destroyed,
48   //  etc., for each upload
49   private JButton findMarket = null;
50   private JLabel resultSummary = null;
51   private JLabel arbitrageResult = null;
52   private ProgressMonitor progmon = null;
53
54   // PCTB protocol parameters
55   private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
56   private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
57   private String PCTB_HOST_URL;
58
59   // YARRG protocol parameters
60   private final static String YARRG_CLIENTNAME = "jpctb greenend";
61   private final static String YARRG_CLIENTVERSION =
62             net.chiark.yarrg.Version.version;
63   private final static String YARRG_CLIENTFIXES = "bug-094";
64   private final static String YARRG_LIVE_URL =
65     "http://upload.yarrg.chiark.net/commod-update-receiver";
66   private final static String YARRG_TEST_URL =
67     "http://upload.yarrg.chiark.net/test/commod-update-receiver";
68   private String YARRG_URL;
69
70   // Preferences
71   private boolean uploadToYarrg;
72   private boolean uploadToPCTB;
73   private boolean showArbitrage;
74
75   // Values cleared/set for each upload, or used during upload processing
76   private long startTime = 0;
77
78   private String islandName = null;
79   private String oceanName = null;
80   private java.util.concurrent.CountDownLatch latch = null;
81
82   private AccessibleContext sidePanel;
83
84   // PCTB-specific variables
85   private int unknownPCTBcommods = 0;
86   private HashMap<String,Integer> commodMap;
87
88
89   /*****************************************
90    * UPLOAD-TARGET-INDEPENDENT CODE        *
91    *****************************************/
92
93
94   /*
95    * UTILITY METHODS AND SUBCLASSES
96    *
97    * Useable on any thread.
98    *
99    */
100   private int parseQty(String str) {
101     if (str.equals(">1000")) {
102       return 1001;
103     } else {
104       return Integer.parseInt(str);
105     }
106   }
107
108   private void debuglog(String s) {
109     if (dtxt == null) return;
110     long now = new Date().getTime();
111     dtxt.println("progress "+(now - startTime)+"ms "
112                  +Thread.currentThread().getName()+": "+s);
113   }
114
115   private void debug_write_stringdata(String what, String data)
116   throws FileNotFoundException,IOException {
117     if (dtxt==null) return;
118     PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
119     strm.print(data);
120     strm.close();
121   }
122
123   private void debug_write_bytes(String what, byte[] data)
124   throws FileNotFoundException,IOException {
125     if (dtxt==null) return;
126     FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
127     strm.write(data);
128     strm.close();
129   }
130
131         
132   /*
133    * ENTRY POINT AND STARTUP
134    *
135    * Main thread and/or event thread
136    */
137
138   public static void main(String[] args) {
139     new MarketUploader();
140   }
141
142   public MarketUploader() {
143     Preferences prefs = Preferences.userNodeForPackage(getClass());
144
145     if (prefs.getBoolean("writeDebugFiles", false)) {
146       try {
147         dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
148       } catch (java.io.FileNotFoundException e) {
149         System.err.println("JARRG: Error opening debug log: "+e);
150       }
151     }
152
153     if (prefs.getBoolean("useLiveServers", true)) {
154       YARRG_URL = YARRG_LIVE_URL;
155       PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
156     } else {
157       YARRG_URL = YARRG_TEST_URL;
158       PCTB_HOST_URL = PCTB_TEST_HOST_URL;
159     }
160                 
161     uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
162     uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
163     showArbitrage=prefs.getBoolean("showArbitrage", true);
164
165     debuglog("main on dispatch thread: "+EventQueue.isDispatchThread());
166     EventQueue.invokeLater(this);
167   }
168
169   /*
170    * We arrange to wait for the GUI to be initialised, then look at
171    * every top-level window to see if the Puzzle Pirates window turns up.
172    */
173   public void run() {
174     debuglog("MarketUploader run()...");
175     if (EventQueueMonitor.isGUIInitialized()) {
176       debuglog("MarketUploader GUI already ready");
177       guiInitialized();
178     } else {
179       debuglog("MarketUploader waiting for GUI");
180       EventQueueMonitor.addGUIInitializedListener(this);
181     }
182   }
183
184   public void guiInitialized() {
185     Window ws[]= EventQueueMonitor.getTopLevelWindows();
186     EventQueueMonitor.addTopLevelWindowListener(this);
187     for (int i=0; i<ws.length; i++) {
188       debuglog("MarketUploader existing toplevel "+i);
189       topLevelWindowCreated(ws[i]);
190     }
191   }
192
193   public void topLevelWindowDestroyed(Window w) {
194     debuglog("MarketUploader destroyed toplevel");
195   }
196         
197   public void topLevelWindowCreated(Window w) {
198     if (frame!=null) 
199       // already got it
200       return;
201     String name = w.getAccessibleContext().getAccessibleName();
202     debuglog("MarketUploader checking toplevel "+name);
203     if (!name.equals("Puzzle Pirates"))
204       // Only if we're running alongside a Window named "Puzzle Pirates"
205       return;
206     debuglog("MarketUploader found toplevel, creating gui");
207     window = w;
208     createGUI();
209     frame.setVisible(true);
210   }
211         
212   private void createGUI() {
213     // Actually set up our GUI
214     on_ui_thread();
215     frame = new JFrame("Jarrg Uploader");
216     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
217     GridLayout layout = new GridLayout(2,1);
218     frame.getContentPane().setLayout(layout);
219     //frame.setPreferredSize(new Dimension(200, 60));
220                 
221     findMarket = new JButton("Upload Market Data");
222     findMarket.addActionListener(new ActionListener() {
223         public void actionPerformed(ActionEvent e) {
224           // This is called when the user clicks "upload"
225           on_ui_thread();
226
227           uploadcounter++;
228           findMarket.setEnabled(false);
229           resultSummary.setText("");
230           arbitrageResult.setText("");
231           new Thread("MarketUploader-uploader-"+uploadcounter) {
232             public void run() {
233               startTime = new Date().getTime();
234               unknownPCTBcommods = 0;
235               try {
236                 runUpload(uploadcounter);
237               } catch(Exception e) {
238                 error(e.toString());
239                 e.printStackTrace();
240               }
241               try {
242                 new UIX() { public void body() { 
243                   if(sidePanel != null) {
244                     sidePanel.removePropertyChangeListener(changeListener);
245                   }
246                   if (progmon != null) {
247                     progmon.close();
248                     progmon = null;
249                   }
250                   findMarket.setEnabled(true);
251                 }}.exec("tidying");
252               } catch (Exception e) {
253                 System.err.println("exception tidying on UI thread:");
254                 e.printStackTrace();
255               }
256             }
257           }.start();
258         }
259       });
260     frame.add(findMarket);
261
262     resultSummary = new JLabel("ready");
263     frame.add(resultSummary);
264                 
265     arbitrageResult = new JLabel("");
266
267     if (showArbitrage) {
268       layout.setRows(layout.getRows() + 1);
269       frame.add(arbitrageResult);
270     }
271
272     frame.pack();
273   }
274
275   /*
276    * THREAD HANDLING
277    *
278    * Special measures are needed because:
279    *  - it is not permitted to use any Swing UI classes or objects
280    *    other than on the Swing event thread
281    *  - we want to run our upload asynchronously
282    *  - we want to do some computation asynchronously (eg, the
283    *    arbitrage and upload data prep)
284    *
285    * So what we do is this:
286    *  1. When the user asks to upload, we spawn a new thread
287    *     to do the upload ("MarketUploader-uploader-*", see
288    *     the call to "new Thread" inside createGUI.
289    *  2. Whenever that thread needs to touch a UI object it
290    *     uses EventQueue.invokeLater or .invokeAndWait to
291    *     perform the relevant action.  We wrap these calls up
292    *     in three utility classes:
293    *        UIA  - runs code on UI thread, asynchronously
294    *        UIX  - runs code on UI thread, waits for it to finish
295    *        UIXR - as UIX but also returns a value
296    *     These hide the details of the EventQueue class and also do
297    *     some debugging and argument shuffling; the calling syntax is
298    *     still painful, unfortunately, and there is a weird constraint
299    *     on variables used inside the inner body.  For a simple
300    *     example, see the handling of "summary" and "summary_final"
301    *     for the call to UIX at the bottom of runUpload.
302    *  3. Try to put everything back when that thread exits.
303    *
304    * Additionally:
305    *  a. There is another thread spawed early to get a timestamp from
306    *     YARRG, if we are uploading there.
307    *  b. Finding the island name can involve callbacks which run in
308    *     the UI event thread.  Basically we do the work there, and use
309    *     a CountDownLatch to cause the uploader thread to wait as
310    *     appropriate.
311    */
312
313   private void on_ui_thread() { assert(EventQueue.isDispatchThread()); }
314   private void on_our_thread() { assert(!EventQueue.isDispatchThread()); }
315
316   private abstract class UIA implements Runnable {
317     private String what;
318     public abstract void body();
319     public void run() {
320       debuglog("UIA 2 "+what+" begin");
321       body();
322       debuglog("UIA 3 "+what+" done");
323     }
324     public void exec(String what_in) {
325       what = what_in;
326       debuglog("UIA 1 "+what+" request");
327       EventQueue.invokeLater(this);
328     }
329   };
330   private abstract class UIXR<ReturnType> implements Runnable {
331     public abstract ReturnType bodyr();
332     public ReturnType return_value;
333     private String what;
334     public void run() { 
335       debuglog("UIX 2 "+what+" begin");
336       return_value = bodyr();
337       debuglog("UIX 3 "+what+" done");
338     }
339     public ReturnType exec(String what_in) throws Exception {
340       what = what_in;
341       if (EventQueue.isDispatchThread()) {
342         debuglog("UIX 1 "+what+" (event thread) entry");
343         this.run();
344         debuglog("UIX 4 "+what+" (event thread) exit");
345       } else {
346         debuglog("UIX 1 "+what+" (other thread) entry");
347         EventQueue.invokeAndWait(this);
348         debuglog("UIX 4 "+what+" (other thread) exit");
349       }
350       return return_value;
351     }
352   };
353   private abstract class UIX extends UIXR<Object> implements Runnable {
354     public abstract void body();
355     public Object bodyr() { body(); return null; }
356   };
357
358   /*
359    * ERROR REPORTING AND GENERAL UTILITIES
360    *
361    * Synchronous modal dialogues
362    * error and error_html may be called from any thread
363    */ 
364
365   public void error(final String msg) {
366     try {
367       new UIX() { public void body() {
368         resultSummary.setText("failed");
369         JOptionPane.showMessageDialog(frame,msg,"Error",
370                                       JOptionPane.ERROR_MESSAGE);
371       }}.exec("error()");
372     } catch (Exception e) {
373       System.err.println("exception reporting to UI thread:");
374       e.printStackTrace();
375     }
376   }
377         
378   public void error_html(final String msg, String html) {
379     Pattern body = Pattern.compile("<body>(.*)</body>",
380                                    Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
381     Matcher m = body.matcher(html);
382     if (m.find()) {
383       html = m.group(1);
384       Pattern fixup = Pattern.compile("<(\\w+) */>");;
385       m = fixup.matcher(html);
386       html = m.replaceAll("<$1>");
387       m = Pattern.compile("[\\r\\n]+").matcher(html);
388       html = m.replaceAll(" ");
389     }
390     String whole_msg = "<html><h1>Error</h1>"+msg
391       +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
392     debuglog("###" + whole_msg + "###");
393   
394     error(whole_msg);
395   }
396
397   public void progressNote(final String s_in) throws Exception {
398     new UIA() { public void body() {
399       String arb = null;
400       arb = arbitrageResult.getText();
401       String s = s_in;
402       if (arb != null && arb.length() != 0)
403         s = "<html>" + arb + "<br>" + s;
404       progmon.setNote(s);
405     }}.exec("progressNote "+s_in);
406   }
407   public void setProgress(final int nv) throws Exception {
408     new UIA() { public void body() {
409       progmon.setProgress(nv);
410     }}.exec("setProgress "+nv);
411   }
412   public boolean checkCancelled() throws Exception {
413     return new UIXR<Boolean>() { public Boolean bodyr() {
414       boolean can = progmon.isCanceled();
415       if (can) resultSummary.setText("cancelled");
416       return new Boolean(can);
417     }}.exec("checkCancelled").booleanValue();
418   }
419
420
421   /*
422    * ACTUAL DATA COLLECTION AND UPLOAD
423    */
424
425   private void runUpload(int counter) throws Exception {
426     // Runs the data collection process, and upload the results.
427     // In most cases of error, we call error() (which synchronously
428     // reports the error) and then simply return.
429
430     on_our_thread();
431
432     boolean doneyarrg = false, donepctb = false;
433     YarrgTimestampFetcher yarrgts_thread = null;
434
435     debuglog("starting");
436
437     if (uploadToYarrg) {
438       debuglog("(async) yarrg timestamp...");
439       yarrgts_thread = new YarrgTimestampFetcher(counter);
440       yarrgts_thread.start();
441     }
442
443     final AccessibleTable accesstable = 
444     new UIXR<AccessibleTable>() { public AccessibleTable bodyr() {
445       progmon = new ProgressMonitor
446         (frame,"Processing Market Data","Getting table data",0,100);
447       progmon.setMillisToDecideToPopup(0);
448       progmon.setMillisToPopup(0);
449
450       AccessibleTable at = findMarketTable();
451       if(at == null) {
452         error("Market table not found!"+
453               " Please open the Buy/Sell Commodities interface.");
454         return null;
455       }
456       if(at.getAccessibleRowCount() == 0) {
457         error("No data found, please wait for the table to have data first!");
458         return null;
459       }
460       if(!isDisplayAll()) {
461         error("Please select \"All\" from the Display: popup menu.");
462         return null;
463       }
464
465       debuglog("(async) getisland...");
466       getIsland();
467       debuglog("getocean...");
468       getOcean();
469       debuglog("getocean done");
470
471       return at;
472     }}.exec("accesstable");
473     if (accesstable == null) return;
474
475     if (latch != null) {
476       latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
477     }
478     debuglog("(async) getisland done");
479
480     String yarrgts = null;
481     if (yarrgts_thread != null) {
482       debuglog("(async) yarrg timestamp join...");
483       yarrgts_thread.join();
484       debuglog("(async) yarrg timestamp joined.");
485       yarrgts = yarrgts_thread.ts;
486     }
487
488     if (islandName == null) {
489       error("Could not find island name in YPP user interface.");
490       return;
491     }
492
493     debuglog("table check...");
494
495     final ArrayList<ArrayList<String>> data =
496     new UIXR<ArrayList<ArrayList<String>>>
497           () { public ArrayList<ArrayList<String>> bodyr() {
498       String headings_expected[] = new String[]
499         { "Commodity", "Trading outlet", "Buy price",
500           "Will buy", "Sell price", "Will sell" };
501
502       ArrayList<ArrayList<String>> headers =
503         getData(accesstable.getAccessibleColumnHeader());
504       if (headers.size() != 1) {
505         error("Table headings not one row! " + headers.toString());
506         return null;
507       }
508       if (headers.get(0).size() < 6 ||
509           headers.get(0).size() > 7) {
510         error("Table headings not six or seven columns! " + headers.toString());
511         return null;
512       }
513       for (int col=0; col<headings_expected.length; col++) {
514         String expd = headings_expected[col];
515         String got = headers.get(0).get(col);
516         if (expd.compareTo(got) != 0) {
517           error("Table heading for column "+col
518                 +" is not \""+expd+"\" but \""+got+"\".\n\n"
519                 +"Please do not reorder the table when using this tool.");
520           return null;
521         }
522       }
523
524       debuglog("table read...");
525
526       return getData(accesstable);
527     }}.exec("data");
528     if (data == null) return;
529
530     if (showArbitrage) {
531       debuglog("arbitrage...");
532       calculateArbitrage(data);
533       debuglog("arbitrage done.");
534     }
535
536     if (uploadToYarrg && yarrgts != null) {
537       debuglog("yarrg prepare...");
538       progressNote("Yarrg: Preparing data");
539       setProgress(10);
540
541       StringBuilder yarrgsb = new StringBuilder();
542       String yarrgdata; // string containing what we'll feed to yarrg
543                 
544       for (ArrayList<String> row : data) {
545         if (row.size() > 6) {
546           row.remove(6);
547         }
548         for (String rowitem : row) {
549           yarrgsb.append(rowitem != null ? rowitem : "");
550           yarrgsb.append("\t");
551         }
552         yarrgsb.setLength(yarrgsb.length()-1); // chop
553         yarrgsb.append("\n");
554       }
555
556       yarrgdata = yarrgsb.toString();
557
558       progressNote("Yarrg: Uploading");
559       debuglog("yarrg upload...");
560
561       doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
562       debuglog("yarrg done.");
563     }
564
565     if (uploadToPCTB) {
566       debuglog("pctb prepare...");
567       progressNote("PCTB: Getting stall names");
568       setProgress(20);
569       if(checkCancelled()) {
570         return;
571       }
572       TreeSet<Offer> buys = new TreeSet<Offer>();
573       TreeSet<Offer> sells = new TreeSet<Offer>();
574       LinkedHashMap<String,Integer> stallMap = getStallMap(data);
575       setProgress(40);
576       progressNote("PCTB: Sorting offers");
577       if(checkCancelled()) {
578         return;
579       }
580       // get commod map
581                 
582       debuglog("pctb commodmap...");
583       HashMap<String,Integer> commodMap = getCommodMap();
584       if(commodMap == null) {
585         return;
586       }
587       debuglog("pctb commodmap done.");
588       int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
589       // debuglog(sells);
590       // debuglog("\n\n\n"+buys);
591
592       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
593       setProgress(60);
594       progressNote("PCTB: Sending data");
595       if(checkCancelled()) {
596         return;
597       }
598       GZIPOutputStream out = new GZIPOutputStream(outStream);
599       DataOutputStream dos = new DataOutputStream(out);
600       dos.writeBytes("005y\n");
601       dos.writeBytes(stallMap.size()+"\n");
602       dos.writeBytes(getAbbrevStallList(stallMap));
603       writeBuySellOffers(buys,sells,offerCount,out);
604       out.finish();
605       debuglog("pctb send...");
606
607       byte[] ba = outStream.toByteArray();
608       debug_write_bytes("pctb-marketdata.gz", ba);
609
610       InputStream in = sendInitialData(new ByteArrayInputStream(ba));
611       debuglog("pctb sent.");
612       if (in == null) return;
613       setProgress(80);
614       if(checkCancelled()) {
615         return;
616       }
617       progressNote("PCTB: Waiting ...");
618       debuglog("pctb finish...");
619       donepctb = finishUpload(in);
620       debuglog("pctb done.");
621     }
622     setProgress(99);
623
624     String summary;
625     if ((uploadToPCTB && !donepctb) ||
626         (uploadToYarrg && !doneyarrg)) {
627       summary= "trouble";
628     } else if (unknownPCTBcommods != 0) {
629       summary= "PCTB lacks "+unknownPCTBcommods+" commod(s)";
630     } else if (donepctb || doneyarrg) {
631       summary= "Done " + islandName;
632     } else {
633       summary= "uploaded nowhere!";
634     }
635     final String summary_final = summary;
636     new UIX() { public void body() {
637       resultSummary.setText(summary_final);
638     }}.exec("resultSummary.setText");
639
640     debuglog("done.");
641   }
642
643   /*
644    * UPLOAD HELPER FUNCTIONS FOR EXTRACTING SPECIFIC UI DATA
645    */
646         
647   private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
648     // Gets the offer data out of the table and returns it as an ArrayList
649
650     on_ui_thread();
651     ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
652     for (int i = 0; i < table.getAccessibleRowCount(); i++) {
653       ArrayList<String> row = new ArrayList<String>();
654       for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
655         row.add(table.getAccessibleAt(i, j)
656                 .getAccessibleContext().getAccessibleName());
657       }
658       data.add(row);
659     }
660     return data;
661   }
662         
663   public AccessibleTable findMarketTable() {
664     // Return the table containing market data if it exists, otherwise null.
665     on_ui_thread();
666
667     Accessible node1 = window;
668     Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); 
669       // commod market
670     // commod market: {0,1,0,0,0,0,1,0,0,1,0}  {0,1,0,0,0,0,1,0,1,0,0,1,0,0})
671     // debuglog(node);
672     if (!(node instanceof JTable)) {
673       node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
674         // commod market
675     }
676     if (!(node instanceof JTable)) return null;
677     AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
678     // debuglog(table);
679     return table;
680   }
681         
682   private boolean isDisplayAll() {
683     // Returns true iff the "Display:" menu on the commodities
684     // interface in YPP is set to "All"
685     on_ui_thread();
686
687     Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
688     if(!(button instanceof JButton)) {
689       button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
690     }
691     String display = button.getAccessibleContext().getAccessibleName();
692     if(!display.equals("All")) {
693       return false;
694     }
695     return true;
696   }
697         
698   /*
699    * FUNCTIONS AND CALLBACKS FOR FINDING ISLAND AND OCEAN
700    */
701
702   private void getOcean() {
703     // Finds the ocean name from the window title.
704     // Stores it in the global oceanName
705     on_ui_thread();
706
707     oceanName = null;
708     AccessibleContext topwindow = window.getAccessibleContext();
709     oceanName = topwindow.getAccessibleName()
710       .replaceAll(".*on the (\\w+) ocean", "$1");
711   }
712
713   private void getIsland() {
714     // Tries to find the island name.  Either:
715     //  (a) sets the islandName global
716     // or
717     //  (b) sets latch to a new CountDownLatch, and arranges that 
718     //      at some point later, islandName will be set and the latch
719     //      decremented to zero
720     on_ui_thread();
721
722     // If the league tracker is there, we can skip the faff
723     // and ask for its tooltip, since we're on a boat
724
725     Accessible leagueTrackerContainer =
726       descendNodes(window,new int[] {0,1,0,0,2,1});
727     Accessible leagueTrackerItself =
728       descendByClass(leagueTrackerContainer,
729                      "com.threerings.yohoho.sea.client.LeagueTracker");
730     Accessible leagueTracker = descend(leagueTrackerItself, 1);
731     try {
732       islandName = ((JLabel)leagueTracker).getToolTipText();
733       latch = null;
734     } catch (NullPointerException e) {
735       // evidently we're actually on an island
736
737       islandName = null;
738       AccessibleContext chatArea =
739         descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
740         .getAccessibleContext();
741       // attach the property change listener to the outer sunshine
742       // panel if the "ahoy" tab is not active, otherwise attach it to
743       // the scroll panel in the "ahoy" tab.
744       if(!"com.threerings.piracy.client.AttentionListPanel".
745          equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
746                 .getClass().getCanonicalName())) {
747         sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
748           .getAccessibleContext();
749       } else {
750         sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
751           .getAccessibleContext();
752       }
753       sidePanel.addPropertyChangeListener(changeListener);
754       latch = new java.util.concurrent.CountDownLatch(1);
755       // make the Players Online ("/who") panel appear
756       AccessibleEditableText chat = chatArea.getAccessibleEditableText();
757       chat.setTextContents("/w");
758       int c = chatArea.getAccessibleAction().getAccessibleActionCount();
759       for(int i=0;i<c;i++) {
760         if("notify-field-accept".equals(chatArea.getAccessibleAction()
761                                         .getAccessibleActionDescription(i))) {
762           chatArea.getAccessibleAction().doAccessibleAction(i);
763         }
764       }
765     }
766   }
767
768   private PropertyChangeListener changeListener = new PropertyChangeListener() {
769     // used by getIsland
770     public void propertyChange(PropertyChangeEvent e) {
771       on_ui_thread();
772       if(e.getNewValue() != null && 
773          e.getPropertyName().equals
774          (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
775         Accessible islandInfo =
776           descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
777         String text = islandInfo.getAccessibleContext().getAccessibleText()
778           .getAtIndex(AccessibleText.SENTENCE,0);
779         int index = text.indexOf(":");
780         String name = text.substring(0,index);
781         islandName = name;
782         // debuglog(islandName);
783         sidePanel.removePropertyChangeListener(this);
784         latch.countDown();
785       }
786     }
787   };
788
789   /*
790    * UTILITY FUNCTIONS FOR WALKING THE UI
791    *
792    * These functions all return null if the specified path or child
793    * was not found.
794    */
795
796   private Accessible descendNodes(Accessible parent, int[] path) {
797     // Descends through several levels of Accessible children in one call.
798     // path[] is an array of ints, each int being the index into the array
799     // of children at a particular point, and thus selects the specific
800     // accessible child to descend to.
801     on_ui_thread();
802
803     for(int i=0;i<path.length;i++) {
804       if (null == (parent = descend(parent, path[i]))) return null;
805     }
806     return parent;
807   }
808
809   private Accessible descend(Accessible parent, int childNum) {
810     // Descends one level to the specified child of the parent
811     // childNum is the index of the child within parent
812     on_ui_thread();
813
814     if (parent == null) return null;
815     int children = parent.getAccessibleContext().getAccessibleChildrenCount();
816     if (childNum >= children) {
817       debuglog("DESCEND "+childNum+" > "+children+" NOT FOUND");
818       return null;
819     }
820     Accessible child = parent.getAccessibleContext()
821       .getAccessibleChild(childNum);
822     debuglog("DESCEND "+childNum+" "+child.getClass().getName()+" OK");
823     return child;
824   }
825
826   private Accessible descendByClass(Accessible parent, String classname) {
827     // Descends one level to the first child which has the specified class.
828     on_ui_thread();
829
830     if (parent == null) return null;
831     AccessibleContext ac = parent.getAccessibleContext();
832     int children = ac.getAccessibleChildrenCount();
833     for (int i=0; i<children; i++) {
834       Accessible child = ac.getAccessibleChild(i);
835       if (child.getClass().getName() == classname) {
836         debuglog("DESCEND CLASS "+classname+" OK");
837         return child;
838       }
839     }
840     debuglog("DESCEND CLASS "+classname+" NOT FOUND");
841     return null;
842   }
843   
844
845   /*****************************************
846    * PCTB-SPECIFIC HELPER FUNCTIONS ETC.   *
847    *****************************************/
848
849   /**
850    *    An abstract market offer, entailing a commodity being bought or sold by
851    *    a shoppe, for a certain price in a certain quantity. Not instantiable.
852    *
853    *    @see Buy
854    *    @see Sell
855    */
856   abstract class Offer {
857     public int commodity, price, quantity, shoppe;
858     /**
859      *  Create an offer from <code>record</code>, determining the shoppe Id from
860      *  <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
861      *  <code>priceIndex</code> should be the index of the price in the record
862      *  (the quantity will be <code>priceIndex + 1</code>).
863      *
864      *  @param record the record with data to create the offer from
865      *  @param stallMap a map containing the ids of the various stalls
866      *  @param commodMap a map containing the ids of the various commodities
867      *  @param priceIndex the index of the price in the record
868      */
869     public Offer(ArrayList<String> record, 
870                  LinkedHashMap<String,Integer> stallMap, 
871                  HashMap<String,Integer> commodMap,
872                  int priceIndex) {
873       Integer commodId = commodMap.get(record.get(0));
874       if(commodId == null) {
875         throw new IllegalArgumentException();
876       }
877       commodity = commodId.intValue();
878       price = Integer.parseInt(record.get(priceIndex));
879       String qty = record.get(priceIndex+1);
880       quantity = parseQty(qty);
881       shoppe = stallMap.get(record.get(1)).intValue();
882     }
883                 
884     /**
885      *  Returns a human-readable version of this offer, useful for debugging
886      *  
887      *  @return human-readable offer
888      */
889     public String toString() {
890       return "[C:" + commodity + ",$" + price + ",Q:"
891         + quantity + ",S:" + shoppe + "]";
892     }
893   }
894         
895   /**
896    *    An offer from a shoppe or stall to buy a certain quantity of a
897    *    commodity for a certain price. If placed in an ordered Set,
898    *    sorts by commodity index ascending, then by buy price
899    *    descending, and finally by stall id ascending.
900    */
901   class Buy extends Offer implements Comparable<Buy> {
902     /**
903      *  Creates a new <code>Buy</code> offer from the given
904      *  <code>record</code> using the other parameters to determine
905      *  stall id and commodity id of the offer.
906      *
907      *  @param record the record with data to create the offer from
908      *  @param stallMap a map containing the ids of the various stalls
909      *  @param commodMap a map containing the ids of the various commodities
910      */
911     public Buy(ArrayList<String> record,
912                LinkedHashMap<String,Integer> stallMap,
913                HashMap<String,Integer> commodMap) {
914       super(record,stallMap,commodMap,2);
915     }
916                 
917     /**
918      *  Sorts by commodity index ascending, then price descending,
919      *  then stall id ascending.
920      */
921     public int compareTo(Buy buy) {
922       // organize by: commodity index, price, stall index
923       if(commodity == buy.commodity) {
924         // organize by price, then by stall index
925         if(price == buy.price) {
926           // organize by stall index
927           return shoppe>buy.shoppe ? 1 : -1;
928         } else if(price > buy.price) {
929           return -1;
930         } else {
931           return 1;
932         }
933       } else if(commodity > buy.commodity) {
934         return 1;
935       } else {
936         return -1;
937       }
938     }
939   }
940         
941   /**
942    *    An offer from a shoppe or stall to sell a certain quantity of
943    *    a commodity for a certain price. If placed in an ordered Set,
944    *    sorts by commodity index ascending, then by sell price
945    *    ascending, and finally by stall id ascending.
946    */
947   class Sell extends Offer implements Comparable<Sell> {
948     /**
949      *  Creates a new <code>Sell</code> offer from the given
950      *  <code>record</code> using the other parameters to determine
951      *  stall id and commodity id of the offer.
952      *
953      *  @param record the record with data to create the offer from
954      *  @param stallMap a map containing the ids of the various stalls
955      *  @param commodMap a map containing the ids of the various commodities
956      */
957     public Sell(ArrayList<String> record,
958                 LinkedHashMap<String,Integer> stallMap,
959                 HashMap<String,Integer> commodMap) {
960       super(record,stallMap,commodMap,4);
961     }
962                 
963     /**
964      *  Sorts by commodity index ascending, then price ascending, then
965      *  stall id ascending.
966      */
967     public int compareTo(Sell sell) {
968       // organize by: commodity index, price, stall index
969       if(commodity == sell.commodity) {
970         // organize by price, then by stall index
971         if(price == sell.price) {
972           // organize by stall index
973           return shoppe>sell.shoppe ? 1 : -1;
974         } else if(price > sell.price) {
975           return 1;
976         } else {
977           return -1;
978         }
979       } else if(commodity > sell.commodity) {
980         return 1;
981       } else {
982         return -1;
983       }
984     }
985   }
986
987   /**
988    *    Gets the list of commodities and their associated commodity ids.
989    *
990    *    @return a map where the key is the commodity and the value is
991    *    the commodity id.
992    */
993   private HashMap<String,Integer> getCommodMap() {
994     on_our_thread();
995     if(commodMap != null) {
996       return commodMap;
997     }
998     HashMap<String,Integer> map = new HashMap<String,Integer>();
999     String xml;
1000     try {
1001       URL host = new URL(PCTB_HOST_URL + "commodmap.php");
1002       BufferedReader br =
1003         new BufferedReader(new InputStreamReader(host.openStream()));
1004       StringBuilder sb = new StringBuilder();
1005       String str;
1006       while((str = br.readLine()) != null) {
1007         sb.append(str);
1008       }
1009       if (dtxt != null)
1010         debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
1011       int first = sb.indexOf("<pre>") + 5;
1012       int last = sb.indexOf("</body>");
1013       xml = sb.substring(first,last);
1014       Reader reader = new CharArrayReader(xml.toCharArray());
1015       Document d = DocumentBuilderFactory.newInstance()
1016         .newDocumentBuilder().parse(new InputSource(reader));
1017       NodeList maps = d.getElementsByTagName("CommodMap");
1018       for(int i=0;i<maps.getLength();i++) {
1019         NodeList content = maps.item(i).getChildNodes();
1020         Integer num = Integer.parseInt(content.item(1).getTextContent());
1021         map.put(content.item(0).getTextContent(),num);
1022       }
1023     } catch(Exception e) {
1024       e.printStackTrace();
1025       error("Unable to load Commodity list from server!");
1026       return null;
1027     }
1028     commodMap = map;
1029     return map;
1030   }
1031         
1032   /**
1033    *    Given the list of offers, this method will find all the unique
1034    *    stall names and return them in a <code>LinkedHashMap</code>
1035    *    where the key is the stall name and the value is the generated
1036    *    stall id (position in the list).  <p> The reason this method
1037    *    returns a LinkedHashMap instead of a simple HashMap is the
1038    *    need for iterating over the stall names in insertion order for
1039    *    output to the server.
1040    *
1041    *    @param offers the list of records from the commodity buy/sell interface
1042    *    @return an iterable ordered map of the stall names and
1043    *    generated stall ids
1044    */
1045   private LinkedHashMap<String,Integer> getStallMap
1046     (ArrayList<ArrayList<String>> offers) {
1047     int count = 0;
1048     LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
1049     for(ArrayList<String> offer : offers) {
1050       String shop = offer.get(1);
1051       if(!map.containsKey(shop)) {
1052         count++;
1053         map.put(shop,count);
1054       }
1055     }
1056     return map;
1057   }
1058         
1059   /**
1060    *    Gets a sorted list of Buys and Sells from the list of
1061    *    records. <code>buys</code> and <code>sells</code> should be
1062    *    pre-initialized and passed into the method to receive the
1063    *    data.  Returns a 2-length int array with the number of buys
1064    *    and sells found.
1065    *    
1066    *    @param offers the data found from the market table in-game
1067    *    @param buys an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
1068    *    hold the Buy offers.
1069    *    @param sells an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
1070    *    hold the Sell offers.
1071    *    @param stalls the map of stalls to their ids
1072    *    @param commodMap the map of commodities to their ids
1073    *    @return a 2-length int[] array containing the number of buys
1074    *    and sells, respectively
1075    */
1076   private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, 
1077                                TreeSet<Offer> buys, 
1078                                TreeSet<Offer> sells, 
1079                                LinkedHashMap<String,Integer> stalls, 
1080                                HashMap<String,Integer> commodMap) {
1081     int[] buySellCount = new int[2];
1082     for(ArrayList<String> offer : offers) {
1083       try {
1084         if(offer.get(2) != null) {
1085           buys.add(new Buy(offer,stalls,commodMap));
1086           buySellCount[0]++;
1087         }
1088         if(offer.get(4) != null) {
1089           sells.add(new Sell(offer,stalls,commodMap));
1090           buySellCount[1]++;
1091         }
1092       } catch(IllegalArgumentException e) {
1093         unknownPCTBcommods++;
1094         debuglog("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
1095       }
1096     }
1097     if (buySellCount[0]==0 && buySellCount[1]==0) {
1098       error("No (valid) offers for PCTB?!");
1099       throw new IllegalArgumentException();
1100     }
1101     return buySellCount;
1102   }
1103         
1104   /**
1105    *    Prepares the list of stalls for writing to the output stream.
1106    *    The <code>String</code> returned by this method is ready to be
1107    *    written directly to the stream.  <p> All shoppe names are left
1108    *    as they are. Stall names are abbreviated just before the
1109    *    apostrophe in the possessive, with an "^" and a letter
1110    *    matching the stall's type appended. Example: "Burninator's
1111    *    Ironworking Stall" would become "Burninator^I".
1112    *
1113    *    @param stallMap the map of stalls and stall ids in an iterable order
1114    *    @return a <code>String</code> containing the list of stalls in
1115    *    format ready to be written to the output stream.
1116    */
1117   private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1118     // set up some mapping
1119     HashMap<String,String> types = new HashMap<String,String>();
1120     types.put("Apothecary Stall", "A");
1121     types.put("Distilling Stall", "D");
1122     types.put("Furnishing Stall", "F");
1123     types.put("Ironworking Stall", "I");
1124     types.put("Shipbuilding Stall", "S");
1125     types.put("Tailoring Stall", "T");
1126     types.put("Weaving Stall", "W");
1127                 
1128     StringBuilder sb = new StringBuilder();
1129     for(String name : stallMap.keySet()) {
1130       int index = name.indexOf("'s");
1131       String finalName = name;
1132       String type = null;
1133       if (index > 0) {
1134         finalName = name.substring(0,index);
1135         if(index + 2 < name.length()) {
1136           String end = name.substring(index+2,name.length()).trim();
1137           type = types.get(end);
1138         }
1139       }
1140       if(type==null) {
1141         sb.append(name+"\n");
1142       } else {
1143         sb.append(finalName+"^"+type+"\n");
1144       }
1145     }
1146     return sb.toString();
1147   }
1148         
1149   /**
1150    *    Writes a list of offers in correct format to the output stream.
1151    *    <p>
1152    *    The format is thus: (all numbers are 2-byte integers in
1153    *    little-endian format) (number of offers of this type, aka
1154    *    buy/sell) (commodity ID) (number of offers for this commodity)
1155    *    [shopID price qty][shopID price qty]...
1156    *
1157    *    @param out the output stream to write the data to
1158    *    @param offers the offers to write
1159    */
1160   private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1161   throws IOException {
1162     ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1163     if(offers.size() == 0) {
1164       // nothing to write, and "0" has already been written
1165       return;
1166     }
1167     int commodity = offers.first().commodity;
1168     int count = 0;
1169     for(Offer offer : offers) {
1170       if(commodity != offer.commodity) {
1171         // write out buffer
1172         writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1173         buffer.reset();
1174         commodity = offer.commodity;
1175         count = 0;
1176       }
1177       writeLEShort(offer.shoppe,buffer); // stall index
1178       writeLEShort(offer.price,buffer); // buy price
1179       writeLEShort(offer.quantity,buffer); // buy qty
1180       count++;
1181     }
1182     writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1183   }
1184         
1185   /**
1186    *    Writes the buffered data to the output strea for one commodity.
1187    *    
1188    *    @param out the stream to write to
1189    *    @param buffer the buffered data to write
1190    *    @param commodity the commmodity id to write before the buffered data
1191    *    @param count the number of offers for this commodity to write
1192    *    before the data
1193    */
1194   private void writeBufferedOffers(OutputStream out, byte[] buffer, 
1195                                    int commodity, int count)
1196   throws IOException {
1197     writeLEShort(commodity,out); // commod index
1198     writeLEShort(count,out); // offer count
1199     out.write(buffer); // the buffered offers
1200   }
1201         
1202   /**
1203    *    Writes the buy and sell offers to the outputstream by calling
1204    *    other methods.
1205    *    
1206    *    @param buys list of Buy offers to write
1207    *    @param sells list of Sell offers to write
1208    *    @param offerCount 2-length int array containing the number of
1209    *    buys and sells to write out
1210    *    @param out the stream to write to
1211    */
1212   private void writeBuySellOffers(TreeSet<Offer> buys,
1213                                   TreeSet<Offer> sells,
1214                                   int[] offerCount, OutputStream out) 
1215   throws IOException {
1216     // # buy offers
1217     writeLEShort(offerCount[0],out);
1218     writeOffers(out,buys);
1219     // # sell offers
1220     writeLEShort(offerCount[1],out);
1221     writeOffers(out,sells);
1222   }
1223         
1224   private String readstreamstring(InputStream in) throws IOException {
1225     StringBuilder sb = new StringBuilder();
1226     BufferedReader br = new BufferedReader(new InputStreamReader(in));
1227     String str;
1228     while((str = br.readLine()) != null) {
1229       sb.append(str+"\n");
1230     }
1231     return sb.toString();
1232   }
1233
1234   /**
1235    *    Sends the data to the server via multipart-formdata POST,
1236    *    with the gzipped data as a file upload.
1237    *
1238    *    @param file an InputStream open to the gzipped data we want to send
1239    */
1240   private InputStream sendInitialData(InputStream file) throws IOException {
1241     on_our_thread();
1242     ClientHttpRequest http =
1243       new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1244     http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1245     if (!http.post()) {
1246       String err = readstreamstring(http.resultstream());
1247       error("Error sending initial data:\n"+err);
1248       return null;
1249     }
1250     return http.resultstream();
1251   }
1252         
1253   /**
1254    *    Utility method to write a 2-byte int in little-endian form to
1255    *    an output stream.
1256    *
1257    *    @param num an integer to write
1258    *    @param out stream to write to
1259    */
1260   private void writeLEShort(int num, OutputStream out) throws IOException {
1261     out.write(num & 0xFF);
1262     out.write((num >>> 8) & 0xFF);
1263   }
1264         
1265   /**
1266    *    Reads the response from the server, and selects the correct parameters
1267    *    which are sent in a GET request to the server asking it to confirm
1268    *    the upload and accept the data into the database. Notably, the island id
1269    *    and ocean id are determined, while other parameter such as the filename
1270    *    are determined from the hidden form fields.
1271    *
1272    *    @param in stream of data from the server to read
1273    */
1274   private boolean finishUpload(InputStream in) throws IOException {
1275     on_our_thread();
1276
1277     String html = readstreamstring(in);
1278     debug_write_stringdata("pctb-initial.html", html);
1279     Matcher m;
1280
1281     Pattern params = Pattern.compile
1282       ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1283        ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1284        ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1285     m = params.matcher(html);
1286     if(!m.find()) {
1287       error_html("The PCTB server returned unusual data."+
1288                  " Maybe you're using an old version of the uploader?",
1289                  html);
1290       return false;
1291     }
1292     String forceReload = m.group(1);
1293     String filename = m.group(2);
1294     
1295     Pattern oceanNumPat =
1296       Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1297     m = oceanNumPat.matcher(html);
1298     if (!m.find()) {
1299       error_html("Unable to find the ocean in the server's list of oceans!",
1300                  html);
1301       return false;
1302     }
1303     String oceanNum = m.group(1);
1304
1305     Pattern oceanIslandNum =
1306       Pattern.compile("islands\\[" + oceanNum
1307                       + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1308                       + "\",(\\d+)");
1309     m = oceanIslandNum.matcher(html);
1310     if(!m.find()) {
1311       error_html("This does not seem to be a valid island! Unable to upload.",
1312                  html);
1313       return false;
1314     }
1315     String islandNum = m.group(1);
1316
1317     URL get = new URL(PCTB_HOST_URL +
1318                       "upload.php?action=setisland&ocean=" + oceanNum
1319                       + "&island=" + islandNum
1320                       + "&forcereload=" + forceReload
1321                       + "&filename=" + filename);
1322     String complete = readstreamstring(get.openStream());
1323     debug_write_stringdata("pctb-final.html", complete);
1324     Pattern done = Pattern.compile
1325       ("Your data has been integrated into the database. Thank you!");
1326     m = done.matcher(complete);
1327     if(m.find()) {
1328       return true;
1329     } else {
1330       error_html("Something was wrong with the final upload parameters!",
1331                  complete);
1332       return false;
1333     }
1334   }
1335
1336
1337   /*****************************************
1338    * YARRG-SPECIFIC HELPER FUNCTIONS ETC.  *
1339    *****************************************/
1340
1341   private InputStream post_for_yarrg(ClientHttpRequest http)
1342   throws IOException {
1343     on_our_thread();
1344     if (!http.post()) {
1345       String err = readstreamstring(http.resultstream());
1346       error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1347       return null;
1348     }
1349     return http.resultstream();
1350   }
1351
1352   private class YarrgTimestampFetcher extends Thread {
1353     public YarrgTimestampFetcher(int counter) {
1354       super("MarketUploader-YarrgTimestampFetcher-"+uploadcounter);
1355     }
1356     public String ts = null;
1357     public void run() {
1358       try {
1359         ts = getYarrgTimestamp();
1360         debuglog("(async) yarrg timestamp ready.");
1361       } catch(Exception e) {
1362         error("Error getting YARRG timestamp: "+e);
1363       }
1364     }
1365   };
1366
1367   private String getYarrgTimestamp() throws IOException {
1368     ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1369     http.setParameter("clientname", YARRG_CLIENTNAME);
1370     http.setParameter("clientversion", YARRG_CLIENTVERSION);
1371     http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1372     http.setParameter("requesttimestamp", "y");
1373     InputStream in = post_for_yarrg(http);
1374     if (in == null) return null;
1375     BufferedReader br = new BufferedReader(new InputStreamReader(in));
1376     String tsresult = br.readLine();
1377     return tsresult.substring(3, tsresult.length()-1);
1378   }
1379
1380   private boolean runYarrg(String timestamp, String ocean, String island,
1381                            String yarrgdata) throws IOException {
1382     ByteArrayOutputStream bos = new ByteArrayOutputStream();
1383     BufferedOutputStream bufos =
1384       new BufferedOutputStream(new GZIPOutputStream(bos));
1385     bufos.write(yarrgdata.getBytes() );
1386     bufos.close();
1387     byte[] compressed = bos.toByteArray();
1388     debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1389     ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1390
1391     ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1392     http.setParameter("clientname", YARRG_CLIENTNAME);
1393     http.setParameter("clientversion", YARRG_CLIENTVERSION);
1394     http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1395     http.setParameter("timestamp", timestamp);
1396     http.setParameter("ocean", ocean);
1397     http.setParameter("island", island);
1398     http.setParameter("data", "deduped.tsv.gz", file,
1399                       "application/octet-stream");
1400     InputStream in = post_for_yarrg(http);
1401     if (in == null) return false;
1402     String output = readstreamstring(in);
1403     if (!output.startsWith("OK")) {
1404       error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1405       return false;
1406     }
1407     debug_write_stringdata("yarrg-result.txt", output);
1408     return true;
1409   }
1410
1411   private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1412     // debuglog("ARBITRAGE?");
1413     int profit = 0;
1414     SortedSet<int[]> buys = arb_bs.get(0);
1415     SortedSet<int[]> sells = arb_bs.get(1);
1416     while (true) {
1417       int[] buy, sell;
1418       try {
1419         // NB "sell" means they sell, ie we buy
1420         sell = sells.last();
1421         buy = buys.first();
1422       } catch (NoSuchElementException e) {
1423         break;
1424       }
1425
1426       int unitprofit = buy[0] - sell[0];
1427       int count = buy[1] < sell[1] ? buy[1] : sell[1];
1428       // debuglog(" sell @"+sell[0]+" x"+sell[1]
1429       //          +" buy @"+buy[0]+" x"+buy[1]
1430       //          +" => x"+count+" @"+unitprofit);
1431
1432       if (unitprofit <= 0)
1433         break;
1434             
1435       profit += count * unitprofit;
1436       buy[1] -= count;
1437       sell[1] -= count;
1438       if (buy[1]==0) buys.remove(buy);
1439       if (sell[1]==0) sells.remove(sell);
1440     }
1441     // debuglog(" PROFIT "+profit);
1442     return profit;
1443   }
1444
1445   /*****************************************
1446    * ARBITRAGE                             *
1447    *****************************************/
1448
1449   private class arbitrageOfferComparator implements Comparator {
1450     public int compare(Object o1, Object o2) {
1451       int p1 = ((int[])o1)[0];
1452       int p2 = ((int[])o2)[0];
1453       return p2 - p1;
1454     }
1455   }
1456
1457   private @SuppressWarnings("unchecked")
1458   void calculateArbitrage(ArrayList<ArrayList<String>> data) 
1459   throws InterruptedException {
1460     int arbitrage = 0;
1461     ArrayList<SortedSet<int[]>> arb_bs = null;
1462     String lastcommod = null;
1463     Comparator compar = new arbitrageOfferComparator();
1464
1465     for (ArrayList<String> row : data) {
1466       String thiscommod = row.get(0);
1467       // debuglog("ROW "+row.toString());
1468       if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1469         if (lastcommod != null)
1470           arbitrage += calculateArbitrageCommodity(arb_bs);
1471         // debuglog("ROW rdy");
1472         arb_bs = new ArrayList<SortedSet<int[]>>(2);
1473         arb_bs.add(0, new TreeSet<int[]>(compar));
1474         arb_bs.add(1, new TreeSet<int[]>(compar));
1475         // debuglog("ROW init");
1476         lastcommod = thiscommod;
1477       }
1478       for (int bs = 0; bs < 2; bs++) {
1479         String pricestr = row.get(bs*2 + 2);
1480         if (pricestr == null)
1481           continue;
1482         int[] entry = new int[2];
1483         // debuglog("ROW BS "+bs);
1484         entry[0] = parseQty(pricestr);
1485         entry[1] = parseQty(row.get(bs*2 + 3));
1486         arb_bs.get(bs).add(entry);
1487       }
1488     }
1489     arbitrage += calculateArbitrageCommodity(arb_bs);
1490     String arb;
1491     if (arbitrage != 0) {
1492       arb = "<html><strong>arbitrage: "+arbitrage+" poe</strong>";
1493     } else {
1494       arb = "no arbitrage";
1495     }
1496     final String arb_final = arb;
1497     EventQueue.invokeLater(new Runnable() { public void run() {
1498       arbitrageResult.setText(arb_final);
1499     }});
1500   }
1501     
1502 }