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