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