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