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