chiark / gitweb /
Initial commit of Yarrg code
[jarrg-owen.git] / src / com / tedpearson / ypp / market / MarketUploader.java
diff --git a/src/com/tedpearson/ypp/market/MarketUploader.java b/src/com/tedpearson/ypp/market/MarketUploader.java
new file mode 100644 (file)
index 0000000..8e0c109
--- /dev/null
@@ -0,0 +1,967 @@
+package com.tedpearson.ypp.market;
+
+import java.awt.*;
+import java.awt.event.*;
+
+import javax.accessibility.*;
+import javax.swing.*;
+
+import com.sun.java.accessibility.util.*;
+
+import java.util.*;
+import java.io.*;
+import java.util.*;
+import java.net.URL;
+import org.w3c.dom.*;
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.xml.sax.InputSource;
+import java.util.zip.GZIPOutputStream;
+import com.myjavatools.web.ClientHttpRequest;
+import java.util.regex.*;
+import java.util.prefs.Preferences;
+import java.beans.*;
+import com.tedpearson.util.update.*;
+
+/*
+       TODO:
+       allow adding new islands
+       allow adding new oceans
+*/
+
+/**
+*      MarketUploader is a class that handles the uploading of market data from
+*      Yohoho! Puzzle Pirates. Currently, it must be launched in the save Java
+*      Virtual Machine as YPP. This is handled by a sister "helper" class,
+*      {@link MarketUploaderRunner}.
+*      <p>
+*      MarketUploader initializes after the main YPP window has initialized. It
+*      provides a simple window with a "Capture Market Data" button displayed.
+*      Upon clicking this button, a progress dialog is displayed, and the data
+*      is processed and submitted to the Pirate Commodities Trader with Bleach (PCTB)
+*      web server. If any errors occur, an error dialog is shown, and processing
+*      returns, the button becoming re-enabled.
+*      
+*      @see MarketUploaderRunner
+*/
+public class MarketUploader implements TopLevelWindowListener, GUIInitializedListener {
+       private JFrame frame = null;
+       private Window window = null;
+       private JButton findMarket = null;
+
+       private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
+       private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
+       private String PCTB_HOST_URL;
+
+       // Yarrg protocol parameters
+       private final static String YARRG_CLIENTNAME = "jpctb greenend";
+       private final static String YARRG_CLIENTVERSION = "0.1";
+       private final static String YARRG_CLIENTFIXES = "";
+       private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
+       private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
+       private String YARRG_URL;
+
+       private boolean uploadToYarrg;
+       private boolean uploadToPCTB;
+
+       private String islandName = null;
+       private String oceanName = null;
+       private java.util.concurrent.CountDownLatch latch = null;
+
+       private AccessibleContext sidePanel;
+       private HashMap<String,Integer> commodMap;
+       private HashMap<String,String> islandNumbers = new HashMap<String,String>();
+       {
+               String[] nums = new String[]
+                       {"","Viridian","Midnight","Hunter","Cobalt","Sage","Ice","Malachite","Crimson","Opal"};
+               for(int i=1;i<nums.length;i++) {
+                       islandNumbers.put(nums[i],""+i);
+               }
+       }
+       private PropertyChangeListener changeListener = new PropertyChangeListener() {
+               public void propertyChange(PropertyChangeEvent e) {
+                       if(e.getNewValue() != null && 
+                                       e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
+                               Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
+                               String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
+                               int index = text.indexOf(":");
+                               String name = text.substring(0,index);
+                               islandName = name;
+                               //System.out.println(islandName);
+                               sidePanel.removePropertyChangeListener(this);
+                               latch.countDown();
+                       }
+               }
+           };
+       
+       /**
+       *       An abstract market offer, entailing a commodity being bought or sold by
+       *       a shoppe, for a certain price in a certain quantity. Not instantiable.
+       *
+       *       @see Buy
+       *       @see Sell
+       */
+       abstract class Offer {
+               public int commodity, price, quantity, shoppe;
+               /**
+               *       Create an offer from <code>record</code>, determining the shoppe Id from
+               *       <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
+               *       <code>priceIndex</code> should be the index of the price in the record
+               *       (the quantity will be <code>priceIndex + 1</code>).
+               *
+               *       @param record the record with data to create the offer from
+               *       @param stallMap a map containing the ids of the various stalls
+               *       @param commodMap a map containing the ids of the various commodities
+               *       @param priceIndex the index of the price in the record
+               */
+               public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
+                               int priceIndex) {
+                       Integer commodId = commodMap.get(record.get(0));
+                       if(commodId == null) {
+                               throw new IllegalArgumentException();
+                       }
+                       commodity = commodId.intValue();
+                       price = Integer.parseInt(record.get(priceIndex));
+                       String qty = record.get(priceIndex+1);
+                       if(qty.equals(">1000")) {
+                               quantity = 1001;
+                       } else {
+                               quantity = Integer.parseInt(record.get(priceIndex+1));
+                       }
+                       shoppe = stallMap.get(record.get(1)).intValue();
+               }
+               
+               /**
+               *       Returns a human-readable version of this offer, useful for debugging
+               *       
+               *       @return human-readable offer
+               */
+               public String toString() {
+                       return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
+               }
+       }
+       
+       /**
+       *       An offer from a shoppe or stall to buy a certain quantity of a commodity
+       *       for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
+       *       then by buy price descending, and finally by stall id ascending.
+       */
+       class Buy extends Offer implements Comparable<Buy> {
+               /**
+               *       Creates a new <code>Buy</code> offer from the given <code>record</code>
+               *       using the other parameters to determine stall id and commodity id of the offer.
+               *
+               *       @param record the record with data to create the offer from
+               *       @param stallMap a map containing the ids of the various stalls
+               *       @param commodMap a map containing the ids of the various commodities
+               */
+               public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
+                       super(record,stallMap,commodMap,2);
+               }
+               
+               /**
+               *       Sorts by commodity index ascending, then price descending, then stall id ascending.
+               */
+               public int compareTo(Buy buy) {
+                       // organize by: commodity index, price, stall index
+                       if(commodity == buy.commodity) {
+                               // organize by price, then by stall index
+                               if(price == buy.price) {
+                                       // organize by stall index
+                                       return shoppe>buy.shoppe ? 1 : -1;
+                               } else if(price > buy.price) {
+                                       return -1;
+                               } else {
+                                       return 1;
+                               }
+                       } else if(commodity > buy.commodity) {
+                               return 1;
+                       } else {
+                               return -1;
+                       }
+               }
+       }
+       
+       /**
+       *       An offer from a shoppe or stall to sell a certain quantity of a commodity
+       *       for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
+       *       then by sell price ascending, and finally by stall id ascending.
+       */
+       class Sell extends Offer implements Comparable<Sell> {
+               /**
+               *       Creates a new <code>Sell</code> offer from the given <code>record</code>
+               *       using the other parameters to determine stall id and commodity id of the offer.
+               *
+               *       @param record the record with data to create the offer from
+               *       @param stallMap a map containing the ids of the various stalls
+               *       @param commodMap a map containing the ids of the various commodities
+               */
+               public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
+                       super(record,stallMap,commodMap,4);
+               }
+               
+               /**
+               *       Sorts by commodity index ascending, then price ascending, then stall id ascending.
+               */
+               public int compareTo(Sell sell) {
+                       // organize by: commodity index, price, stall index
+                       if(commodity == sell.commodity) {
+                               // organize by price, then by stall index
+                               if(price == sell.price) {
+                                       // organize by stall index
+                                       return shoppe>sell.shoppe ? 1 : -1;
+                               } else if(price > sell.price) {
+                                       return 1;
+                               } else {
+                                       return -1;
+                               }
+                       } else if(commodity > sell.commodity) {
+                               return 1;
+                       } else {
+                               return -1;
+                       }
+               }
+       }
+       
+       /**
+       *       Entry point. Remove modified files and replace with backups.
+       *       Register the jar file we are running from to be deleted upon quit.
+       *       Finally, conditionally set up the GUI.
+       */
+       public MarketUploader() {
+               // check if we've been turned off in the control panel
+               Preferences prefs = Preferences.userNodeForPackage(getClass());
+               boolean launch = prefs.getBoolean("launchAtStartup", true);
+               if(!launch) {
+                       return;
+               }
+
+               if (prefs.getBoolean("useLiveServers", false)) {
+                       YARRG_URL = YARRG_LIVE_URL;
+                       PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
+               } else {
+                       YARRG_URL = YARRG_TEST_URL;
+                       PCTB_HOST_URL = PCTB_TEST_HOST_URL;
+               }
+               
+               uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
+               uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
+
+               EventQueueMonitor.addTopLevelWindowListener(this);
+               if (EventQueueMonitor.isGUIInitialized()) {
+                       createGUI();
+               } else {
+                       EventQueueMonitor.addGUIInitializedListener(this);
+               }
+       }
+       
+       /**
+       *       Set up the GUI, with its window and one-button interface. Only initialize
+       *       if we're running alongside a Window named "Puzzle Pirates" though.
+       */
+       private void createGUI() {
+               if (frame != null && window != null) {
+                       if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
+                       return;
+               }
+               frame = new JFrame("MarketUploader");
+               frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
+               frame.getContentPane().setLayout(new FlowLayout());
+               //frame.setPreferredSize(new Dimension(200, 60));
+               
+               findMarket = new JButton("Upload Market Data");
+               findMarket.addActionListener(new ActionListener() {
+                       public void actionPerformed(ActionEvent e) {
+                               findMarket.setEnabled(false);
+                               new Thread() {
+                                       public void run() {
+                                               try {
+                                                       runPCTB();
+                                               } catch(Exception e) {
+                                                       error(e.toString());
+                                                       e.printStackTrace();
+                                               } finally {
+                                                       if(sidePanel != null) {
+                                                               // remove it if it's still attached
+                                                               sidePanel.removePropertyChangeListener(changeListener);
+                                                       }
+                                               }
+                                               //findMarketTable();
+                                               findMarket.setEnabled(true);
+                                       }
+                               }.start();
+                       }
+               });
+               frame.add(findMarket);
+               frame.pack();
+       }
+       
+       /**
+       *       Finds the island name from the /who tab, sets global islandName variable
+       */
+       private void getIsland() {
+
+               // If the league tracker is there, we can skip the faff
+               // and ask for its tooltip, since we're on a boat
+
+               Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
+               try {
+                       islandName = ((JLabel)leagueTracker).getToolTipText();
+               } catch (NullPointerException e) {
+                       
+                       // evidently we're actually on an island
+
+                       islandName = null;
+                       AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
+                       // attach the property change listener to the outer sunshine panel if the "ahoy" tab
+                       // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
+                       if(!"com.threerings.piracy.client.AttentionListPanel".
+                          equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
+                               sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
+                       } else {
+                               sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
+                       }
+                       sidePanel.addPropertyChangeListener(changeListener);
+                       latch = new java.util.concurrent.CountDownLatch(1);
+                       // make the Players Online ("/who") panel appear
+                       AccessibleEditableText chat = chatArea.getAccessibleEditableText();
+                       chat.setTextContents("/w");
+                       int c = chatArea.getAccessibleAction().getAccessibleActionCount();
+                       for(int i=0;i<c;i++) {
+                               if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
+                                       chatArea.getAccessibleAction().doAccessibleAction(i);
+                               }
+                       }
+               }
+               // if we don't find the island name, hopefully the server will
+       }
+
+       /**
+        *      Find the ocean name from the window title, and set global oceanName variable
+        */
+       private void getOcean() {
+               oceanName = null;
+               AccessibleContext topwindow = window.getAccessibleContext();
+               oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
+       }
+
+
+       /**
+       *       Shows a dialog with the error <code>msg</code>.
+       *
+       *       @param msg a String describing the error that occured.
+       */
+       private void error(String msg) {
+               JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
+       }
+       
+       /**
+       *       Run the data collection process, and upload the results. This is the method
+       *       that calls most of the other worker methods for the process. If an error occurs,
+       *       the method will call the error method and return early, freeing up the button
+       *       to be clicked again.
+       *
+       *       @exception Exception if an error we didn't expect occured
+       */
+       private void runPCTB() throws Exception {
+               String yarrgts = "";
+               ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
+               pm.setMillisToDecideToPopup(0);
+               pm.setMillisToPopup(0);
+
+               if (uploadToYarrg) {
+                       yarrgts = getYarrgTimestamp();
+               }
+
+               AccessibleTable t = findMarketTable();
+               if(t == null) {
+                       error("Market table not found! Please open the Buy/Sell Commodities interface.");
+                       return;
+               }
+               if(t.getAccessibleRowCount() == 0) {
+                       error("No data found, please wait for the table to have data first!");
+                       return;
+               }
+               if(!isDisplayAll()) {
+                       error("Please select \"All\" from the Display: popup menu.");
+                       return;
+               }
+
+               getIsland();
+               getOcean();
+
+               latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
+
+               ArrayList<ArrayList<String>> data = getData(t);
+
+               if (uploadToYarrg) {
+                       pm.setNote("Preparing data for Yarrg");
+                       pm.setProgress(10);
+
+                       StringBuilder yarrgsb = new StringBuilder();
+                       String yarrgdata; // string containing what we'll feed to yarrg
+               
+                       for (ArrayList<String> row : data) {
+                               if (row.size() > 6) {
+                                       row.remove(6);
+                               }
+                               for (String rowitem : row) {
+                                       yarrgsb.append(rowitem != null ? rowitem : "");
+                                       yarrgsb.append("\t");
+                               }
+                               yarrgsb.setLength(yarrgsb.length()-1); // chop
+                               yarrgsb.append("\n");
+                       }
+
+                       yarrgdata = yarrgsb.toString();
+
+                       pm.setNote("Uploading to Yarrg");
+
+                       if (islandName != null) {
+                               runYarrg(yarrgts, oceanName, islandName, yarrgdata);
+                       } else {
+                               System.out.println("Couldn't upload to Yarrg - no island name found");
+                       }
+               }
+
+               pm.setNote("Getting stall names");
+               pm.setProgress(20);
+               if(pm.isCanceled()) {
+                       return;
+               }
+               TreeSet<Offer> buys = new TreeSet<Offer>();
+               TreeSet<Offer> sells = new TreeSet<Offer>();
+               LinkedHashMap<String,Integer> stallMap = getStallMap(data);
+               pm.setProgress(40);
+               pm.setNote("Sorting offers");
+               if(pm.isCanceled()) {
+                       return;
+               }
+               // get commod map
+               
+               HashMap<String,Integer> commodMap = getCommodMap();
+               if(commodMap == null) {
+                       return;
+               }
+               int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
+               //println(buys.toString());
+               //System.out.println(sells);
+               //System.out.println("\n\n\n"+buys);
+
+               if (uploadToPCTB) {
+                       ByteArrayOutputStream outStream = new ByteArrayOutputStream();
+                       pm.setProgress(60);
+                       pm.setNote("Sending data");
+                       if(pm.isCanceled()) {
+                               return;
+                       }
+                       GZIPOutputStream out = new GZIPOutputStream(outStream);
+                       //FileOutputStream out = new FileOutputStream(new File("output.text"));
+                       DataOutputStream dos = new DataOutputStream(out);
+                       dos.writeBytes("005\n");
+                       dos.writeBytes(stallMap.size()+"\n");
+                       dos.writeBytes(getAbbrevStallList(stallMap));
+                       writeBuySellOffers(buys,sells,offerCount,out);
+                       out.finish();
+                       InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
+                       pm.setProgress(80);
+                       if(pm.isCanceled()) {
+                               return;
+                       }
+                       pm.setNote("Waiting for PCTB...");
+                       finishUpload(in);
+               }
+               pm.setProgress(100);
+       }
+       
+       /**
+       *       Get the offer data out of the table and cache it in an <code>ArrayList</code>.
+       *       
+       *       @param table the <code>AccessibleTable</code> containing the market data
+       *       @return an array of record arrays, each representing a row of the table
+       */
+       private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
+               ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
+               for (int i = 0; i < table.getAccessibleRowCount(); i++) {
+                       ArrayList<String> row = new ArrayList<String>();
+                       for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
+                               row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
+                       }
+                       data.add(row);
+               }
+               return data;
+       }
+       
+       /**
+       *       @return the table containing market data if it exists, otherwise <code>null</code>
+       */
+       public AccessibleTable findMarketTable() {
+               Accessible node1 = window;
+               Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
+               // 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})
+               //System.out.println(node);
+               if (!(node instanceof JTable)) {
+                       node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
+               }
+               if (!(node instanceof JTable)) return null;
+               AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
+               //System.out.println(table);
+               return table;
+       }
+       
+       /**
+       *       Utility method to descend through several levels of Accessible children
+       *       at once.
+       *
+       *       @param parent the node on which to start the descent
+       *       @param path an array of ints, each int being the index of the next
+       *       accessible child to descend.
+       *       @return the <code>Accessible</code> reached by following the descent path,
+       *       or <code>null</code> if the desired path was invalid.
+       */
+       private Accessible descendNodes(Accessible parent, int[] path) {
+               for(int i=0;i<path.length;i++) {
+                       if (null == (parent = descend(parent, path[i]))) return null;
+                       // System.out.println(parent.getClass());
+               }
+               return parent;
+       }
+       
+       /**
+       *       Descends one level to the specified child of the parent <code>Accessible</code> "node".
+       *       
+       *       @param parent the node with children
+       *       @param childNum the index of the child of <code>parent</code> to return
+       *       @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
+       *       if the child is not found.
+       */
+       private Accessible descend(Accessible parent, int childNum) {
+               if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
+               return parent.getAccessibleContext().getAccessibleChild(childNum);
+       }
+       
+       public static void main(String[] args) {
+               new MarketUploader();
+       }
+
+       /**
+       *       Set the global window variable after the YPP window is created,
+       *       remove the top level window listener, and start the GUI
+       */
+       public void topLevelWindowCreated(Window w) {
+               window = w;
+               EventQueueMonitor.removeTopLevelWindowListener(this);
+               createGUI();
+       }
+       
+       /**
+       *       Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
+       *
+       *       @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
+       */
+       private boolean isDisplayAll() {
+               Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
+               if(!(button instanceof JButton)) {
+                       button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
+               }
+               String display = button.getAccessibleContext().getAccessibleName();
+               if(!display.equals("All")) {
+                       return false;
+               }
+               return true;
+       }
+       
+       public void topLevelWindowDestroyed(Window w) {}
+
+       public void guiInitialized() {
+               createGUI();
+       }
+       
+       /**
+       *       Gets the list of commodities and their associated commodity ids.
+       *       On the first run, the data is downloaded from the PCTB server. 
+       *       After the first run, the data is cached using <code>Preferences</code>.
+       *       <p>
+       *       Potential issues: When more commodities are added to the server, this
+       *       program will currently break unless the user deletes the preferences
+       *       file or we give them a new release with a slighly different storage
+       *       location for the data.
+       *
+       *       @return a map where the key is the commodity and the value is the commodity id.
+       */
+       private HashMap<String,Integer> getCommodMap() {
+               if(commodMap != null) {
+                       return commodMap;
+               }
+               HashMap<String,Integer> map = new HashMap<String,Integer>();
+               Preferences prefs = Preferences.userNodeForPackage(getClass());
+               String xml;
+               try {
+                       URL host = new URL(PCTB_HOST_URL + "commodmap.php");
+                       BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
+                       StringBuilder sb = new StringBuilder();
+                       String str;
+                       while((str = br.readLine()) != null) {
+                               sb.append(str);
+                       }
+                       int first = sb.indexOf("<pre>") + 5;
+                       int last = sb.indexOf("</body>");
+                       xml = sb.substring(first,last);
+                       //System.out.println(xml);
+                       Reader reader = new CharArrayReader(xml.toCharArray());
+                       Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
+                       NodeList maps = d.getElementsByTagName("c");
+                       for(int i=0;i<maps.getLength();i++) {
+                               NodeList content = maps.item(i).getChildNodes();
+                               Integer num = Integer.parseInt(content.item(1).getTextContent());
+                               map.put(content.item(0).getTextContent(),num);
+                       }
+               } catch(Exception e) {
+                       e.printStackTrace();
+                       error("Unable to load Commodity list from server!");
+                       return null;
+               }
+               commodMap = map;
+               return map;
+       }
+       
+       /**
+       *       Given the list of offers, this method will find all the unique stall names
+       *       and return them in a <code>LinkedHashMap</code> where the key is the stall name
+       *       and the value is the generated stall id (position in the list).
+       *       <p>
+       *       The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
+       *       for iterating over the stall names in insertion order for output to the server.
+       *
+       *       @param offers the list of records from the commodity buy/sell interface
+       *       @return an iterable ordered map of the stall names and generated stall ids
+       */
+       private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
+               int count = 0;
+               LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
+               for(ArrayList<String> offer : offers) {
+                       String shop = offer.get(1);
+                       if(!map.containsKey(shop)) {
+                               count++;
+                               map.put(shop,count);
+                       }
+               }
+               return map;
+       }
+       
+       /**
+       *       Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
+       *       should be pre-initialized and passed into the method to receive the data.
+       *       Returns a 2-length int array with the number of buys and sells found.
+       *       
+       *       @param offers the data found from the market table in-game
+       *       @param buys an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
+       *       hold the Buy offers.
+       *       @param sells an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
+       *       hold the Sell offers.
+       *       @param stalls the map of stalls to their ids
+       *       @param commodMap the map of commodities to their ids
+       *       @return a 2-length int[] array containing the number of buys and sells, respectively
+       */
+       private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
+                       TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
+               int[] buySellCount = new int[2];
+               for(ArrayList<String> offer : offers) {
+                       try {
+                               if(offer.get(2) != null) {
+                                       buys.add(new Buy(offer,stalls,commodMap));
+                                       buySellCount[0]++;
+                               }
+                               if(offer.get(4) != null) {
+                                       sells.add(new Sell(offer,stalls,commodMap));
+                                       buySellCount[1]++;
+                               }
+                       } catch(IllegalArgumentException e) {
+                               // System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
+                       }
+               }
+               return buySellCount;
+       }
+       
+       /**
+       *       Prepares the list of stalls for writing to the output stream.
+       *       The <code>String</code> returned by this method is ready to be written
+       *       directly to the stream.
+       *       <p>
+       *       All shoppe names are left as they are. Stall names are abbreviated just before the
+       *       apostrophe in the possessive, with an "^" and a letter matching the stall's type
+       *       appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
+       *
+       *       @param stallMap the map of stalls and stall ids in an iterable order
+       *       @return a <code>String</code> containing the list of stalls in format ready
+       *       to be written to the output stream.
+       */
+       private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
+               // set up some mapping
+               HashMap<String,String> types = new HashMap<String,String>();
+               types.put("Apothecary Stall", "A");
+               types.put("Distilling Stall", "D");
+               types.put("Furnishing Stall", "F");
+               types.put("Ironworking Stall", "I");
+               types.put("Shipbuilding Stall", "S");
+               types.put("Tailoring Stall", "T");
+               types.put("Weaving Stall", "W");
+               
+               StringBuilder sb = new StringBuilder();
+               for(String name : stallMap.keySet()) {
+                       int index = name.indexOf("'s");
+                       String finalName = name;
+                       String type = null;
+                       if (index > 0) {
+                               finalName = name.substring(0,index);
+                               if(index + 2 < name.length()) {
+                                       String end = name.substring(index+2,name.length()).trim();
+                                       type = types.get(end);
+                               }
+                       }
+                       if(type==null) {
+                               sb.append(name+"\n");
+                       } else {
+                               sb.append(finalName+"^"+type+"\n");
+                       }
+               }
+               return sb.toString();
+       }
+       
+       /**
+       *       Writes a list of offers in correct format to the output stream.
+       *       <p>
+       *       The format is thus: (all numbers are 2-byte integers in little-endian format)
+       *       (number of offers of this type, aka buy/sell)
+       *       (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]... 
+       *
+       *       @param out the output stream to write the data to
+       *       @param offers the offers to write
+       */
+       private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
+               ByteArrayOutputStream buffer = new ByteArrayOutputStream();
+               if(offers.size() == 0) {
+                       // nothing to write, and "0" has already been written
+                       return;
+               }
+               int commodity = offers.first().commodity;
+               int count = 0;
+               for(Offer offer : offers) {
+                       if(commodity != offer.commodity) {
+                               // write out buffer
+                               writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
+                               buffer.reset();
+                               commodity = offer.commodity;
+                               count = 0;
+                       }
+                       writeLEShort(offer.shoppe,buffer); // stall index
+                       writeLEShort(offer.price,buffer); // buy price
+                       writeLEShort(offer.quantity,buffer); // buy qty
+                       count++;
+               }
+               writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
+       }
+       
+       /**
+       *       Writes the buffered data to the output strea for one commodity.
+       *       
+       *       @param out the stream to write to
+       *       @param buffer the buffered data to write
+       *       @param commodity the commmodity id to write before the buffered data
+       *       @param count the number of offers for this commodity to write before the data
+       */
+       private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
+               writeLEShort(commodity,out); // commod index
+               writeLEShort(count,out); // offer count
+               out.write(buffer); // the buffered offers
+       }
+       
+       /**
+       *       Writes the buy and sell offers to the outputstream by calling other methods.
+       *       
+       *       @param buys list of Buy offers to write
+       *       @param sells list of Sell offers to write
+       *       @param offerCount 2-length int array containing the number of buys and sells to write out
+       *       @param out the stream to write to
+       */
+       private void writeBuySellOffers(TreeSet<Offer> buys,
+                       TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
+               // # buy offers
+               writeLEShort(offerCount[0],out);
+               writeOffers(out,buys);
+               // # sell offers
+               writeLEShort(offerCount[1],out);
+               writeOffers(out,sells);
+       }
+       
+       /**
+       *       Sends the data to the server via multipart-formdata POST,
+       *       with the gzipped data as a file upload.
+       *
+       *       @param file an InputStream open to the gzipped data we want to send
+       */
+       private InputStream sendInitialData(InputStream file) throws IOException {
+               ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
+               http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
+               return http.post();
+       }
+       
+       /**
+       *       Utility method to write a 2-byte int in little-endian form to an output stream.
+       *
+       *       @param num an integer to write
+       *       @param out stream to write to
+       */
+       private void writeLEShort(int num, OutputStream out) throws IOException {
+               out.write(num & 0xFF);
+               out.write((num >>> 8) & 0xFF);
+       }
+       
+       /**
+       *       Reads the response from the server, and selects the correct parameters
+       *       which are sent in a GET request to the server asking it to confirm
+       *       the upload and accept the data into the database. Notably, the island id
+       *       and ocean id are determined, while other parameter such as the filename
+       *       are determined from the hidden form fields.
+       *
+       *       @param in stream of data from the server to read
+       */
+       private void finishUpload(InputStream in) throws IOException {
+               StringBuilder sb = new StringBuilder();
+               BufferedReader br = new BufferedReader(new InputStreamReader(in));
+               String str;
+               while((str = br.readLine()) != null) {
+                       sb.append(str+"\n");
+               }
+               String html = sb.toString();
+               //System.out.println(html);
+               String topIsland = "0", ocean, islandNum, action, forceReload, filename;
+               Matcher m;
+               Pattern whoIsland = Pattern.compile("<option value=\"\\d+\">" + islandName + ", ([^<]+)</ocean>");
+               m = whoIsland.matcher(html);
+               if(m.find()) {
+                       // the server agrees with us
+                       ocean = islandNumbers.get(m.group(1));
+               } else {
+                       // if the server doesn't agree with us:
+                       Pattern island = Pattern.compile("<option value=\"(\\d+)\">([^,]+), ([^<]+)</ocean>");
+                       m = island.matcher(html);
+                       if(!m.find()) {
+                               // server doesn't know what island. if we do, let's select it.
+                               if(islandName != null && !islandName.equals("")) {
+                                       // find the island name in the list as many times as it occurs
+                                       // if more than once, present a dialog
+                                       // set the ocean, we have the islandname, topIsland = 0
+                                       Pattern myIsland = Pattern.compile("islands\\[(\\d+)\\]\\[\\d+\\]=new Option\\(\"" + islandName +
+                                               "\",\\d+");
+                                       Matcher m1 = myIsland.matcher(html);
+                                       ArrayList<Integer> myOceanNums = new ArrayList<Integer>();
+                                       while(m1.find()) {
+                                               myOceanNums.add(new Integer(m1.group(1)));
+                                       }
+                                       if(myOceanNums.size() > 0) {
+                                               if(myOceanNums.size() > 1) {
+                                                       String[] myOceansList = new String[myOceanNums.size()];
+                                                       int i = 0;
+                                                       for(int myOcean : myOceanNums) {
+                                                               Pattern oceanNumPat = Pattern.compile("<option value=\"\\" + myOcean + "\">([^<]+)</option>");
+                                                               m1 = oceanNumPat.matcher(html);
+                                                               if(m1.find()) {
+                                                                       myOceansList[i++] = m1.group(1);
+                                                               }
+                                                       }
+                                                       Object option = JOptionPane.showInputDialog(null,"We found islands named \"" +
+                                                               islandName +"\" on " + myOceansList.length + " oceans:","Choose Ocean",
+                                                               JOptionPane.QUESTION_MESSAGE, null, myOceansList, null);
+                                                       if(option == null) {
+                                                               error("Unable to determine the current island!");
+                                                               return;
+                                                       }
+                                                       ocean = islandNumbers.get(option).toString();
+                                               } else {
+                                                       ocean = myOceanNums.get(0).toString();
+                                               }
+                                       } else {
+                                               error("Unknown island!");
+                                               return;
+                                       }
+                               } else {
+                                       error("Unable to determine island name from the client!");
+                                       return;
+                               }
+                       } else {
+                               topIsland = m.group(1);
+                               islandName = m.group(2);
+                               ocean = islandNumbers.get(m.group(3));
+                       }
+               }
+               Pattern oceanIslandNum = Pattern.compile("islands\\[" + ocean + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
+               m = oceanIslandNum.matcher(html);
+               if(!m.find()) {
+                       error("This does not seem to be a valid island! Unable to upload.");
+                       return;
+               }
+               islandNum = m.group(1);
+               Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
+               m = params.matcher(html);
+               if(!m.find()) {
+                       error("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?");
+                       return;
+               }
+               action = m.group(1);
+               forceReload = m.group(2);
+               filename = m.group(3);
+               URL get = new URL(PCTB_HOST_URL + "upload.php?topisland=" + topIsland + "&ocean=" + ocean + "&island="
+                       + islandNum + "&action=" + action + "&forcereload=" + forceReload + "&filename=" + filename);
+               // System.out.println(get);
+               BufferedReader br2 = new BufferedReader(new InputStreamReader(get.openStream()));
+               sb = new StringBuilder();
+               while((str = br2.readLine()) != null) {
+                       sb.append(str+"\n");
+               }
+               Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
+               m = done.matcher(sb.toString());
+               if(m.find()) {
+                       //System.out.println("FILE upload successful!!!");
+               } else {
+                       error("Something was wrong with the final upload parameters!");
+                       System.err.println(sb.toString());
+                       System.err.println(html);
+               }
+       }
+
+    private String getYarrgTimestamp() throws IOException {
+       ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
+       http.setParameter("clientname", YARRG_CLIENTNAME);
+       http.setParameter("clientversion", YARRG_CLIENTVERSION);
+       http.setParameter("clientfixes", YARRG_CLIENTFIXES);
+       http.setParameter("requesttimestamp", "y");
+       InputStream in = http.post();
+       BufferedReader br = new BufferedReader(new InputStreamReader(in));
+       String tsresult = br.readLine();
+       return tsresult.substring(3, tsresult.length()-1);
+    }
+
+    private void runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
+       ByteArrayOutputStream bos = new ByteArrayOutputStream();
+       BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
+       bufos.write(yarrgdata.getBytes() );
+       bufos.close();
+       ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
+
+       ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
+       http.setParameter("clientname", YARRG_CLIENTNAME);
+       http.setParameter("clientversion", YARRG_CLIENTVERSION);
+       http.setParameter("clientfixes", YARRG_CLIENTFIXES);
+       http.setParameter("timestamp", timestamp);
+       http.setParameter("ocean", ocean);
+       http.setParameter("island", island);
+       http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
+       InputStream in = http.post();
+       BufferedReader br = new BufferedReader(new InputStreamReader(in));
+       String yarrgresult; 
+       while((yarrgresult = br.readLine()) != null) {
+           System.out.println(yarrgresult);
+       }
+    }
+    
+}