chiark / gitweb /
b3fa49fdb99ed99dc0eb60974d88bc4f18fd380d
[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("(async) 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                 progresslog("(async) getisland done");
451
452                 if (islandName == null) {
453                     error("Could not find island name in YPP user interface.");
454                     return;
455                 }
456
457                 progresslog("table check...");
458
459                 String headings_expected[] = new String[]
460                     { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
461                 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
462                 if (headers.size() != 1) {
463                     error("Table headings not one row! " + headers.toString());
464                     return;
465                 }
466                 if (headers.get(0).size() != 6) {
467                     error("Table headings not six columns! " + headers.toString());
468                     return;
469                 }
470                 for (int col=0; col<headings_expected.length; col++) {
471                     String expd = headings_expected[col];
472                     String got = headers.get(0).get(col);
473                     if (expd.compareTo(got) != 0) {
474                         error("Table heading for column "+col
475                               +" is not \""+expd+"\" but \""+got+"\".\n\n"
476                               +"Please do not reorder the table when using this tool.");
477                         return;
478                     }
479                 }
480
481                 progresslog("table read...");
482
483                 ArrayList<ArrayList<String>> data = getData(accesstable);
484
485                 if (showArbitrage) {
486                         progresslog("arbitrage...");
487                         calculateArbitrage(data);
488                         progresslog("arbitrage done.");
489                 }
490
491                 if (uploadToYarrg && yarrgts != null) {
492                         progresslog("yarrg prepare...");
493                         progressNote(pm, "Yarrg: Preparing data");
494                         pm.setProgress(10);
495
496                         StringBuilder yarrgsb = new StringBuilder();
497                         String yarrgdata; // string containing what we'll feed to yarrg
498                 
499                         for (ArrayList<String> row : data) {
500                                 if (row.size() > 6) {
501                                         row.remove(6);
502                                 }
503                                 for (String rowitem : row) {
504                                         yarrgsb.append(rowitem != null ? rowitem : "");
505                                         yarrgsb.append("\t");
506                                 }
507                                 yarrgsb.setLength(yarrgsb.length()-1); // chop
508                                 yarrgsb.append("\n");
509                         }
510
511                         yarrgdata = yarrgsb.toString();
512
513                         progressNote(pm, "Yarrg: Uploading");
514                         progresslog("yarrg upload...");
515
516                         doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
517                         progresslog("yarrg done.");
518                 }
519
520                 if (uploadToPCTB) {
521                     progresslog("pctb prepare...");
522                     progressNote(pm, "PCTB: Getting stall names");
523                     pm.setProgress(20);
524                     if(pm.isCanceled()) {
525                         return;
526                     }
527                     TreeSet<Offer> buys = new TreeSet<Offer>();
528                     TreeSet<Offer> sells = new TreeSet<Offer>();
529                     LinkedHashMap<String,Integer> stallMap = getStallMap(data);
530                     pm.setProgress(40);
531                     progressNote(pm, "PCTB: Sorting offers");
532                     if(pm.isCanceled()) {
533                         return;
534                     }
535                     // get commod map
536                 
537                     progresslog("pctb commodmap...");
538                     HashMap<String,Integer> commodMap = getCommodMap();
539                     if(commodMap == null) {
540                         return;
541                     }
542                     progresslog("pctb commodmap done.");
543                     int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
544                     //println(buys.toString());
545                     // if (dtxt!=null) dtxt.println(sells);
546                     // if (dtxt!=null) dtxt.println("\n\n\n"+buys);
547
548                     ByteArrayOutputStream outStream = new ByteArrayOutputStream();
549                     pm.setProgress(60);
550                     progressNote(pm, "PCTB: Sending data");
551                     if(pm.isCanceled()) {
552                         return;
553                     }
554                     GZIPOutputStream out = new GZIPOutputStream(outStream);
555                     //FileOutputStream out = new FileOutputStream(new File("output.text"));
556                     DataOutputStream dos = new DataOutputStream(out);
557                     dos.writeBytes("005y\n");
558                     dos.writeBytes(stallMap.size()+"\n");
559                     dos.writeBytes(getAbbrevStallList(stallMap));
560                     writeBuySellOffers(buys,sells,offerCount,out);
561                     out.finish();
562                     progresslog("pctb send...");
563
564                     byte[] ba = outStream.toByteArray();
565                     if (dtxt!=null) {
566                         FileOutputStream dbgdata = new FileOutputStream(new File("jarrg-debug-pctb-marketdata.gz"));
567                         dbgdata.write(ba);
568                         dbgdata.close();
569                     }
570
571                     InputStream in = sendInitialData(new ByteArrayInputStream(ba));
572                     progresslog("pctb sent.");
573                     if (in == null) return;
574                     pm.setProgress(80);
575                     if(pm.isCanceled()) {
576                         return;
577                     }
578                     progressNote(pm, "PCTB: Waiting ...");
579                     progresslog("pctb finish...");
580                     donepctb = finishUpload(in);
581                     progresslog("pctb done.");
582                 }
583                 pm.setProgress(100);
584
585                 if ((uploadToPCTB && !donepctb) ||
586                     (uploadToYarrg && !doneyarrg)) {
587                         resultSummary.setText("trouble");
588                 } else if (donepctb || doneyarrg) {
589                         resultSummary.setText("Done " + islandName);
590                 } else {
591                         resultSummary.setText("uploaded nowhere!");
592                 }
593                 progresslog("done.");
594         }
595         
596         /**
597         *       Get the offer data out of the table and cache it in an <code>ArrayList</code>.
598         *       
599         *       @param table the <code>AccessibleTable</code> containing the market data
600         *       @return an array of record arrays, each representing a row of the table
601         */
602         private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
603                 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
604                 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
605                         ArrayList<String> row = new ArrayList<String>();
606                         for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
607                                 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
608                         }
609                         data.add(row);
610                 }
611                 return data;
612         }
613         
614         /**
615         *       @return the table containing market data if it exists, otherwise <code>null</code>
616         */
617         public AccessibleTable findMarketTable() {
618                 Accessible node1 = window;
619                 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
620                 // 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})
621                 // if (dtxt!=null) dtxt.println(node);
622                 if (!(node instanceof JTable)) {
623                         node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
624                 }
625                 if (!(node instanceof JTable)) return null;
626                 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
627                 // if (dtxt!=null) dtxt.println(table);
628                 return table;
629         }
630         
631         /**
632         *       Utility method to descend through several levels of Accessible children
633         *       at once.
634         *
635         *       @param parent the node on which to start the descent
636         *       @param path an array of ints, each int being the index of the next
637         *       accessible child to descend.
638         *       @return the <code>Accessible</code> reached by following the descent path,
639         *       or <code>null</code> if the desired path was invalid.
640         */
641         private Accessible descendNodes(Accessible parent, int[] path) {
642                 for(int i=0;i<path.length;i++) {
643                         if (null == (parent = descend(parent, path[i]))) return null;
644                         // if (dtxt!=null) dtxt.println(parent.getClass());
645                 }
646                 return parent;
647         }
648         
649         /**
650         *       Descends one level to the specified child of the parent <code>Accessible</code> "node".
651         *       
652         *       @param parent the node with children
653         *       @param childNum the index of the child of <code>parent</code> to return
654         *       @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
655         *       if the child is not found.
656         */
657         private Accessible descend(Accessible parent, int childNum) {
658                 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
659                 return parent.getAccessibleContext().getAccessibleChild(childNum);
660         }
661         
662         public static void main(String[] args) {
663                 new MarketUploader();
664         }
665
666         /**
667         *       Set the global window variable after the YPP window is created,
668         *       remove the top level window listener, and start the GUI
669         */
670         public void topLevelWindowCreated(Window w) {
671                 window = w;
672                 EventQueueMonitor.removeTopLevelWindowListener(this);
673                 createGUI();
674         }
675         
676         /**
677         *       Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
678         *
679         *       @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
680         */
681         private boolean isDisplayAll() {
682                 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
683                 if(!(button instanceof JButton)) {
684                         button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
685                 }
686                 String display = button.getAccessibleContext().getAccessibleName();
687                 if(!display.equals("All")) {
688                         return false;
689                 }
690                 return true;
691         }
692         
693         public void topLevelWindowDestroyed(Window w) {}
694
695         public void guiInitialized() {
696                 createGUI();
697         }
698         
699         /**
700         *       Gets the list of commodities and their associated commodity ids.
701         *
702         *       @return a map where the key is the commodity and the value is the commodity id.
703         */
704         private HashMap<String,Integer> getCommodMap() {
705                 if(commodMap != null) {
706                         return commodMap;
707                 }
708                 HashMap<String,Integer> map = new HashMap<String,Integer>();
709                 String xml;
710                 try {
711                         URL host = new URL(PCTB_HOST_URL + "commodmap.php");
712                         BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
713                         StringBuilder sb = new StringBuilder();
714                         String str;
715                         while((str = br.readLine()) != null) {
716                                 sb.append(str);
717                         }
718                         int first = sb.indexOf("<pre>") + 5;
719                         int last = sb.indexOf("</body>");
720                         xml = sb.substring(first,last);
721                         //if (dtxt!=null) {
722                         //        dtxt.println(">>");
723                         //        dtxt.println(sb);;
724                         //        dtxt.println("||");
725                         //        dtxt.println(xml);
726                         //        dtxt.println("<<");
727                         //}
728                         // if (dtxt!=null) dtxt.println(xml);
729                         Reader reader = new CharArrayReader(xml.toCharArray());
730                         Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
731                         NodeList maps = d.getElementsByTagName("CommodMap");
732                         for(int i=0;i<maps.getLength();i++) {
733                                 NodeList content = maps.item(i).getChildNodes();
734                                 Integer num = Integer.parseInt(content.item(1).getTextContent());
735                                 map.put(content.item(0).getTextContent(),num);
736                         }
737                 } catch(Exception e) {
738                         e.printStackTrace();
739                         error("Unable to load Commodity list from server!");
740                         return null;
741                 }
742                 commodMap = map;
743                 return map;
744         }
745         
746         /**
747         *       Given the list of offers, this method will find all the unique stall names
748         *       and return them in a <code>LinkedHashMap</code> where the key is the stall name
749         *       and the value is the generated stall id (position in the list).
750         *       <p>
751         *       The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
752         *       for iterating over the stall names in insertion order for output to the server.
753         *
754         *       @param offers the list of records from the commodity buy/sell interface
755         *       @return an iterable ordered map of the stall names and generated stall ids
756         */
757         private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
758                 int count = 0;
759                 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
760                 for(ArrayList<String> offer : offers) {
761                         String shop = offer.get(1);
762                         if(!map.containsKey(shop)) {
763                                 count++;
764                                 map.put(shop,count);
765                         }
766                 }
767                 return map;
768         }
769         
770         /**
771         *       Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
772         *       should be pre-initialized and passed into the method to receive the data.
773         *       Returns a 2-length int array with the number of buys and sells found.
774         *       
775         *       @param offers the data found from the market table in-game
776         *       @param buys an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
777         *       hold the Buy offers.
778         *       @param sells an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
779         *       hold the Sell offers.
780         *       @param stalls the map of stalls to their ids
781         *       @param commodMap the map of commodities to their ids
782         *       @return a 2-length int[] array containing the number of buys and sells, respectively
783         */
784         private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
785                         TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
786                 int[] buySellCount = new int[2];
787                 for(ArrayList<String> offer : offers) {
788                         try {
789                                 if(offer.get(2) != null) {
790                                         buys.add(new Buy(offer,stalls,commodMap));
791                                         buySellCount[0]++;
792                                 }
793                                 if(offer.get(4) != null) {
794                                         sells.add(new Sell(offer,stalls,commodMap));
795                                         buySellCount[1]++;
796                                 }
797                         } catch(IllegalArgumentException e) {
798                                 if (dtxt!=null) dtxt.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
799                         }
800                 }
801                 if (buySellCount[0]==0 && buySellCount[1]==0) {
802                     error("No (valid) offers for PCTB?!");
803                     throw new IllegalArgumentException();
804                 }
805                 return buySellCount;
806         }
807         
808         /**
809         *       Prepares the list of stalls for writing to the output stream.
810         *       The <code>String</code> returned by this method is ready to be written
811         *       directly to the stream.
812         *       <p>
813         *       All shoppe names are left as they are. Stall names are abbreviated just before the
814         *       apostrophe in the possessive, with an "^" and a letter matching the stall's type
815         *       appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
816         *
817         *       @param stallMap the map of stalls and stall ids in an iterable order
818         *       @return a <code>String</code> containing the list of stalls in format ready
819         *       to be written to the output stream.
820         */
821         private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
822                 // set up some mapping
823                 HashMap<String,String> types = new HashMap<String,String>();
824                 types.put("Apothecary Stall", "A");
825                 types.put("Distilling Stall", "D");
826                 types.put("Furnishing Stall", "F");
827                 types.put("Ironworking Stall", "I");
828                 types.put("Shipbuilding Stall", "S");
829                 types.put("Tailoring Stall", "T");
830                 types.put("Weaving Stall", "W");
831                 
832                 StringBuilder sb = new StringBuilder();
833                 for(String name : stallMap.keySet()) {
834                         int index = name.indexOf("'s");
835                         String finalName = name;
836                         String type = null;
837                         if (index > 0) {
838                                 finalName = name.substring(0,index);
839                                 if(index + 2 < name.length()) {
840                                         String end = name.substring(index+2,name.length()).trim();
841                                         type = types.get(end);
842                                 }
843                         }
844                         if(type==null) {
845                                 sb.append(name+"\n");
846                         } else {
847                                 sb.append(finalName+"^"+type+"\n");
848                         }
849                 }
850                 return sb.toString();
851         }
852         
853         /**
854         *       Writes a list of offers in correct format to the output stream.
855         *       <p>
856         *       The format is thus: (all numbers are 2-byte integers in little-endian format)
857         *       (number of offers of this type, aka buy/sell)
858         *       (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]... 
859         *
860         *       @param out the output stream to write the data to
861         *       @param offers the offers to write
862         */
863         private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
864                 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
865                 if(offers.size() == 0) {
866                         // nothing to write, and "0" has already been written
867                         return;
868                 }
869                 int commodity = offers.first().commodity;
870                 int count = 0;
871                 for(Offer offer : offers) {
872                         if(commodity != offer.commodity) {
873                                 // write out buffer
874                                 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
875                                 buffer.reset();
876                                 commodity = offer.commodity;
877                                 count = 0;
878                         }
879                         writeLEShort(offer.shoppe,buffer); // stall index
880                         writeLEShort(offer.price,buffer); // buy price
881                         writeLEShort(offer.quantity,buffer); // buy qty
882                         count++;
883                 }
884                 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
885         }
886         
887         /**
888         *       Writes the buffered data to the output strea for one commodity.
889         *       
890         *       @param out the stream to write to
891         *       @param buffer the buffered data to write
892         *       @param commodity the commmodity id to write before the buffered data
893         *       @param count the number of offers for this commodity to write before the data
894         */
895         private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
896                 writeLEShort(commodity,out); // commod index
897                 writeLEShort(count,out); // offer count
898                 out.write(buffer); // the buffered offers
899         }
900         
901         /**
902         *       Writes the buy and sell offers to the outputstream by calling other methods.
903         *       
904         *       @param buys list of Buy offers to write
905         *       @param sells list of Sell offers to write
906         *       @param offerCount 2-length int array containing the number of buys and sells to write out
907         *       @param out the stream to write to
908         */
909         private void writeBuySellOffers(TreeSet<Offer> buys,
910                         TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
911                 // # buy offers
912                 writeLEShort(offerCount[0],out);
913                 writeOffers(out,buys);
914                 // # sell offers
915                 writeLEShort(offerCount[1],out);
916                 writeOffers(out,sells);
917         }
918         
919         private String readstreamstring(InputStream in) throws IOException {
920                 StringBuilder sb = new StringBuilder();
921                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
922                 String str;
923                 while((str = br.readLine()) != null) {
924                         sb.append(str+"\n");
925                 }
926                 return sb.toString();
927         }
928
929         /**
930         *       Sends the data to the server via multipart-formdata POST,
931         *       with the gzipped data as a file upload.
932         *
933         *       @param file an InputStream open to the gzipped data we want to send
934         */
935         private InputStream sendInitialData(InputStream file) throws IOException {
936                 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
937                 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
938                 if (!http.post()) {
939                         String err = readstreamstring(http.resultstream());
940                         error("Error sending initial data:\n"+err);
941                         return null;
942                 }
943                 return http.resultstream();
944         }
945         
946         /**
947         *       Utility method to write a 2-byte int in little-endian form to an output stream.
948         *
949         *       @param num an integer to write
950         *       @param out stream to write to
951         */
952         private void writeLEShort(int num, OutputStream out) throws IOException {
953                 out.write(num & 0xFF);
954                 out.write((num >>> 8) & 0xFF);
955         }
956         
957         /**
958         *       Reads the response from the server, and selects the correct parameters
959         *       which are sent in a GET request to the server asking it to confirm
960         *       the upload and accept the data into the database. Notably, the island id
961         *       and ocean id are determined, while other parameter such as the filename
962         *       are determined from the hidden form fields.
963         *
964         *       @param in stream of data from the server to read
965         */
966         private boolean finishUpload(InputStream in) throws IOException {
967                 String html = readstreamstring(in);
968                 // if (dtxt!=null) dtxt.println(html);
969                 Matcher m;
970
971                 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
972                 m = params.matcher(html);
973                 if(!m.find()) {
974                         error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
975                                    html);
976                         return false;
977                 }
978                 String forceReload = m.group(1);
979                 String filename = m.group(2);
980
981                 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
982                 m = oceanNumPat.matcher(html);
983                 if (!m.find()) {
984                         error_html("Unable to find the ocean in the server's list of oceans!", html);
985                         return false;
986                 }
987                 String oceanNum = m.group(1);
988
989                 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
990                 m = oceanIslandNum.matcher(html);
991                 if(!m.find()) {
992                         error_html("This does not seem to be a valid island! Unable to upload.", html);
993                         return false;
994                 }
995                 String islandNum = m.group(1);
996
997                 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
998                         + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
999                 String complete = readstreamstring(get.openStream());
1000                 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
1001                 m = done.matcher(complete);
1002                 if(m.find()) {
1003                         if (dtxt!=null) dtxt.println("FILE upload successful!!!");
1004                         return true;
1005                 } else {
1006                         error_html("Something was wrong with the final upload parameters!", complete);
1007                         return false;
1008                 }
1009         }
1010
1011     private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
1012         if (!http.post()) {
1013             String err = readstreamstring(http.resultstream());
1014             error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1015             return null;
1016         }
1017         return http.resultstream();
1018     }
1019
1020     private String getYarrgTimestamp() throws IOException {
1021         ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1022         http.setParameter("clientname", YARRG_CLIENTNAME);
1023         http.setParameter("clientversion", YARRG_CLIENTVERSION);
1024         http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1025         http.setParameter("requesttimestamp", "y");
1026         InputStream in = post_for_yarrg(http);
1027         if (in == null) return null;
1028         BufferedReader br = new BufferedReader(new InputStreamReader(in));
1029         String tsresult = br.readLine();
1030         return tsresult.substring(3, tsresult.length()-1);
1031     }
1032
1033     private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
1034         ByteArrayOutputStream bos = new ByteArrayOutputStream();
1035         BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
1036         bufos.write(yarrgdata.getBytes() );
1037         bufos.close();
1038         ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
1039
1040         ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1041         http.setParameter("clientname", YARRG_CLIENTNAME);
1042         http.setParameter("clientversion", YARRG_CLIENTVERSION);
1043         http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1044         http.setParameter("timestamp", timestamp);
1045         http.setParameter("ocean", ocean);
1046         http.setParameter("island", island);
1047         http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
1048         InputStream in = post_for_yarrg(http);
1049         if (in == null) return false;
1050         BufferedReader br = new BufferedReader(new InputStreamReader(in));
1051         String yarrgresult; 
1052         while((yarrgresult = br.readLine()) != null) {
1053             if (dtxt!=null) dtxt.println(yarrgresult);
1054         }
1055         return true;
1056     }
1057
1058     private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1059         // if (dtxt!=null) dtxt.println("ARBITRAGE?");
1060         int profit = 0;
1061         SortedSet<int[]> buys = arb_bs.get(0);
1062         SortedSet<int[]> sells = arb_bs.get(1);
1063         while (true) {
1064             int[] buy, sell;
1065             try {
1066                 // NB "sell" means they sell, ie we buy
1067                 sell = sells.last();
1068                 buy = buys.first();
1069             } catch (NoSuchElementException e) {
1070                 break;
1071             }
1072
1073             int unitprofit = buy[0] - sell[0];
1074             int count = buy[1] < sell[1] ? buy[1] : sell[1];
1075             // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1076             //                 +" => x"+count+" @"+unitprofit);
1077
1078             if (unitprofit <= 0)
1079                 break;
1080             
1081             profit += count * unitprofit;
1082             buy[1] -= count;
1083             sell[1] -= count;
1084             if (buy[1]==0) buys.remove(buy);
1085             if (sell[1]==0) sells.remove(sell);
1086         }
1087         // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
1088         return profit;
1089     }
1090
1091     private class arbitrageOfferComparator implements Comparator {
1092         public int compare(Object o1, Object o2) {
1093             int p1 = ((int[])o1)[0];
1094             int p2 = ((int[])o2)[0];
1095             return p2 - p1;
1096         }
1097     }
1098
1099     private @SuppressWarnings("unchecked")
1100     void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1101         int arbitrage = 0;
1102         ArrayList<SortedSet<int[]>> arb_bs = null;
1103         String lastcommod = null;
1104         Comparator compar = new arbitrageOfferComparator();
1105
1106         for (ArrayList<String> row : data) {
1107             String thiscommod = row.get(0);
1108             // if (dtxt!=null) dtxt.println("ROW "+row.toString());
1109             if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1110                 if (lastcommod != null)
1111                     arbitrage += calculateArbitrageCommodity(arb_bs);
1112                 // if (dtxt!=null) dtxt.println("ROW rdy");
1113                 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1114                 arb_bs.add(0, new TreeSet<int[]>(compar));
1115                 arb_bs.add(1, new TreeSet<int[]>(compar));
1116                 // if (dtxt!=null) dtxt.println("ROW init");
1117                 lastcommod = thiscommod;
1118             }
1119             for (int bs = 0; bs < 2; bs++) {
1120                 String pricestr = row.get(bs*2 + 2);
1121                 if (pricestr == null)
1122                     continue;
1123                 int[] entry = new int[2];
1124                 // if (dtxt!=null) dtxt.println("ROW BS "+bs);
1125                 entry[0] = parseQty(pricestr);
1126                 entry[1] = parseQty(row.get(bs*2 + 3));
1127                 arb_bs.get(bs).add(entry);
1128             }
1129         }
1130         arbitrage += calculateArbitrageCommodity(arb_bs);
1131         if (arbitrage != 0) {
1132             arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1133         } else {
1134             arbitrageResult.setText("no arbitrage");
1135         }
1136     }
1137     
1138 }