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;
46 private ProgressMonitor progmon = null;
48 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
49 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
50 private String PCTB_HOST_URL;
52 // Yarrg protocol parameters
53 private final static String YARRG_CLIENTNAME = "jpctb greenend";
54 private final static String YARRG_CLIENTVERSION =
55 net.chiark.yarrg.Version.version;
56 private final static String YARRG_CLIENTFIXES = "bug-094";
57 private final static String YARRG_LIVE_URL =
58 "http://upload.yarrg.chiark.net/commod-update-receiver";
59 private final static String YARRG_TEST_URL =
60 "http://upload.yarrg.chiark.net/test/commod-update-receiver";
61 private String YARRG_URL;
63 private boolean uploadToYarrg;
64 private boolean uploadToPCTB;
65 private boolean showArbitrage;
67 private String islandName = null;
68 private String oceanName = null;
69 private java.util.concurrent.CountDownLatch latch = null;
71 private AccessibleContext sidePanel;
72 private HashMap<String,Integer> commodMap;
73 public PrintStream dtxt = null;
76 * UTILITY METHODS AND SUBCLASSES
78 * Useable on any thread.
81 private int parseQty(String str) {
82 if (str.equals(">1000")) {
85 return Integer.parseInt(str);
89 private void debuglog(String s) {
90 if (dtxt == null) return;
91 long now = new Date().getTime();
92 dtxt.println("progress "+(now - startTime)+"ms "+s);
95 private void debug_write_stringdata(String what, String data)
96 throws FileNotFoundException,IOException {
97 if (dtxt==null) return;
98 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
103 private void debug_write_bytes(String what, byte[] data)
104 throws FileNotFoundException,IOException {
105 if (dtxt==null) return;
106 FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
112 * An abstract market offer, entailing a commodity being bought or sold by
113 * a shoppe, for a certain price in a certain quantity. Not instantiable.
118 abstract class Offer {
119 public int commodity, price, quantity, shoppe;
121 * Create an offer from <code>record</code>, determining the shoppe Id from
122 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
123 * <code>priceIndex</code> should be the index of the price in the record
124 * (the quantity will be <code>priceIndex + 1</code>).
126 * @param record the record with data to create the offer from
127 * @param stallMap a map containing the ids of the various stalls
128 * @param commodMap a map containing the ids of the various commodities
129 * @param priceIndex the index of the price in the record
131 public Offer(ArrayList<String> record,
132 LinkedHashMap<String,Integer> stallMap,
133 HashMap<String,Integer> commodMap,
135 Integer commodId = commodMap.get(record.get(0));
136 if(commodId == null) {
137 throw new IllegalArgumentException();
139 commodity = commodId.intValue();
140 price = Integer.parseInt(record.get(priceIndex));
141 String qty = record.get(priceIndex+1);
142 quantity = parseQty(qty);
143 shoppe = stallMap.get(record.get(1)).intValue();
147 * Returns a human-readable version of this offer, useful for debugging
149 * @return human-readable offer
151 public String toString() {
152 return "[C:" + commodity + ",$" + price + ",Q:"
153 + quantity + ",S:" + shoppe + "]";
158 * An offer from a shoppe or stall to buy a certain quantity of a
159 * commodity for a certain price. If placed in an ordered Set,
160 * sorts by commodity index ascending, then by buy price
161 * descending, and finally by stall id ascending.
163 class Buy extends Offer implements Comparable<Buy> {
165 * Creates a new <code>Buy</code> offer from the given
166 * <code>record</code> using the other parameters to determine
167 * stall id and commodity id of the offer.
169 * @param record the record with data to create the offer from
170 * @param stallMap a map containing the ids of the various stalls
171 * @param commodMap a map containing the ids of the various commodities
173 public Buy(ArrayList<String> record,
174 LinkedHashMap<String,Integer> stallMap,
175 HashMap<String,Integer> commodMap) {
176 super(record,stallMap,commodMap,2);
180 * Sorts by commodity index ascending, then price descending,
181 * then stall id ascending.
183 public int compareTo(Buy buy) {
184 // organize by: commodity index, price, stall index
185 if(commodity == buy.commodity) {
186 // organize by price, then by stall index
187 if(price == buy.price) {
188 // organize by stall index
189 return shoppe>buy.shoppe ? 1 : -1;
190 } else if(price > buy.price) {
195 } else if(commodity > buy.commodity) {
204 * An offer from a shoppe or stall to sell a certain quantity of
205 * a commodity for a certain price. If placed in an ordered Set,
206 * sorts by commodity index ascending, then by sell price
207 * ascending, and finally by stall id ascending.
209 class Sell extends Offer implements Comparable<Sell> {
211 * Creates a new <code>Sell</code> offer from the given
212 * <code>record</code> using the other parameters to determine
213 * stall id and commodity id of the offer.
215 * @param record the record with data to create the offer from
216 * @param stallMap a map containing the ids of the various stalls
217 * @param commodMap a map containing the ids of the various commodities
219 public Sell(ArrayList<String> record,
220 LinkedHashMap<String,Integer> stallMap,
221 HashMap<String,Integer> commodMap) {
222 super(record,stallMap,commodMap,4);
226 * Sorts by commodity index ascending, then price ascending, then
227 * stall id ascending.
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) {
241 } else if(commodity > sell.commodity) {
249 private void progressNote(final String s_in) throws Exception {
250 new UIX() { public void body() {
252 arb = arbitrageResult.getText();
254 if (arb != null && arb.length() != 0)
255 s = "<html>" + arb + "<br>" + s;
261 * ENTRY POINT AND STARTUP
263 * Main thread and/or event thread
266 * Entry point. Read our preferences.
268 public MarketUploader() {
269 Preferences prefs = Preferences.userNodeForPackage(getClass());
271 if (prefs.getBoolean("writeDebugFiles", false)) {
273 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
274 } catch (java.io.FileNotFoundException e) {
275 System.err.println("JARRG: Error opening debug log: "+e);
279 if (prefs.getBoolean("useLiveServers", true)) {
280 YARRG_URL = YARRG_LIVE_URL;
281 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
283 YARRG_URL = YARRG_TEST_URL;
284 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
287 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
288 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
289 showArbitrage=prefs.getBoolean("showArbitrage", true);
291 debuglog("main on dispatch thread: "+EventQueue.isDispatchThread());
292 EventQueue.invokeLater(this);
296 * We arrange to wait for the GUI to be initialised, then look at
297 * every top-level window, and if it
300 debuglog("MarketUploader run()...");
301 if (EventQueueMonitor.isGUIInitialized()) {
302 debuglog("MarketUploader GUI already ready");
305 debuglog("MarketUploader waiting for GUI");
306 EventQueueMonitor.addGUIInitializedListener(this);
310 public void guiInitialized() {
311 Window ws[]= EventQueueMonitor.getTopLevelWindows();
312 EventQueueMonitor.addTopLevelWindowListener(this);
313 for (int i=0; i<ws.length; i++) {
314 debuglog("MarketUploader existing toplevel "+i);
315 topLevelWindowCreated(ws[i]);
319 public void topLevelWindowDestroyed(Window w) {
320 debuglog("MarketUploader destroyed toplevel");
323 public void topLevelWindowCreated(Window w) {
327 String name = w.getAccessibleContext().getAccessibleName();
328 debuglog("MarketUploader new toplevel "+name);
329 if (!name.equals("Puzzle Pirates"))
331 debuglog("MarketUploader found toplevel, creating gui");
334 frame.setVisible(true);
338 * Set up the GUI, with its window and one-button
339 * interface. Only initialize if we're running alongside
340 * a Window named "Puzzle Pirates" though.
342 private void createGUI() {
344 frame = new JFrame("Jarrg Uploader");
345 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
346 GridLayout layout = new GridLayout(2,1);
347 frame.getContentPane().setLayout(layout);
348 //frame.setPreferredSize(new Dimension(200, 60));
350 findMarket = new JButton("Upload Market Data");
351 findMarket.addActionListener(new ActionListener() {
352 public void actionPerformed(ActionEvent e) {
354 findMarket.setEnabled(false);
355 resultSummary.setText("");
356 arbitrageResult.setText("");
359 startTime = new Date().getTime();
360 unknownPCTBcommods = 0;
363 } catch(Exception e) {
368 new UIX() { public void body() {
369 if(sidePanel != null) {
370 sidePanel.removePropertyChangeListener(changeListener);
372 if (progmon != null) {
376 findMarket.setEnabled(true);
378 } catch (Exception e) {
379 System.err.println("exception tidying on UI thread:");
386 frame.add(findMarket);
388 resultSummary = new JLabel("ready");
389 frame.add(resultSummary);
391 arbitrageResult = new JLabel("");
394 layout.setRows(layout.getRows() + 1);
395 frame.add(arbitrageResult);
402 * ERROR REPORTING AND GENERAL UTILITIES
404 * Synchronous modal dialogues
405 * error and error_html may be called from any thread
408 private abstract class UIXR<ReturnType> implements Runnable {
409 public abstract ReturnType bodyr();
410 public ReturnType return_value;
411 public void run() { return_value = bodyr(); };
412 public ReturnType exec() throws Exception {
413 if (EventQueue.isDispatchThread()) {
416 EventQueue.invokeAndWait(this);
421 private abstract class UIX extends UIXR<Object> implements Runnable {
422 public abstract void body();
423 public Object bodyr() { body(); return null; }
426 private void on_ui_thread() { assert(EventQueue.isDispatchThread()); }
427 private void on_our_thread() { assert(!EventQueue.isDispatchThread()); }
429 private void error(final String msg) {
431 new UIX() { public void body() {
432 resultSummary.setText("failed");
433 JOptionPane.showMessageDialog(frame,msg,"Error",
434 JOptionPane.ERROR_MESSAGE);
436 } catch (Exception e) {
437 System.err.println("exception reporting to UI thread:");
442 private void error_html(final String msg, String html) {
443 Pattern body = Pattern.compile("<body>(.*)</body>",
444 Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
445 Matcher m = body.matcher(html);
448 Pattern fixup = Pattern.compile("<(\\w+) */>");;
449 m = fixup.matcher(html);
450 html = m.replaceAll("<$1>");
451 m = Pattern.compile("[\\r\\n]+").matcher(html);
452 html = m.replaceAll(" ");
454 String whole_msg = "<html><h1>Error</h1>"+msg
455 +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
456 debuglog("###" + whole_msg + "###");
461 private void setProgress(final int nv) throws Exception {
462 new UIX() { public void body() {
463 progmon.setProgress(nv);
466 private boolean isCanceled() throws Exception {
467 return new UIXR<Boolean>() { public Boolean bodyr() {
468 return new Boolean(progmon.isCanceled());
469 }}.exec().booleanValue();
473 * GUI MANIPULATION CALLBACKS
476 private PropertyChangeListener changeListener = new PropertyChangeListener() {
477 public void propertyChange(PropertyChangeEvent e) {
479 if(e.getNewValue() != null &&
480 e.getPropertyName().equals
481 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
482 Accessible islandInfo =
483 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
484 String text = islandInfo.getAccessibleContext().getAccessibleText()
485 .getAtIndex(AccessibleText.SENTENCE,0);
486 int index = text.indexOf(":");
487 String name = text.substring(0,index);
489 // debuglog(islandName);
490 sidePanel.removePropertyChangeListener(this);
496 private void getIsland() {
499 // If the league tracker is there, we can skip the faff
500 // and ask for its tooltip, since we're on a boat
502 Accessible leagueTrackerContainer =
503 descendNodes(window,new int[] {0,1,0,0,2,1});
504 Accessible leagueTrackerItself =
505 descendByClass(leagueTrackerContainer,
506 "com.threerings.yohoho.sea.client.LeagueTracker");
507 Accessible leagueTracker = descend(leagueTrackerItself, 1);
509 islandName = ((JLabel)leagueTracker).getToolTipText();
510 } catch (NullPointerException e) {
511 // evidently we're actually on an island
514 AccessibleContext chatArea =
515 descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
516 .getAccessibleContext();
517 // attach the property change listener to the outer sunshine
518 // panel if the "ahoy" tab is not active, otherwise attach it to
519 // the scroll panel in the "ahoy" tab.
520 if(!"com.threerings.piracy.client.AttentionListPanel".
521 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
522 .getClass().getCanonicalName())) {
523 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
524 .getAccessibleContext();
526 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
527 .getAccessibleContext();
529 sidePanel.addPropertyChangeListener(changeListener);
530 latch = new java.util.concurrent.CountDownLatch(1);
531 // make the Players Online ("/who") panel appear
532 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
533 chat.setTextContents("/w");
534 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
535 for(int i=0;i<c;i++) {
536 if("notify-field-accept".equals(chatArea.getAccessibleAction()
537 .getAccessibleActionDescription(i))) {
538 chatArea.getAccessibleAction().doAccessibleAction(i);
545 * Find the ocean name from the window title, and set global
548 private void getOcean() {
551 AccessibleContext topwindow = window.getAccessibleContext();
552 oceanName = topwindow.getAccessibleName()
553 .replaceAll(".*on the (\\w+) ocean", "$1");
558 * Run the data collection process, and upload the results. This
559 * is the method that calls most of the other worker methods for
560 * the process. If an error occurs, the method will call the
561 * error method and return early, freeing up the button to be
564 * @exception Exception if an error we didn't expect occured
566 private class YarrgTimestampFetcher extends Thread {
567 public String ts = null;
570 ts = getYarrgTimestamp();
571 debuglog("(async) yarrg timestamp ready.");
572 } catch(Exception e) {
573 error("Error getting YARRG timestamp: "+e);
578 private void runUpload() throws Exception {
581 boolean doneyarrg = false, donepctb = false;
582 YarrgTimestampFetcher yarrgts_thread = null;
584 debuglog("starting");
587 debuglog("(async) yarrg timestamp...");
588 yarrgts_thread = new YarrgTimestampFetcher();
589 yarrgts_thread.start();
592 final AccessibleTable accesstable =
593 new UIXR<AccessibleTable>() { public AccessibleTable bodyr() {
594 progmon = new ProgressMonitor
595 (frame,"Processing Market Data","Getting table data",0,100);
596 progmon.setMillisToDecideToPopup(0);
597 progmon.setMillisToPopup(0);
599 AccessibleTable at = findMarketTable();
601 error("Market table not found!"+
602 " Please open the Buy/Sell Commodities interface.");
605 if(at.getAccessibleRowCount() == 0) {
606 error("No data found, please wait for the table to have data first!");
609 if(!isDisplayAll()) {
610 error("Please select \"All\" from the Display: popup menu.");
614 debuglog("(async) getisland...");
616 debuglog("getocean...");
618 debuglog("getocean done");
622 if (accesstable == null) return;
625 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
627 debuglog("(async) getisland done");
629 String yarrgts = null;
630 if (yarrgts_thread != null) {
631 debuglog("(async) yarrg timestamp join...");
632 yarrgts_thread.join();
633 debuglog("(async) yarrg timestamp joined.");
634 yarrgts = yarrgts_thread.ts;
637 if (islandName == null) {
638 error("Could not find island name in YPP user interface.");
642 debuglog("table check...");
644 final ArrayList<ArrayList<String>> data =
645 new UIXR<ArrayList<ArrayList<String>>>
646 () { public ArrayList<ArrayList<String>> bodyr() {
647 String headings_expected[] = new String[]
648 { "Commodity", "Trading outlet", "Buy price",
649 "Will buy", "Sell price", "Will sell" };
651 ArrayList<ArrayList<String>> headers =
652 getData(accesstable.getAccessibleColumnHeader());
653 if (headers.size() != 1) {
654 error("Table headings not one row! " + headers.toString());
657 if (headers.get(0).size() < 6 ||
658 headers.get(0).size() > 7) {
659 error("Table headings not six or seven columns! " + headers.toString());
662 for (int col=0; col<headings_expected.length; col++) {
663 String expd = headings_expected[col];
664 String got = headers.get(0).get(col);
665 if (expd.compareTo(got) != 0) {
666 error("Table heading for column "+col
667 +" is not \""+expd+"\" but \""+got+"\".\n\n"
668 +"Please do not reorder the table when using this tool.");
673 debuglog("table read...");
675 return getData(accesstable);
677 if (data == null) return;
680 debuglog("arbitrage...");
681 calculateArbitrage(data);
682 debuglog("arbitrage done.");
685 if (uploadToYarrg && yarrgts != null) {
686 debuglog("yarrg prepare...");
687 progressNote("Yarrg: Preparing data");
690 StringBuilder yarrgsb = new StringBuilder();
691 String yarrgdata; // string containing what we'll feed to yarrg
693 for (ArrayList<String> row : data) {
694 if (row.size() > 6) {
697 for (String rowitem : row) {
698 yarrgsb.append(rowitem != null ? rowitem : "");
699 yarrgsb.append("\t");
701 yarrgsb.setLength(yarrgsb.length()-1); // chop
702 yarrgsb.append("\n");
705 yarrgdata = yarrgsb.toString();
707 progressNote("Yarrg: Uploading");
708 debuglog("yarrg upload...");
710 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
711 debuglog("yarrg done.");
715 debuglog("pctb prepare...");
716 progressNote("PCTB: Getting stall names");
721 TreeSet<Offer> buys = new TreeSet<Offer>();
722 TreeSet<Offer> sells = new TreeSet<Offer>();
723 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
725 progressNote("PCTB: Sorting offers");
731 debuglog("pctb commodmap...");
732 HashMap<String,Integer> commodMap = getCommodMap();
733 if(commodMap == null) {
736 debuglog("pctb commodmap done.");
737 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
739 // debuglog("\n\n\n"+buys);
741 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
743 progressNote("PCTB: Sending data");
747 GZIPOutputStream out = new GZIPOutputStream(outStream);
748 DataOutputStream dos = new DataOutputStream(out);
749 dos.writeBytes("005y\n");
750 dos.writeBytes(stallMap.size()+"\n");
751 dos.writeBytes(getAbbrevStallList(stallMap));
752 writeBuySellOffers(buys,sells,offerCount,out);
754 debuglog("pctb send...");
756 byte[] ba = outStream.toByteArray();
757 debug_write_bytes("pctb-marketdata.gz", ba);
759 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
760 debuglog("pctb sent.");
761 if (in == null) return;
766 progressNote("PCTB: Waiting ...");
767 debuglog("pctb finish...");
768 donepctb = finishUpload(in);
769 debuglog("pctb done.");
774 if ((uploadToPCTB && !donepctb) ||
775 (uploadToYarrg && !doneyarrg)) {
777 } else if (unknownPCTBcommods != 0) {
778 summary= "PCTB lacks "+unknownPCTBcommods+" commod(s)";
779 } else if (donepctb || doneyarrg) {
780 summary= "Done " + islandName;
782 summary= "uploaded nowhere!";
784 final String summary_final = summary;
785 new UIX() { public void body() {
786 resultSummary.setText(summary_final);
793 * Get the offer data out of the table and cache it in an
794 * <code>ArrayList</code>.
796 * @param table the <code>AccessibleTable</code> containing the market data
797 * @return an array of record arrays, each representing a row of the table
799 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
801 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
802 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
803 ArrayList<String> row = new ArrayList<String>();
804 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
805 row.add(table.getAccessibleAt(i, j)
806 .getAccessibleContext().getAccessibleName());
814 * @return the table containing market data if it exists,
815 * otherwise <code>null</code>
817 public AccessibleTable findMarketTable() {
819 Accessible node1 = window;
820 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0});
822 // 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})
824 if (!(node instanceof JTable)) {
825 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
828 if (!(node instanceof JTable)) return null;
829 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
835 * Utility method to descend through several levels of Accessible children
838 * @param parent the node on which to start the descent
839 * @param path an array of ints, each int being the index of the next
840 * accessible child to descend.
841 * @return the <code>Accessible</code> reached by following the
842 * descent path, or <code>null</code> if the desired path was
845 private Accessible descendNodes(Accessible parent, int[] path) {
847 for(int i=0;i<path.length;i++) {
848 if (null == (parent = descend(parent, path[i]))) return null;
854 * Descends one level to the specified child of the parent
855 * <code>Accessible</code> "node".
857 * @param parent the node with children
858 * @param childNum the index of the child of <code>parent</code> to return
859 * @return the <code>childNum</code> child of <code>parent</code>
860 * or <code>null</code> if the child is not found.
862 private Accessible descend(Accessible parent, int childNum) {
864 if (parent == null) return null;
865 int children = parent.getAccessibleContext().getAccessibleChildrenCount();
866 if (childNum >= children) {
867 debuglog("DESCEND "+childNum+" > "+children+" NOT FOUND");
870 Accessible child = parent.getAccessibleContext()
871 .getAccessibleChild(childNum);
872 debuglog("DESCEND "+childNum+" "+child.getClass().getName()+" OK");
877 * Descends one level to the child which has the specified class.
879 * @param parent the node with children
880 * @param classname the name of the class, as a string
881 * @return the child or <code>null</code> if the child is not found.
883 private Accessible descendByClass(Accessible parent, String classname) {
885 if (parent == null) return null;
886 AccessibleContext ac = parent.getAccessibleContext();
887 int children = ac.getAccessibleChildrenCount();
888 for (int i=0; i<children; i++) {
889 Accessible child = ac.getAccessibleChild(i);
890 if (child.getClass().getName() == classname) {
891 debuglog("DESCEND CLASS "+classname+" OK");
895 debuglog("DESCEND CLASS "+classname+" NOT FOUND");
899 public static void main(String[] args) {
900 new MarketUploader();
904 * Returns true if the "Display:" menu on the commodities
905 * interface in YPP is set to "All"
907 * @return <code>true</code> if all commodities are displayed,
908 * otherwise <code>false</code>
910 private boolean isDisplayAll() {
912 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
913 if(!(button instanceof JButton)) {
914 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
916 String display = button.getAccessibleContext().getAccessibleName();
917 if(!display.equals("All")) {
924 * Gets the list of commodities and their associated commodity ids.
926 * @return a map where the key is the commodity and the value is
929 private HashMap<String,Integer> getCommodMap() {
931 if(commodMap != null) {
934 HashMap<String,Integer> map = new HashMap<String,Integer>();
937 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
939 new BufferedReader(new InputStreamReader(host.openStream()));
940 StringBuilder sb = new StringBuilder();
942 while((str = br.readLine()) != null) {
946 debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
947 int first = sb.indexOf("<pre>") + 5;
948 int last = sb.indexOf("</body>");
949 xml = sb.substring(first,last);
950 Reader reader = new CharArrayReader(xml.toCharArray());
951 Document d = DocumentBuilderFactory.newInstance()
952 .newDocumentBuilder().parse(new InputSource(reader));
953 NodeList maps = d.getElementsByTagName("CommodMap");
954 for(int i=0;i<maps.getLength();i++) {
955 NodeList content = maps.item(i).getChildNodes();
956 Integer num = Integer.parseInt(content.item(1).getTextContent());
957 map.put(content.item(0).getTextContent(),num);
959 } catch(Exception e) {
961 error("Unable to load Commodity list from server!");
969 * Given the list of offers, this method will find all the unique
970 * stall names and return them in a <code>LinkedHashMap</code>
971 * where the key is the stall name and the value is the generated
972 * stall id (position in the list). <p> The reason this method
973 * returns a LinkedHashMap instead of a simple HashMap is the
974 * need for iterating over the stall names in insertion order for
975 * output to the server.
977 * @param offers the list of records from the commodity buy/sell interface
978 * @return an iterable ordered map of the stall names and
979 * generated stall ids
981 private LinkedHashMap<String,Integer> getStallMap
982 (ArrayList<ArrayList<String>> offers) {
984 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
985 for(ArrayList<String> offer : offers) {
986 String shop = offer.get(1);
987 if(!map.containsKey(shop)) {
996 * Gets a sorted list of Buys and Sells from the list of
997 * records. <code>buys</code> and <code>sells</code> should be
998 * pre-initialized and passed into the method to receive the
999 * data. Returns a 2-length int array with the number of buys
1002 * @param offers the data found from the market table in-game
1003 * @param buys an empty initialized <code>TreeSet<Offer></code> to
1004 * hold the Buy offers.
1005 * @param sells an empty initialized <code>TreeSet<Offer></code> to
1006 * hold the Sell offers.
1007 * @param stalls the map of stalls to their ids
1008 * @param commodMap the map of commodities to their ids
1009 * @return a 2-length int[] array containing the number of buys
1010 * and sells, respectively
1012 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers,
1013 TreeSet<Offer> buys,
1014 TreeSet<Offer> sells,
1015 LinkedHashMap<String,Integer> stalls,
1016 HashMap<String,Integer> commodMap) {
1017 int[] buySellCount = new int[2];
1018 for(ArrayList<String> offer : offers) {
1020 if(offer.get(2) != null) {
1021 buys.add(new Buy(offer,stalls,commodMap));
1024 if(offer.get(4) != null) {
1025 sells.add(new Sell(offer,stalls,commodMap));
1028 } catch(IllegalArgumentException e) {
1029 unknownPCTBcommods++;
1030 debuglog("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
1033 if (buySellCount[0]==0 && buySellCount[1]==0) {
1034 error("No (valid) offers for PCTB?!");
1035 throw new IllegalArgumentException();
1037 return buySellCount;
1041 * Prepares the list of stalls for writing to the output stream.
1042 * The <code>String</code> returned by this method is ready to be
1043 * written directly to the stream. <p> All shoppe names are left
1044 * as they are. Stall names are abbreviated just before the
1045 * apostrophe in the possessive, with an "^" and a letter
1046 * matching the stall's type appended. Example: "Burninator's
1047 * Ironworking Stall" would become "Burninator^I".
1049 * @param stallMap the map of stalls and stall ids in an iterable order
1050 * @return a <code>String</code> containing the list of stalls in
1051 * format ready to be written to the output stream.
1053 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1054 // set up some mapping
1055 HashMap<String,String> types = new HashMap<String,String>();
1056 types.put("Apothecary Stall", "A");
1057 types.put("Distilling Stall", "D");
1058 types.put("Furnishing Stall", "F");
1059 types.put("Ironworking Stall", "I");
1060 types.put("Shipbuilding Stall", "S");
1061 types.put("Tailoring Stall", "T");
1062 types.put("Weaving Stall", "W");
1064 StringBuilder sb = new StringBuilder();
1065 for(String name : stallMap.keySet()) {
1066 int index = name.indexOf("'s");
1067 String finalName = name;
1070 finalName = name.substring(0,index);
1071 if(index + 2 < name.length()) {
1072 String end = name.substring(index+2,name.length()).trim();
1073 type = types.get(end);
1077 sb.append(name+"\n");
1079 sb.append(finalName+"^"+type+"\n");
1082 return sb.toString();
1086 * Writes a list of offers in correct format to the output stream.
1088 * The format is thus: (all numbers are 2-byte integers in
1089 * little-endian format) (number of offers of this type, aka
1090 * buy/sell) (commodity ID) (number of offers for this commodity)
1091 * [shopID price qty][shopID price qty]...
1093 * @param out the output stream to write the data to
1094 * @param offers the offers to write
1096 private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1097 throws IOException {
1098 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1099 if(offers.size() == 0) {
1100 // nothing to write, and "0" has already been written
1103 int commodity = offers.first().commodity;
1105 for(Offer offer : offers) {
1106 if(commodity != offer.commodity) {
1108 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1110 commodity = offer.commodity;
1113 writeLEShort(offer.shoppe,buffer); // stall index
1114 writeLEShort(offer.price,buffer); // buy price
1115 writeLEShort(offer.quantity,buffer); // buy qty
1118 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1122 * Writes the buffered data to the output strea for one commodity.
1124 * @param out the stream to write to
1125 * @param buffer the buffered data to write
1126 * @param commodity the commmodity id to write before the buffered data
1127 * @param count the number of offers for this commodity to write
1130 private void writeBufferedOffers(OutputStream out, byte[] buffer,
1131 int commodity, int count)
1132 throws IOException {
1133 writeLEShort(commodity,out); // commod index
1134 writeLEShort(count,out); // offer count
1135 out.write(buffer); // the buffered offers
1139 * Writes the buy and sell offers to the outputstream by calling
1142 * @param buys list of Buy offers to write
1143 * @param sells list of Sell offers to write
1144 * @param offerCount 2-length int array containing the number of
1145 * buys and sells to write out
1146 * @param out the stream to write to
1148 private void writeBuySellOffers(TreeSet<Offer> buys,
1149 TreeSet<Offer> sells,
1150 int[] offerCount, OutputStream out)
1151 throws IOException {
1153 writeLEShort(offerCount[0],out);
1154 writeOffers(out,buys);
1156 writeLEShort(offerCount[1],out);
1157 writeOffers(out,sells);
1160 private String readstreamstring(InputStream in) throws IOException {
1161 StringBuilder sb = new StringBuilder();
1162 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1164 while((str = br.readLine()) != null) {
1165 sb.append(str+"\n");
1167 return sb.toString();
1171 * Sends the data to the server via multipart-formdata POST,
1172 * with the gzipped data as a file upload.
1174 * @param file an InputStream open to the gzipped data we want to send
1176 private InputStream sendInitialData(InputStream file) throws IOException {
1178 ClientHttpRequest http =
1179 new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1180 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1182 String err = readstreamstring(http.resultstream());
1183 error("Error sending initial data:\n"+err);
1186 return http.resultstream();
1190 * Utility method to write a 2-byte int in little-endian form to
1193 * @param num an integer to write
1194 * @param out stream to write to
1196 private void writeLEShort(int num, OutputStream out) throws IOException {
1197 out.write(num & 0xFF);
1198 out.write((num >>> 8) & 0xFF);
1202 * Reads the response from the server, and selects the correct parameters
1203 * which are sent in a GET request to the server asking it to confirm
1204 * the upload and accept the data into the database. Notably, the island id
1205 * and ocean id are determined, while other parameter such as the filename
1206 * are determined from the hidden form fields.
1208 * @param in stream of data from the server to read
1210 private boolean finishUpload(InputStream in) throws IOException {
1213 String html = readstreamstring(in);
1214 debug_write_stringdata("pctb-initial.html", html);
1217 Pattern params = Pattern.compile
1218 ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1219 ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1220 ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1221 m = params.matcher(html);
1223 error_html("The PCTB server returned unusual data."+
1224 " Maybe you're using an old version of the uploader?",
1228 String forceReload = m.group(1);
1229 String filename = m.group(2);
1231 Pattern oceanNumPat =
1232 Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1233 m = oceanNumPat.matcher(html);
1235 error_html("Unable to find the ocean in the server's list of oceans!",
1239 String oceanNum = m.group(1);
1241 Pattern oceanIslandNum =
1242 Pattern.compile("islands\\[" + oceanNum
1243 + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1245 m = oceanIslandNum.matcher(html);
1247 error_html("This does not seem to be a valid island! Unable to upload.",
1251 String islandNum = m.group(1);
1253 URL get = new URL(PCTB_HOST_URL +
1254 "upload.php?action=setisland&ocean=" + oceanNum
1255 + "&island=" + islandNum
1256 + "&forcereload=" + forceReload
1257 + "&filename=" + filename);
1258 String complete = readstreamstring(get.openStream());
1259 debug_write_stringdata("pctb-final.html", complete);
1260 Pattern done = Pattern.compile
1261 ("Your data has been integrated into the database. Thank you!");
1262 m = done.matcher(complete);
1266 error_html("Something was wrong with the final upload parameters!",
1272 private InputStream post_for_yarrg(ClientHttpRequest http)
1273 throws IOException {
1276 String err = readstreamstring(http.resultstream());
1277 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1280 return http.resultstream();
1283 private String getYarrgTimestamp() throws IOException {
1284 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1285 http.setParameter("clientname", YARRG_CLIENTNAME);
1286 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1287 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1288 http.setParameter("requesttimestamp", "y");
1289 InputStream in = post_for_yarrg(http);
1290 if (in == null) return null;
1291 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1292 String tsresult = br.readLine();
1293 return tsresult.substring(3, tsresult.length()-1);
1296 private boolean runYarrg(String timestamp, String ocean, String island,
1297 String yarrgdata) throws IOException {
1298 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1299 BufferedOutputStream bufos =
1300 new BufferedOutputStream(new GZIPOutputStream(bos));
1301 bufos.write(yarrgdata.getBytes() );
1303 byte[] compressed = bos.toByteArray();
1304 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1305 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1307 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1308 http.setParameter("clientname", YARRG_CLIENTNAME);
1309 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1310 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1311 http.setParameter("timestamp", timestamp);
1312 http.setParameter("ocean", ocean);
1313 http.setParameter("island", island);
1314 http.setParameter("data", "deduped.tsv.gz", file,
1315 "application/octet-stream");
1316 InputStream in = post_for_yarrg(http);
1317 if (in == null) return false;
1318 String output = readstreamstring(in);
1319 if (!output.startsWith("OK")) {
1320 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1323 debug_write_stringdata("yarrg-result.txt", output);
1327 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1328 // debuglog("ARBITRAGE?");
1330 SortedSet<int[]> buys = arb_bs.get(0);
1331 SortedSet<int[]> sells = arb_bs.get(1);
1335 // NB "sell" means they sell, ie we buy
1336 sell = sells.last();
1338 } catch (NoSuchElementException e) {
1342 int unitprofit = buy[0] - sell[0];
1343 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1344 // debuglog(" sell @"+sell[0]+" x"+sell[1]
1345 // +" buy @"+buy[0]+" x"+buy[1]
1346 // +" => x"+count+" @"+unitprofit);
1348 if (unitprofit <= 0)
1351 profit += count * unitprofit;
1354 if (buy[1]==0) buys.remove(buy);
1355 if (sell[1]==0) sells.remove(sell);
1357 // debuglog(" PROFIT "+profit);
1361 private class arbitrageOfferComparator implements Comparator {
1362 public int compare(Object o1, Object o2) {
1363 int p1 = ((int[])o1)[0];
1364 int p2 = ((int[])o2)[0];
1369 private @SuppressWarnings("unchecked")
1370 void calculateArbitrage(ArrayList<ArrayList<String>> data)
1371 throws InterruptedException {
1373 ArrayList<SortedSet<int[]>> arb_bs = null;
1374 String lastcommod = null;
1375 Comparator compar = new arbitrageOfferComparator();
1377 for (ArrayList<String> row : data) {
1378 String thiscommod = row.get(0);
1379 // debuglog("ROW "+row.toString());
1380 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1381 if (lastcommod != null)
1382 arbitrage += calculateArbitrageCommodity(arb_bs);
1383 // debuglog("ROW rdy");
1384 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1385 arb_bs.add(0, new TreeSet<int[]>(compar));
1386 arb_bs.add(1, new TreeSet<int[]>(compar));
1387 // debuglog("ROW init");
1388 lastcommod = thiscommod;
1390 for (int bs = 0; bs < 2; bs++) {
1391 String pricestr = row.get(bs*2 + 2);
1392 if (pricestr == null)
1394 int[] entry = new int[2];
1395 // debuglog("ROW BS "+bs);
1396 entry[0] = parseQty(pricestr);
1397 entry[1] = parseQty(row.get(bs*2 + 3));
1398 arb_bs.get(bs).add(entry);
1401 arbitrage += calculateArbitrageCommodity(arb_bs);
1403 if (arbitrage != 0) {
1404 arb = "<html><strong>arbitrage: "+arbitrage+" poe</strong>";
1406 arb = "no arbitrage";
1408 final String arb_final = arb;
1409 EventQueue.invokeLater(new Runnable() { public void run() {
1410 arbitrageResult.setText(arb_final);