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