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