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