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