chiark / gitweb /
f8437f94d85758511f7f1067076cba4f3c56238f
[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                         if (dtxt != null) debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
741                         int first = sb.indexOf("<pre>") + 5;
742                         int last = sb.indexOf("</body>");
743                         xml = sb.substring(first,last);
744                         Reader reader = new CharArrayReader(xml.toCharArray());
745                         Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
746                         NodeList maps = d.getElementsByTagName("CommodMap");
747                         for(int i=0;i<maps.getLength();i++) {
748                                 NodeList content = maps.item(i).getChildNodes();
749                                 Integer num = Integer.parseInt(content.item(1).getTextContent());
750                                 map.put(content.item(0).getTextContent(),num);
751                         }
752                 } catch(Exception e) {
753                         e.printStackTrace();
754                         error("Unable to load Commodity list from server!");
755                         return null;
756                 }
757                 commodMap = map;
758                 return map;
759         }
760         
761         /**
762         *       Given the list of offers, this method will find all the unique stall names
763         *       and return them in a <code>LinkedHashMap</code> where the key is the stall name
764         *       and the value is the generated stall id (position in the list).
765         *       <p>
766         *       The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
767         *       for iterating over the stall names in insertion order for output to the server.
768         *
769         *       @param offers the list of records from the commodity buy/sell interface
770         *       @return an iterable ordered map of the stall names and generated stall ids
771         */
772         private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
773                 int count = 0;
774                 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
775                 for(ArrayList<String> offer : offers) {
776                         String shop = offer.get(1);
777                         if(!map.containsKey(shop)) {
778                                 count++;
779                                 map.put(shop,count);
780                         }
781                 }
782                 return map;
783         }
784         
785         /**
786         *       Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
787         *       should be pre-initialized and passed into the method to receive the data.
788         *       Returns a 2-length int array with the number of buys and sells found.
789         *       
790         *       @param offers the data found from the market table in-game
791         *       @param buys an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
792         *       hold the Buy offers.
793         *       @param sells an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
794         *       hold the Sell offers.
795         *       @param stalls the map of stalls to their ids
796         *       @param commodMap the map of commodities to their ids
797         *       @return a 2-length int[] array containing the number of buys and sells, respectively
798         */
799         private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
800                         TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
801                 int[] buySellCount = new int[2];
802                 for(ArrayList<String> offer : offers) {
803                         try {
804                                 if(offer.get(2) != null) {
805                                         buys.add(new Buy(offer,stalls,commodMap));
806                                         buySellCount[0]++;
807                                 }
808                                 if(offer.get(4) != null) {
809                                         sells.add(new Sell(offer,stalls,commodMap));
810                                         buySellCount[1]++;
811                                 }
812                         } catch(IllegalArgumentException e) {
813                                 if (dtxt!=null) dtxt.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
814                         }
815                 }
816                 if (buySellCount[0]==0 && buySellCount[1]==0) {
817                     error("No (valid) offers for PCTB?!");
818                     throw new IllegalArgumentException();
819                 }
820                 return buySellCount;
821         }
822         
823         /**
824         *       Prepares the list of stalls for writing to the output stream.
825         *       The <code>String</code> returned by this method is ready to be written
826         *       directly to the stream.
827         *       <p>
828         *       All shoppe names are left as they are. Stall names are abbreviated just before the
829         *       apostrophe in the possessive, with an "^" and a letter matching the stall's type
830         *       appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
831         *
832         *       @param stallMap the map of stalls and stall ids in an iterable order
833         *       @return a <code>String</code> containing the list of stalls in format ready
834         *       to be written to the output stream.
835         */
836         private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
837                 // set up some mapping
838                 HashMap<String,String> types = new HashMap<String,String>();
839                 types.put("Apothecary Stall", "A");
840                 types.put("Distilling Stall", "D");
841                 types.put("Furnishing Stall", "F");
842                 types.put("Ironworking Stall", "I");
843                 types.put("Shipbuilding Stall", "S");
844                 types.put("Tailoring Stall", "T");
845                 types.put("Weaving Stall", "W");
846                 
847                 StringBuilder sb = new StringBuilder();
848                 for(String name : stallMap.keySet()) {
849                         int index = name.indexOf("'s");
850                         String finalName = name;
851                         String type = null;
852                         if (index > 0) {
853                                 finalName = name.substring(0,index);
854                                 if(index + 2 < name.length()) {
855                                         String end = name.substring(index+2,name.length()).trim();
856                                         type = types.get(end);
857                                 }
858                         }
859                         if(type==null) {
860                                 sb.append(name+"\n");
861                         } else {
862                                 sb.append(finalName+"^"+type+"\n");
863                         }
864                 }
865                 return sb.toString();
866         }
867         
868         /**
869         *       Writes a list of offers in correct format to the output stream.
870         *       <p>
871         *       The format is thus: (all numbers are 2-byte integers in little-endian format)
872         *       (number of offers of this type, aka buy/sell)
873         *       (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]... 
874         *
875         *       @param out the output stream to write the data to
876         *       @param offers the offers to write
877         */
878         private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
879                 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
880                 if(offers.size() == 0) {
881                         // nothing to write, and "0" has already been written
882                         return;
883                 }
884                 int commodity = offers.first().commodity;
885                 int count = 0;
886                 for(Offer offer : offers) {
887                         if(commodity != offer.commodity) {
888                                 // write out buffer
889                                 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
890                                 buffer.reset();
891                                 commodity = offer.commodity;
892                                 count = 0;
893                         }
894                         writeLEShort(offer.shoppe,buffer); // stall index
895                         writeLEShort(offer.price,buffer); // buy price
896                         writeLEShort(offer.quantity,buffer); // buy qty
897                         count++;
898                 }
899                 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
900         }
901         
902         /**
903         *       Writes the buffered data to the output strea for one commodity.
904         *       
905         *       @param out the stream to write to
906         *       @param buffer the buffered data to write
907         *       @param commodity the commmodity id to write before the buffered data
908         *       @param count the number of offers for this commodity to write before the data
909         */
910         private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
911                 writeLEShort(commodity,out); // commod index
912                 writeLEShort(count,out); // offer count
913                 out.write(buffer); // the buffered offers
914         }
915         
916         /**
917         *       Writes the buy and sell offers to the outputstream by calling other methods.
918         *       
919         *       @param buys list of Buy offers to write
920         *       @param sells list of Sell offers to write
921         *       @param offerCount 2-length int array containing the number of buys and sells to write out
922         *       @param out the stream to write to
923         */
924         private void writeBuySellOffers(TreeSet<Offer> buys,
925                         TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
926                 // # buy offers
927                 writeLEShort(offerCount[0],out);
928                 writeOffers(out,buys);
929                 // # sell offers
930                 writeLEShort(offerCount[1],out);
931                 writeOffers(out,sells);
932         }
933         
934         private String readstreamstring(InputStream in) throws IOException {
935                 StringBuilder sb = new StringBuilder();
936                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
937                 String str;
938                 while((str = br.readLine()) != null) {
939                         sb.append(str+"\n");
940                 }
941                 return sb.toString();
942         }
943
944         /**
945         *       Sends the data to the server via multipart-formdata POST,
946         *       with the gzipped data as a file upload.
947         *
948         *       @param file an InputStream open to the gzipped data we want to send
949         */
950         private InputStream sendInitialData(InputStream file) throws IOException {
951                 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
952                 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
953                 if (!http.post()) {
954                         String err = readstreamstring(http.resultstream());
955                         error("Error sending initial data:\n"+err);
956                         return null;
957                 }
958                 return http.resultstream();
959         }
960         
961         /**
962         *       Utility method to write a 2-byte int in little-endian form to an output stream.
963         *
964         *       @param num an integer to write
965         *       @param out stream to write to
966         */
967         private void writeLEShort(int num, OutputStream out) throws IOException {
968                 out.write(num & 0xFF);
969                 out.write((num >>> 8) & 0xFF);
970         }
971         
972         /**
973         *       Reads the response from the server, and selects the correct parameters
974         *       which are sent in a GET request to the server asking it to confirm
975         *       the upload and accept the data into the database. Notably, the island id
976         *       and ocean id are determined, while other parameter such as the filename
977         *       are determined from the hidden form fields.
978         *
979         *       @param in stream of data from the server to read
980         */
981         private boolean finishUpload(InputStream in) throws IOException {
982                 String html = readstreamstring(in);
983                 debug_write_stringdata("pctb-initial.html", html);
984                 Matcher m;
985
986                 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
987                 m = params.matcher(html);
988                 if(!m.find()) {
989                         error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
990                                    html);
991                         return false;
992                 }
993                 String forceReload = m.group(1);
994                 String filename = m.group(2);
995
996                 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
997                 m = oceanNumPat.matcher(html);
998                 if (!m.find()) {
999                         error_html("Unable to find the ocean in the server's list of oceans!", html);
1000                         return false;
1001                 }
1002                 String oceanNum = m.group(1);
1003
1004                 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
1005                 m = oceanIslandNum.matcher(html);
1006                 if(!m.find()) {
1007                         error_html("This does not seem to be a valid island! Unable to upload.", html);
1008                         return false;
1009                 }
1010                 String islandNum = m.group(1);
1011
1012                 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
1013                         + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
1014                 String complete = readstreamstring(get.openStream());
1015                 debug_write_stringdata("pctb-final.html", complete);
1016                 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
1017                 m = done.matcher(complete);
1018                 if(m.find()) {
1019                         return true;
1020                 } else {
1021                         error_html("Something was wrong with the final upload parameters!", complete);
1022                         return false;
1023                 }
1024         }
1025
1026     private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
1027         if (!http.post()) {
1028             String err = readstreamstring(http.resultstream());
1029             error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1030             return null;
1031         }
1032         return http.resultstream();
1033     }
1034
1035     private String getYarrgTimestamp() throws IOException {
1036         ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1037         http.setParameter("clientname", YARRG_CLIENTNAME);
1038         http.setParameter("clientversion", YARRG_CLIENTVERSION);
1039         http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1040         http.setParameter("requesttimestamp", "y");
1041         InputStream in = post_for_yarrg(http);
1042         if (in == null) return null;
1043         BufferedReader br = new BufferedReader(new InputStreamReader(in));
1044         String tsresult = br.readLine();
1045         return tsresult.substring(3, tsresult.length()-1);
1046     }
1047
1048     private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
1049         ByteArrayOutputStream bos = new ByteArrayOutputStream();
1050         BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
1051         bufos.write(yarrgdata.getBytes() );
1052         bufos.close();
1053         ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
1054
1055         ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1056         http.setParameter("clientname", YARRG_CLIENTNAME);
1057         http.setParameter("clientversion", YARRG_CLIENTVERSION);
1058         http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1059         http.setParameter("timestamp", timestamp);
1060         http.setParameter("ocean", ocean);
1061         http.setParameter("island", island);
1062         http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
1063         InputStream in = post_for_yarrg(http);
1064         if (in == null) return false;
1065         String output = readstreamstring(in);
1066         if (!output.startsWith("OK")) {
1067             error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1068             return false;
1069         }
1070         debug_write_stringdata("yarrg-result.txt", output);
1071         return true;
1072     }
1073
1074     private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1075         // if (dtxt!=null) dtxt.println("ARBITRAGE?");
1076         int profit = 0;
1077         SortedSet<int[]> buys = arb_bs.get(0);
1078         SortedSet<int[]> sells = arb_bs.get(1);
1079         while (true) {
1080             int[] buy, sell;
1081             try {
1082                 // NB "sell" means they sell, ie we buy
1083                 sell = sells.last();
1084                 buy = buys.first();
1085             } catch (NoSuchElementException e) {
1086                 break;
1087             }
1088
1089             int unitprofit = buy[0] - sell[0];
1090             int count = buy[1] < sell[1] ? buy[1] : sell[1];
1091             // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1092             //                 +" => x"+count+" @"+unitprofit);
1093
1094             if (unitprofit <= 0)
1095                 break;
1096             
1097             profit += count * unitprofit;
1098             buy[1] -= count;
1099             sell[1] -= count;
1100             if (buy[1]==0) buys.remove(buy);
1101             if (sell[1]==0) sells.remove(sell);
1102         }
1103         // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
1104         return profit;
1105     }
1106
1107     private class arbitrageOfferComparator implements Comparator {
1108         public int compare(Object o1, Object o2) {
1109             int p1 = ((int[])o1)[0];
1110             int p2 = ((int[])o2)[0];
1111             return p2 - p1;
1112         }
1113     }
1114
1115     private @SuppressWarnings("unchecked")
1116     void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1117         int arbitrage = 0;
1118         ArrayList<SortedSet<int[]>> arb_bs = null;
1119         String lastcommod = null;
1120         Comparator compar = new arbitrageOfferComparator();
1121
1122         for (ArrayList<String> row : data) {
1123             String thiscommod = row.get(0);
1124             // if (dtxt!=null) dtxt.println("ROW "+row.toString());
1125             if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1126                 if (lastcommod != null)
1127                     arbitrage += calculateArbitrageCommodity(arb_bs);
1128                 // if (dtxt!=null) dtxt.println("ROW rdy");
1129                 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1130                 arb_bs.add(0, new TreeSet<int[]>(compar));
1131                 arb_bs.add(1, new TreeSet<int[]>(compar));
1132                 // if (dtxt!=null) dtxt.println("ROW init");
1133                 lastcommod = thiscommod;
1134             }
1135             for (int bs = 0; bs < 2; bs++) {
1136                 String pricestr = row.get(bs*2 + 2);
1137                 if (pricestr == null)
1138                     continue;
1139                 int[] entry = new int[2];
1140                 // if (dtxt!=null) dtxt.println("ROW BS "+bs);
1141                 entry[0] = parseQty(pricestr);
1142                 entry[1] = parseQty(row.get(bs*2 + 3));
1143                 arb_bs.get(bs).add(entry);
1144             }
1145         }
1146         arbitrage += calculateArbitrageCommodity(arb_bs);
1147         if (arbitrage != 0) {
1148             arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1149         } else {
1150             arbitrageResult.setText("no arbitrage");
1151         }
1152     }
1153     
1154 }