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