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