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