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