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