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 private PrintStream dtxt = null;
45 public 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 // This is not normally called, it seems.
140 new MarketUploader();
143 public MarketUploader() {
144 Preferences prefs = Preferences.userNodeForPackage(getClass());
146 if (prefs.getBoolean("writeDebugFiles", false)) {
148 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
149 } catch (java.io.FileNotFoundException e) {
150 System.err.println("JARRG: Error opening debug log: "+e);
154 if (prefs.getBoolean("useLiveServers", true)) {
155 YARRG_URL = YARRG_LIVE_URL;
156 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
158 YARRG_URL = YARRG_TEST_URL;
159 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
162 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
163 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
164 showArbitrage=prefs.getBoolean("showArbitrage", true);
166 debuglog("main on dispatch thread: "+EventQueue.isDispatchThread());
167 EventQueue.invokeLater(this);
171 * We arrange to wait for the GUI to be initialised, then look at
172 * every top-level window to see if the Puzzle Pirates window turns up.
175 debuglog("MarketUploader run()...");
176 if (EventQueueMonitor.isGUIInitialized()) {
177 debuglog("MarketUploader GUI already ready");
180 debuglog("MarketUploader waiting for GUI");
181 EventQueueMonitor.addGUIInitializedListener(this);
185 public void guiInitialized() {
186 Window ws[]= EventQueueMonitor.getTopLevelWindows();
187 EventQueueMonitor.addTopLevelWindowListener(this);
188 for (int i=0; i<ws.length; i++) {
189 debuglog("MarketUploader existing toplevel "+i);
190 topLevelWindowCreated(ws[i]);
194 public void topLevelWindowDestroyed(Window w) {
195 debuglog("MarketUploader destroyed toplevel");
198 public void topLevelWindowCreated(Window w) {
202 String name = w.getAccessibleContext().getAccessibleName();
203 debuglog("MarketUploader checking toplevel "+name);
204 if (!name.equals("Puzzle Pirates"))
205 // Only if we're running alongside a Window named "Puzzle Pirates"
207 debuglog("MarketUploader found toplevel, creating gui");
210 frame.setVisible(true);
213 private void createGUI() {
214 // Actually set up our GUI
216 frame = new JFrame("Jarrg Uploader");
217 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
218 GridLayout layout = new GridLayout(2,1);
219 frame.getContentPane().setLayout(layout);
220 //frame.setPreferredSize(new Dimension(200, 60));
222 findMarket = new JButton("Upload Market Data");
223 findMarket.addActionListener(new ActionListener() {
224 public void actionPerformed(ActionEvent e) {
225 // This is called when the user clicks "upload"
229 findMarket.setEnabled(false);
230 resultSummary.setText("");
231 arbitrageResult.setText("");
232 new Thread("MarketUploader-uploader-"+uploadcounter) {
234 startTime = new Date().getTime();
235 unknownPCTBcommods = 0;
237 runUpload(uploadcounter);
238 } catch(Exception e) {
243 new UIX() { public void body() {
244 if(sidePanel != null) {
245 sidePanel.removePropertyChangeListener(changeListener);
247 if (progmon != null) {
251 findMarket.setEnabled(true);
253 } catch (Exception e) {
254 System.err.println("exception tidying on UI thread:");
261 frame.add(findMarket);
263 resultSummary = new JLabel("ready");
264 frame.add(resultSummary);
266 arbitrageResult = new JLabel("");
269 layout.setRows(layout.getRows() + 1);
270 frame.add(arbitrageResult);
279 * Special measures are needed because:
280 * - it is not permitted to use any Swing UI classes or objects
281 * other than on the Swing event thread
282 * - we want to run our upload asynchronously
283 * - we want to do some computation asynchronously (eg, the
284 * arbitrage and upload data prep)
286 * So what we do is this:
287 * 1. When the user asks to upload, we spawn a new thread
288 * to do the upload ("MarketUploader-uploader-*", see
289 * the call to "new Thread" inside createGUI.
290 * 2. Whenever that thread needs to touch a UI object it
291 * uses EventQueue.invokeLater or .invokeAndWait to
292 * perform the relevant action. We wrap these calls up
293 * in three utility classes:
294 * UIA - runs code on UI thread, asynchronously
295 * UIX - runs code on UI thread, waits for it to finish
296 * UIXR - as UIX but also returns a value
297 * These hide the details of the EventQueue class and also do
298 * some debugging and argument shuffling; the calling syntax is
299 * still painful, unfortunately, and there is a weird constraint
300 * on variables used inside the inner body. For a simple
301 * example, see the handling of "summary" and "summary_final"
302 * for the call to UIX at the bottom of runUpload.
303 * 3. Try to put everything back when that thread exits.
306 * a. There is another thread spawed early to get a timestamp from
307 * YARRG, if we are uploading there.
308 * b. Finding the island name can involve callbacks which run in
309 * the UI event thread. Basically we do the work there, and use
310 * a CountDownLatch to cause the uploader thread to wait as
314 private void on_ui_thread() { assert(EventQueue.isDispatchThread()); }
315 private void on_our_thread() { assert(!EventQueue.isDispatchThread()); }
317 private abstract class UIA implements Runnable {
319 public abstract void body();
321 debuglog("UIA 2 "+what+" begin");
323 debuglog("UIA 3 "+what+" done");
325 public void exec(String what_in) {
327 debuglog("UIA 1 "+what+" request");
328 EventQueue.invokeLater(this);
331 private abstract class UIXR<ReturnType> implements Runnable {
332 public abstract ReturnType bodyr();
333 public ReturnType return_value;
336 debuglog("UIX 2 "+what+" begin");
337 return_value = bodyr();
338 debuglog("UIX 3 "+what+" done");
340 public ReturnType exec(String what_in) throws Exception {
342 if (EventQueue.isDispatchThread()) {
343 debuglog("UIX 1 "+what+" (event thread) entry");
345 debuglog("UIX 4 "+what+" (event thread) exit");
347 debuglog("UIX 1 "+what+" (other thread) entry");
348 EventQueue.invokeAndWait(this);
349 debuglog("UIX 4 "+what+" (other thread) exit");
354 private abstract class UIX extends UIXR<Object> implements Runnable {
355 public abstract void body();
356 public Object bodyr() { body(); return null; }
360 * ERROR REPORTING AND GENERAL UTILITIES
362 * Synchronous modal dialogues
363 * error and error_html may be called from any thread
366 public void error(final String msg) {
368 new UIX() { public void body() {
369 resultSummary.setText("failed");
370 JOptionPane.showMessageDialog(frame,msg,"Error",
371 JOptionPane.ERROR_MESSAGE);
373 } catch (Exception e) {
374 System.err.println("exception reporting to UI thread:");
379 public void error_html(final String msg, String html) {
380 Pattern body = Pattern.compile("<body>(.*)</body>",
381 Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
382 Matcher m = body.matcher(html);
385 Pattern fixup = Pattern.compile("<(\\w+) */>");;
386 m = fixup.matcher(html);
387 html = m.replaceAll("<$1>");
388 m = Pattern.compile("[\\r\\n]+").matcher(html);
389 html = m.replaceAll(" ");
391 String whole_msg = "<html><h1>Error</h1>"+msg
392 +"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
393 debuglog("###" + whole_msg + "###");
398 public void progressNote(final String s_in) throws Exception {
399 new UIA() { public void body() {
401 arb = arbitrageResult.getText();
403 if (arb != null && arb.length() != 0)
404 s = "<html>" + arb + "<br>" + s;
406 }}.exec("progressNote "+s_in);
408 public void setProgress(final int nv) throws Exception {
409 new UIA() { public void body() {
410 progmon.setProgress(nv);
411 }}.exec("setProgress "+nv);
413 public boolean checkCancelled() throws Exception {
414 return new UIXR<Boolean>() { public Boolean bodyr() {
415 boolean can = progmon.isCanceled();
416 if (can) resultSummary.setText("cancelled");
417 return new Boolean(can);
418 }}.exec("checkCancelled").booleanValue();
423 * ACTUAL DATA COLLECTION AND UPLOAD
426 private void runUpload(int counter) throws Exception {
427 // Runs the data collection process, and upload the results.
428 // In most cases of error, we call error() (which synchronously
429 // reports the error) and then simply return.
433 boolean doneyarrg = false, donepctb = false;
434 YarrgTimestampFetcher yarrgts_thread = null;
436 debuglog("starting");
439 debuglog("(async) yarrg timestamp...");
440 yarrgts_thread = new YarrgTimestampFetcher(counter);
441 yarrgts_thread.start();
444 final AccessibleTable accesstable =
445 new UIXR<AccessibleTable>() { public AccessibleTable bodyr() {
446 progmon = new ProgressMonitor
447 (frame,"Processing Market Data","Getting table data",0,100);
448 progmon.setMillisToDecideToPopup(0);
449 progmon.setMillisToPopup(0);
451 AccessibleTable at = findMarketTable();
453 error("Market table not found!"+
454 " Please open the Buy/Sell Commodities interface.");
457 if(at.getAccessibleRowCount() == 0) {
458 error("No data found, please wait for the table to have data first!");
461 if(!isDisplayAll()) {
462 error("Please select \"All\" from the Display: popup menu.");
466 debuglog("(async) getisland...");
468 debuglog("getocean...");
470 debuglog("getocean done");
473 }}.exec("accesstable");
474 if (accesstable == null) return;
477 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
479 debuglog("(async) getisland done");
481 String yarrgts = null;
482 if (yarrgts_thread != null) {
483 debuglog("(async) yarrg timestamp join...");
484 yarrgts_thread.join();
485 debuglog("(async) yarrg timestamp joined.");
486 yarrgts = yarrgts_thread.ts;
489 if (islandName == null) {
490 error("Could not find island name in YPP user interface.");
494 debuglog("table check...");
496 final ArrayList<ArrayList<String>> data =
497 new UIXR<ArrayList<ArrayList<String>>>
498 () { public ArrayList<ArrayList<String>> bodyr() {
499 String headings_expected[] = new String[]
500 { "Commodity", "Trading outlet", "Buy price",
501 "Will buy", "Sell price", "Will sell" };
503 ArrayList<ArrayList<String>> headers =
504 getData(accesstable.getAccessibleColumnHeader());
505 if (headers.size() != 1) {
506 error("Table headings not one row! " + headers.toString());
509 if (headers.get(0).size() < 6 ||
510 headers.get(0).size() > 7) {
511 error("Table headings not six or seven columns! " + headers.toString());
514 for (int col=0; col<headings_expected.length; col++) {
515 String expd = headings_expected[col];
516 String got = headers.get(0).get(col);
517 if (expd.compareTo(got) != 0) {
518 error("Table heading for column "+col
519 +" is not \""+expd+"\" but \""+got+"\".\n\n"
520 +"Please do not reorder the table when using this tool.");
525 debuglog("table read...");
527 return getData(accesstable);
529 if (data == null) return;
532 debuglog("arbitrage...");
533 calculateArbitrage(data);
534 debuglog("arbitrage done.");
537 if (uploadToYarrg && yarrgts != null) {
538 debuglog("yarrg prepare...");
539 progressNote("Yarrg: Preparing data");
542 StringBuilder yarrgsb = new StringBuilder();
543 String yarrgdata; // string containing what we'll feed to yarrg
545 for (ArrayList<String> row : data) {
546 if (row.size() > 6) {
549 for (String rowitem : row) {
550 yarrgsb.append(rowitem != null ? rowitem : "");
551 yarrgsb.append("\t");
553 yarrgsb.setLength(yarrgsb.length()-1); // chop
554 yarrgsb.append("\n");
557 yarrgdata = yarrgsb.toString();
559 progressNote("Yarrg: Uploading");
560 debuglog("yarrg upload...");
562 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
563 debuglog("yarrg done.");
567 debuglog("pctb prepare...");
568 progressNote("PCTB: Getting stall names");
570 if(checkCancelled()) {
573 TreeSet<Offer> buys = new TreeSet<Offer>();
574 TreeSet<Offer> sells = new TreeSet<Offer>();
575 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
577 progressNote("PCTB: Sorting offers");
578 if(checkCancelled()) {
583 debuglog("pctb commodmap...");
584 HashMap<String,Integer> commodMap = getCommodMap();
585 if(commodMap == null) {
588 debuglog("pctb commodmap done.");
589 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
591 // debuglog("\n\n\n"+buys);
593 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
595 progressNote("PCTB: Sending data");
596 if(checkCancelled()) {
599 GZIPOutputStream out = new GZIPOutputStream(outStream);
600 DataOutputStream dos = new DataOutputStream(out);
601 dos.writeBytes("005y\n");
602 dos.writeBytes(stallMap.size()+"\n");
603 dos.writeBytes(getAbbrevStallList(stallMap));
604 writeBuySellOffers(buys,sells,offerCount,out);
606 debuglog("pctb send...");
608 byte[] ba = outStream.toByteArray();
609 debug_write_bytes("pctb-marketdata.gz", ba);
611 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
612 debuglog("pctb sent.");
613 if (in == null) return;
615 if(checkCancelled()) {
618 progressNote("PCTB: Waiting ...");
619 debuglog("pctb finish...");
620 donepctb = finishUpload(in);
621 debuglog("pctb done.");
626 if ((uploadToPCTB && !donepctb) ||
627 (uploadToYarrg && !doneyarrg)) {
629 } else if (unknownPCTBcommods != 0) {
630 summary= "PCTB lacks "+unknownPCTBcommods+" commod(s)";
631 } else if (donepctb || doneyarrg) {
632 summary= "Done " + islandName;
634 summary= "uploaded nowhere!";
636 final String summary_final = summary;
637 new UIX() { public void body() {
638 resultSummary.setText(summary_final);
639 }}.exec("resultSummary.setText");
645 * UPLOAD HELPER FUNCTIONS FOR EXTRACTING SPECIFIC UI DATA
648 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
649 // Gets the offer data out of the table and returns it as an ArrayList
652 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
653 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
654 ArrayList<String> row = new ArrayList<String>();
655 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
656 row.add(table.getAccessibleAt(i, j)
657 .getAccessibleContext().getAccessibleName());
664 public AccessibleTable findMarketTable() {
665 // Return the table containing market data if it exists, otherwise null.
668 Accessible node1 = window;
669 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0});
671 // 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})
673 if (!(node instanceof JTable)) {
674 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
677 if (!(node instanceof JTable)) return null;
678 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
683 private boolean isDisplayAll() {
684 // Returns true iff the "Display:" menu on the commodities
685 // interface in YPP is set to "All"
688 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
689 if(!(button instanceof JButton)) {
690 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
692 String display = button.getAccessibleContext().getAccessibleName();
693 if(!display.equals("All")) {
700 * FUNCTIONS AND CALLBACKS FOR FINDING ISLAND AND OCEAN
703 private void getOcean() {
704 // Finds the ocean name from the window title.
705 // Stores it in the global oceanName
709 AccessibleContext topwindow = window.getAccessibleContext();
710 oceanName = topwindow.getAccessibleName()
711 .replaceAll(".*on the (\\w+) ocean", "$1");
714 private void getIsland() {
715 // Tries to find the island name. Either:
716 // (a) sets the islandName global
718 // (b) sets latch to a new CountDownLatch, and arranges that
719 // at some point later, islandName will be set and the latch
720 // decremented to zero
723 // If the league tracker is there, we can skip the faff
724 // and ask for its tooltip, since we're on a boat
726 Accessible leagueTrackerContainer =
727 descendNodes(window,new int[] {0,1,0,0,2,1});
728 Accessible leagueTrackerItself =
729 descendByClass(leagueTrackerContainer,
730 "com.threerings.yohoho.sea.client.LeagueTracker");
731 Accessible leagueTracker = descend(leagueTrackerItself, 1);
733 islandName = ((JLabel)leagueTracker).getToolTipText();
735 } catch (NullPointerException e) {
736 // evidently we're actually on an island
739 AccessibleContext chatArea =
740 descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
741 .getAccessibleContext();
742 // attach the property change listener to the outer sunshine
743 // panel if the "ahoy" tab is not active, otherwise attach it to
744 // the scroll panel in the "ahoy" tab.
745 if(!"com.threerings.piracy.client.AttentionListPanel".
746 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
747 .getClass().getCanonicalName())) {
748 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
749 .getAccessibleContext();
751 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
752 .getAccessibleContext();
754 sidePanel.addPropertyChangeListener(changeListener);
755 latch = new java.util.concurrent.CountDownLatch(1);
756 // make the Players Online ("/who") panel appear
757 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
758 chat.setTextContents("/w");
759 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
760 for(int i=0;i<c;i++) {
761 if("notify-field-accept".equals(chatArea.getAccessibleAction()
762 .getAccessibleActionDescription(i))) {
763 chatArea.getAccessibleAction().doAccessibleAction(i);
769 private PropertyChangeListener changeListener = new PropertyChangeListener() {
771 public void propertyChange(PropertyChangeEvent e) {
773 if(e.getNewValue() != null &&
774 e.getPropertyName().equals
775 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
776 Accessible islandInfo =
777 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
778 String text = islandInfo.getAccessibleContext().getAccessibleText()
779 .getAtIndex(AccessibleText.SENTENCE,0);
780 int index = text.indexOf(":");
781 String name = text.substring(0,index);
783 // debuglog(islandName);
784 sidePanel.removePropertyChangeListener(this);
791 * UTILITY FUNCTIONS FOR WALKING THE UI
793 * These functions all return null if the specified path or child
797 private Accessible descendNodes(Accessible parent, int[] path) {
798 // Descends through several levels of Accessible children in one call.
799 // path[] is an array of ints, each int being the index into the array
800 // of children at a particular point, and thus selects the specific
801 // accessible child to descend to.
804 for(int i=0;i<path.length;i++) {
805 if (null == (parent = descend(parent, path[i]))) return null;
810 private Accessible descend(Accessible parent, int childNum) {
811 // Descends one level to the specified child of the parent
812 // childNum is the index of the child within parent
815 if (parent == null) return null;
816 int children = parent.getAccessibleContext().getAccessibleChildrenCount();
817 if (childNum >= children) {
818 debuglog("DESCEND "+childNum+" > "+children+" NOT FOUND");
821 Accessible child = parent.getAccessibleContext()
822 .getAccessibleChild(childNum);
823 debuglog("DESCEND "+childNum+" "+child.getClass().getName()+" OK");
827 private Accessible descendByClass(Accessible parent, String classname) {
828 // Descends one level to the first child which has the specified class.
831 if (parent == null) return null;
832 AccessibleContext ac = parent.getAccessibleContext();
833 int children = ac.getAccessibleChildrenCount();
834 for (int i=0; i<children; i++) {
835 Accessible child = ac.getAccessibleChild(i);
836 if (child.getClass().getName() == classname) {
837 debuglog("DESCEND CLASS "+classname+" OK");
841 debuglog("DESCEND CLASS "+classname+" NOT FOUND");
846 /*****************************************
847 * PCTB-SPECIFIC HELPER FUNCTIONS ETC. *
848 *****************************************/
851 * An abstract market offer, entailing a commodity being bought or sold by
852 * a shoppe, for a certain price in a certain quantity. Not instantiable.
857 abstract class Offer {
858 public int commodity, price, quantity, shoppe;
860 * Create an offer from <code>record</code>, determining the shoppe Id from
861 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
862 * <code>priceIndex</code> should be the index of the price in the record
863 * (the quantity will be <code>priceIndex + 1</code>).
865 * @param record the record with data to create the offer from
866 * @param stallMap a map containing the ids of the various stalls
867 * @param commodMap a map containing the ids of the various commodities
868 * @param priceIndex the index of the price in the record
870 public Offer(ArrayList<String> record,
871 LinkedHashMap<String,Integer> stallMap,
872 HashMap<String,Integer> commodMap,
874 Integer commodId = commodMap.get(record.get(0));
875 if(commodId == null) {
876 throw new IllegalArgumentException();
878 commodity = commodId.intValue();
879 price = Integer.parseInt(record.get(priceIndex));
880 String qty = record.get(priceIndex+1);
881 quantity = parseQty(qty);
882 shoppe = stallMap.get(record.get(1)).intValue();
886 * Returns a human-readable version of this offer, useful for debugging
888 * @return human-readable offer
890 public String toString() {
891 return "[C:" + commodity + ",$" + price + ",Q:"
892 + quantity + ",S:" + shoppe + "]";
897 * An offer from a shoppe or stall to buy a certain quantity of a
898 * commodity for a certain price. If placed in an ordered Set,
899 * sorts by commodity index ascending, then by buy price
900 * descending, and finally by stall id ascending.
902 class Buy extends Offer implements Comparable<Buy> {
904 * Creates a new <code>Buy</code> offer from the given
905 * <code>record</code> using the other parameters to determine
906 * stall id and commodity id of the offer.
908 * @param record the record with data to create the offer from
909 * @param stallMap a map containing the ids of the various stalls
910 * @param commodMap a map containing the ids of the various commodities
912 public Buy(ArrayList<String> record,
913 LinkedHashMap<String,Integer> stallMap,
914 HashMap<String,Integer> commodMap) {
915 super(record,stallMap,commodMap,2);
919 * Sorts by commodity index ascending, then price descending,
920 * then stall id ascending.
922 public int compareTo(Buy buy) {
923 // organize by: commodity index, price, stall index
924 if(commodity == buy.commodity) {
925 // organize by price, then by stall index
926 if(price == buy.price) {
927 // organize by stall index
928 return shoppe>buy.shoppe ? 1 : -1;
929 } else if(price > buy.price) {
934 } else if(commodity > buy.commodity) {
943 * An offer from a shoppe or stall to sell a certain quantity of
944 * a commodity for a certain price. If placed in an ordered Set,
945 * sorts by commodity index ascending, then by sell price
946 * ascending, and finally by stall id ascending.
948 class Sell extends Offer implements Comparable<Sell> {
950 * Creates a new <code>Sell</code> offer from the given
951 * <code>record</code> using the other parameters to determine
952 * stall id and commodity id of the offer.
954 * @param record the record with data to create the offer from
955 * @param stallMap a map containing the ids of the various stalls
956 * @param commodMap a map containing the ids of the various commodities
958 public Sell(ArrayList<String> record,
959 LinkedHashMap<String,Integer> stallMap,
960 HashMap<String,Integer> commodMap) {
961 super(record,stallMap,commodMap,4);
965 * Sorts by commodity index ascending, then price ascending, then
966 * stall id ascending.
968 public int compareTo(Sell sell) {
969 // organize by: commodity index, price, stall index
970 if(commodity == sell.commodity) {
971 // organize by price, then by stall index
972 if(price == sell.price) {
973 // organize by stall index
974 return shoppe>sell.shoppe ? 1 : -1;
975 } else if(price > sell.price) {
980 } else if(commodity > sell.commodity) {
989 * Gets the list of commodities and their associated commodity ids.
991 * @return a map where the key is the commodity and the value is
994 private HashMap<String,Integer> getCommodMap() {
996 if(commodMap != null) {
999 HashMap<String,Integer> map = new HashMap<String,Integer>();
1002 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
1004 new BufferedReader(new InputStreamReader(host.openStream()));
1005 StringBuilder sb = new StringBuilder();
1007 while((str = br.readLine()) != null) {
1011 debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
1012 int first = sb.indexOf("<pre>") + 5;
1013 int last = sb.indexOf("</body>");
1014 xml = sb.substring(first,last);
1015 Reader reader = new CharArrayReader(xml.toCharArray());
1016 Document d = DocumentBuilderFactory.newInstance()
1017 .newDocumentBuilder().parse(new InputSource(reader));
1018 NodeList maps = d.getElementsByTagName("CommodMap");
1019 for(int i=0;i<maps.getLength();i++) {
1020 NodeList content = maps.item(i).getChildNodes();
1021 Integer num = Integer.parseInt(content.item(1).getTextContent());
1022 map.put(content.item(0).getTextContent(),num);
1024 } catch(Exception e) {
1025 e.printStackTrace();
1026 error("Unable to load Commodity list from server!");
1034 * Given the list of offers, this method will find all the unique
1035 * stall names and return them in a <code>LinkedHashMap</code>
1036 * where the key is the stall name and the value is the generated
1037 * stall id (position in the list). <p> The reason this method
1038 * returns a LinkedHashMap instead of a simple HashMap is the
1039 * need for iterating over the stall names in insertion order for
1040 * output to the server.
1042 * @param offers the list of records from the commodity buy/sell interface
1043 * @return an iterable ordered map of the stall names and
1044 * generated stall ids
1046 private LinkedHashMap<String,Integer> getStallMap
1047 (ArrayList<ArrayList<String>> offers) {
1049 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
1050 for(ArrayList<String> offer : offers) {
1051 String shop = offer.get(1);
1052 if(!map.containsKey(shop)) {
1054 map.put(shop,count);
1061 * Gets a sorted list of Buys and Sells from the list of
1062 * records. <code>buys</code> and <code>sells</code> should be
1063 * pre-initialized and passed into the method to receive the
1064 * data. Returns a 2-length int array with the number of buys
1067 * @param offers the data found from the market table in-game
1068 * @param buys an empty initialized <code>TreeSet<Offer></code> to
1069 * hold the Buy offers.
1070 * @param sells an empty initialized <code>TreeSet<Offer></code> to
1071 * hold the Sell offers.
1072 * @param stalls the map of stalls to their ids
1073 * @param commodMap the map of commodities to their ids
1074 * @return a 2-length int[] array containing the number of buys
1075 * and sells, respectively
1077 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers,
1078 TreeSet<Offer> buys,
1079 TreeSet<Offer> sells,
1080 LinkedHashMap<String,Integer> stalls,
1081 HashMap<String,Integer> commodMap) {
1082 int[] buySellCount = new int[2];
1083 for(ArrayList<String> offer : offers) {
1085 if(offer.get(2) != null) {
1086 buys.add(new Buy(offer,stalls,commodMap));
1089 if(offer.get(4) != null) {
1090 sells.add(new Sell(offer,stalls,commodMap));
1093 } catch(IllegalArgumentException e) {
1094 unknownPCTBcommods++;
1095 debuglog("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
1098 if (buySellCount[0]==0 && buySellCount[1]==0) {
1099 error("No (valid) offers for PCTB?!");
1100 throw new IllegalArgumentException();
1102 return buySellCount;
1106 * Prepares the list of stalls for writing to the output stream.
1107 * The <code>String</code> returned by this method is ready to be
1108 * written directly to the stream. <p> All shoppe names are left
1109 * as they are. Stall names are abbreviated just before the
1110 * apostrophe in the possessive, with an "^" and a letter
1111 * matching the stall's type appended. Example: "Burninator's
1112 * Ironworking Stall" would become "Burninator^I".
1114 * @param stallMap the map of stalls and stall ids in an iterable order
1115 * @return a <code>String</code> containing the list of stalls in
1116 * format ready to be written to the output stream.
1118 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
1119 // set up some mapping
1120 HashMap<String,String> types = new HashMap<String,String>();
1121 types.put("Apothecary Stall", "A");
1122 types.put("Distilling Stall", "D");
1123 types.put("Furnishing Stall", "F");
1124 types.put("Ironworking Stall", "I");
1125 types.put("Shipbuilding Stall", "S");
1126 types.put("Tailoring Stall", "T");
1127 types.put("Weaving Stall", "W");
1129 StringBuilder sb = new StringBuilder();
1130 for(String name : stallMap.keySet()) {
1131 int index = name.indexOf("'s");
1132 String finalName = name;
1135 finalName = name.substring(0,index);
1136 if(index + 2 < name.length()) {
1137 String end = name.substring(index+2,name.length()).trim();
1138 type = types.get(end);
1142 sb.append(name+"\n");
1144 sb.append(finalName+"^"+type+"\n");
1147 return sb.toString();
1151 * Writes a list of offers in correct format to the output stream.
1153 * The format is thus: (all numbers are 2-byte integers in
1154 * little-endian format) (number of offers of this type, aka
1155 * buy/sell) (commodity ID) (number of offers for this commodity)
1156 * [shopID price qty][shopID price qty]...
1158 * @param out the output stream to write the data to
1159 * @param offers the offers to write
1161 private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1162 throws IOException {
1163 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1164 if(offers.size() == 0) {
1165 // nothing to write, and "0" has already been written
1168 int commodity = offers.first().commodity;
1170 for(Offer offer : offers) {
1171 if(commodity != offer.commodity) {
1173 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1175 commodity = offer.commodity;
1178 writeLEShort(offer.shoppe,buffer); // stall index
1179 writeLEShort(offer.price,buffer); // buy price
1180 writeLEShort(offer.quantity,buffer); // buy qty
1183 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1187 * Writes the buffered data to the output strea for one commodity.
1189 * @param out the stream to write to
1190 * @param buffer the buffered data to write
1191 * @param commodity the commmodity id to write before the buffered data
1192 * @param count the number of offers for this commodity to write
1195 private void writeBufferedOffers(OutputStream out, byte[] buffer,
1196 int commodity, int count)
1197 throws IOException {
1198 writeLEShort(commodity,out); // commod index
1199 writeLEShort(count,out); // offer count
1200 out.write(buffer); // the buffered offers
1204 * Writes the buy and sell offers to the outputstream by calling
1207 * @param buys list of Buy offers to write
1208 * @param sells list of Sell offers to write
1209 * @param offerCount 2-length int array containing the number of
1210 * buys and sells to write out
1211 * @param out the stream to write to
1213 private void writeBuySellOffers(TreeSet<Offer> buys,
1214 TreeSet<Offer> sells,
1215 int[] offerCount, OutputStream out)
1216 throws IOException {
1218 writeLEShort(offerCount[0],out);
1219 writeOffers(out,buys);
1221 writeLEShort(offerCount[1],out);
1222 writeOffers(out,sells);
1225 private String readstreamstring(InputStream in) throws IOException {
1226 StringBuilder sb = new StringBuilder();
1227 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1229 while((str = br.readLine()) != null) {
1230 sb.append(str+"\n");
1232 return sb.toString();
1236 * Sends the data to the server via multipart-formdata POST,
1237 * with the gzipped data as a file upload.
1239 * @param file an InputStream open to the gzipped data we want to send
1241 private InputStream sendInitialData(InputStream file) throws IOException {
1243 ClientHttpRequest http =
1244 new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1245 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1247 String err = readstreamstring(http.resultstream());
1248 error("Error sending initial data:\n"+err);
1251 return http.resultstream();
1255 * Utility method to write a 2-byte int in little-endian form to
1258 * @param num an integer to write
1259 * @param out stream to write to
1261 private void writeLEShort(int num, OutputStream out) throws IOException {
1262 out.write(num & 0xFF);
1263 out.write((num >>> 8) & 0xFF);
1267 * Reads the response from the server, and selects the correct parameters
1268 * which are sent in a GET request to the server asking it to confirm
1269 * the upload and accept the data into the database. Notably, the island id
1270 * and ocean id are determined, while other parameter such as the filename
1271 * are determined from the hidden form fields.
1273 * @param in stream of data from the server to read
1275 private boolean finishUpload(InputStream in) throws IOException {
1278 String html = readstreamstring(in);
1279 debug_write_stringdata("pctb-initial.html", html);
1282 Pattern params = Pattern.compile
1283 ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1284 ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1285 ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1286 m = params.matcher(html);
1288 error_html("The PCTB server returned unusual data."+
1289 " Maybe you're using an old version of the uploader?",
1293 String forceReload = m.group(1);
1294 String filename = m.group(2);
1296 Pattern oceanNumPat =
1297 Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1298 m = oceanNumPat.matcher(html);
1300 error_html("Unable to find the ocean in the server's list of oceans!",
1304 String oceanNum = m.group(1);
1306 Pattern oceanIslandNum =
1307 Pattern.compile("islands\\[" + oceanNum
1308 + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1310 m = oceanIslandNum.matcher(html);
1312 error_html("This does not seem to be a valid island! Unable to upload.",
1316 String islandNum = m.group(1);
1318 URL get = new URL(PCTB_HOST_URL +
1319 "upload.php?action=setisland&ocean=" + oceanNum
1320 + "&island=" + islandNum
1321 + "&forcereload=" + forceReload
1322 + "&filename=" + filename);
1323 String complete = readstreamstring(get.openStream());
1324 debug_write_stringdata("pctb-final.html", complete);
1325 Pattern done = Pattern.compile
1326 ("Your data has been integrated into the database. Thank you!");
1327 m = done.matcher(complete);
1331 error_html("Something was wrong with the final upload parameters!",
1338 /*****************************************
1339 * YARRG-SPECIFIC HELPER FUNCTIONS ETC. *
1340 *****************************************/
1342 private InputStream post_for_yarrg(ClientHttpRequest http)
1343 throws IOException {
1346 String err = readstreamstring(http.resultstream());
1347 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1350 return http.resultstream();
1353 private class YarrgTimestampFetcher extends Thread {
1354 public YarrgTimestampFetcher(int counter) {
1355 super("MarketUploader-YarrgTimestampFetcher-"+uploadcounter);
1357 public String ts = null;
1360 ts = getYarrgTimestamp();
1361 debuglog("(async) yarrg timestamp ready.");
1362 } catch(Exception e) {
1363 error("Error getting YARRG timestamp: "+e);
1368 private String getYarrgTimestamp() throws IOException {
1369 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1370 http.setParameter("clientname", YARRG_CLIENTNAME);
1371 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1372 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1373 http.setParameter("requesttimestamp", "y");
1374 InputStream in = post_for_yarrg(http);
1375 if (in == null) return null;
1376 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1377 String tsresult = br.readLine();
1378 return tsresult.substring(3, tsresult.length()-1);
1381 private boolean runYarrg(String timestamp, String ocean, String island,
1382 String yarrgdata) throws IOException {
1383 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1384 BufferedOutputStream bufos =
1385 new BufferedOutputStream(new GZIPOutputStream(bos));
1386 bufos.write(yarrgdata.getBytes() );
1388 byte[] compressed = bos.toByteArray();
1389 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1390 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1392 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1393 http.setParameter("clientname", YARRG_CLIENTNAME);
1394 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1395 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1396 http.setParameter("timestamp", timestamp);
1397 http.setParameter("ocean", ocean);
1398 http.setParameter("island", island);
1399 http.setParameter("data", "deduped.tsv.gz", file,
1400 "application/octet-stream");
1401 InputStream in = post_for_yarrg(http);
1402 if (in == null) return false;
1403 String output = readstreamstring(in);
1404 if (!output.startsWith("OK")) {
1405 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1408 debug_write_stringdata("yarrg-result.txt", output);
1412 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1413 // debuglog("ARBITRAGE?");
1415 SortedSet<int[]> buys = arb_bs.get(0);
1416 SortedSet<int[]> sells = arb_bs.get(1);
1420 // NB "sell" means they sell, ie we buy
1421 sell = sells.last();
1423 } catch (NoSuchElementException e) {
1427 int unitprofit = buy[0] - sell[0];
1428 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1429 // debuglog(" sell @"+sell[0]+" x"+sell[1]
1430 // +" buy @"+buy[0]+" x"+buy[1]
1431 // +" => x"+count+" @"+unitprofit);
1433 if (unitprofit <= 0)
1436 profit += count * unitprofit;
1439 if (buy[1]==0) buys.remove(buy);
1440 if (sell[1]==0) sells.remove(sell);
1442 // debuglog(" PROFIT "+profit);
1446 /*****************************************
1448 *****************************************/
1450 private class arbitrageOfferComparator implements Comparator {
1451 public int compare(Object o1, Object o2) {
1452 int p1 = ((int[])o1)[0];
1453 int p2 = ((int[])o2)[0];
1458 private @SuppressWarnings("unchecked")
1459 void calculateArbitrage(ArrayList<ArrayList<String>> data)
1460 throws InterruptedException {
1462 ArrayList<SortedSet<int[]>> arb_bs = null;
1463 String lastcommod = null;
1464 Comparator compar = new arbitrageOfferComparator();
1466 for (ArrayList<String> row : data) {
1467 String thiscommod = row.get(0);
1468 // debuglog("ROW "+row.toString());
1469 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1470 if (lastcommod != null)
1471 arbitrage += calculateArbitrageCommodity(arb_bs);
1472 // debuglog("ROW rdy");
1473 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1474 arb_bs.add(0, new TreeSet<int[]>(compar));
1475 arb_bs.add(1, new TreeSet<int[]>(compar));
1476 // debuglog("ROW init");
1477 lastcommod = thiscommod;
1479 for (int bs = 0; bs < 2; bs++) {
1480 String pricestr = row.get(bs*2 + 2);
1481 if (pricestr == null)
1483 int[] entry = new int[2];
1484 // debuglog("ROW BS "+bs);
1485 entry[0] = parseQty(pricestr);
1486 entry[1] = parseQty(row.get(bs*2 + 3));
1487 arb_bs.get(bs).add(entry);
1490 arbitrage += calculateArbitrageCommodity(arb_bs);
1492 if (arbitrage != 0) {
1493 arb = "<html><strong>arbitrage: "+arbitrage+" poe</strong>";
1495 arb = "no arbitrage";
1497 final String arb_final = arb;
1498 EventQueue.invokeLater(new Runnable() { public void run() {
1499 arbitrageResult.setText(arb_final);