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 // UI object references which are set during startup
40 private JFrame frame = null;
41 private Window window = null;
43 // Genuinely global variables
44 public PrintStream dtxt = null;
45 private int uploadcounter = 0;
47 // UI objects which are enabled/disabled, cleared/set, created/destroyed,
48 // etc., for each upload
49 private JButton findMarket = null;
50 private JLabel resultSummary = null;
51 private JLabel arbitrageResult = null;
52 private ProgressMonitor progmon = null;
54 // PCTB protocol parameters
55 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
56 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
57 private String PCTB_HOST_URL;
59 // YARRG protocol parameters
60 private final static String YARRG_CLIENTNAME = "jpctb greenend";
61 private final static String YARRG_CLIENTVERSION =
62 net.chiark.yarrg.Version.version;
63 private final static String YARRG_CLIENTFIXES = "bug-094";
64 private final static String YARRG_LIVE_URL =
65 "http://upload.yarrg.chiark.net/commod-update-receiver";
66 private final static String YARRG_TEST_URL =
67 "http://upload.yarrg.chiark.net/test/commod-update-receiver";
68 private String YARRG_URL;
71 private boolean uploadToYarrg;
72 private boolean uploadToPCTB;
73 private boolean showArbitrage;
75 // Values cleared/set for each upload, or used during upload processing
76 private long startTime = 0;
78 private String islandName = null;
79 private String oceanName = null;
80 private java.util.concurrent.CountDownLatch latch = null;
82 private AccessibleContext sidePanel;
84 // PCTB-specific variables
85 private int unknownPCTBcommods = 0;
86 private HashMap<String,Integer> commodMap;
89 /*****************************************
90 * UPLOAD-TARGET-INDEPENDENT CODE *
91 *****************************************/
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 debuglog(String s) {
109 if (dtxt == null) return;
110 long now = new Date().getTime();
111 dtxt.println("progress "+(now - startTime)+"ms "
112 +Thread.currentThread().getName()+": "+s);
115 private void debug_write_stringdata(String what, String data)
116 throws FileNotFoundException,IOException {
117 if (dtxt==null) return;
118 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
123 private void debug_write_bytes(String what, byte[] data)
124 throws FileNotFoundException,IOException {
125 if (dtxt==null) return;
126 FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
133 * ENTRY POINT AND STARTUP
135 * Main thread and/or event thread
138 public static void main(String[] args) {
139 new MarketUploader();
142 public MarketUploader() {
143 Preferences prefs = Preferences.userNodeForPackage(getClass());
145 if (prefs.getBoolean("writeDebugFiles", false)) {
147 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
148 } catch (java.io.FileNotFoundException e) {
149 System.err.println("JARRG: Error opening debug log: "+e);
153 if (prefs.getBoolean("useLiveServers", true)) {
154 YARRG_URL = YARRG_LIVE_URL;
155 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
157 YARRG_URL = YARRG_TEST_URL;
158 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
161 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
162 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
163 showArbitrage=prefs.getBoolean("showArbitrage", true);
165 debuglog("main on dispatch thread: "+EventQueue.isDispatchThread());
166 EventQueue.invokeLater(this);
170 * We arrange to wait for the GUI to be initialised, then look at
171 * every top-level window to see if the Puzzle Pirates window turns up.
174 debuglog("MarketUploader run()...");
175 if (EventQueueMonitor.isGUIInitialized()) {
176 debuglog("MarketUploader GUI already ready");
179 debuglog("MarketUploader waiting for GUI");
180 EventQueueMonitor.addGUIInitializedListener(this);
184 public void guiInitialized() {
185 Window ws[]= EventQueueMonitor.getTopLevelWindows();
186 EventQueueMonitor.addTopLevelWindowListener(this);
187 for (int i=0; i<ws.length; i++) {
188 debuglog("MarketUploader existing toplevel "+i);
189 topLevelWindowCreated(ws[i]);
193 public void topLevelWindowDestroyed(Window w) {
194 debuglog("MarketUploader destroyed toplevel");
197 public void topLevelWindowCreated(Window w) {
201 String name = w.getAccessibleContext().getAccessibleName();
202 debuglog("MarketUploader checking toplevel "+name);
203 if (!name.equals("Puzzle Pirates"))
204 // Only if we're running alongside a Window named "Puzzle Pirates"
206 debuglog("MarketUploader found toplevel, creating gui");
209 frame.setVisible(true);
212 private void createGUI() {
213 // Actually set up our GUI
215 frame = new JFrame("Jarrg Uploader");
216 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
217 GridLayout layout = new GridLayout(2,1);
218 frame.getContentPane().setLayout(layout);
219 //frame.setPreferredSize(new Dimension(200, 60));
221 findMarket = new JButton("Upload Market Data");
222 findMarket.addActionListener(new ActionListener() {
223 public void actionPerformed(ActionEvent e) {
224 // This is called when the user clicks "upload"
228 findMarket.setEnabled(false);
229 resultSummary.setText("");
230 arbitrageResult.setText("");
231 new Thread("MarketUploader-uploader-"+uploadcounter) {
233 startTime = new Date().getTime();
234 unknownPCTBcommods = 0;
236 runUpload(uploadcounter);
237 } catch(Exception e) {
242 new UIX() { public void body() {
243 if(sidePanel != null) {
244 sidePanel.removePropertyChangeListener(changeListener);
246 if (progmon != null) {
250 findMarket.setEnabled(true);
252 } catch (Exception e) {
253 System.err.println("exception tidying on UI thread:");
260 frame.add(findMarket);
262 resultSummary = new JLabel("ready");
263 frame.add(resultSummary);
265 arbitrageResult = new JLabel("");
268 layout.setRows(layout.getRows() + 1);
269 frame.add(arbitrageResult);
278 * Special measures are needed because:
279 * - it is not permitted to use any Swing UI classes or objects
280 * other than on the Swing event thread
281 * - we want to run our upload asynchronously
282 * - we want to do some computation asynchronously (eg, the
283 * arbitrage and upload data prep)
285 * So what we do is this:
286 * 1. When the user asks to upload, we spawn a new thread
287 * to do the upload ("MarketUploader-uploader-*", see
288 * the call to "new Thread" inside createGUI.
289 * 2. Whenever that thread needs to touch a UI object it
290 * uses EventQueue.invokeLater or .invokeAndWait to
291 * perform the relevant action. We wrap these calls up
292 * in three utility classes:
293 * UIA - runs code on UI thread, asynchronously
294 * UIX - runs code on UI thread, waits for it to finish
295 * UIXR - as UIX but also returns a value
296 * These hide the details of the EventQueue class and also do
297 * some debugging and argument shuffling; the calling syntax is
298 * still painful, unfortunately, and there is a weird constraint
299 * on variables used inside the inner body. For a simple
300 * example, see the handling of "summary" and "summary_final"
301 * for the call to UIX at the bottom of runUpload.
302 * 3. Try to put everything back when that thread exits.
305 * a. There is another thread spawed early to get a timestamp from
306 * YARRG, if we are uploading there.
307 * b. Finding the island name can involve callbacks which run in
308 * the UI event thread. Basically we do the work there, and use
309 * a CountDownLatch to cause the uploader thread to wait as
313 private void on_ui_thread() { assert(EventQueue.isDispatchThread()); }
314 private void on_our_thread() { assert(!EventQueue.isDispatchThread()); }
316 private abstract class UIA implements Runnable {
318 public abstract void body();
320 debuglog("UIA 2 "+what+" begin");
322 debuglog("UIA 3 "+what+" done");
324 public void exec(String what_in) {
326 debuglog("UIA 1 "+what+" request");
327 EventQueue.invokeLater(this);
330 private abstract class UIXR<ReturnType> implements Runnable {
331 public abstract ReturnType bodyr();
332 public ReturnType return_value;
335 debuglog("UIX 2 "+what+" begin");
336 return_value = bodyr();
337 debuglog("UIX 3 "+what+" done");
339 public ReturnType exec(String what_in) throws Exception {
341 if (EventQueue.isDispatchThread()) {
342 debuglog("UIX 1 "+what+" (event thread) entry");
344 debuglog("UIX 4 "+what+" (event thread) exit");
346 debuglog("UIX 1 "+what+" (other thread) entry");
347 EventQueue.invokeAndWait(this);
348 debuglog("UIX 4 "+what+" (other thread) exit");
353 private abstract class UIX extends UIXR<Object> implements Runnable {
354 public abstract void body();
355 public Object bodyr() { body(); return null; }
359 * ERROR REPORTING AND GENERAL UTILITIES
361 * Synchronous modal dialogues
362 * error and error_html may be called from any thread
365 private void error(final String msg) {
367 new UIX() { public void body() {
368 resultSummary.setText("failed");
369 JOptionPane.showMessageDialog(frame,msg,"Error",
370 JOptionPane.ERROR_MESSAGE);
372 } catch (Exception e) {
373 System.err.println("exception reporting to UI thread:");
378 private void error_html(final String msg, String html) {
379 Pattern body = Pattern.compile("<body>(.*)</body>",
380 Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
381 Matcher m = body.matcher(html);
384 Pattern fixup = Pattern.compile("<(\\w+) */>");;
385 m = fixup.matcher(html);
386 html = m.replaceAll("<$1>");
387 m = Pattern.compile("[\\r\\n]+").matcher(html);
388 html = m.replaceAll(" ");
390 String whole_msg = "<html><h1>Error</h1>"+msg
391 +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
392 debuglog("###" + whole_msg + "###");
397 private void progressNote(final String s_in) throws Exception {
398 new UIA() { public void body() {
400 arb = arbitrageResult.getText();
402 if (arb != null && arb.length() != 0)
403 s = "<html>" + arb + "<br>" + s;
405 }}.exec("progressNote "+s_in);
407 private void setProgress(final int nv) throws Exception {
408 new UIA() { public void body() {
409 progmon.setProgress(nv);
410 }}.exec("setProgress "+nv);
412 private boolean checkCancelled() throws Exception {
413 return new UIXR<Boolean>() { public Boolean bodyr() {
414 boolean can = progmon.isCanceled();
415 if (can) resultSummary.setText("cancelled");
416 return new Boolean(can);
417 }}.exec("checkCancelled").booleanValue();
422 * ACTUAL DATA COLLECTION AND UPLOAD
425 private void runUpload(int counter) throws Exception {
426 // Runs the data collection process, and upload the results.
427 // In most cases of error, we call error() (which synchronously
428 // reports the error) and then simply return.
432 boolean doneyarrg = false, donepctb = false;
433 YarrgTimestampFetcher yarrgts_thread = null;
435 debuglog("starting");
438 debuglog("(async) yarrg timestamp...");
439 yarrgts_thread = new YarrgTimestampFetcher(counter);
440 yarrgts_thread.start();
443 final AccessibleTable accesstable =
444 new UIXR<AccessibleTable>() { public AccessibleTable bodyr() {
445 progmon = new ProgressMonitor
446 (frame,"Processing Market Data","Getting table data",0,100);
447 progmon.setMillisToDecideToPopup(0);
448 progmon.setMillisToPopup(0);
450 AccessibleTable at = findMarketTable();
452 error("Market table not found!"+
453 " Please open the Buy/Sell Commodities interface.");
456 if(at.getAccessibleRowCount() == 0) {
457 error("No data found, please wait for the table to have data first!");
460 if(!isDisplayAll()) {
461 error("Please select \"All\" from the Display: popup menu.");
465 debuglog("(async) getisland...");
467 debuglog("getocean...");
469 debuglog("getocean done");
472 }}.exec("accesstable");
473 if (accesstable == null) return;
476 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
478 debuglog("(async) getisland done");
480 String yarrgts = null;
481 if (yarrgts_thread != null) {
482 debuglog("(async) yarrg timestamp join...");
483 yarrgts_thread.join();
484 debuglog("(async) yarrg timestamp joined.");
485 yarrgts = yarrgts_thread.ts;
488 if (islandName == null) {
489 error("Could not find island name in YPP user interface.");
493 debuglog("table check...");
495 final ArrayList<ArrayList<String>> data =
496 new UIXR<ArrayList<ArrayList<String>>>
497 () { public ArrayList<ArrayList<String>> bodyr() {
498 String headings_expected[] = new String[]
499 { "Commodity", "Trading outlet", "Buy price",
500 "Will buy", "Sell price", "Will sell" };
502 ArrayList<ArrayList<String>> headers =
503 getData(accesstable.getAccessibleColumnHeader());
504 if (headers.size() != 1) {
505 error("Table headings not one row! " + headers.toString());
508 if (headers.get(0).size() < 6 ||
509 headers.get(0).size() > 7) {
510 error("Table headings not six or seven columns! " + headers.toString());
513 for (int col=0; col<headings_expected.length; col++) {
514 String expd = headings_expected[col];
515 String got = headers.get(0).get(col);
516 if (expd.compareTo(got) != 0) {
517 error("Table heading for column "+col
518 +" is not \""+expd+"\" but \""+got+"\".\n\n"
519 +"Please do not reorder the table when using this tool.");
524 debuglog("table read...");
526 return getData(accesstable);
528 if (data == null) return;
531 debuglog("arbitrage...");
532 calculateArbitrage(data);
533 debuglog("arbitrage done.");
536 if (uploadToYarrg && yarrgts != null) {
537 debuglog("yarrg prepare...");
538 progressNote("Yarrg: Preparing data");
541 StringBuilder yarrgsb = new StringBuilder();
542 String yarrgdata; // string containing what we'll feed to yarrg
544 for (ArrayList<String> row : data) {
545 if (row.size() > 6) {
548 for (String rowitem : row) {
549 yarrgsb.append(rowitem != null ? rowitem : "");
550 yarrgsb.append("\t");
552 yarrgsb.setLength(yarrgsb.length()-1); // chop
553 yarrgsb.append("\n");
556 yarrgdata = yarrgsb.toString();
558 progressNote("Yarrg: Uploading");
559 debuglog("yarrg upload...");
561 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
562 debuglog("yarrg done.");
566 debuglog("pctb prepare...");
567 progressNote("PCTB: Getting stall names");
569 if(checkCancelled()) {
572 TreeSet<Offer> buys = new TreeSet<Offer>();
573 TreeSet<Offer> sells = new TreeSet<Offer>();
574 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
576 progressNote("PCTB: Sorting offers");
577 if(checkCancelled()) {
582 debuglog("pctb commodmap...");
583 HashMap<String,Integer> commodMap = getCommodMap();
584 if(commodMap == null) {
587 debuglog("pctb commodmap done.");
588 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
590 // debuglog("\n\n\n"+buys);
592 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
594 progressNote("PCTB: Sending data");
595 if(checkCancelled()) {
598 GZIPOutputStream out = new GZIPOutputStream(outStream);
599 DataOutputStream dos = new DataOutputStream(out);
600 dos.writeBytes("005y\n");
601 dos.writeBytes(stallMap.size()+"\n");
602 dos.writeBytes(getAbbrevStallList(stallMap));
603 writeBuySellOffers(buys,sells,offerCount,out);
605 debuglog("pctb send...");
607 byte[] ba = outStream.toByteArray();
608 debug_write_bytes("pctb-marketdata.gz", ba);
610 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
611 debuglog("pctb sent.");
612 if (in == null) return;
614 if(checkCancelled()) {
617 progressNote("PCTB: Waiting ...");
618 debuglog("pctb finish...");
619 donepctb = finishUpload(in);
620 debuglog("pctb done.");
625 if ((uploadToPCTB && !donepctb) ||
626 (uploadToYarrg && !doneyarrg)) {
628 } else if (unknownPCTBcommods != 0) {
629 summary= "PCTB lacks "+unknownPCTBcommods+" commod(s)";
630 } else if (donepctb || doneyarrg) {
631 summary= "Done " + islandName;
633 summary= "uploaded nowhere!";
635 final String summary_final = summary;
636 new UIX() { public void body() {
637 resultSummary.setText(summary_final);
638 }}.exec("resultSummary.setText");
644 * UPLOAD HELPER FUNCTIONS FOR EXTRACTING SPECIFIC UI DATA
647 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
648 // Gets the offer data out of the table and returns it as an ArrayList
651 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
652 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
653 ArrayList<String> row = new ArrayList<String>();
654 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
655 row.add(table.getAccessibleAt(i, j)
656 .getAccessibleContext().getAccessibleName());
663 public AccessibleTable findMarketTable() {
664 // Return the table containing market data if it exists, otherwise null.
667 Accessible node1 = window;
668 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0});
670 // 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})
672 if (!(node instanceof JTable)) {
673 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
676 if (!(node instanceof JTable)) return null;
677 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
682 private boolean isDisplayAll() {
683 // Returns true iff the "Display:" menu on the commodities
684 // interface in YPP is set to "All"
687 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
688 if(!(button instanceof JButton)) {
689 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
691 String display = button.getAccessibleContext().getAccessibleName();
692 if(!display.equals("All")) {
699 * FUNCTIONS AND CALLBACKS FOR FINDING ISLAND AND OCEAN
702 private void getOcean() {
703 // Finds the ocean name from the window title.
704 // Stores it in the global oceanName
708 AccessibleContext topwindow = window.getAccessibleContext();
709 oceanName = topwindow.getAccessibleName()
710 .replaceAll(".*on the (\\w+) ocean", "$1");
713 private void getIsland() {
714 // Tries to find the island name. Either:
715 // (a) sets the islandName global
717 // (b) sets latch to a new CountDownLatch, and arranges that
718 // at some point later, islandName will be set and the latch
719 // decremented to zero
722 // If the league tracker is there, we can skip the faff
723 // and ask for its tooltip, since we're on a boat
725 Accessible leagueTrackerContainer =
726 descendNodes(window,new int[] {0,1,0,0,2,1});
727 Accessible leagueTrackerItself =
728 descendByClass(leagueTrackerContainer,
729 "com.threerings.yohoho.sea.client.LeagueTracker");
730 Accessible leagueTracker = descend(leagueTrackerItself, 1);
732 islandName = ((JLabel)leagueTracker).getToolTipText();
734 } catch (NullPointerException e) {
735 // evidently we're actually on an island
738 AccessibleContext chatArea =
739 descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
740 .getAccessibleContext();
741 // attach the property change listener to the outer sunshine
742 // panel if the "ahoy" tab is not active, otherwise attach it to
743 // the scroll panel in the "ahoy" tab.
744 if(!"com.threerings.piracy.client.AttentionListPanel".
745 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
746 .getClass().getCanonicalName())) {
747 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
748 .getAccessibleContext();
750 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
751 .getAccessibleContext();
753 sidePanel.addPropertyChangeListener(changeListener);
754 latch = new java.util.concurrent.CountDownLatch(1);
755 // make the Players Online ("/who") panel appear
756 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
757 chat.setTextContents("/w");
758 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
759 for(int i=0;i<c;i++) {
760 if("notify-field-accept".equals(chatArea.getAccessibleAction()
761 .getAccessibleActionDescription(i))) {
762 chatArea.getAccessibleAction().doAccessibleAction(i);
768 private PropertyChangeListener changeListener = new PropertyChangeListener() {
770 public void propertyChange(PropertyChangeEvent e) {
772 if(e.getNewValue() != null &&
773 e.getPropertyName().equals
774 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
775 Accessible islandInfo =
776 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
777 String text = islandInfo.getAccessibleContext().getAccessibleText()
778 .getAtIndex(AccessibleText.SENTENCE,0);
779 int index = text.indexOf(":");
780 String name = text.substring(0,index);
782 // debuglog(islandName);
783 sidePanel.removePropertyChangeListener(this);
790 * UTILITY FUNCTIONS FOR WALKING THE UI
792 * These functions all return null if the specified path or child
796 private Accessible descendNodes(Accessible parent, int[] path) {
797 // Descends through several levels of Accessible children in one call.
798 // path[] is an array of ints, each int being the index into the array
799 // of children at a particular point, and thus selects the specific
800 // accessible child to descend to.
803 for(int i=0;i<path.length;i++) {
804 if (null == (parent = descend(parent, path[i]))) return null;
809 private Accessible descend(Accessible parent, int childNum) {
810 // Descends one level to the specified child of the parent
811 // childNum is the index of the child within parent
814 if (parent == null) return null;
815 int children = parent.getAccessibleContext().getAccessibleChildrenCount();
816 if (childNum >= children) {
817 debuglog("DESCEND "+childNum+" > "+children+" NOT FOUND");
820 Accessible child = parent.getAccessibleContext()
821 .getAccessibleChild(childNum);
822 debuglog("DESCEND "+childNum+" "+child.getClass().getName()+" OK");
826 private Accessible descendByClass(Accessible parent, String classname) {
827 // Descends one level to the first child which has the specified class.
830 if (parent == null) return null;
831 AccessibleContext ac = parent.getAccessibleContext();
832 int children = ac.getAccessibleChildrenCount();
833 for (int i=0; i<children; i++) {
834 Accessible child = ac.getAccessibleChild(i);
835 if (child.getClass().getName() == classname) {
836 debuglog("DESCEND CLASS "+classname+" OK");
840 debuglog("DESCEND CLASS "+classname+" NOT FOUND");
845 /*****************************************
846 * PCTB-SPECIFIC HELPER FUNCTIONS ETC. *
847 *****************************************/
850 * An abstract market offer, entailing a commodity being bought or sold by
851 * a shoppe, for a certain price in a certain quantity. Not instantiable.
856 abstract class Offer {
857 public int commodity, price, quantity, shoppe;
859 * Create an offer from <code>record</code>, determining the shoppe Id from
860 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
861 * <code>priceIndex</code> should be the index of the price in the record
862 * (the quantity will be <code>priceIndex + 1</code>).
864 * @param record the record with data to create the offer from
865 * @param stallMap a map containing the ids of the various stalls
866 * @param commodMap a map containing the ids of the various commodities
867 * @param priceIndex the index of the price in the record
869 public Offer(ArrayList<String> record,
870 LinkedHashMap<String,Integer> stallMap,
871 HashMap<String,Integer> commodMap,
873 Integer commodId = commodMap.get(record.get(0));
874 if(commodId == null) {
875 throw new IllegalArgumentException();
877 commodity = commodId.intValue();
878 price = Integer.parseInt(record.get(priceIndex));
879 String qty = record.get(priceIndex+1);
880 quantity = parseQty(qty);
881 shoppe = stallMap.get(record.get(1)).intValue();
885 * Returns a human-readable version of this offer, useful for debugging
887 * @return human-readable offer
889 public String toString() {
890 return "[C:" + commodity + ",$" + price + ",Q:"
891 + quantity + ",S:" + shoppe + "]";
896 * An offer from a shoppe or stall to buy a certain quantity of a
897 * commodity for a certain price. If placed in an ordered Set,
898 * sorts by commodity index ascending, then by buy price
899 * descending, and finally by stall id ascending.
901 class Buy extends Offer implements Comparable<Buy> {
903 * Creates a new <code>Buy</code> offer from the given
904 * <code>record</code> using the other parameters to determine
905 * stall id and commodity id of the offer.
907 * @param record the record with data to create the offer from
908 * @param stallMap a map containing the ids of the various stalls
909 * @param commodMap a map containing the ids of the various commodities
911 public Buy(ArrayList<String> record,
912 LinkedHashMap<String,Integer> stallMap,
913 HashMap<String,Integer> commodMap) {
914 super(record,stallMap,commodMap,2);
918 * Sorts by commodity index ascending, then price descending,
919 * then stall id ascending.
921 public int compareTo(Buy buy) {
922 // organize by: commodity index, price, stall index
923 if(commodity == buy.commodity) {
924 // organize by price, then by stall index
925 if(price == buy.price) {
926 // organize by stall index
927 return shoppe>buy.shoppe ? 1 : -1;
928 } else if(price > buy.price) {
933 } else if(commodity > buy.commodity) {
942 * An offer from a shoppe or stall to sell a certain quantity of
943 * a commodity for a certain price. If placed in an ordered Set,
944 * sorts by commodity index ascending, then by sell price
945 * ascending, and finally by stall id ascending.
947 class Sell extends Offer implements Comparable<Sell> {
949 * Creates a new <code>Sell</code> offer from the given
950 * <code>record</code> using the other parameters to determine
951 * stall id and commodity id of the offer.
953 * @param record the record with data to create the offer from
954 * @param stallMap a map containing the ids of the various stalls
955 * @param commodMap a map containing the ids of the various commodities
957 public Sell(ArrayList<String> record,
958 LinkedHashMap<String,Integer> stallMap,
959 HashMap<String,Integer> commodMap) {
960 super(record,stallMap,commodMap,4);
964 * Sorts by commodity index ascending, then price ascending, then
965 * stall id ascending.
967 public int compareTo(Sell sell) {
968 // organize by: commodity index, price, stall index
969 if(commodity == sell.commodity) {
970 // organize by price, then by stall index
971 if(price == sell.price) {
972 // organize by stall index
973 return shoppe>sell.shoppe ? 1 : -1;
974 } else if(price > sell.price) {
979 } else if(commodity > sell.commodity) {
988 * Gets the list of commodities and their associated commodity ids.
990 * @return a map where the key is the commodity and the value is
993 private HashMap<String,Integer> getCommodMap() {
995 if(commodMap != null) {
998 HashMap<String,Integer> map = new HashMap<String,Integer>();
1001 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
1003 new BufferedReader(new InputStreamReader(host.openStream()));
1004 StringBuilder sb = new StringBuilder();
1006 while((str = br.readLine()) != null) {
1010 debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
1011 int first = sb.indexOf("<pre>") + 5;
1012 int last = sb.indexOf("</body>");
1013 xml = sb.substring(first,last);
1014 Reader reader = new CharArrayReader(xml.toCharArray());
1015 Document d = DocumentBuilderFactory.newInstance()
1016 .newDocumentBuilder().parse(new InputSource(reader));
1017 NodeList maps = d.getElementsByTagName("CommodMap");
1018 for(int i=0;i<maps.getLength();i++) {
1019 NodeList content = maps.item(i).getChildNodes();
1020 Integer num = Integer.parseInt(content.item(1).getTextContent());
1021 map.put(content.item(0).getTextContent(),num);
1023 } catch(Exception e) {
1024 e.printStackTrace();
1025 error("Unable to load Commodity list from server!");
1033 * Given the list of offers, this method will find all the unique
1034 * stall names and return them in a <code>LinkedHashMap</code>
1035 * where the key is the stall name and the value is the generated
1036 * stall id (position in the list). <p> The reason this method
1037 * returns a LinkedHashMap instead of a simple HashMap is the
1038 * need for iterating over the stall names in insertion order for
1039 * output to the server.
1041 * @param offers the list of records from the commodity buy/sell interface
1042 * @return an iterable ordered map of the stall names and
1043 * generated stall ids
1045 private LinkedHashMap<String,Integer> getStallMap
1046 (ArrayList<ArrayList<String>> offers) {
1048 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
1049 for(ArrayList<String> offer : offers) {
1050 String shop = offer.get(1);
1051 if(!map.containsKey(shop)) {
1053 map.put(shop,count);
1060 * Gets a sorted list of Buys and Sells from the list of
1061 * records. <code>buys</code> and <code>sells</code> should be
1062 * pre-initialized and passed into the method to receive the
1063 * data. Returns a 2-length int array with the number of buys
1066 * @param offers the data found from the market table in-game
1067 * @param buys an empty initialized <code>TreeSet<Offer></code> to
1068 * hold the Buy offers.
1069 * @param sells an empty initialized <code>TreeSet<Offer></code> to
1070 * hold the Sell offers.
1071 * @param stalls the map of stalls to their ids
1072 * @param commodMap the map of commodities to their ids
1073 * @return a 2-length int[] array containing the number of buys
1074 * and sells, respectively
1076 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers,
1077 TreeSet<Offer> buys,
1078 TreeSet<Offer> sells,
1079 LinkedHashMap<String,Integer> stalls,
1080 HashMap<String,Integer> commodMap) {
1081 int[] buySellCount = new int[2];
1082 for(ArrayList<String> offer : offers) {
1084 if(offer.get(2) != null) {
1085 buys.add(new Buy(offer,stalls,commodMap));
1088 if(offer.get(4) != null) {
1089 sells.add(new Sell(offer,stalls,commodMap));
1092 } catch(IllegalArgumentException e) {
1093 unknownPCTBcommods++;
1094 debuglog("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
1097 if (buySellCount[0]==0 && buySellCount[1]==0) {
1098 error("No (valid) offers for PCTB?!");
1099 throw new IllegalArgumentException();
1101 return buySellCount;
1105 * Prepares the list of stalls for writing to the output stream.
1106 * The <code>String</code> returned by this method is ready to be
1107 * written directly to the stream. <p> All shoppe names are left
1108 * as they are. Stall names are abbreviated just before the
1109 * apostrophe in the possessive, with an "^" and a letter
1110 * matching the stall's type appended. Example: "Burninator's
1111 * Ironworking Stall" would become "Burninator^I".
1113 * @param stallMap the map of stalls and stall ids in an iterable order
1114 * @return a <code>String</code> containing the list of stalls in
1115 * format ready to be written to the output stream.
1117 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1118 // set up some mapping
1119 HashMap<String,String> types = new HashMap<String,String>();
1120 types.put("Apothecary Stall", "A");
1121 types.put("Distilling Stall", "D");
1122 types.put("Furnishing Stall", "F");
1123 types.put("Ironworking Stall", "I");
1124 types.put("Shipbuilding Stall", "S");
1125 types.put("Tailoring Stall", "T");
1126 types.put("Weaving Stall", "W");
1128 StringBuilder sb = new StringBuilder();
1129 for(String name : stallMap.keySet()) {
1130 int index = name.indexOf("'s");
1131 String finalName = name;
1134 finalName = name.substring(0,index);
1135 if(index + 2 < name.length()) {
1136 String end = name.substring(index+2,name.length()).trim();
1137 type = types.get(end);
1141 sb.append(name+"\n");
1143 sb.append(finalName+"^"+type+"\n");
1146 return sb.toString();
1150 * Writes a list of offers in correct format to the output stream.
1152 * The format is thus: (all numbers are 2-byte integers in
1153 * little-endian format) (number of offers of this type, aka
1154 * buy/sell) (commodity ID) (number of offers for this commodity)
1155 * [shopID price qty][shopID price qty]...
1157 * @param out the output stream to write the data to
1158 * @param offers the offers to write
1160 private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1161 throws IOException {
1162 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1163 if(offers.size() == 0) {
1164 // nothing to write, and "0" has already been written
1167 int commodity = offers.first().commodity;
1169 for(Offer offer : offers) {
1170 if(commodity != offer.commodity) {
1172 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1174 commodity = offer.commodity;
1177 writeLEShort(offer.shoppe,buffer); // stall index
1178 writeLEShort(offer.price,buffer); // buy price
1179 writeLEShort(offer.quantity,buffer); // buy qty
1182 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1186 * Writes the buffered data to the output strea for one commodity.
1188 * @param out the stream to write to
1189 * @param buffer the buffered data to write
1190 * @param commodity the commmodity id to write before the buffered data
1191 * @param count the number of offers for this commodity to write
1194 private void writeBufferedOffers(OutputStream out, byte[] buffer,
1195 int commodity, int count)
1196 throws IOException {
1197 writeLEShort(commodity,out); // commod index
1198 writeLEShort(count,out); // offer count
1199 out.write(buffer); // the buffered offers
1203 * Writes the buy and sell offers to the outputstream by calling
1206 * @param buys list of Buy offers to write
1207 * @param sells list of Sell offers to write
1208 * @param offerCount 2-length int array containing the number of
1209 * buys and sells to write out
1210 * @param out the stream to write to
1212 private void writeBuySellOffers(TreeSet<Offer> buys,
1213 TreeSet<Offer> sells,
1214 int[] offerCount, OutputStream out)
1215 throws IOException {
1217 writeLEShort(offerCount[0],out);
1218 writeOffers(out,buys);
1220 writeLEShort(offerCount[1],out);
1221 writeOffers(out,sells);
1224 private String readstreamstring(InputStream in) throws IOException {
1225 StringBuilder sb = new StringBuilder();
1226 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1228 while((str = br.readLine()) != null) {
1229 sb.append(str+"\n");
1231 return sb.toString();
1235 * Sends the data to the server via multipart-formdata POST,
1236 * with the gzipped data as a file upload.
1238 * @param file an InputStream open to the gzipped data we want to send
1240 private InputStream sendInitialData(InputStream file) throws IOException {
1242 ClientHttpRequest http =
1243 new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1244 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1246 String err = readstreamstring(http.resultstream());
1247 error("Error sending initial data:\n"+err);
1250 return http.resultstream();
1254 * Utility method to write a 2-byte int in little-endian form to
1257 * @param num an integer to write
1258 * @param out stream to write to
1260 private void writeLEShort(int num, OutputStream out) throws IOException {
1261 out.write(num & 0xFF);
1262 out.write((num >>> 8) & 0xFF);
1266 * Reads the response from the server, and selects the correct parameters
1267 * which are sent in a GET request to the server asking it to confirm
1268 * the upload and accept the data into the database. Notably, the island id
1269 * and ocean id are determined, while other parameter such as the filename
1270 * are determined from the hidden form fields.
1272 * @param in stream of data from the server to read
1274 private boolean finishUpload(InputStream in) throws IOException {
1277 String html = readstreamstring(in);
1278 debug_write_stringdata("pctb-initial.html", html);
1281 Pattern params = Pattern.compile
1282 ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1283 ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1284 ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1285 m = params.matcher(html);
1287 error_html("The PCTB server returned unusual data."+
1288 " Maybe you're using an old version of the uploader?",
1292 String forceReload = m.group(1);
1293 String filename = m.group(2);
1295 Pattern oceanNumPat =
1296 Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1297 m = oceanNumPat.matcher(html);
1299 error_html("Unable to find the ocean in the server's list of oceans!",
1303 String oceanNum = m.group(1);
1305 Pattern oceanIslandNum =
1306 Pattern.compile("islands\\[" + oceanNum
1307 + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1309 m = oceanIslandNum.matcher(html);
1311 error_html("This does not seem to be a valid island! Unable to upload.",
1315 String islandNum = m.group(1);
1317 URL get = new URL(PCTB_HOST_URL +
1318 "upload.php?action=setisland&ocean=" + oceanNum
1319 + "&island=" + islandNum
1320 + "&forcereload=" + forceReload
1321 + "&filename=" + filename);
1322 String complete = readstreamstring(get.openStream());
1323 debug_write_stringdata("pctb-final.html", complete);
1324 Pattern done = Pattern.compile
1325 ("Your data has been integrated into the database. Thank you!");
1326 m = done.matcher(complete);
1330 error_html("Something was wrong with the final upload parameters!",
1337 /*****************************************
1338 * YARRG-SPECIFIC HELPER FUNCTIONS ETC. *
1339 *****************************************/
1341 private InputStream post_for_yarrg(ClientHttpRequest http)
1342 throws IOException {
1345 String err = readstreamstring(http.resultstream());
1346 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1349 return http.resultstream();
1352 private class YarrgTimestampFetcher extends Thread {
1353 public YarrgTimestampFetcher(int counter) {
1354 super("MarketUploader-YarrgTimestampFetcher-"+uploadcounter);
1356 public String ts = null;
1359 ts = getYarrgTimestamp();
1360 debuglog("(async) yarrg timestamp ready.");
1361 } catch(Exception e) {
1362 error("Error getting YARRG timestamp: "+e);
1367 private String getYarrgTimestamp() throws IOException {
1368 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1369 http.setParameter("clientname", YARRG_CLIENTNAME);
1370 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1371 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1372 http.setParameter("requesttimestamp", "y");
1373 InputStream in = post_for_yarrg(http);
1374 if (in == null) return null;
1375 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1376 String tsresult = br.readLine();
1377 return tsresult.substring(3, tsresult.length()-1);
1380 private boolean runYarrg(String timestamp, String ocean, String island,
1381 String yarrgdata) throws IOException {
1382 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1383 BufferedOutputStream bufos =
1384 new BufferedOutputStream(new GZIPOutputStream(bos));
1385 bufos.write(yarrgdata.getBytes() );
1387 byte[] compressed = bos.toByteArray();
1388 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1389 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1391 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1392 http.setParameter("clientname", YARRG_CLIENTNAME);
1393 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1394 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1395 http.setParameter("timestamp", timestamp);
1396 http.setParameter("ocean", ocean);
1397 http.setParameter("island", island);
1398 http.setParameter("data", "deduped.tsv.gz", file,
1399 "application/octet-stream");
1400 InputStream in = post_for_yarrg(http);
1401 if (in == null) return false;
1402 String output = readstreamstring(in);
1403 if (!output.startsWith("OK")) {
1404 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1407 debug_write_stringdata("yarrg-result.txt", output);
1411 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1412 // debuglog("ARBITRAGE?");
1414 SortedSet<int[]> buys = arb_bs.get(0);
1415 SortedSet<int[]> sells = arb_bs.get(1);
1419 // NB "sell" means they sell, ie we buy
1420 sell = sells.last();
1422 } catch (NoSuchElementException e) {
1426 int unitprofit = buy[0] - sell[0];
1427 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1428 // debuglog(" sell @"+sell[0]+" x"+sell[1]
1429 // +" buy @"+buy[0]+" x"+buy[1]
1430 // +" => x"+count+" @"+unitprofit);
1432 if (unitprofit <= 0)
1435 profit += count * unitprofit;
1438 if (buy[1]==0) buys.remove(buy);
1439 if (sell[1]==0) sells.remove(sell);
1441 // debuglog(" PROFIT "+profit);
1445 /*****************************************
1447 *****************************************/
1449 private class arbitrageOfferComparator implements Comparator {
1450 public int compare(Object o1, Object o2) {
1451 int p1 = ((int[])o1)[0];
1452 int p2 = ((int[])o2)[0];
1457 private @SuppressWarnings("unchecked")
1458 void calculateArbitrage(ArrayList<ArrayList<String>> data)
1459 throws InterruptedException {
1461 ArrayList<SortedSet<int[]>> arb_bs = null;
1462 String lastcommod = null;
1463 Comparator compar = new arbitrageOfferComparator();
1465 for (ArrayList<String> row : data) {
1466 String thiscommod = row.get(0);
1467 // debuglog("ROW "+row.toString());
1468 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1469 if (lastcommod != null)
1470 arbitrage += calculateArbitrageCommodity(arb_bs);
1471 // debuglog("ROW rdy");
1472 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1473 arb_bs.add(0, new TreeSet<int[]>(compar));
1474 arb_bs.add(1, new TreeSet<int[]>(compar));
1475 // debuglog("ROW init");
1476 lastcommod = thiscommod;
1478 for (int bs = 0; bs < 2; bs++) {
1479 String pricestr = row.get(bs*2 + 2);
1480 if (pricestr == null)
1482 int[] entry = new int[2];
1483 // debuglog("ROW BS "+bs);
1484 entry[0] = parseQty(pricestr);
1485 entry[1] = parseQty(row.get(bs*2 + 3));
1486 arb_bs.get(bs).add(entry);
1489 arbitrage += calculateArbitrageCommodity(arb_bs);
1491 if (arbitrage != 0) {
1492 arb = "<html><strong>arbitrage: "+arbitrage+" poe</strong>";
1494 arb = "no arbitrage";
1496 final String arb_final = arb;
1497 EventQueue.invokeLater(new Runnable() { public void run() {
1498 arbitrageResult.setText(arb_final);