chiark / gitweb /
pctb: use definite island setting like yarrg
[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 t = findMarketTable();
382                 if(t == null) {
383                         error("Market table not found! Please open the Buy/Sell Commodities interface.");
384                         return;
385                 }
386                 if(t.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                 ArrayList<ArrayList<String>> data = getData(t);
403
404                 if (uploadToYarrg && yarrgts != null) {
405                         pm.setNote("Preparing data for Yarrg");
406                         pm.setProgress(10);
407
408                         StringBuilder yarrgsb = new StringBuilder();
409                         String yarrgdata; // string containing what we'll feed to yarrg
410                 
411                         for (ArrayList<String> row : data) {
412                                 if (row.size() > 6) {
413                                         row.remove(6);
414                                 }
415                                 for (String rowitem : row) {
416                                         yarrgsb.append(rowitem != null ? rowitem : "");
417                                         yarrgsb.append("\t");
418                                 }
419                                 yarrgsb.setLength(yarrgsb.length()-1); // chop
420                                 yarrgsb.append("\n");
421                         }
422
423                         yarrgdata = yarrgsb.toString();
424
425                         pm.setNote("Uploading to Yarrg");
426
427                         if (islandName != null) {
428                                 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
429                         } else {
430                                 System.out.println("Couldn't upload to Yarrg - no island name found");
431                         }
432                 }
433
434                 pm.setNote("Getting stall names");
435                 pm.setProgress(20);
436                 if(pm.isCanceled()) {
437                         return;
438                 }
439                 TreeSet<Offer> buys = new TreeSet<Offer>();
440                 TreeSet<Offer> sells = new TreeSet<Offer>();
441                 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
442                 pm.setProgress(40);
443                 pm.setNote("Sorting offers");
444                 if(pm.isCanceled()) {
445                         return;
446                 }
447                 // get commod map
448                 
449                 HashMap<String,Integer> commodMap = getCommodMap();
450                 if(commodMap == null) {
451                         return;
452                 }
453                 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
454                 //println(buys.toString());
455                 //System.out.println(sells);
456                 //System.out.println("\n\n\n"+buys);
457
458                 if (uploadToPCTB) {
459                         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
460                         pm.setProgress(60);
461                         pm.setNote("Sending data");
462                         if(pm.isCanceled()) {
463                                 return;
464                         }
465                         GZIPOutputStream out = new GZIPOutputStream(outStream);
466                         //FileOutputStream out = new FileOutputStream(new File("output.text"));
467                         DataOutputStream dos = new DataOutputStream(out);
468                         dos.writeBytes("005y\n");
469                         dos.writeBytes(stallMap.size()+"\n");
470                         dos.writeBytes(getAbbrevStallList(stallMap));
471                         writeBuySellOffers(buys,sells,offerCount,out);
472                         out.finish();
473                         InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
474                         if (in == null) return;
475                         pm.setProgress(80);
476                         if(pm.isCanceled()) {
477                                 return;
478                         }
479                         pm.setNote("Waiting for PCTB...");
480                         donepctb = finishUpload(in);
481                 }
482                 pm.setProgress(100);
483
484                 if ((uploadToPCTB && !donepctb) ||
485                     (uploadToYarrg && !doneyarrg)) {
486                         resultSummary.setText("trouble");
487                 } else if (donepctb || doneyarrg) {
488                         resultSummary.setText("Done " + islandName);
489                 } else {
490                         resultSummary.setText("uploaded nowhere!");
491                 }
492         }
493         
494         /**
495         *       Get the offer data out of the table and cache it in an <code>ArrayList</code>.
496         *       
497         *       @param table the <code>AccessibleTable</code> containing the market data
498         *       @return an array of record arrays, each representing a row of the table
499         */
500         private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
501                 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
502                 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
503                         ArrayList<String> row = new ArrayList<String>();
504                         for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
505                                 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
506                         }
507                         data.add(row);
508                 }
509                 return data;
510         }
511         
512         /**
513         *       @return the table containing market data if it exists, otherwise <code>null</code>
514         */
515         public AccessibleTable findMarketTable() {
516                 Accessible node1 = window;
517                 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
518                 // 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})
519                 //System.out.println(node);
520                 if (!(node instanceof JTable)) {
521                         node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
522                 }
523                 if (!(node instanceof JTable)) return null;
524                 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
525                 //System.out.println(table);
526                 return table;
527         }
528         
529         /**
530         *       Utility method to descend through several levels of Accessible children
531         *       at once.
532         *
533         *       @param parent the node on which to start the descent
534         *       @param path an array of ints, each int being the index of the next
535         *       accessible child to descend.
536         *       @return the <code>Accessible</code> reached by following the descent path,
537         *       or <code>null</code> if the desired path was invalid.
538         */
539         private Accessible descendNodes(Accessible parent, int[] path) {
540                 for(int i=0;i<path.length;i++) {
541                         if (null == (parent = descend(parent, path[i]))) return null;
542                         // System.out.println(parent.getClass());
543                 }
544                 return parent;
545         }
546         
547         /**
548         *       Descends one level to the specified child of the parent <code>Accessible</code> "node".
549         *       
550         *       @param parent the node with children
551         *       @param childNum the index of the child of <code>parent</code> to return
552         *       @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
553         *       if the child is not found.
554         */
555         private Accessible descend(Accessible parent, int childNum) {
556                 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
557                 return parent.getAccessibleContext().getAccessibleChild(childNum);
558         }
559         
560         public static void main(String[] args) {
561                 new MarketUploader();
562         }
563
564         /**
565         *       Set the global window variable after the YPP window is created,
566         *       remove the top level window listener, and start the GUI
567         */
568         public void topLevelWindowCreated(Window w) {
569                 window = w;
570                 EventQueueMonitor.removeTopLevelWindowListener(this);
571                 createGUI();
572         }
573         
574         /**
575         *       Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
576         *
577         *       @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
578         */
579         private boolean isDisplayAll() {
580                 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
581                 if(!(button instanceof JButton)) {
582                         button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
583                 }
584                 String display = button.getAccessibleContext().getAccessibleName();
585                 if(!display.equals("All")) {
586                         return false;
587                 }
588                 return true;
589         }
590         
591         public void topLevelWindowDestroyed(Window w) {}
592
593         public void guiInitialized() {
594                 createGUI();
595         }
596         
597         /**
598         *       Gets the list of commodities and their associated commodity ids.
599         *       On the first run, the data is downloaded from the PCTB server. 
600         *       After the first run, the data is cached using <code>Preferences</code>.
601         *       <p>
602         *       Potential issues: When more commodities are added to the server, this
603         *       program will currently break unless the user deletes the preferences
604         *       file or we give them a new release with a slighly different storage
605         *       location for the data.
606         *
607         *       @return a map where the key is the commodity and the value is the commodity id.
608         */
609         private HashMap<String,Integer> getCommodMap() {
610                 if(commodMap != null) {
611                         return commodMap;
612                 }
613                 HashMap<String,Integer> map = new HashMap<String,Integer>();
614                 Preferences prefs = Preferences.userNodeForPackage(getClass());
615                 String xml;
616                 try {
617                         URL host = new URL(PCTB_HOST_URL + "commodmap.php");
618                         BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
619                         StringBuilder sb = new StringBuilder();
620                         String str;
621                         while((str = br.readLine()) != null) {
622                                 sb.append(str);
623                         }
624                         int first = sb.indexOf("<pre>") + 5;
625                         int last = sb.indexOf("</body>");
626                         xml = sb.substring(first,last);
627                         //System.out.println(xml);
628                         Reader reader = new CharArrayReader(xml.toCharArray());
629                         Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
630                         NodeList maps = d.getElementsByTagName("CommodMap");
631                         for(int i=0;i<maps.getLength();i++) {
632                                 NodeList content = maps.item(i).getChildNodes();
633                                 Integer num = Integer.parseInt(content.item(1).getTextContent());
634                                 map.put(content.item(0).getTextContent(),num);
635                         }
636                 } catch(Exception e) {
637                         e.printStackTrace();
638                         error("Unable to load Commodity list from server!");
639                         return null;
640                 }
641                 commodMap = map;
642                 return map;
643         }
644         
645         /**
646         *       Given the list of offers, this method will find all the unique stall names
647         *       and return them in a <code>LinkedHashMap</code> where the key is the stall name
648         *       and the value is the generated stall id (position in the list).
649         *       <p>
650         *       The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
651         *       for iterating over the stall names in insertion order for output to the server.
652         *
653         *       @param offers the list of records from the commodity buy/sell interface
654         *       @return an iterable ordered map of the stall names and generated stall ids
655         */
656         private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
657                 int count = 0;
658                 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
659                 for(ArrayList<String> offer : offers) {
660                         String shop = offer.get(1);
661                         if(!map.containsKey(shop)) {
662                                 count++;
663                                 map.put(shop,count);
664                         }
665                 }
666                 return map;
667         }
668         
669         /**
670         *       Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
671         *       should be pre-initialized and passed into the method to receive the data.
672         *       Returns a 2-length int array with the number of buys and sells found.
673         *       
674         *       @param offers the data found from the market table in-game
675         *       @param buys an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
676         *       hold the Buy offers.
677         *       @param sells an empty initialized <code>TreeSet&lt;Offer&gt;</code> to
678         *       hold the Sell offers.
679         *       @param stalls the map of stalls to their ids
680         *       @param commodMap the map of commodities to their ids
681         *       @return a 2-length int[] array containing the number of buys and sells, respectively
682         */
683         private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
684                         TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
685                 int[] buySellCount = new int[2];
686                 for(ArrayList<String> offer : offers) {
687                         try {
688                                 if(offer.get(2) != null) {
689                                         buys.add(new Buy(offer,stalls,commodMap));
690                                         buySellCount[0]++;
691                                 }
692                                 if(offer.get(4) != null) {
693                                         sells.add(new Sell(offer,stalls,commodMap));
694                                         buySellCount[1]++;
695                                 }
696                         } catch(IllegalArgumentException e) {
697                                 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
698                         }
699                 }
700                 if (buySellCount[0]==0 && buySellCount[1]==0) {
701                     error("No (valid) offers for PCTB?!");
702                     throw new IllegalArgumentException();
703                 }
704                 return buySellCount;
705         }
706         
707         /**
708         *       Prepares the list of stalls for writing to the output stream.
709         *       The <code>String</code> returned by this method is ready to be written
710         *       directly to the stream.
711         *       <p>
712         *       All shoppe names are left as they are. Stall names are abbreviated just before the
713         *       apostrophe in the possessive, with an "^" and a letter matching the stall's type
714         *       appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
715         *
716         *       @param stallMap the map of stalls and stall ids in an iterable order
717         *       @return a <code>String</code> containing the list of stalls in format ready
718         *       to be written to the output stream.
719         */
720         private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
721                 // set up some mapping
722                 HashMap<String,String> types = new HashMap<String,String>();
723                 types.put("Apothecary Stall", "A");
724                 types.put("Distilling Stall", "D");
725                 types.put("Furnishing Stall", "F");
726                 types.put("Ironworking Stall", "I");
727                 types.put("Shipbuilding Stall", "S");
728                 types.put("Tailoring Stall", "T");
729                 types.put("Weaving Stall", "W");
730                 
731                 StringBuilder sb = new StringBuilder();
732                 for(String name : stallMap.keySet()) {
733                         int index = name.indexOf("'s");
734                         String finalName = name;
735                         String type = null;
736                         if (index > 0) {
737                                 finalName = name.substring(0,index);
738                                 if(index + 2 < name.length()) {
739                                         String end = name.substring(index+2,name.length()).trim();
740                                         type = types.get(end);
741                                 }
742                         }
743                         if(type==null) {
744                                 sb.append(name+"\n");
745                         } else {
746                                 sb.append(finalName+"^"+type+"\n");
747                         }
748                 }
749                 return sb.toString();
750         }
751         
752         /**
753         *       Writes a list of offers in correct format to the output stream.
754         *       <p>
755         *       The format is thus: (all numbers are 2-byte integers in little-endian format)
756         *       (number of offers of this type, aka buy/sell)
757         *       (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]... 
758         *
759         *       @param out the output stream to write the data to
760         *       @param offers the offers to write
761         */
762         private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
763                 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
764                 if(offers.size() == 0) {
765                         // nothing to write, and "0" has already been written
766                         return;
767                 }
768                 int commodity = offers.first().commodity;
769                 int count = 0;
770                 for(Offer offer : offers) {
771                         if(commodity != offer.commodity) {
772                                 // write out buffer
773                                 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
774                                 buffer.reset();
775                                 commodity = offer.commodity;
776                                 count = 0;
777                         }
778                         writeLEShort(offer.shoppe,buffer); // stall index
779                         writeLEShort(offer.price,buffer); // buy price
780                         writeLEShort(offer.quantity,buffer); // buy qty
781                         count++;
782                 }
783                 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
784         }
785         
786         /**
787         *       Writes the buffered data to the output strea for one commodity.
788         *       
789         *       @param out the stream to write to
790         *       @param buffer the buffered data to write
791         *       @param commodity the commmodity id to write before the buffered data
792         *       @param count the number of offers for this commodity to write before the data
793         */
794         private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
795                 writeLEShort(commodity,out); // commod index
796                 writeLEShort(count,out); // offer count
797                 out.write(buffer); // the buffered offers
798         }
799         
800         /**
801         *       Writes the buy and sell offers to the outputstream by calling other methods.
802         *       
803         *       @param buys list of Buy offers to write
804         *       @param sells list of Sell offers to write
805         *       @param offerCount 2-length int array containing the number of buys and sells to write out
806         *       @param out the stream to write to
807         */
808         private void writeBuySellOffers(TreeSet<Offer> buys,
809                         TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
810                 // # buy offers
811                 writeLEShort(offerCount[0],out);
812                 writeOffers(out,buys);
813                 // # sell offers
814                 writeLEShort(offerCount[1],out);
815                 writeOffers(out,sells);
816         }
817         
818         private String readstreamstring(InputStream in) throws IOException {
819                 StringBuilder sb = new StringBuilder();
820                 BufferedReader br = new BufferedReader(new InputStreamReader(in));
821                 String str;
822                 while((str = br.readLine()) != null) {
823                         sb.append(str+"\n");
824                 }
825                 return sb.toString();
826         }
827
828         /**
829         *       Sends the data to the server via multipart-formdata POST,
830         *       with the gzipped data as a file upload.
831         *
832         *       @param file an InputStream open to the gzipped data we want to send
833         */
834         private InputStream sendInitialData(InputStream file) throws IOException {
835                 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
836                 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
837                 if (!http.post()) {
838                         String err = readstreamstring(http.resultstream());
839                         error("Error sending initial data:\n"+err);
840                         return null;
841                 }
842                 return http.resultstream();
843         }
844         
845         /**
846         *       Utility method to write a 2-byte int in little-endian form to an output stream.
847         *
848         *       @param num an integer to write
849         *       @param out stream to write to
850         */
851         private void writeLEShort(int num, OutputStream out) throws IOException {
852                 out.write(num & 0xFF);
853                 out.write((num >>> 8) & 0xFF);
854         }
855         
856         /**
857         *       Reads the response from the server, and selects the correct parameters
858         *       which are sent in a GET request to the server asking it to confirm
859         *       the upload and accept the data into the database. Notably, the island id
860         *       and ocean id are determined, while other parameter such as the filename
861         *       are determined from the hidden form fields.
862         *
863         *       @param in stream of data from the server to read
864         */
865         private boolean finishUpload(InputStream in) throws IOException {
866                 String html = readstreamstring(in);
867                 //System.out.println(html);
868                 Matcher m;
869
870                 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
871                 m = params.matcher(html);
872                 if(!m.find()) {
873                         error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
874                                    html);
875                         return false;
876                 }
877                 String forceReload = m.group(1);
878                 String filename = m.group(2);
879
880                 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
881                 m = oceanNumPat.matcher(html);
882                 if (!m.find()) {
883                         error_html("Unable to find the ocean in the server's list of oceans!", html);
884                         return false;
885                 }
886                 String oceanNum = m.group(1);
887
888                 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
889                 m = oceanIslandNum.matcher(html);
890                 if(!m.find()) {
891                         error_html("This does not seem to be a valid island! Unable to upload.", html);
892                         return false;
893                 }
894                 String islandNum = m.group(1);
895
896                 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
897                         + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
898                 String complete = readstreamstring(get.openStream());
899                 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
900                 m = done.matcher(complete);
901                 if(m.find()) {
902                         System.out.println("FILE upload successful!!!");
903                         return true;
904                 } else {
905                         error_html("Something was wrong with the final upload parameters!", complete);
906                         return false;
907                 }
908         }
909
910     private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
911         if (!http.post()) {
912             String err = readstreamstring(http.resultstream());
913             error("<html><h1>Error reported by YARRG server</h1>\n" + err);
914             return null;
915         }
916         return http.resultstream();
917     }
918
919     private String getYarrgTimestamp() throws IOException {
920         ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
921         http.setParameter("clientname", YARRG_CLIENTNAME);
922         http.setParameter("clientversion", YARRG_CLIENTVERSION);
923         http.setParameter("clientfixes", YARRG_CLIENTFIXES);
924         http.setParameter("requesttimestamp", "y");
925         InputStream in = post_for_yarrg(http);
926         if (in == null) return null;
927         BufferedReader br = new BufferedReader(new InputStreamReader(in));
928         String tsresult = br.readLine();
929         return tsresult.substring(3, tsresult.length()-1);
930     }
931
932     private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
933         ByteArrayOutputStream bos = new ByteArrayOutputStream();
934         BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
935         bufos.write(yarrgdata.getBytes() );
936         bufos.close();
937         ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
938
939         ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
940         http.setParameter("clientname", YARRG_CLIENTNAME);
941         http.setParameter("clientversion", YARRG_CLIENTVERSION);
942         http.setParameter("clientfixes", YARRG_CLIENTFIXES);
943         http.setParameter("timestamp", timestamp);
944         http.setParameter("ocean", ocean);
945         http.setParameter("island", island);
946         http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
947         InputStream in = post_for_yarrg(http);
948         if (in == null) return false;
949         BufferedReader br = new BufferedReader(new InputStreamReader(in));
950         String yarrgresult; 
951         while((yarrgresult = br.readLine()) != null) {
952             System.out.println(yarrgresult);
953         }
954         return true;
955     }
956     
957 }