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