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