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