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