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