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