1 package net.chiark.yarrg;
4 import java.awt.event.*;
6 import javax.accessibility.*;
9 import com.sun.java.accessibility.util.*;
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;
25 * MarketUploader is a class that handles the uploading of market
26 * data from Yohoho! Puzzle Pirates via the Java Accessibility
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.
37 public class MarketUploader
38 implements Runnable, TopLevelWindowListener, GUIInitializedListener {
39 private JFrame frame = null;
40 private Window window = null;
41 private JButton findMarket = null;
42 private JLabel resultSummary = null;
43 private JLabel arbitrageResult = null;
44 private int unknownPCTBcommods = 0;
45 private long startTime = 0;
47 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
48 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
49 private String PCTB_HOST_URL;
51 // Yarrg protocol parameters
52 private final static String YARRG_CLIENTNAME = "jpctb greenend";
53 private final static String YARRG_CLIENTVERSION =
54 net.chiark.yarrg.Version.version;
55 private final static String YARRG_CLIENTFIXES = "bug-094";
56 private final static String YARRG_LIVE_URL =
57 "http://upload.yarrg.chiark.net/commod-update-receiver";
58 private final static String YARRG_TEST_URL =
59 "http://upload.yarrg.chiark.net/test/commod-update-receiver";
60 private String YARRG_URL;
62 private boolean uploadToYarrg;
63 private boolean uploadToPCTB;
64 private boolean showArbitrage;
66 private String islandName = null;
67 private String oceanName = null;
68 private java.util.concurrent.CountDownLatch latch = null;
70 private AccessibleContext sidePanel;
71 private HashMap<String,Integer> commodMap;
72 public PrintStream dtxt = null;
74 private PropertyChangeListener changeListener = new PropertyChangeListener() {
75 public void propertyChange(PropertyChangeEvent e) {
76 if(e.getNewValue() != null &&
77 e.getPropertyName().equals
78 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
79 Accessible islandInfo =
80 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
82 islandInfo.getAccessibleContext().getAccessibleText()
83 .getAtIndex(AccessibleText.SENTENCE,0);
84 int index = text.indexOf(":");
85 String name = text.substring(0,index);
87 // if (dtxt!=null) dtxt.println(islandName);
88 sidePanel.removePropertyChangeListener(this);
95 * UTILITY METHODS AND SUBCLASSES
97 * Useable on any thread.
100 private int parseQty(String str) {
101 if (str.equals(">1000")) {
104 return Integer.parseInt(str);
108 private void progresslog(String s) {
109 if (dtxt == null) return;
110 long now = new Date().getTime();
111 dtxt.println("progress "+(now - startTime)+"ms "+s);
114 private void debug_write_stringdata(String what, String data)
115 throws FileNotFoundException,IOException {
116 if (dtxt==null) return;
117 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
122 private void debug_write_bytes(String what, byte[] data)
123 throws FileNotFoundException,IOException {
124 if (dtxt==null) return;
125 FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
131 * An abstract market offer, entailing a commodity being bought or sold by
132 * a shoppe, for a certain price in a certain quantity. Not instantiable.
137 abstract class Offer {
138 public int commodity, price, quantity, shoppe;
140 * Create an offer from <code>record</code>, determining the shoppe Id from
141 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
142 * <code>priceIndex</code> should be the index of the price in the record
143 * (the quantity will be <code>priceIndex + 1</code>).
145 * @param record the record with data to create the offer from
146 * @param stallMap a map containing the ids of the various stalls
147 * @param commodMap a map containing the ids of the various commodities
148 * @param priceIndex the index of the price in the record
150 public Offer(ArrayList<String> record,
151 LinkedHashMap<String,Integer> stallMap,
152 HashMap<String,Integer> commodMap,
154 Integer commodId = commodMap.get(record.get(0));
155 if(commodId == null) {
156 throw new IllegalArgumentException();
158 commodity = commodId.intValue();
159 price = Integer.parseInt(record.get(priceIndex));
160 String qty = record.get(priceIndex+1);
161 quantity = parseQty(qty);
162 shoppe = stallMap.get(record.get(1)).intValue();
166 * Returns a human-readable version of this offer, useful for debugging
168 * @return human-readable offer
170 public String toString() {
171 return "[C:" + commodity + ",$" + price + ",Q:"
172 + quantity + ",S:" + shoppe + "]";
177 * An offer from a shoppe or stall to buy a certain quantity of a
178 * commodity for a certain price. If placed in an ordered Set,
179 * sorts by commodity index ascending, then by buy price
180 * descending, and finally by stall id ascending.
182 class Buy extends Offer implements Comparable<Buy> {
184 * Creates a new <code>Buy</code> offer from the given
185 * <code>record</code> using the other parameters to determine
186 * stall id and commodity id of the offer.
188 * @param record the record with data to create the offer from
189 * @param stallMap a map containing the ids of the various stalls
190 * @param commodMap a map containing the ids of the various commodities
192 public Buy(ArrayList<String> record,
193 LinkedHashMap<String,Integer> stallMap,
194 HashMap<String,Integer> commodMap) {
195 super(record,stallMap,commodMap,2);
199 * Sorts by commodity index ascending, then price descending,
200 * then stall id ascending.
202 public int compareTo(Buy buy) {
203 // organize by: commodity index, price, stall index
204 if(commodity == buy.commodity) {
205 // organize by price, then by stall index
206 if(price == buy.price) {
207 // organize by stall index
208 return shoppe>buy.shoppe ? 1 : -1;
209 } else if(price > buy.price) {
214 } else if(commodity > buy.commodity) {
223 * An offer from a shoppe or stall to sell a certain quantity of
224 * a commodity for a certain price. If placed in an ordered Set,
225 * sorts by commodity index ascending, then by sell price
226 * ascending, and finally by stall id ascending.
228 class Sell extends Offer implements Comparable<Sell> {
230 * Creates a new <code>Sell</code> offer from the given
231 * <code>record</code> using the other parameters to determine
232 * stall id and commodity id of the offer.
234 * @param record the record with data to create the offer from
235 * @param stallMap a map containing the ids of the various stalls
236 * @param commodMap a map containing the ids of the various commodities
238 public Sell(ArrayList<String> record,
239 LinkedHashMap<String,Integer> stallMap,
240 HashMap<String,Integer> commodMap) {
241 super(record,stallMap,commodMap,4);
245 * Sorts by commodity index ascending, then price ascending, then
246 * stall id ascending.
248 public int compareTo(Sell sell) {
249 // organize by: commodity index, price, stall index
250 if(commodity == sell.commodity) {
251 // organize by price, then by stall index
252 if(price == sell.price) {
253 // organize by stall index
254 return shoppe>sell.shoppe ? 1 : -1;
255 } else if(price > sell.price) {
260 } else if(commodity > sell.commodity) {
268 private void progressNote(ProgressMonitor pm, String s) {
270 new UI() { public void body() {
271 if (arbitrageResult != null)
272 arb = arbitrageResult.getText();
273 if (arb != null && arb.length() != 0)
274 s = "<html>" + arb + "<br>" + s;
280 * ENTRY POINT AND STARTUP
282 * Main thread and/or event thread
285 * Entry point. Read our preferences.
287 public MarketUploader() {
288 Preferences prefs = Preferences.userNodeForPackage(getClass());
290 if (prefs.getBoolean("writeDebugFiles", false)) {
292 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
293 } catch (java.io.FileNotFoundException e) {
294 System.err.println("JARRG: Error opening debug log: "+e);
298 if (prefs.getBoolean("useLiveServers", true)) {
299 YARRG_URL = YARRG_LIVE_URL;
300 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
302 YARRG_URL = YARRG_TEST_URL;
303 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
306 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
307 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
308 showArbitrage=prefs.getBoolean("showArbitrage", true);
310 if (dtxt!=null) dtxt.println("main on dispatch thread: "+
311 EventQueue.isDispatchThread());
312 EventQueue.invokeLater(this);
316 * We arrange to wait for the GUI to be initialised, then look at
317 * every top-level window, and if it
320 if (dtxt!=null) dtxt.println("MarketUploader run()...");
321 if (EventQueueMonitor.isGUIInitialized()) {
322 if (dtxt!=null) dtxt.println("MarketUploader GUI already ready");
325 if (dtxt!=null) dtxt.println("MarketUploader waiting for GUI");
326 EventQueueMonitor.addGUIInitializedListener(this);
330 public void guiInitialized() {
331 Window ws[]= EventQueueMonitor.getTopLevelWindows();
332 EventQueueMonitor.addTopLevelWindowListener(this);
333 for (int i=0; i<ws.length; i++) {
334 if (dtxt!=null) dtxt.println("MarketUploader existing toplevel "+i);
335 topLevelWindowCreated(ws[i]);
339 public void topLevelWindowDestroyed(Window w) {
340 if (dtxt!=null) dtxt.println("MarketUploader destroyed toplevel");
343 public void topLevelWindowCreated(Window w) {
347 String name = w.getAccessibleContext().getAccessibleName();
348 if (dtxt!=null) dtxt.println("MarketUploader new toplevel "+name);
349 if (!name.equals("Puzzle Pirates"))
351 if (dtxt!=null) dtxt.println("MarketUploader found toplevel, creating gui");
354 frame.setVisible(true);
358 * Set up the GUI, with its window and one-button
359 * interface. Only initialize if we're running alongside
360 * a Window named "Puzzle Pirates" though.
362 private void createGUI() {
364 frame = new JFrame("Jarrg Uploader");
365 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
366 GridLayout layout = new GridLayout(2,1);
367 frame.getContentPane().setLayout(layout);
368 //frame.setPreferredSize(new Dimension(200, 60));
370 findMarket = new JButton("Upload Market Data");
371 findMarket.addActionListener(new ActionListener() {
372 public void actionPerformed(ActionEvent e) {
373 findMarket.setEnabled(false);
374 resultSummary.setText("");
375 arbitrageResult.setText("");
378 startTime = new Date().getTime();
379 unknownPCTBcommods = 0;
382 } catch(Exception e) {
386 EventQueue.invokeAndWait(new Runnable() { public void run() {
387 if(sidePanel != null) {
388 sidePanel.removePropertyChangeListener(changeListener);
390 findMarket.setEnabled(true);
396 frame.add(findMarket);
398 resultSummary = new JLabel("ready");
399 frame.add(resultSummary);
401 arbitrageResult = new JLabel("");
404 layout.setRows(layout.getRows() + 1);
405 frame.add(arbitrageResult);
412 * ERROR REPORTING AND GENERAL UTILITIES
414 * Synchronous modal dialogues
415 * error and error_html may be called from any thread
418 private Class UI implements Runnable {
419 public virtual void body();
420 public void run() { body(); };
422 if (EventQueue.isDispatchThread()) {
430 private void error(String msg) {
431 new UI() { public booolean body() {
432 resultSummary.setText("failed");
433 JOptionPane.showMessageDialog(frame,msg,"Error",
434 JOptionPane.ERROR_MESSAGE);
439 private void error_html(String msg, String html) {
440 Pattern body = Pattern.compile("<body>(.*)</body>",
441 Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
442 Matcher m = body.matcher(html);
445 Pattern fixup = Pattern.compile("<(\\w+) */>");;
446 m = fixup.matcher(html);
447 html = m.replaceAll("<$1>");
448 m = Pattern.compile("[\\r\\n]+").matcher(html);
449 html = m.replaceAll(" ");
451 String whole_msg = "<html><h1>Error</h1>"+msg
452 +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
453 if (dtxt!=null) dtxt.println("###" + whole_msg + "###");
459 * GUI MANIPULATION CALLBACKS
462 private PropertyChangeListener changeListener = new PropertyChangeListener() {
463 public void propertyChange(PropertyChangeEvent e) {
464 if(e.getNewValue() != null &&
465 e.getPropertyName().equals
466 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
467 Accessible islandInfo =
468 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
469 String text = islandInfo.getAccessibleContext().getAccessibleText()
470 .getAtIndex(AccessibleText.SENTENCE,0);
471 int index = text.indexOf(":");
472 String name = text.substring(0,index);
474 // if (dtxt!=null) dtxt.println(islandName);
475 sidePanel.removePropertyChangeListener(this);
481 private void getIsland() {
482 // runs on event thread
484 // If the league tracker is there, we can skip the faff
485 // and ask for its tooltip, since we're on a boat
487 Accessible leagueTrackerContainer =
488 descendNodes(window,new int[] {0,1,0,0,2,1});
489 Accessible leagueTrackerItself =
490 descendByClass(leagueTrackerContainer,
491 "com.threerings.yohoho.sea.client.LeagueTracker");
492 Accessible leagueTracker = descend(leagueTrackerItself, 1);
494 islandName = ((JLabel)leagueTracker).getToolTipText();
495 } catch (NullPointerException e) {
496 // evidently we're actually on an island
499 AccessibleContext chatArea =
500 descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
501 .getAccessibleContext();
502 // attach the property change listener to the outer sunshine
503 // panel if the "ahoy" tab is not active, otherwise attach it to
504 // the scroll panel in the "ahoy" tab.
505 if(!"com.threerings.piracy.client.AttentionListPanel".
506 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
507 .getClass().getCanonicalName())) {
508 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
509 .getAccessibleContext();
511 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
512 .getAccessibleContext();
514 sidePanel.addPropertyChangeListener(changeListener);
515 latch = new java.util.concurrent.CountDownLatch(1);
516 // make the Players Online ("/who") panel appear
517 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
518 chat.setTextContents("/w");
519 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
520 for(int i=0;i<c;i++) {
521 if("notify-field-accept".equals(chatArea.getAccessibleAction()
522 .getAccessibleActionDescription(i))) {
523 chatArea.getAccessibleAction().doAccessibleAction(i);
530 * Find the ocean name from the window title, and set global
533 private void getOcean() {
534 // runs on event thread
536 AccessibleContext topwindow = window.getAccessibleContext();
537 oceanName = topwindow.getAccessibleName()
538 .replaceAll(".*on the (\\w+) ocean", "$1");
543 * Run the data collection process, and upload the results. This
544 * is the method that calls most of the other worker methods for
545 * the process. If an error occurs, the method will call the
546 * error method and return early, freeing up the button to be
549 * @exception Exception if an error we didn't expect occured
551 private class YarrgTimestampFetcher extends Thread {
552 public String ts = null;
555 ts = getYarrgTimestamp();
556 progresslog("(async) yarrg timestamp ready.");
557 } catch(Exception e) {
558 error("Error getting YARRG timestamp: "+e);
563 private void runUpload() throws Exception {
564 boolean doneyarrg = false, donepctb = false;
565 YarrgTimestampFetcher yarrgts_thread = null;
567 progresslog("starting");
570 progresslog("(async) yarrg timestamp...");
571 yarrgts_thread = new YarrgTimestampFetcher();
572 yarrgts_thread.start();
575 AccessibleTable accesstable = null;
576 new UI() { public boolean body() {
577 ProgressMonitor pm = new ProgressMonitor
578 (frame,"Processing Market Data","Getting table data",0,100);
579 pm.setMillisToDecideToPopup(0);
580 pm.setMillisToPopup(0);
582 accesstable = findMarketTable();
583 if(accesstable == null) {
584 error("Market table not found!"+
585 " Please open the Buy/Sell Commodities interface.");
588 if(accesstable.getAccessibleRowCount() == 0) {
589 error("No data found, please wait for the table to have data first!");
592 if(!isDisplayAll()) {
593 error("Please select \"All\" from the Display: popup menu.");
597 progresslog("(async) getisland...");
599 progresslog("getocean...");
601 progresslog("getocean done");
603 if (accesstable == null) return;
606 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
608 progresslog("(async) getisland done");
610 String yarrgts = null;
611 if (yarrgts_thread != null) {
612 progresslog("(async) yarrg timestamp join...");
613 yarrgts_thread.join();
614 progresslog("(async) yarrg timestamp joined.");
615 yarrgts = yarrgts_thread.ts;
618 if (islandName == null) {
619 error("Could not find island name in YPP user interface.");
623 progresslog("table check...");
625 ArrayList<ArrayList<String>> data = null;
626 String headings_expected[] = new String[]
627 { "Commodity", "Trading outlet", "Buy price",
628 "Will buy", "Sell price", "Will sell" };
630 new UI() { public void body() {
631 ArrayList<ArrayList<String>> headers =
632 getData(accesstable.getAccessibleColumnHeader());
633 if (headers.size() != 1) {
634 error("Table headings not one row! " + headers.toString());
637 if (headers.get(0).size() < 6 ||
638 headers.get(0).size() > 7) {
639 error("Table headings not six or seven columns! " + headers.toString());
642 for (int col=0; col<headings_expected.length; col++) {
643 String expd = headings_expected[col];
644 String got = headers.get(0).get(col);
645 if (expd.compareTo(got) != 0) {
646 error("Table heading for column "+col
647 +" is not \""+expd+"\" but \""+got+"\".\n\n"
648 +"Please do not reorder the table when using this tool.");
653 progresslog("table read...");
655 ArrayList<ArrayList<String>> data = getData(accesstable);
660 progresslog("arbitrage...");
661 calculateArbitrage(data);
662 progresslog("arbitrage done.");
665 if (uploadToYarrg && yarrgts != null) {
666 progresslog("yarrg prepare...");
667 progressNote(pm, "Yarrg: Preparing data");
670 StringBuilder yarrgsb = new StringBuilder();
671 String yarrgdata; // string containing what we'll feed to yarrg
673 for (ArrayList<String> row : data) {
674 if (row.size() > 6) {
677 for (String rowitem : row) {
678 yarrgsb.append(rowitem != null ? rowitem : "");
679 yarrgsb.append("\t");
681 yarrgsb.setLength(yarrgsb.length()-1); // chop
682 yarrgsb.append("\n");
685 yarrgdata = yarrgsb.toString();
687 progressNote(pm, "Yarrg: Uploading");
688 progresslog("yarrg upload...");
690 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
691 progresslog("yarrg done.");
695 progresslog("pctb prepare...");
696 progressNote(pm, "PCTB: Getting stall names");
698 if(pm.isCanceled()) {
701 TreeSet<Offer> buys = new TreeSet<Offer>();
702 TreeSet<Offer> sells = new TreeSet<Offer>();
703 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
705 progressNote(pm, "PCTB: Sorting offers");
706 if(pm.isCanceled()) {
711 progresslog("pctb commodmap...");
712 HashMap<String,Integer> commodMap = getCommodMap();
713 if(commodMap == null) {
716 progresslog("pctb commodmap done.");
717 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
718 // if (dtxt!=null) dtxt.println(sells);
719 // if (dtxt!=null) dtxt.println("\n\n\n"+buys);
721 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
723 progressNote(pm, "PCTB: Sending data");
724 if(pm.isCanceled()) {
727 GZIPOutputStream out = new GZIPOutputStream(outStream);
728 DataOutputStream dos = new DataOutputStream(out);
729 dos.writeBytes("005y\n");
730 dos.writeBytes(stallMap.size()+"\n");
731 dos.writeBytes(getAbbrevStallList(stallMap));
732 writeBuySellOffers(buys,sells,offerCount,out);
734 progresslog("pctb send...");
736 byte[] ba = outStream.toByteArray();
737 debug_write_bytes("pctb-marketdata.gz", ba);
739 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
740 progresslog("pctb sent.");
741 if (in == null) return;
743 if(pm.isCanceled()) {
746 progressNote(pm, "PCTB: Waiting ...");
747 progresslog("pctb finish...");
748 donepctb = finishUpload(in);
749 progresslog("pctb done.");
753 if ((uploadToPCTB && !donepctb) ||
754 (uploadToYarrg && !doneyarrg)) {
755 resultSummary.setText("trouble");
756 } else if (unknownPCTBcommods != 0) {
757 resultSummary.setText("PCTB lacks "+unknownPCTBcommods+" commod");
758 } else if (donepctb || doneyarrg) {
759 resultSummary.setText("Done " + islandName);
761 resultSummary.setText("uploaded nowhere!");
763 progresslog("done.");
767 * Get the offer data out of the table and cache it in an
768 * <code>ArrayList</code>.
770 * @param table the <code>AccessibleTable</code> containing the market data
771 * @return an array of record arrays, each representing a row of the table
773 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
774 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
775 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
776 ArrayList<String> row = new ArrayList<String>();
777 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
778 row.add(table.getAccessibleAt(i, j)
779 .getAccessibleContext().getAccessibleName());
787 * @return the table containing market data if it exists,
788 * otherwise <code>null</code>
790 public AccessibleTable findMarketTable() {
791 Accessible node1 = window;
792 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0});
794 // 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})
795 // if (dtxt!=null) dtxt.println(node);
796 if (!(node instanceof JTable)) {
797 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
800 if (!(node instanceof JTable)) return null;
801 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
802 // if (dtxt!=null) dtxt.println(table);
807 * Utility method to descend through several levels of Accessible children
810 * @param parent the node on which to start the descent
811 * @param path an array of ints, each int being the index of the next
812 * accessible child to descend.
813 * @return the <code>Accessible</code> reached by following the
814 * descent path, or <code>null</code> if the desired path was
817 private Accessible descendNodes(Accessible parent, int[] path) {
818 for(int i=0;i<path.length;i++) {
819 if (null == (parent = descend(parent, path[i]))) return null;
825 * Descends one level to the specified child of the parent
826 * <code>Accessible</code> "node".
828 * @param parent the node with children
829 * @param childNum the index of the child of <code>parent</code> to return
830 * @return the <code>childNum</code> child of <code>parent</code>
831 * or <code>null</code> if the child is not found.
833 private Accessible descend(Accessible parent, int childNum) {
834 if (parent == null) return null;
835 int children = parent.getAccessibleContext().getAccessibleChildrenCount();
836 if (childNum >= children) {
837 if (dtxt!=null) dtxt.println("DESCEND "+childNum+" > "
838 +children+" NOT FOUND");
841 Accessible child = parent.getAccessibleContext()
842 .getAccessibleChild(childNum);
843 if (dtxt!=null) dtxt.println("DESCEND "+childNum+" "
844 +child.getClass().getName()+" OK");
849 * Descends one level to the child which has the specified class.
851 * @param parent the node with children
852 * @param classname the name of the class, as a string
853 * @return the child or <code>null</code> if the child is not found.
855 private Accessible descendByClass(Accessible parent, String classname) {
856 if (parent == null) return null;
857 AccessibleContext ac = parent.getAccessibleContext();
858 int children = ac.getAccessibleChildrenCount();
859 for (int i=0; i<children; i++) {
860 Accessible child = ac.getAccessibleChild(i);
861 if (child.getClass().getName() == classname) {
862 if (dtxt!=null) dtxt.println("DESCEND CLASS "+classname+" OK");
866 if (dtxt!=null) dtxt.println("DESCEND CLASS "+classname+" NOT FOUND");
870 public static void main(String[] args) {
871 new MarketUploader();
875 * Returns true if the "Display:" menu on the commodities
876 * interface in YPP is set to "All"
878 * @return <code>true</code> if all commodities are displayed,
879 * otherwise <code>false</code>
881 private boolean isDisplayAll() {
882 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
883 if(!(button instanceof JButton)) {
884 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
886 String display = button.getAccessibleContext().getAccessibleName();
887 if(!display.equals("All")) {
894 * Gets the list of commodities and their associated commodity ids.
896 * @return a map where the key is the commodity and the value is
899 private HashMap<String,Integer> getCommodMap() {
900 if(commodMap != null) {
903 HashMap<String,Integer> map = new HashMap<String,Integer>();
906 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
908 new BufferedReader(new InputStreamReader(host.openStream()));
909 StringBuilder sb = new StringBuilder();
911 while((str = br.readLine()) != null) {
915 debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
916 int first = sb.indexOf("<pre>") + 5;
917 int last = sb.indexOf("</body>");
918 xml = sb.substring(first,last);
919 Reader reader = new CharArrayReader(xml.toCharArray());
920 Document d = DocumentBuilderFactory.newInstance()
921 .newDocumentBuilder().parse(new InputSource(reader));
922 NodeList maps = d.getElementsByTagName("CommodMap");
923 for(int i=0;i<maps.getLength();i++) {
924 NodeList content = maps.item(i).getChildNodes();
925 Integer num = Integer.parseInt(content.item(1).getTextContent());
926 map.put(content.item(0).getTextContent(),num);
928 } catch(Exception e) {
930 error("Unable to load Commodity list from server!");
938 * Given the list of offers, this method will find all the unique
939 * stall names and return them in a <code>LinkedHashMap</code>
940 * where the key is the stall name and the value is the generated
941 * stall id (position in the list). <p> The reason this method
942 * returns a LinkedHashMap instead of a simple HashMap is the
943 * need for iterating over the stall names in insertion order for
944 * output to the server.
946 * @param offers the list of records from the commodity buy/sell interface
947 * @return an iterable ordered map of the stall names and
948 * generated stall ids
950 private LinkedHashMap<String,Integer> getStallMap
951 (ArrayList<ArrayList<String>> offers) {
953 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
954 for(ArrayList<String> offer : offers) {
955 String shop = offer.get(1);
956 if(!map.containsKey(shop)) {
965 * Gets a sorted list of Buys and Sells from the list of
966 * records. <code>buys</code> and <code>sells</code> should be
967 * pre-initialized and passed into the method to receive the
968 * data. Returns a 2-length int array with the number of buys
971 * @param offers the data found from the market table in-game
972 * @param buys an empty initialized <code>TreeSet<Offer></code> to
973 * hold the Buy offers.
974 * @param sells an empty initialized <code>TreeSet<Offer></code> to
975 * hold the Sell offers.
976 * @param stalls the map of stalls to their ids
977 * @param commodMap the map of commodities to their ids
978 * @return a 2-length int[] array containing the number of buys
979 * and sells, respectively
981 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers,
983 TreeSet<Offer> sells,
984 LinkedHashMap<String,Integer> stalls,
985 HashMap<String,Integer> commodMap) {
986 int[] buySellCount = new int[2];
987 for(ArrayList<String> offer : offers) {
989 if(offer.get(2) != null) {
990 buys.add(new Buy(offer,stalls,commodMap));
993 if(offer.get(4) != null) {
994 sells.add(new Sell(offer,stalls,commodMap));
997 } catch(IllegalArgumentException e) {
998 unknownPCTBcommods++;
999 if (dtxt!=null) dtxt.println("Error: Unsupported Commodity \""
1000 + offer.get(0) + "\"");
1003 if (buySellCount[0]==0 && buySellCount[1]==0) {
1004 error("No (valid) offers for PCTB?!");
1005 throw new IllegalArgumentException();
1007 return buySellCount;
1011 * Prepares the list of stalls for writing to the output stream.
1012 * The <code>String</code> returned by this method is ready to be
1013 * written directly to the stream. <p> All shoppe names are left
1014 * as they are. Stall names are abbreviated just before the
1015 * apostrophe in the possessive, with an "^" and a letter
1016 * matching the stall's type appended. Example: "Burninator's
1017 * Ironworking Stall" would become "Burninator^I".
1019 * @param stallMap the map of stalls and stall ids in an iterable order
1020 * @return a <code>String</code> containing the list of stalls in
1021 * format ready to be written to the output stream.
1023 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1024 // set up some mapping
1025 HashMap<String,String> types = new HashMap<String,String>();
1026 types.put("Apothecary Stall", "A");
1027 types.put("Distilling Stall", "D");
1028 types.put("Furnishing Stall", "F");
1029 types.put("Ironworking Stall", "I");
1030 types.put("Shipbuilding Stall", "S");
1031 types.put("Tailoring Stall", "T");
1032 types.put("Weaving Stall", "W");
1034 StringBuilder sb = new StringBuilder();
1035 for(String name : stallMap.keySet()) {
1036 int index = name.indexOf("'s");
1037 String finalName = name;
1040 finalName = name.substring(0,index);
1041 if(index + 2 < name.length()) {
1042 String end = name.substring(index+2,name.length()).trim();
1043 type = types.get(end);
1047 sb.append(name+"\n");
1049 sb.append(finalName+"^"+type+"\n");
1052 return sb.toString();
1056 * Writes a list of offers in correct format to the output stream.
1058 * The format is thus: (all numbers are 2-byte integers in
1059 * little-endian format) (number of offers of this type, aka
1060 * buy/sell) (commodity ID) (number of offers for this commodity)
1061 * [shopID price qty][shopID price qty]...
1063 * @param out the output stream to write the data to
1064 * @param offers the offers to write
1066 private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1067 throws IOException {
1068 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1069 if(offers.size() == 0) {
1070 // nothing to write, and "0" has already been written
1073 int commodity = offers.first().commodity;
1075 for(Offer offer : offers) {
1076 if(commodity != offer.commodity) {
1078 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1080 commodity = offer.commodity;
1083 writeLEShort(offer.shoppe,buffer); // stall index
1084 writeLEShort(offer.price,buffer); // buy price
1085 writeLEShort(offer.quantity,buffer); // buy qty
1088 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1092 * Writes the buffered data to the output strea for one commodity.
1094 * @param out the stream to write to
1095 * @param buffer the buffered data to write
1096 * @param commodity the commmodity id to write before the buffered data
1097 * @param count the number of offers for this commodity to write
1100 private void writeBufferedOffers(OutputStream out, byte[] buffer,
1101 int commodity, int count)
1102 throws IOException {
1103 writeLEShort(commodity,out); // commod index
1104 writeLEShort(count,out); // offer count
1105 out.write(buffer); // the buffered offers
1109 * Writes the buy and sell offers to the outputstream by calling
1112 * @param buys list of Buy offers to write
1113 * @param sells list of Sell offers to write
1114 * @param offerCount 2-length int array containing the number of
1115 * buys and sells to write out
1116 * @param out the stream to write to
1118 private void writeBuySellOffers(TreeSet<Offer> buys,
1119 TreeSet<Offer> sells,
1120 int[] offerCount, OutputStream out)
1121 throws IOException {
1123 writeLEShort(offerCount[0],out);
1124 writeOffers(out,buys);
1126 writeLEShort(offerCount[1],out);
1127 writeOffers(out,sells);
1130 private String readstreamstring(InputStream in) throws IOException {
1131 StringBuilder sb = new StringBuilder();
1132 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1134 while((str = br.readLine()) != null) {
1135 sb.append(str+"\n");
1137 return sb.toString();
1141 * Sends the data to the server via multipart-formdata POST,
1142 * with the gzipped data as a file upload.
1144 * @param file an InputStream open to the gzipped data we want to send
1146 private InputStream sendInitialData(InputStream file) throws IOException {
1147 ClientHttpRequest http =
1148 new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1149 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1151 String err = readstreamstring(http.resultstream());
1152 error("Error sending initial data:\n"+err);
1155 return http.resultstream();
1159 * Utility method to write a 2-byte int in little-endian form to
1162 * @param num an integer to write
1163 * @param out stream to write to
1165 private void writeLEShort(int num, OutputStream out) throws IOException {
1166 out.write(num & 0xFF);
1167 out.write((num >>> 8) & 0xFF);
1171 * Reads the response from the server, and selects the correct parameters
1172 * which are sent in a GET request to the server asking it to confirm
1173 * the upload and accept the data into the database. Notably, the island id
1174 * and ocean id are determined, while other parameter such as the filename
1175 * are determined from the hidden form fields.
1177 * @param in stream of data from the server to read
1179 private boolean finishUpload(InputStream in) throws IOException {
1180 String html = readstreamstring(in);
1181 debug_write_stringdata("pctb-initial.html", html);
1184 Pattern params = Pattern.compile
1185 ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1186 ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1187 ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1188 m = params.matcher(html);
1190 error_html("The PCTB server returned unusual data."+
1191 " Maybe you're using an old version of the uploader?",
1195 String forceReload = m.group(1);
1196 String filename = m.group(2);
1198 Pattern oceanNumPat =
1199 Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1200 m = oceanNumPat.matcher(html);
1202 error_html("Unable to find the ocean in the server's list of oceans!",
1206 String oceanNum = m.group(1);
1208 Pattern oceanIslandNum =
1209 Pattern.compile("islands\\[" + oceanNum
1210 + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1212 m = oceanIslandNum.matcher(html);
1214 error_html("This does not seem to be a valid island! Unable to upload.",
1218 String islandNum = m.group(1);
1220 URL get = new URL(PCTB_HOST_URL +
1221 "upload.php?action=setisland&ocean=" + oceanNum
1222 + "&island=" + islandNum
1223 + "&forcereload=" + forceReload
1224 + "&filename=" + filename);
1225 String complete = readstreamstring(get.openStream());
1226 debug_write_stringdata("pctb-final.html", complete);
1227 Pattern done = Pattern.compile
1228 ("Your data has been integrated into the database. Thank you!");
1229 m = done.matcher(complete);
1233 error_html("Something was wrong with the final upload parameters!",
1239 private InputStream post_for_yarrg(ClientHttpRequest http)
1240 throws IOException {
1242 String err = readstreamstring(http.resultstream());
1243 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1246 return http.resultstream();
1249 private String getYarrgTimestamp() throws IOException {
1250 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1251 http.setParameter("clientname", YARRG_CLIENTNAME);
1252 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1253 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1254 http.setParameter("requesttimestamp", "y");
1255 InputStream in = post_for_yarrg(http);
1256 if (in == null) return null;
1257 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1258 String tsresult = br.readLine();
1259 return tsresult.substring(3, tsresult.length()-1);
1262 private boolean runYarrg(String timestamp, String ocean, String island,
1263 String yarrgdata) throws IOException {
1264 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1265 BufferedOutputStream bufos =
1266 new BufferedOutputStream(new GZIPOutputStream(bos));
1267 bufos.write(yarrgdata.getBytes() );
1269 byte[] compressed = bos.toByteArray();
1270 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1271 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1273 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1274 http.setParameter("clientname", YARRG_CLIENTNAME);
1275 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1276 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1277 http.setParameter("timestamp", timestamp);
1278 http.setParameter("ocean", ocean);
1279 http.setParameter("island", island);
1280 http.setParameter("data", "deduped.tsv.gz", file,
1281 "application/octet-stream");
1282 InputStream in = post_for_yarrg(http);
1283 if (in == null) return false;
1284 String output = readstreamstring(in);
1285 if (!output.startsWith("OK")) {
1286 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1289 debug_write_stringdata("yarrg-result.txt", output);
1293 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1294 // if (dtxt!=null) dtxt.println("ARBITRAGE?");
1296 SortedSet<int[]> buys = arb_bs.get(0);
1297 SortedSet<int[]> sells = arb_bs.get(1);
1301 // NB "sell" means they sell, ie we buy
1302 sell = sells.last();
1304 } catch (NoSuchElementException e) {
1308 int unitprofit = buy[0] - sell[0];
1309 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1310 // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]
1311 // +" buy @"+buy[0]+" x"+buy[1]
1312 // +" => x"+count+" @"+unitprofit);
1314 if (unitprofit <= 0)
1317 profit += count * unitprofit;
1320 if (buy[1]==0) buys.remove(buy);
1321 if (sell[1]==0) sells.remove(sell);
1323 // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
1327 private class arbitrageOfferComparator implements Comparator {
1328 public int compare(Object o1, Object o2) {
1329 int p1 = ((int[])o1)[0];
1330 int p2 = ((int[])o2)[0];
1335 private @SuppressWarnings("unchecked")
1336 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1338 ArrayList<SortedSet<int[]>> arb_bs = null;
1339 String lastcommod = null;
1340 Comparator compar = new arbitrageOfferComparator();
1342 for (ArrayList<String> row : data) {
1343 String thiscommod = row.get(0);
1344 // if (dtxt!=null) dtxt.println("ROW "+row.toString());
1345 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1346 if (lastcommod != null)
1347 arbitrage += calculateArbitrageCommodity(arb_bs);
1348 // if (dtxt!=null) dtxt.println("ROW rdy");
1349 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1350 arb_bs.add(0, new TreeSet<int[]>(compar));
1351 arb_bs.add(1, new TreeSet<int[]>(compar));
1352 // if (dtxt!=null) dtxt.println("ROW init");
1353 lastcommod = thiscommod;
1355 for (int bs = 0; bs < 2; bs++) {
1356 String pricestr = row.get(bs*2 + 2);
1357 if (pricestr == null)
1359 int[] entry = new int[2];
1360 // if (dtxt!=null) dtxt.println("ROW BS "+bs);
1361 entry[0] = parseQty(pricestr);
1362 entry[1] = parseQty(row.get(bs*2 + 3));
1363 arb_bs.get(bs).add(entry);
1366 arbitrage += calculateArbitrageCommodity(arb_bs);
1367 if (arbitrage != 0) {
1368 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage
1371 arbitrageResult.setText("no arbitrage");