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