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