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