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;
74 private int uploadcounter = 0;
77 * UTILITY METHODS AND SUBCLASSES
79 * Useable on any thread.
82 private int parseQty(String str) {
83 if (str.equals(">1000")) {
86 return Integer.parseInt(str);
90 private void debuglog(String s) {
91 if (dtxt == null) return;
92 long now = new Date().getTime();
93 dtxt.println("progress "+(now - startTime)+"ms "
94 +Thread.currentThread().getName()+": "+s);
97 private void debug_write_stringdata(String what, String data)
98 throws FileNotFoundException,IOException {
99 if (dtxt==null) return;
100 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
105 private void debug_write_bytes(String what, byte[] data)
106 throws FileNotFoundException,IOException {
107 if (dtxt==null) return;
108 FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
114 * An abstract market offer, entailing a commodity being bought or sold by
115 * a shoppe, for a certain price in a certain quantity. Not instantiable.
120 abstract class Offer {
121 public int commodity, price, quantity, shoppe;
123 * Create an offer from <code>record</code>, determining the shoppe Id from
124 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
125 * <code>priceIndex</code> should be the index of the price in the record
126 * (the quantity will be <code>priceIndex + 1</code>).
128 * @param record the record with data to create the offer from
129 * @param stallMap a map containing the ids of the various stalls
130 * @param commodMap a map containing the ids of the various commodities
131 * @param priceIndex the index of the price in the record
133 public Offer(ArrayList<String> record,
134 LinkedHashMap<String,Integer> stallMap,
135 HashMap<String,Integer> commodMap,
137 Integer commodId = commodMap.get(record.get(0));
138 if(commodId == null) {
139 throw new IllegalArgumentException();
141 commodity = commodId.intValue();
142 price = Integer.parseInt(record.get(priceIndex));
143 String qty = record.get(priceIndex+1);
144 quantity = parseQty(qty);
145 shoppe = stallMap.get(record.get(1)).intValue();
149 * Returns a human-readable version of this offer, useful for debugging
151 * @return human-readable offer
153 public String toString() {
154 return "[C:" + commodity + ",$" + price + ",Q:"
155 + quantity + ",S:" + shoppe + "]";
160 * An offer from a shoppe or stall to buy a certain quantity of a
161 * commodity for a certain price. If placed in an ordered Set,
162 * sorts by commodity index ascending, then by buy price
163 * descending, and finally by stall id ascending.
165 class Buy extends Offer implements Comparable<Buy> {
167 * Creates a new <code>Buy</code> offer from the given
168 * <code>record</code> using the other parameters to determine
169 * stall id and commodity id of the offer.
171 * @param record the record with data to create the offer from
172 * @param stallMap a map containing the ids of the various stalls
173 * @param commodMap a map containing the ids of the various commodities
175 public Buy(ArrayList<String> record,
176 LinkedHashMap<String,Integer> stallMap,
177 HashMap<String,Integer> commodMap) {
178 super(record,stallMap,commodMap,2);
182 * Sorts by commodity index ascending, then price descending,
183 * then stall id ascending.
185 public int compareTo(Buy buy) {
186 // organize by: commodity index, price, stall index
187 if(commodity == buy.commodity) {
188 // organize by price, then by stall index
189 if(price == buy.price) {
190 // organize by stall index
191 return shoppe>buy.shoppe ? 1 : -1;
192 } else if(price > buy.price) {
197 } else if(commodity > buy.commodity) {
206 * An offer from a shoppe or stall to sell a certain quantity of
207 * a commodity for a certain price. If placed in an ordered Set,
208 * sorts by commodity index ascending, then by sell price
209 * ascending, and finally by stall id ascending.
211 class Sell extends Offer implements Comparable<Sell> {
213 * Creates a new <code>Sell</code> offer from the given
214 * <code>record</code> using the other parameters to determine
215 * stall id and commodity id of the offer.
217 * @param record the record with data to create the offer from
218 * @param stallMap a map containing the ids of the various stalls
219 * @param commodMap a map containing the ids of the various commodities
221 public Sell(ArrayList<String> record,
222 LinkedHashMap<String,Integer> stallMap,
223 HashMap<String,Integer> commodMap) {
224 super(record,stallMap,commodMap,4);
228 * Sorts by commodity index ascending, then price ascending, then
229 * stall id ascending.
231 public int compareTo(Sell sell) {
232 // organize by: commodity index, price, stall index
233 if(commodity == sell.commodity) {
234 // organize by price, then by stall index
235 if(price == sell.price) {
236 // organize by stall index
237 return shoppe>sell.shoppe ? 1 : -1;
238 } else if(price > sell.price) {
243 } else if(commodity > sell.commodity) {
251 private void progressNote(final String s_in) throws Exception {
252 new UIA() { public void body() {
254 arb = arbitrageResult.getText();
256 if (arb != null && arb.length() != 0)
257 s = "<html>" + arb + "<br>" + s;
259 }}.exec("progressNote "+s_in);
263 * ENTRY POINT AND STARTUP
265 * Main thread and/or event thread
268 * Entry point. Read our preferences.
270 public MarketUploader() {
271 Preferences prefs = Preferences.userNodeForPackage(getClass());
273 if (prefs.getBoolean("writeDebugFiles", false)) {
275 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
276 } catch (java.io.FileNotFoundException e) {
277 System.err.println("JARRG: Error opening debug log: "+e);
281 if (prefs.getBoolean("useLiveServers", true)) {
282 YARRG_URL = YARRG_LIVE_URL;
283 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
285 YARRG_URL = YARRG_TEST_URL;
286 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
289 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
290 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
291 showArbitrage=prefs.getBoolean("showArbitrage", true);
293 debuglog("main on dispatch thread: "+EventQueue.isDispatchThread());
294 EventQueue.invokeLater(this);
298 * We arrange to wait for the GUI to be initialised, then look at
299 * every top-level window, and if it
302 debuglog("MarketUploader run()...");
303 if (EventQueueMonitor.isGUIInitialized()) {
304 debuglog("MarketUploader GUI already ready");
307 debuglog("MarketUploader waiting for GUI");
308 EventQueueMonitor.addGUIInitializedListener(this);
312 public void guiInitialized() {
313 Window ws[]= EventQueueMonitor.getTopLevelWindows();
314 EventQueueMonitor.addTopLevelWindowListener(this);
315 for (int i=0; i<ws.length; i++) {
316 debuglog("MarketUploader existing toplevel "+i);
317 topLevelWindowCreated(ws[i]);
321 public void topLevelWindowDestroyed(Window w) {
322 debuglog("MarketUploader destroyed toplevel");
325 public void topLevelWindowCreated(Window w) {
329 String name = w.getAccessibleContext().getAccessibleName();
330 debuglog("MarketUploader checking toplevel "+name);
331 if (!name.equals("Puzzle Pirates"))
333 debuglog("MarketUploader found toplevel, creating gui");
336 frame.setVisible(true);
340 * Set up the GUI, with its window and one-button
341 * interface. Only initialize if we're running alongside
342 * a Window named "Puzzle Pirates" though.
344 private void createGUI() {
346 frame = new JFrame("Jarrg Uploader");
347 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
348 GridLayout layout = new GridLayout(2,1);
349 frame.getContentPane().setLayout(layout);
350 //frame.setPreferredSize(new Dimension(200, 60));
352 findMarket = new JButton("Upload Market Data");
353 findMarket.addActionListener(new ActionListener() {
354 public void actionPerformed(ActionEvent e) {
357 findMarket.setEnabled(false);
358 resultSummary.setText("");
359 arbitrageResult.setText("");
360 new Thread("MarketUploader-uploader-"+uploadcounter) {
362 startTime = new Date().getTime();
363 unknownPCTBcommods = 0;
365 runUpload(uploadcounter);
366 } catch(Exception e) {
371 new UIX() { public void body() {
372 if(sidePanel != null) {
373 sidePanel.removePropertyChangeListener(changeListener);
375 if (progmon != null) {
379 findMarket.setEnabled(true);
381 } catch (Exception e) {
382 System.err.println("exception tidying on UI thread:");
389 frame.add(findMarket);
391 resultSummary = new JLabel("ready");
392 frame.add(resultSummary);
394 arbitrageResult = new JLabel("");
397 layout.setRows(layout.getRows() + 1);
398 frame.add(arbitrageResult);
405 * ERROR REPORTING AND GENERAL UTILITIES
407 * Synchronous modal dialogues
408 * error and error_html may be called from any thread
411 private abstract class UIA implements Runnable {
413 public abstract void body();
415 debuglog("UIA 2 "+what+" begin");
417 debuglog("UIA 3 "+what+" done");
419 public void exec(String what_in) {
421 debuglog("UIA 1 "+what+" request");
422 EventQueue.invokeLater(this);
425 private abstract class UIXR<ReturnType> implements Runnable {
426 public abstract ReturnType bodyr();
427 public ReturnType return_value;
430 debuglog("UIX 2 "+what+" begin");
431 return_value = bodyr();
432 debuglog("UIX 3 "+what+" done");
434 public ReturnType exec(String what_in) throws Exception {
436 if (EventQueue.isDispatchThread()) {
437 debuglog("UIX 1 "+what+" (event thread) entry");
439 debuglog("UIX 4 "+what+" (event thread) exit");
441 debuglog("UIX 1 "+what+" (other thread) entry");
442 EventQueue.invokeAndWait(this);
443 debuglog("UIX 4 "+what+" (other thread) exit");
448 private abstract class UIX extends UIXR<Object> implements Runnable {
449 public abstract void body();
450 public Object bodyr() { body(); return null; }
453 private void on_ui_thread() { assert(EventQueue.isDispatchThread()); }
454 private void on_our_thread() { assert(!EventQueue.isDispatchThread()); }
456 private void error(final String msg) {
458 new UIX() { public void body() {
459 resultSummary.setText("failed");
460 JOptionPane.showMessageDialog(frame,msg,"Error",
461 JOptionPane.ERROR_MESSAGE);
463 } catch (Exception e) {
464 System.err.println("exception reporting to UI thread:");
469 private void error_html(final String msg, String html) {
470 Pattern body = Pattern.compile("<body>(.*)</body>",
471 Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
472 Matcher m = body.matcher(html);
475 Pattern fixup = Pattern.compile("<(\\w+) */>");;
476 m = fixup.matcher(html);
477 html = m.replaceAll("<$1>");
478 m = Pattern.compile("[\\r\\n]+").matcher(html);
479 html = m.replaceAll(" ");
481 String whole_msg = "<html><h1>Error</h1>"+msg
482 +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
483 debuglog("###" + whole_msg + "###");
488 private void setProgress(final int nv) throws Exception {
489 new UIA() { public void body() {
490 progmon.setProgress(nv);
491 }}.exec("setProgress "+nv);
493 private boolean checkCancelled() throws Exception {
494 return new UIXR<Boolean>() { public Boolean bodyr() {
495 boolean can = progmon.isCanceled();
496 if (can) resultSummary.setText("cancelled");
497 return new Boolean(can);
498 }}.exec("checkCancelled").booleanValue();
502 * GUI MANIPULATION CALLBACKS
505 private PropertyChangeListener changeListener = new PropertyChangeListener() {
506 public void propertyChange(PropertyChangeEvent e) {
508 if(e.getNewValue() != null &&
509 e.getPropertyName().equals
510 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
511 Accessible islandInfo =
512 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
513 String text = islandInfo.getAccessibleContext().getAccessibleText()
514 .getAtIndex(AccessibleText.SENTENCE,0);
515 int index = text.indexOf(":");
516 String name = text.substring(0,index);
518 // debuglog(islandName);
519 sidePanel.removePropertyChangeListener(this);
525 private void getIsland() {
528 // If the league tracker is there, we can skip the faff
529 // and ask for its tooltip, since we're on a boat
531 Accessible leagueTrackerContainer =
532 descendNodes(window,new int[] {0,1,0,0,2,1});
533 Accessible leagueTrackerItself =
534 descendByClass(leagueTrackerContainer,
535 "com.threerings.yohoho.sea.client.LeagueTracker");
536 Accessible leagueTracker = descend(leagueTrackerItself, 1);
538 islandName = ((JLabel)leagueTracker).getToolTipText();
539 } catch (NullPointerException e) {
540 // evidently we're actually on an island
543 AccessibleContext chatArea =
544 descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
545 .getAccessibleContext();
546 // attach the property change listener to the outer sunshine
547 // panel if the "ahoy" tab is not active, otherwise attach it to
548 // the scroll panel in the "ahoy" tab.
549 if(!"com.threerings.piracy.client.AttentionListPanel".
550 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
551 .getClass().getCanonicalName())) {
552 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
553 .getAccessibleContext();
555 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
556 .getAccessibleContext();
558 sidePanel.addPropertyChangeListener(changeListener);
559 latch = new java.util.concurrent.CountDownLatch(1);
560 // make the Players Online ("/who") panel appear
561 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
562 chat.setTextContents("/w");
563 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
564 for(int i=0;i<c;i++) {
565 if("notify-field-accept".equals(chatArea.getAccessibleAction()
566 .getAccessibleActionDescription(i))) {
567 chatArea.getAccessibleAction().doAccessibleAction(i);
574 * Find the ocean name from the window title, and set global
577 private void getOcean() {
580 AccessibleContext topwindow = window.getAccessibleContext();
581 oceanName = topwindow.getAccessibleName()
582 .replaceAll(".*on the (\\w+) ocean", "$1");
587 * Run the data collection process, and upload the results. This
588 * is the method that calls most of the other worker methods for
589 * the process. If an error occurs, the method will call the
590 * error method and return early, freeing up the button to be
593 * @exception Exception if an error we didn't expect occured
595 private class YarrgTimestampFetcher extends Thread {
596 public YarrgTimestampFetcher(int counter) {
597 super("MarketUploader-YarrgTimestampFetcher-"+uploadcounter);
599 public String ts = null;
602 ts = getYarrgTimestamp();
603 debuglog("(async) yarrg timestamp ready.");
604 } catch(Exception e) {
605 error("Error getting YARRG timestamp: "+e);
610 private void runUpload(int counter) throws Exception {
613 boolean doneyarrg = false, donepctb = false;
614 YarrgTimestampFetcher yarrgts_thread = null;
616 debuglog("starting");
619 debuglog("(async) yarrg timestamp...");
620 yarrgts_thread = new YarrgTimestampFetcher(counter);
621 yarrgts_thread.start();
624 final AccessibleTable accesstable =
625 new UIXR<AccessibleTable>() { public AccessibleTable bodyr() {
626 progmon = new ProgressMonitor
627 (frame,"Processing Market Data","Getting table data",0,100);
628 progmon.setMillisToDecideToPopup(0);
629 progmon.setMillisToPopup(0);
631 AccessibleTable at = findMarketTable();
633 error("Market table not found!"+
634 " Please open the Buy/Sell Commodities interface.");
637 if(at.getAccessibleRowCount() == 0) {
638 error("No data found, please wait for the table to have data first!");
641 if(!isDisplayAll()) {
642 error("Please select \"All\" from the Display: popup menu.");
646 debuglog("(async) getisland...");
648 debuglog("getocean...");
650 debuglog("getocean done");
653 }}.exec("accesstable");
654 if (accesstable == null) return;
657 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
659 debuglog("(async) getisland done");
661 String yarrgts = null;
662 if (yarrgts_thread != null) {
663 debuglog("(async) yarrg timestamp join...");
664 yarrgts_thread.join();
665 debuglog("(async) yarrg timestamp joined.");
666 yarrgts = yarrgts_thread.ts;
669 if (islandName == null) {
670 error("Could not find island name in YPP user interface.");
674 debuglog("table check...");
676 final ArrayList<ArrayList<String>> data =
677 new UIXR<ArrayList<ArrayList<String>>>
678 () { public ArrayList<ArrayList<String>> bodyr() {
679 String headings_expected[] = new String[]
680 { "Commodity", "Trading outlet", "Buy price",
681 "Will buy", "Sell price", "Will sell" };
683 ArrayList<ArrayList<String>> headers =
684 getData(accesstable.getAccessibleColumnHeader());
685 if (headers.size() != 1) {
686 error("Table headings not one row! " + headers.toString());
689 if (headers.get(0).size() < 6 ||
690 headers.get(0).size() > 7) {
691 error("Table headings not six or seven columns! " + headers.toString());
694 for (int col=0; col<headings_expected.length; col++) {
695 String expd = headings_expected[col];
696 String got = headers.get(0).get(col);
697 if (expd.compareTo(got) != 0) {
698 error("Table heading for column "+col
699 +" is not \""+expd+"\" but \""+got+"\".\n\n"
700 +"Please do not reorder the table when using this tool.");
705 debuglog("table read...");
707 return getData(accesstable);
709 if (data == null) return;
712 debuglog("arbitrage...");
713 calculateArbitrage(data);
714 debuglog("arbitrage done.");
717 if (uploadToYarrg && yarrgts != null) {
718 debuglog("yarrg prepare...");
719 progressNote("Yarrg: Preparing data");
722 StringBuilder yarrgsb = new StringBuilder();
723 String yarrgdata; // string containing what we'll feed to yarrg
725 for (ArrayList<String> row : data) {
726 if (row.size() > 6) {
729 for (String rowitem : row) {
730 yarrgsb.append(rowitem != null ? rowitem : "");
731 yarrgsb.append("\t");
733 yarrgsb.setLength(yarrgsb.length()-1); // chop
734 yarrgsb.append("\n");
737 yarrgdata = yarrgsb.toString();
739 progressNote("Yarrg: Uploading");
740 debuglog("yarrg upload...");
742 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
743 debuglog("yarrg done.");
747 debuglog("pctb prepare...");
748 progressNote("PCTB: Getting stall names");
750 if(checkCancelled()) {
753 TreeSet<Offer> buys = new TreeSet<Offer>();
754 TreeSet<Offer> sells = new TreeSet<Offer>();
755 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
757 progressNote("PCTB: Sorting offers");
758 if(checkCancelled()) {
763 debuglog("pctb commodmap...");
764 HashMap<String,Integer> commodMap = getCommodMap();
765 if(commodMap == null) {
768 debuglog("pctb commodmap done.");
769 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
771 // debuglog("\n\n\n"+buys);
773 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
775 progressNote("PCTB: Sending data");
776 if(checkCancelled()) {
779 GZIPOutputStream out = new GZIPOutputStream(outStream);
780 DataOutputStream dos = new DataOutputStream(out);
781 dos.writeBytes("005y\n");
782 dos.writeBytes(stallMap.size()+"\n");
783 dos.writeBytes(getAbbrevStallList(stallMap));
784 writeBuySellOffers(buys,sells,offerCount,out);
786 debuglog("pctb send...");
788 byte[] ba = outStream.toByteArray();
789 debug_write_bytes("pctb-marketdata.gz", ba);
791 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
792 debuglog("pctb sent.");
793 if (in == null) return;
795 if(checkCancelled()) {
798 progressNote("PCTB: Waiting ...");
799 debuglog("pctb finish...");
800 donepctb = finishUpload(in);
801 debuglog("pctb done.");
806 if ((uploadToPCTB && !donepctb) ||
807 (uploadToYarrg && !doneyarrg)) {
809 } else if (unknownPCTBcommods != 0) {
810 summary= "PCTB lacks "+unknownPCTBcommods+" commod(s)";
811 } else if (donepctb || doneyarrg) {
812 summary= "Done " + islandName;
814 summary= "uploaded nowhere!";
816 final String summary_final = summary;
817 new UIX() { public void body() {
818 resultSummary.setText(summary_final);
819 }}.exec("resultSummary.setText");
825 * Get the offer data out of the table and cache it in an
826 * <code>ArrayList</code>.
828 * @param table the <code>AccessibleTable</code> containing the market data
829 * @return an array of record arrays, each representing a row of the table
831 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
833 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
834 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
835 ArrayList<String> row = new ArrayList<String>();
836 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
837 row.add(table.getAccessibleAt(i, j)
838 .getAccessibleContext().getAccessibleName());
846 * @return the table containing market data if it exists,
847 * otherwise <code>null</code>
849 public AccessibleTable findMarketTable() {
851 Accessible node1 = window;
852 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0});
854 // 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})
856 if (!(node instanceof JTable)) {
857 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
860 if (!(node instanceof JTable)) return null;
861 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
867 * Utility method to descend through several levels of Accessible children
870 * @param parent the node on which to start the descent
871 * @param path an array of ints, each int being the index of the next
872 * accessible child to descend.
873 * @return the <code>Accessible</code> reached by following the
874 * descent path, or <code>null</code> if the desired path was
877 private Accessible descendNodes(Accessible parent, int[] path) {
879 for(int i=0;i<path.length;i++) {
880 if (null == (parent = descend(parent, path[i]))) return null;
886 * Descends one level to the specified child of the parent
887 * <code>Accessible</code> "node".
889 * @param parent the node with children
890 * @param childNum the index of the child of <code>parent</code> to return
891 * @return the <code>childNum</code> child of <code>parent</code>
892 * or <code>null</code> if the child is not found.
894 private Accessible descend(Accessible parent, int childNum) {
896 if (parent == null) return null;
897 int children = parent.getAccessibleContext().getAccessibleChildrenCount();
898 if (childNum >= children) {
899 debuglog("DESCEND "+childNum+" > "+children+" NOT FOUND");
902 Accessible child = parent.getAccessibleContext()
903 .getAccessibleChild(childNum);
904 debuglog("DESCEND "+childNum+" "+child.getClass().getName()+" OK");
909 * Descends one level to the child which has the specified class.
911 * @param parent the node with children
912 * @param classname the name of the class, as a string
913 * @return the child or <code>null</code> if the child is not found.
915 private Accessible descendByClass(Accessible parent, String classname) {
917 if (parent == null) return null;
918 AccessibleContext ac = parent.getAccessibleContext();
919 int children = ac.getAccessibleChildrenCount();
920 for (int i=0; i<children; i++) {
921 Accessible child = ac.getAccessibleChild(i);
922 if (child.getClass().getName() == classname) {
923 debuglog("DESCEND CLASS "+classname+" OK");
927 debuglog("DESCEND CLASS "+classname+" NOT FOUND");
931 public static void main(String[] args) {
932 new MarketUploader();
936 * Returns true if the "Display:" menu on the commodities
937 * interface in YPP is set to "All"
939 * @return <code>true</code> if all commodities are displayed,
940 * otherwise <code>false</code>
942 private boolean isDisplayAll() {
944 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
945 if(!(button instanceof JButton)) {
946 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
948 String display = button.getAccessibleContext().getAccessibleName();
949 if(!display.equals("All")) {
956 * Gets the list of commodities and their associated commodity ids.
958 * @return a map where the key is the commodity and the value is
961 private HashMap<String,Integer> getCommodMap() {
963 if(commodMap != null) {
966 HashMap<String,Integer> map = new HashMap<String,Integer>();
969 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
971 new BufferedReader(new InputStreamReader(host.openStream()));
972 StringBuilder sb = new StringBuilder();
974 while((str = br.readLine()) != null) {
978 debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
979 int first = sb.indexOf("<pre>") + 5;
980 int last = sb.indexOf("</body>");
981 xml = sb.substring(first,last);
982 Reader reader = new CharArrayReader(xml.toCharArray());
983 Document d = DocumentBuilderFactory.newInstance()
984 .newDocumentBuilder().parse(new InputSource(reader));
985 NodeList maps = d.getElementsByTagName("CommodMap");
986 for(int i=0;i<maps.getLength();i++) {
987 NodeList content = maps.item(i).getChildNodes();
988 Integer num = Integer.parseInt(content.item(1).getTextContent());
989 map.put(content.item(0).getTextContent(),num);
991 } catch(Exception e) {
993 error("Unable to load Commodity list from server!");
1001 * Given the list of offers, this method will find all the unique
1002 * stall names and return them in a <code>LinkedHashMap</code>
1003 * where the key is the stall name and the value is the generated
1004 * stall id (position in the list). <p> The reason this method
1005 * returns a LinkedHashMap instead of a simple HashMap is the
1006 * need for iterating over the stall names in insertion order for
1007 * output to the server.
1009 * @param offers the list of records from the commodity buy/sell interface
1010 * @return an iterable ordered map of the stall names and
1011 * generated stall ids
1013 private LinkedHashMap<String,Integer> getStallMap
1014 (ArrayList<ArrayList<String>> offers) {
1016 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
1017 for(ArrayList<String> offer : offers) {
1018 String shop = offer.get(1);
1019 if(!map.containsKey(shop)) {
1021 map.put(shop,count);
1028 * Gets a sorted list of Buys and Sells from the list of
1029 * records. <code>buys</code> and <code>sells</code> should be
1030 * pre-initialized and passed into the method to receive the
1031 * data. Returns a 2-length int array with the number of buys
1034 * @param offers the data found from the market table in-game
1035 * @param buys an empty initialized <code>TreeSet<Offer></code> to
1036 * hold the Buy offers.
1037 * @param sells an empty initialized <code>TreeSet<Offer></code> to
1038 * hold the Sell offers.
1039 * @param stalls the map of stalls to their ids
1040 * @param commodMap the map of commodities to their ids
1041 * @return a 2-length int[] array containing the number of buys
1042 * and sells, respectively
1044 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers,
1045 TreeSet<Offer> buys,
1046 TreeSet<Offer> sells,
1047 LinkedHashMap<String,Integer> stalls,
1048 HashMap<String,Integer> commodMap) {
1049 int[] buySellCount = new int[2];
1050 for(ArrayList<String> offer : offers) {
1052 if(offer.get(2) != null) {
1053 buys.add(new Buy(offer,stalls,commodMap));
1056 if(offer.get(4) != null) {
1057 sells.add(new Sell(offer,stalls,commodMap));
1060 } catch(IllegalArgumentException e) {
1061 unknownPCTBcommods++;
1062 debuglog("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
1065 if (buySellCount[0]==0 && buySellCount[1]==0) {
1066 error("No (valid) offers for PCTB?!");
1067 throw new IllegalArgumentException();
1069 return buySellCount;
1073 * Prepares the list of stalls for writing to the output stream.
1074 * The <code>String</code> returned by this method is ready to be
1075 * written directly to the stream. <p> All shoppe names are left
1076 * as they are. Stall names are abbreviated just before the
1077 * apostrophe in the possessive, with an "^" and a letter
1078 * matching the stall's type appended. Example: "Burninator's
1079 * Ironworking Stall" would become "Burninator^I".
1081 * @param stallMap the map of stalls and stall ids in an iterable order
1082 * @return a <code>String</code> containing the list of stalls in
1083 * format ready to be written to the output stream.
1085 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1086 // set up some mapping
1087 HashMap<String,String> types = new HashMap<String,String>();
1088 types.put("Apothecary Stall", "A");
1089 types.put("Distilling Stall", "D");
1090 types.put("Furnishing Stall", "F");
1091 types.put("Ironworking Stall", "I");
1092 types.put("Shipbuilding Stall", "S");
1093 types.put("Tailoring Stall", "T");
1094 types.put("Weaving Stall", "W");
1096 StringBuilder sb = new StringBuilder();
1097 for(String name : stallMap.keySet()) {
1098 int index = name.indexOf("'s");
1099 String finalName = name;
1102 finalName = name.substring(0,index);
1103 if(index + 2 < name.length()) {
1104 String end = name.substring(index+2,name.length()).trim();
1105 type = types.get(end);
1109 sb.append(name+"\n");
1111 sb.append(finalName+"^"+type+"\n");
1114 return sb.toString();
1118 * Writes a list of offers in correct format to the output stream.
1120 * The format is thus: (all numbers are 2-byte integers in
1121 * little-endian format) (number of offers of this type, aka
1122 * buy/sell) (commodity ID) (number of offers for this commodity)
1123 * [shopID price qty][shopID price qty]...
1125 * @param out the output stream to write the data to
1126 * @param offers the offers to write
1128 private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1129 throws IOException {
1130 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1131 if(offers.size() == 0) {
1132 // nothing to write, and "0" has already been written
1135 int commodity = offers.first().commodity;
1137 for(Offer offer : offers) {
1138 if(commodity != offer.commodity) {
1140 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1142 commodity = offer.commodity;
1145 writeLEShort(offer.shoppe,buffer); // stall index
1146 writeLEShort(offer.price,buffer); // buy price
1147 writeLEShort(offer.quantity,buffer); // buy qty
1150 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1154 * Writes the buffered data to the output strea for one commodity.
1156 * @param out the stream to write to
1157 * @param buffer the buffered data to write
1158 * @param commodity the commmodity id to write before the buffered data
1159 * @param count the number of offers for this commodity to write
1162 private void writeBufferedOffers(OutputStream out, byte[] buffer,
1163 int commodity, int count)
1164 throws IOException {
1165 writeLEShort(commodity,out); // commod index
1166 writeLEShort(count,out); // offer count
1167 out.write(buffer); // the buffered offers
1171 * Writes the buy and sell offers to the outputstream by calling
1174 * @param buys list of Buy offers to write
1175 * @param sells list of Sell offers to write
1176 * @param offerCount 2-length int array containing the number of
1177 * buys and sells to write out
1178 * @param out the stream to write to
1180 private void writeBuySellOffers(TreeSet<Offer> buys,
1181 TreeSet<Offer> sells,
1182 int[] offerCount, OutputStream out)
1183 throws IOException {
1185 writeLEShort(offerCount[0],out);
1186 writeOffers(out,buys);
1188 writeLEShort(offerCount[1],out);
1189 writeOffers(out,sells);
1192 private String readstreamstring(InputStream in) throws IOException {
1193 StringBuilder sb = new StringBuilder();
1194 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1196 while((str = br.readLine()) != null) {
1197 sb.append(str+"\n");
1199 return sb.toString();
1203 * Sends the data to the server via multipart-formdata POST,
1204 * with the gzipped data as a file upload.
1206 * @param file an InputStream open to the gzipped data we want to send
1208 private InputStream sendInitialData(InputStream file) throws IOException {
1210 ClientHttpRequest http =
1211 new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1212 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1214 String err = readstreamstring(http.resultstream());
1215 error("Error sending initial data:\n"+err);
1218 return http.resultstream();
1222 * Utility method to write a 2-byte int in little-endian form to
1225 * @param num an integer to write
1226 * @param out stream to write to
1228 private void writeLEShort(int num, OutputStream out) throws IOException {
1229 out.write(num & 0xFF);
1230 out.write((num >>> 8) & 0xFF);
1234 * Reads the response from the server, and selects the correct parameters
1235 * which are sent in a GET request to the server asking it to confirm
1236 * the upload and accept the data into the database. Notably, the island id
1237 * and ocean id are determined, while other parameter such as the filename
1238 * are determined from the hidden form fields.
1240 * @param in stream of data from the server to read
1242 private boolean finishUpload(InputStream in) throws IOException {
1245 String html = readstreamstring(in);
1246 debug_write_stringdata("pctb-initial.html", html);
1249 Pattern params = Pattern.compile
1250 ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1251 ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1252 ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1253 m = params.matcher(html);
1255 error_html("The PCTB server returned unusual data."+
1256 " Maybe you're using an old version of the uploader?",
1260 String forceReload = m.group(1);
1261 String filename = m.group(2);
1263 Pattern oceanNumPat =
1264 Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1265 m = oceanNumPat.matcher(html);
1267 error_html("Unable to find the ocean in the server's list of oceans!",
1271 String oceanNum = m.group(1);
1273 Pattern oceanIslandNum =
1274 Pattern.compile("islands\\[" + oceanNum
1275 + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1277 m = oceanIslandNum.matcher(html);
1279 error_html("This does not seem to be a valid island! Unable to upload.",
1283 String islandNum = m.group(1);
1285 URL get = new URL(PCTB_HOST_URL +
1286 "upload.php?action=setisland&ocean=" + oceanNum
1287 + "&island=" + islandNum
1288 + "&forcereload=" + forceReload
1289 + "&filename=" + filename);
1290 String complete = readstreamstring(get.openStream());
1291 debug_write_stringdata("pctb-final.html", complete);
1292 Pattern done = Pattern.compile
1293 ("Your data has been integrated into the database. Thank you!");
1294 m = done.matcher(complete);
1298 error_html("Something was wrong with the final upload parameters!",
1304 private InputStream post_for_yarrg(ClientHttpRequest http)
1305 throws IOException {
1308 String err = readstreamstring(http.resultstream());
1309 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1312 return http.resultstream();
1315 private String getYarrgTimestamp() throws IOException {
1316 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1317 http.setParameter("clientname", YARRG_CLIENTNAME);
1318 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1319 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1320 http.setParameter("requesttimestamp", "y");
1321 InputStream in = post_for_yarrg(http);
1322 if (in == null) return null;
1323 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1324 String tsresult = br.readLine();
1325 return tsresult.substring(3, tsresult.length()-1);
1328 private boolean runYarrg(String timestamp, String ocean, String island,
1329 String yarrgdata) throws IOException {
1330 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1331 BufferedOutputStream bufos =
1332 new BufferedOutputStream(new GZIPOutputStream(bos));
1333 bufos.write(yarrgdata.getBytes() );
1335 byte[] compressed = bos.toByteArray();
1336 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1337 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1339 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1340 http.setParameter("clientname", YARRG_CLIENTNAME);
1341 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1342 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1343 http.setParameter("timestamp", timestamp);
1344 http.setParameter("ocean", ocean);
1345 http.setParameter("island", island);
1346 http.setParameter("data", "deduped.tsv.gz", file,
1347 "application/octet-stream");
1348 InputStream in = post_for_yarrg(http);
1349 if (in == null) return false;
1350 String output = readstreamstring(in);
1351 if (!output.startsWith("OK")) {
1352 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1355 debug_write_stringdata("yarrg-result.txt", output);
1359 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1360 // debuglog("ARBITRAGE?");
1362 SortedSet<int[]> buys = arb_bs.get(0);
1363 SortedSet<int[]> sells = arb_bs.get(1);
1367 // NB "sell" means they sell, ie we buy
1368 sell = sells.last();
1370 } catch (NoSuchElementException e) {
1374 int unitprofit = buy[0] - sell[0];
1375 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1376 // debuglog(" sell @"+sell[0]+" x"+sell[1]
1377 // +" buy @"+buy[0]+" x"+buy[1]
1378 // +" => x"+count+" @"+unitprofit);
1380 if (unitprofit <= 0)
1383 profit += count * unitprofit;
1386 if (buy[1]==0) buys.remove(buy);
1387 if (sell[1]==0) sells.remove(sell);
1389 // debuglog(" PROFIT "+profit);
1393 private class arbitrageOfferComparator implements Comparator {
1394 public int compare(Object o1, Object o2) {
1395 int p1 = ((int[])o1)[0];
1396 int p2 = ((int[])o2)[0];
1401 private @SuppressWarnings("unchecked")
1402 void calculateArbitrage(ArrayList<ArrayList<String>> data)
1403 throws InterruptedException {
1405 ArrayList<SortedSet<int[]>> arb_bs = null;
1406 String lastcommod = null;
1407 Comparator compar = new arbitrageOfferComparator();
1409 for (ArrayList<String> row : data) {
1410 String thiscommod = row.get(0);
1411 // debuglog("ROW "+row.toString());
1412 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1413 if (lastcommod != null)
1414 arbitrage += calculateArbitrageCommodity(arb_bs);
1415 // debuglog("ROW rdy");
1416 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1417 arb_bs.add(0, new TreeSet<int[]>(compar));
1418 arb_bs.add(1, new TreeSet<int[]>(compar));
1419 // debuglog("ROW init");
1420 lastcommod = thiscommod;
1422 for (int bs = 0; bs < 2; bs++) {
1423 String pricestr = row.get(bs*2 + 2);
1424 if (pricestr == null)
1426 int[] entry = new int[2];
1427 // debuglog("ROW BS "+bs);
1428 entry[0] = parseQty(pricestr);
1429 entry[1] = parseQty(row.get(bs*2 + 3));
1430 arb_bs.get(bs).add(entry);
1433 arbitrage += calculateArbitrageCommodity(arb_bs);
1435 if (arbitrage != 0) {
1436 arb = "<html><strong>arbitrage: "+arbitrage+" poe</strong>";
1438 arb = "no arbitrage";
1440 final String arb_final = arb;
1441 EventQueue.invokeLater(new Runnable() { public void run() {
1442 arbitrageResult.setText(arb_final);