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