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