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