1 package net.chiark.yarrg;
4 import java.awt.event.*;
6 import javax.accessibility.*;
9 import com.sun.java.accessibility.util.*;
16 import javax.xml.parsers.DocumentBuilderFactory;
17 import org.xml.sax.InputSource;
18 import java.util.zip.GZIPOutputStream;
19 import net.chiark.yarrg.ClientHttpRequest;
20 import java.util.regex.*;
21 import java.util.prefs.Preferences;
25 * MarketUploader is a class that handles the uploading of market
26 * data from Yohoho! Puzzle Pirates via the Java Accessibility
29 * MarketUploader initializes after the main YPP window has
30 * initialized. It provides a simple window with a "Capture
31 * Market Data" button displayed. Upon clicking this button, a
32 * progress dialog is displayed, and the data is processed and
33 * submitted to the YARRG and PCTB servers. If any errors occur,
34 * an error dialog is shown, and processing returns, the button
35 * becoming re-enabled.
37 public class MarketUploader
38 implements Runnable, TopLevelWindowListener, GUIInitializedListener {
39 private JFrame frame = null;
40 private Window window = null;
41 private JButton findMarket = null;
42 private JLabel resultSummary = null;
43 private JLabel arbitrageResult = null;
44 private int unknownPCTBcommods = 0;
45 private long startTime = 0;
47 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
48 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
49 private String PCTB_HOST_URL;
51 // Yarrg protocol parameters
52 private final static String YARRG_CLIENTNAME = "jpctb greenend";
53 private final static String YARRG_CLIENTVERSION =
54 net.chiark.yarrg.Version.version;
55 private final static String YARRG_CLIENTFIXES = "bug-094";
56 private final static String YARRG_LIVE_URL =
57 "http://upload.yarrg.chiark.net/commod-update-receiver";
58 private final static String YARRG_TEST_URL =
59 "http://upload.yarrg.chiark.net/test/commod-update-receiver";
60 private String YARRG_URL;
62 private boolean uploadToYarrg;
63 private boolean uploadToPCTB;
64 private boolean showArbitrage;
66 private String islandName = null;
67 private String oceanName = null;
68 private java.util.concurrent.CountDownLatch latch = null;
70 private AccessibleContext sidePanel;
71 private HashMap<String,Integer> commodMap;
72 public PrintStream dtxt = null;
74 private PropertyChangeListener changeListener = new PropertyChangeListener() {
75 public void propertyChange(PropertyChangeEvent e) {
76 if(e.getNewValue() != null &&
77 e.getPropertyName().equals
78 (AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
79 Accessible islandInfo =
80 descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
82 islandInfo.getAccessibleContext().getAccessibleText()
83 .getAtIndex(AccessibleText.SENTENCE,0);
84 int index = text.indexOf(":");
85 String name = text.substring(0,index);
87 // if (dtxt!=null) dtxt.println(islandName);
88 sidePanel.removePropertyChangeListener(this);
94 private int parseQty(String str) {
95 if (str.equals(">1000")) {
98 return Integer.parseInt(str);
102 private void progresslog(String s) {
103 if (dtxt == null) return;
104 long now = new Date().getTime();
105 dtxt.println("progress "+(now - startTime)+"ms "+s);
108 private void debug_write_stringdata(String what, String data)
109 throws FileNotFoundException,IOException {
110 if (dtxt==null) return;
111 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
116 private void debug_write_bytes(String what, byte[] data)
117 throws FileNotFoundException,IOException {
118 if (dtxt==null) return;
119 FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
124 private void progressNote(ProgressMonitor pm, String s) {
126 if (arbitrageResult != null)
127 arb = arbitrageResult.getText();
128 if (arb != null && arb.length() != 0)
129 s = "<html>" + arb + "<br>" + s;
134 * An abstract market offer, entailing a commodity being bought or sold by
135 * a shoppe, for a certain price in a certain quantity. Not instantiable.
140 abstract class Offer {
141 public int commodity, price, quantity, shoppe;
143 * Create an offer from <code>record</code>, determining the shoppe Id from
144 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
145 * <code>priceIndex</code> should be the index of the price in the record
146 * (the quantity will be <code>priceIndex + 1</code>).
148 * @param record the record with data to create the offer from
149 * @param stallMap a map containing the ids of the various stalls
150 * @param commodMap a map containing the ids of the various commodities
151 * @param priceIndex the index of the price in the record
153 public Offer(ArrayList<String> record,
154 LinkedHashMap<String,Integer> stallMap,
155 HashMap<String,Integer> commodMap,
157 Integer commodId = commodMap.get(record.get(0));
158 if(commodId == null) {
159 throw new IllegalArgumentException();
161 commodity = commodId.intValue();
162 price = Integer.parseInt(record.get(priceIndex));
163 String qty = record.get(priceIndex+1);
164 quantity = parseQty(qty);
165 shoppe = stallMap.get(record.get(1)).intValue();
169 * Returns a human-readable version of this offer, useful for debugging
171 * @return human-readable offer
173 public String toString() {
174 return "[C:" + commodity + ",$" + price + ",Q:"
175 + quantity + ",S:" + shoppe + "]";
180 * An offer from a shoppe or stall to buy a certain quantity of a
181 * commodity for a certain price. If placed in an ordered Set,
182 * sorts by commodity index ascending, then by buy price
183 * descending, and finally by stall id ascending.
185 class Buy extends Offer implements Comparable<Buy> {
187 * Creates a new <code>Buy</code> offer from the given
188 * <code>record</code> using the other parameters to determine
189 * stall id and commodity id of the offer.
191 * @param record the record with data to create the offer from
192 * @param stallMap a map containing the ids of the various stalls
193 * @param commodMap a map containing the ids of the various commodities
195 public Buy(ArrayList<String> record,
196 LinkedHashMap<String,Integer> stallMap,
197 HashMap<String,Integer> commodMap) {
198 super(record,stallMap,commodMap,2);
202 * Sorts by commodity index ascending, then price descending,
203 * then stall id ascending.
205 public int compareTo(Buy buy) {
206 // organize by: commodity index, price, stall index
207 if(commodity == buy.commodity) {
208 // organize by price, then by stall index
209 if(price == buy.price) {
210 // organize by stall index
211 return shoppe>buy.shoppe ? 1 : -1;
212 } else if(price > buy.price) {
217 } else if(commodity > buy.commodity) {
226 * An offer from a shoppe or stall to sell a certain quantity of
227 * a commodity for a certain price. If placed in an ordered Set,
228 * sorts by commodity index ascending, then by sell price
229 * ascending, and finally by stall id ascending.
231 class Sell extends Offer implements Comparable<Sell> {
233 * Creates a new <code>Sell</code> offer from the given
234 * <code>record</code> using the other parameters to determine
235 * stall id and commodity id of the offer.
237 * @param record the record with data to create the offer from
238 * @param stallMap a map containing the ids of the various stalls
239 * @param commodMap a map containing the ids of the various commodities
241 public Sell(ArrayList<String> record,
242 LinkedHashMap<String,Integer> stallMap,
243 HashMap<String,Integer> commodMap) {
244 super(record,stallMap,commodMap,4);
248 * Sorts by commodity index ascending, then price ascending, then
249 * stall id ascending.
251 public int compareTo(Sell sell) {
252 // organize by: commodity index, price, stall index
253 if(commodity == sell.commodity) {
254 // organize by price, then by stall index
255 if(price == sell.price) {
256 // organize by stall index
257 return shoppe>sell.shoppe ? 1 : -1;
258 } else if(price > sell.price) {
263 } else if(commodity > sell.commodity) {
272 * Entry point. Read our preferences.
274 public MarketUploader() {
275 Preferences prefs = Preferences.userNodeForPackage(getClass());
277 if (prefs.getBoolean("writeDebugFiles", false)) {
279 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
280 } catch (java.io.FileNotFoundException e) {
281 System.err.println("JARRG: Error opening debug log: "+e);
285 if (prefs.getBoolean("useLiveServers", true)) {
286 YARRG_URL = YARRG_LIVE_URL;
287 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
289 YARRG_URL = YARRG_TEST_URL;
290 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
293 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
294 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
295 showArbitrage=prefs.getBoolean("showArbitrage", true);
297 if (dtxt!=null) dtxt.println("main on dispatch thread: "+
298 EventQueue.isDispatchThread());
299 EventQueue.invokeLater(this);
303 * We arrange to wait for the GUI to be initialised, then look at
304 * every top-level window, and if it
307 if (dtxt!=null) dtxt.println("MarketUploader run()...");
308 if (EventQueueMonitor.isGUIInitialized()) {
309 if (dtxt!=null) dtxt.println("MarketUploader GUI already ready");
312 if (dtxt!=null) dtxt.println("MarketUploader waiting for GUI");
313 EventQueueMonitor.addGUIInitializedListener(this);
317 public void guiInitialized() {
318 Window ws[]= EventQueueMonitor.getTopLevelWindows();
319 EventQueueMonitor.addTopLevelWindowListener(this);
320 for (int i=0; i<ws.length; i++) {
321 if (dtxt!=null) dtxt.println("MarketUploader existing toplevel "+i);
322 topLevelWindowCreated(ws[i]);
326 public void topLevelWindowDestroyed(Window w) {
327 if (dtxt!=null) dtxt.println("MarketUploader destroyed toplevel");
330 public void topLevelWindowCreated(Window w) {
334 String name = w.getAccessibleContext().getAccessibleName();
335 if (dtxt!=null) dtxt.println("MarketUploader new toplevel "+name);
336 if (!name.equals("Puzzle Pirates"))
338 if (dtxt!=null) dtxt.println("MarketUploader found toplevel, creating gui");
341 frame.setVisible(true);
345 * Set up the GUI, with its window and one-button
346 * interface. Only initialize if we're running alongside
347 * a Window named "Puzzle Pirates" though.
349 private void createGUI() {
350 frame = new JFrame("Jarrg Uploader");
351 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
352 GridLayout layout = new GridLayout(2,1);
353 frame.getContentPane().setLayout(layout);
354 //frame.setPreferredSize(new Dimension(200, 60));
356 findMarket = new JButton("Upload Market Data");
357 findMarket.addActionListener(new ActionListener() {
358 public void actionPerformed(ActionEvent e) {
359 findMarket.setEnabled(false);
362 startTime = new Date().getTime();
363 resultSummary.setText("");
364 arbitrageResult.setText("");
365 unknownPCTBcommods = 0;
368 } catch(Exception e) {
371 resultSummary.setText("failed");
373 if(sidePanel != null) {
374 // remove it if it's still attached
375 sidePanel.removePropertyChangeListener(changeListener);
378 findMarket.setEnabled(true);
383 frame.add(findMarket);
385 resultSummary = new JLabel("ready");
386 frame.add(resultSummary);
388 arbitrageResult = new JLabel("");
391 layout.setRows(layout.getRows() + 1);
392 frame.add(arbitrageResult);
399 * Finds the island name from the /who tab, sets global islandName variable
401 private void getIsland() {
403 // If the league tracker is there, we can skip the faff
404 // and ask for its tooltip, since we're on a boat
406 Accessible leagueTrackerContainer =
407 descendNodes(window,new int[] {0,1,0,0,2,1});
408 Accessible leagueTrackerItself =
409 descendByClass(leagueTrackerContainer,
410 "com.threerings.yohoho.sea.client.LeagueTracker");
411 Accessible leagueTracker = descend(leagueTrackerItself, 1);
413 islandName = ((JLabel)leagueTracker).getToolTipText();
414 } catch (NullPointerException e) {
415 // evidently we're actually on an island
418 AccessibleContext chatArea =
419 descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2})
420 .getAccessibleContext();
421 // attach the property change listener to the outer sunshine
422 // panel if the "ahoy" tab is not active, otherwise attach it to
423 // the scroll panel in the "ahoy" tab.
424 if(!"com.threerings.piracy.client.AttentionListPanel".
425 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0})
426 .getClass().getCanonicalName())) {
427 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2})
428 .getAccessibleContext();
430 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0})
431 .getAccessibleContext();
433 sidePanel.addPropertyChangeListener(changeListener);
434 latch = new java.util.concurrent.CountDownLatch(1);
435 // make the Players Online ("/who") panel appear
436 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
437 chat.setTextContents("/w");
438 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
439 for(int i=0;i<c;i++) {
440 if("notify-field-accept".equals(chatArea.getAccessibleAction()
441 .getAccessibleActionDescription(i))) {
442 chatArea.getAccessibleAction().doAccessibleAction(i);
449 * Find the ocean name from the window title, and set global
452 private void getOcean() {
454 AccessibleContext topwindow = window.getAccessibleContext();
455 oceanName = topwindow.getAccessibleName()
456 .replaceAll(".*on the (\\w+) ocean", "$1");
461 * Shows a dialog with the error <code>msg</code>.
463 * @param msg a String describing the error that occured.
465 private void error(String msg) {
466 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
469 private void error_html(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 if (dtxt!=null) dtxt.println("###" + whole_msg + "###");
485 JOptionPane.showMessageDialog(frame,whole_msg,"Error",
486 JOptionPane.ERROR_MESSAGE);
490 * Run the data collection process, and upload the results. This
491 * is the method that calls most of the other worker methods for
492 * the process. If an error occurs, the method will call the
493 * error method and return early, freeing up the button to be
496 * @exception Exception if an error we didn't expect occured
498 private class YarrgTimestampFetcher extends Thread {
499 public String ts = null;
502 ts = getYarrgTimestamp();
503 progresslog("(async) yarrg timestamp ready.");
504 } catch(Exception e) {
505 error("Error getting YARRG timestamp: "+e);
510 private void runUpload() throws Exception {
511 progresslog("starting");
513 ProgressMonitor pm = new ProgressMonitor
514 (frame,"Processing Market Data","Getting table data",0,100);
515 pm.setMillisToDecideToPopup(0);
516 pm.setMillisToPopup(0);
517 boolean doneyarrg = false, donepctb = false;
518 YarrgTimestampFetcher yarrgts_thread = null;
521 progresslog("(async) yarrg timestamp...");
522 yarrgts_thread = new YarrgTimestampFetcher();
523 yarrgts_thread.start();
526 AccessibleTable accesstable = findMarketTable();
527 if(accesstable == null) {
528 error("Market table not found!"+
529 " Please open the Buy/Sell Commodities interface.");
532 if(accesstable.getAccessibleRowCount() == 0) {
533 error("No data found, please wait for the table to have data first!");
536 if(!isDisplayAll()) {
537 error("Please select \"All\" from the Display: popup menu.");
541 progresslog("(async) getisland...");
543 progresslog("getocean...");
545 progresslog("getocean done");
548 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
550 progresslog("(async) getisland done");
552 String yarrgts = null;
553 if (yarrgts_thread != null) {
554 progresslog("(async) yarrg timestamp join...");
555 yarrgts_thread.join();
556 progresslog("(async) yarrg timestamp joined.");
557 yarrgts = yarrgts_thread.ts;
560 if (islandName == null) {
561 error("Could not find island name in YPP user interface.");
565 progresslog("table check...");
567 String headings_expected[] = new String[]
568 { "Commodity", "Trading outlet", "Buy price",
569 "Will buy", "Sell price", "Will sell" };
570 ArrayList<ArrayList<String>> headers =
571 getData(accesstable.getAccessibleColumnHeader());
572 if (headers.size() != 1) {
573 error("Table headings not one row! " + headers.toString());
576 if (headers.get(0).size() < 6 ||
577 headers.get(0).size() > 7) {
578 error("Table headings not six or seven columns! " + headers.toString());
581 for (int col=0; col<headings_expected.length; col++) {
582 String expd = headings_expected[col];
583 String got = headers.get(0).get(col);
584 if (expd.compareTo(got) != 0) {
585 error("Table heading for column "+col
586 +" is not \""+expd+"\" but \""+got+"\".\n\n"
587 +"Please do not reorder the table when using this tool.");
592 progresslog("table read...");
594 ArrayList<ArrayList<String>> data = getData(accesstable);
597 progresslog("arbitrage...");
598 calculateArbitrage(data);
599 progresslog("arbitrage done.");
602 if (uploadToYarrg && yarrgts != null) {
603 progresslog("yarrg prepare...");
604 progressNote(pm, "Yarrg: Preparing data");
607 StringBuilder yarrgsb = new StringBuilder();
608 String yarrgdata; // string containing what we'll feed to yarrg
610 for (ArrayList<String> row : data) {
611 if (row.size() > 6) {
614 for (String rowitem : row) {
615 yarrgsb.append(rowitem != null ? rowitem : "");
616 yarrgsb.append("\t");
618 yarrgsb.setLength(yarrgsb.length()-1); // chop
619 yarrgsb.append("\n");
622 yarrgdata = yarrgsb.toString();
624 progressNote(pm, "Yarrg: Uploading");
625 progresslog("yarrg upload...");
627 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
628 progresslog("yarrg done.");
632 progresslog("pctb prepare...");
633 progressNote(pm, "PCTB: Getting stall names");
635 if(pm.isCanceled()) {
638 TreeSet<Offer> buys = new TreeSet<Offer>();
639 TreeSet<Offer> sells = new TreeSet<Offer>();
640 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
642 progressNote(pm, "PCTB: Sorting offers");
643 if(pm.isCanceled()) {
648 progresslog("pctb commodmap...");
649 HashMap<String,Integer> commodMap = getCommodMap();
650 if(commodMap == null) {
653 progresslog("pctb commodmap done.");
654 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
655 // if (dtxt!=null) dtxt.println(sells);
656 // if (dtxt!=null) dtxt.println("\n\n\n"+buys);
658 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
660 progressNote(pm, "PCTB: Sending data");
661 if(pm.isCanceled()) {
664 GZIPOutputStream out = new GZIPOutputStream(outStream);
665 DataOutputStream dos = new DataOutputStream(out);
666 dos.writeBytes("005y\n");
667 dos.writeBytes(stallMap.size()+"\n");
668 dos.writeBytes(getAbbrevStallList(stallMap));
669 writeBuySellOffers(buys,sells,offerCount,out);
671 progresslog("pctb send...");
673 byte[] ba = outStream.toByteArray();
674 debug_write_bytes("pctb-marketdata.gz", ba);
676 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
677 progresslog("pctb sent.");
678 if (in == null) return;
680 if(pm.isCanceled()) {
683 progressNote(pm, "PCTB: Waiting ...");
684 progresslog("pctb finish...");
685 donepctb = finishUpload(in);
686 progresslog("pctb done.");
690 if ((uploadToPCTB && !donepctb) ||
691 (uploadToYarrg && !doneyarrg)) {
692 resultSummary.setText("trouble");
693 } else if (unknownPCTBcommods != 0) {
694 resultSummary.setText("PCTB lacks "+unknownPCTBcommods+" commod");
695 } else if (donepctb || doneyarrg) {
696 resultSummary.setText("Done " + islandName);
698 resultSummary.setText("uploaded nowhere!");
700 progresslog("done.");
704 * Get the offer data out of the table and cache it in an
705 * <code>ArrayList</code>.
707 * @param table the <code>AccessibleTable</code> containing the market data
708 * @return an array of record arrays, each representing a row of the table
710 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
711 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
712 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
713 ArrayList<String> row = new ArrayList<String>();
714 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
715 row.add(table.getAccessibleAt(i, j)
716 .getAccessibleContext().getAccessibleName());
724 * @return the table containing market data if it exists,
725 * otherwise <code>null</code>
727 public AccessibleTable findMarketTable() {
728 Accessible node1 = window;
729 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0});
731 // 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})
732 // if (dtxt!=null) dtxt.println(node);
733 if (!(node instanceof JTable)) {
734 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0});
737 if (!(node instanceof JTable)) return null;
738 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
739 // if (dtxt!=null) dtxt.println(table);
744 * Utility method to descend through several levels of Accessible children
747 * @param parent the node on which to start the descent
748 * @param path an array of ints, each int being the index of the next
749 * accessible child to descend.
750 * @return the <code>Accessible</code> reached by following the
751 * descent path, or <code>null</code> if the desired path was
754 private Accessible descendNodes(Accessible parent, int[] path) {
755 for(int i=0;i<path.length;i++) {
756 if (null == (parent = descend(parent, path[i]))) return null;
762 * Descends one level to the specified child of the parent
763 * <code>Accessible</code> "node".
765 * @param parent the node with children
766 * @param childNum the index of the child of <code>parent</code> to return
767 * @return the <code>childNum</code> child of <code>parent</code>
768 * or <code>null</code> if the child is not found.
770 private Accessible descend(Accessible parent, int childNum) {
771 if (parent == null) return null;
772 int children = parent.getAccessibleContext().getAccessibleChildrenCount();
773 if (childNum >= children) {
774 if (dtxt!=null) dtxt.println("DESCEND "+childNum+" > "
775 +children+" NOT FOUND");
778 Accessible child = parent.getAccessibleContext()
779 .getAccessibleChild(childNum);
780 if (dtxt!=null) dtxt.println("DESCEND "+childNum+" "
781 +child.getClass().getName()+" OK");
786 * Descends one level to the child which has the specified class.
788 * @param parent the node with children
789 * @param classname the name of the class, as a string
790 * @return the child or <code>null</code> if the child is not found.
792 private Accessible descendByClass(Accessible parent, String classname) {
793 if (parent == null) return null;
794 AccessibleContext ac = parent.getAccessibleContext();
795 int children = ac.getAccessibleChildrenCount();
796 for (int i=0; i<children; i++) {
797 Accessible child = ac.getAccessibleChild(i);
798 if (child.getClass().getName() == classname) {
799 if (dtxt!=null) dtxt.println("DESCEND CLASS "+classname+" OK");
803 if (dtxt!=null) dtxt.println("DESCEND CLASS "+classname+" NOT FOUND");
807 public static void main(String[] args) {
808 new MarketUploader();
812 * Returns true if the "Display:" menu on the commodities
813 * interface in YPP is set to "All"
815 * @return <code>true</code> if all commodities are displayed,
816 * otherwise <code>false</code>
818 private boolean isDisplayAll() {
819 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
820 if(!(button instanceof JButton)) {
821 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
823 String display = button.getAccessibleContext().getAccessibleName();
824 if(!display.equals("All")) {
831 * Gets the list of commodities and their associated commodity ids.
833 * @return a map where the key is the commodity and the value is
836 private HashMap<String,Integer> getCommodMap() {
837 if(commodMap != null) {
840 HashMap<String,Integer> map = new HashMap<String,Integer>();
843 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
845 new BufferedReader(new InputStreamReader(host.openStream()));
846 StringBuilder sb = new StringBuilder();
848 while((str = br.readLine()) != null) {
852 debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
853 int first = sb.indexOf("<pre>") + 5;
854 int last = sb.indexOf("</body>");
855 xml = sb.substring(first,last);
856 Reader reader = new CharArrayReader(xml.toCharArray());
857 Document d = DocumentBuilderFactory.newInstance()
858 .newDocumentBuilder().parse(new InputSource(reader));
859 NodeList maps = d.getElementsByTagName("CommodMap");
860 for(int i=0;i<maps.getLength();i++) {
861 NodeList content = maps.item(i).getChildNodes();
862 Integer num = Integer.parseInt(content.item(1).getTextContent());
863 map.put(content.item(0).getTextContent(),num);
865 } catch(Exception e) {
867 error("Unable to load Commodity list from server!");
875 * Given the list of offers, this method will find all the unique
876 * stall names and return them in a <code>LinkedHashMap</code>
877 * where the key is the stall name and the value is the generated
878 * stall id (position in the list). <p> The reason this method
879 * returns a LinkedHashMap instead of a simple HashMap is the
880 * need for iterating over the stall names in insertion order for
881 * output to the server.
883 * @param offers the list of records from the commodity buy/sell interface
884 * @return an iterable ordered map of the stall names and
885 * generated stall ids
887 private LinkedHashMap<String,Integer> getStallMap
888 (ArrayList<ArrayList<String>> offers) {
890 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
891 for(ArrayList<String> offer : offers) {
892 String shop = offer.get(1);
893 if(!map.containsKey(shop)) {
902 * Gets a sorted list of Buys and Sells from the list of
903 * records. <code>buys</code> and <code>sells</code> should be
904 * pre-initialized and passed into the method to receive the
905 * data. Returns a 2-length int array with the number of buys
908 * @param offers the data found from the market table in-game
909 * @param buys an empty initialized <code>TreeSet<Offer></code> to
910 * hold the Buy offers.
911 * @param sells an empty initialized <code>TreeSet<Offer></code> to
912 * hold the Sell offers.
913 * @param stalls the map of stalls to their ids
914 * @param commodMap the map of commodities to their ids
915 * @return a 2-length int[] array containing the number of buys
916 * and sells, respectively
918 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers,
920 TreeSet<Offer> sells,
921 LinkedHashMap<String,Integer> stalls,
922 HashMap<String,Integer> commodMap) {
923 int[] buySellCount = new int[2];
924 for(ArrayList<String> offer : offers) {
926 if(offer.get(2) != null) {
927 buys.add(new Buy(offer,stalls,commodMap));
930 if(offer.get(4) != null) {
931 sells.add(new Sell(offer,stalls,commodMap));
934 } catch(IllegalArgumentException e) {
935 unknownPCTBcommods++;
936 if (dtxt!=null) dtxt.println("Error: Unsupported Commodity \""
937 + offer.get(0) + "\"");
940 if (buySellCount[0]==0 && buySellCount[1]==0) {
941 error("No (valid) offers for PCTB?!");
942 throw new IllegalArgumentException();
948 * Prepares the list of stalls for writing to the output stream.
949 * The <code>String</code> returned by this method is ready to be
950 * written directly to the stream. <p> All shoppe names are left
951 * as they are. Stall names are abbreviated just before the
952 * apostrophe in the possessive, with an "^" and a letter
953 * matching the stall's type appended. Example: "Burninator's
954 * Ironworking Stall" would become "Burninator^I".
956 * @param stallMap the map of stalls and stall ids in an iterable order
957 * @return a <code>String</code> containing the list of stalls in
958 * format ready to be written to the output stream.
960 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
961 // set up some mapping
962 HashMap<String,String> types = new HashMap<String,String>();
963 types.put("Apothecary Stall", "A");
964 types.put("Distilling Stall", "D");
965 types.put("Furnishing Stall", "F");
966 types.put("Ironworking Stall", "I");
967 types.put("Shipbuilding Stall", "S");
968 types.put("Tailoring Stall", "T");
969 types.put("Weaving Stall", "W");
971 StringBuilder sb = new StringBuilder();
972 for(String name : stallMap.keySet()) {
973 int index = name.indexOf("'s");
974 String finalName = name;
977 finalName = name.substring(0,index);
978 if(index + 2 < name.length()) {
979 String end = name.substring(index+2,name.length()).trim();
980 type = types.get(end);
984 sb.append(name+"\n");
986 sb.append(finalName+"^"+type+"\n");
989 return sb.toString();
993 * Writes a list of offers in correct format to the output stream.
995 * The format is thus: (all numbers are 2-byte integers in
996 * little-endian format) (number of offers of this type, aka
997 * buy/sell) (commodity ID) (number of offers for this commodity)
998 * [shopID price qty][shopID price qty]...
1000 * @param out the output stream to write the data to
1001 * @param offers the offers to write
1003 private void writeOffers(OutputStream out, TreeSet<Offer> offers)
1004 throws IOException {
1005 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
1006 if(offers.size() == 0) {
1007 // nothing to write, and "0" has already been written
1010 int commodity = offers.first().commodity;
1012 for(Offer offer : offers) {
1013 if(commodity != offer.commodity) {
1015 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1017 commodity = offer.commodity;
1020 writeLEShort(offer.shoppe,buffer); // stall index
1021 writeLEShort(offer.price,buffer); // buy price
1022 writeLEShort(offer.quantity,buffer); // buy qty
1025 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
1029 * Writes the buffered data to the output strea for one commodity.
1031 * @param out the stream to write to
1032 * @param buffer the buffered data to write
1033 * @param commodity the commmodity id to write before the buffered data
1034 * @param count the number of offers for this commodity to write
1037 private void writeBufferedOffers(OutputStream out, byte[] buffer,
1038 int commodity, int count)
1039 throws IOException {
1040 writeLEShort(commodity,out); // commod index
1041 writeLEShort(count,out); // offer count
1042 out.write(buffer); // the buffered offers
1046 * Writes the buy and sell offers to the outputstream by calling
1049 * @param buys list of Buy offers to write
1050 * @param sells list of Sell offers to write
1051 * @param offerCount 2-length int array containing the number of
1052 * buys and sells to write out
1053 * @param out the stream to write to
1055 private void writeBuySellOffers(TreeSet<Offer> buys,
1056 TreeSet<Offer> sells,
1057 int[] offerCount, OutputStream out)
1058 throws IOException {
1060 writeLEShort(offerCount[0],out);
1061 writeOffers(out,buys);
1063 writeLEShort(offerCount[1],out);
1064 writeOffers(out,sells);
1067 private String readstreamstring(InputStream in) throws IOException {
1068 StringBuilder sb = new StringBuilder();
1069 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1071 while((str = br.readLine()) != null) {
1072 sb.append(str+"\n");
1074 return sb.toString();
1078 * Sends the data to the server via multipart-formdata POST,
1079 * with the gzipped data as a file upload.
1081 * @param file an InputStream open to the gzipped data we want to send
1083 private InputStream sendInitialData(InputStream file) throws IOException {
1084 ClientHttpRequest http =
1085 new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
1086 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
1088 String err = readstreamstring(http.resultstream());
1089 error("Error sending initial data:\n"+err);
1092 return http.resultstream();
1096 * Utility method to write a 2-byte int in little-endian form to
1099 * @param num an integer to write
1100 * @param out stream to write to
1102 private void writeLEShort(int num, OutputStream out) throws IOException {
1103 out.write(num & 0xFF);
1104 out.write((num >>> 8) & 0xFF);
1108 * Reads the response from the server, and selects the correct parameters
1109 * which are sent in a GET request to the server asking it to confirm
1110 * the upload and accept the data into the database. Notably, the island id
1111 * and ocean id are determined, while other parameter such as the filename
1112 * are determined from the hidden form fields.
1114 * @param in stream of data from the server to read
1116 private boolean finishUpload(InputStream in) throws IOException {
1117 String html = readstreamstring(in);
1118 debug_write_stringdata("pctb-initial.html", html);
1121 Pattern params = Pattern.compile
1122 ("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />"+
1123 ".+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />"+
1124 ".+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
1125 m = params.matcher(html);
1127 error_html("The PCTB server returned unusual data."+
1128 " Maybe you're using an old version of the uploader?",
1132 String forceReload = m.group(1);
1133 String filename = m.group(2);
1135 Pattern oceanNumPat =
1136 Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1137 m = oceanNumPat.matcher(html);
1139 error_html("Unable to find the ocean in the server's list of oceans!",
1143 String oceanNum = m.group(1);
1145 Pattern oceanIslandNum =
1146 Pattern.compile("islands\\[" + oceanNum
1147 + "\\]\\[\\d+\\]=new Option\\(\"" + islandName
1149 m = oceanIslandNum.matcher(html);
1151 error_html("This does not seem to be a valid island! Unable to upload.",
1155 String islandNum = m.group(1);
1157 URL get = new URL(PCTB_HOST_URL +
1158 "upload.php?action=setisland&ocean=" + oceanNum
1159 + "&island=" + islandNum
1160 + "&forcereload=" + forceReload
1161 + "&filename=" + filename);
1162 String complete = readstreamstring(get.openStream());
1163 debug_write_stringdata("pctb-final.html", complete);
1164 Pattern done = Pattern.compile
1165 ("Your data has been integrated into the database. Thank you!");
1166 m = done.matcher(complete);
1170 error_html("Something was wrong with the final upload parameters!",
1176 private InputStream post_for_yarrg(ClientHttpRequest http)
1177 throws IOException {
1179 String err = readstreamstring(http.resultstream());
1180 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1183 return http.resultstream();
1186 private String getYarrgTimestamp() throws IOException {
1187 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1188 http.setParameter("clientname", YARRG_CLIENTNAME);
1189 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1190 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1191 http.setParameter("requesttimestamp", "y");
1192 InputStream in = post_for_yarrg(http);
1193 if (in == null) return null;
1194 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1195 String tsresult = br.readLine();
1196 return tsresult.substring(3, tsresult.length()-1);
1199 private boolean runYarrg(String timestamp, String ocean, String island,
1200 String yarrgdata) throws IOException {
1201 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1202 BufferedOutputStream bufos =
1203 new BufferedOutputStream(new GZIPOutputStream(bos));
1204 bufos.write(yarrgdata.getBytes() );
1206 byte[] compressed = bos.toByteArray();
1207 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1208 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1210 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1211 http.setParameter("clientname", YARRG_CLIENTNAME);
1212 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1213 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1214 http.setParameter("timestamp", timestamp);
1215 http.setParameter("ocean", ocean);
1216 http.setParameter("island", island);
1217 http.setParameter("data", "deduped.tsv.gz", file,
1218 "application/octet-stream");
1219 InputStream in = post_for_yarrg(http);
1220 if (in == null) return false;
1221 String output = readstreamstring(in);
1222 if (!output.startsWith("OK")) {
1223 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1226 debug_write_stringdata("yarrg-result.txt", output);
1230 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1231 // if (dtxt!=null) dtxt.println("ARBITRAGE?");
1233 SortedSet<int[]> buys = arb_bs.get(0);
1234 SortedSet<int[]> sells = arb_bs.get(1);
1238 // NB "sell" means they sell, ie we buy
1239 sell = sells.last();
1241 } catch (NoSuchElementException e) {
1245 int unitprofit = buy[0] - sell[0];
1246 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1247 // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]
1248 // +" buy @"+buy[0]+" x"+buy[1]
1249 // +" => x"+count+" @"+unitprofit);
1251 if (unitprofit <= 0)
1254 profit += count * unitprofit;
1257 if (buy[1]==0) buys.remove(buy);
1258 if (sell[1]==0) sells.remove(sell);
1260 // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
1264 private class arbitrageOfferComparator implements Comparator {
1265 public int compare(Object o1, Object o2) {
1266 int p1 = ((int[])o1)[0];
1267 int p2 = ((int[])o2)[0];
1272 private @SuppressWarnings("unchecked")
1273 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1275 ArrayList<SortedSet<int[]>> arb_bs = null;
1276 String lastcommod = null;
1277 Comparator compar = new arbitrageOfferComparator();
1279 for (ArrayList<String> row : data) {
1280 String thiscommod = row.get(0);
1281 // if (dtxt!=null) dtxt.println("ROW "+row.toString());
1282 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1283 if (lastcommod != null)
1284 arbitrage += calculateArbitrageCommodity(arb_bs);
1285 // if (dtxt!=null) dtxt.println("ROW rdy");
1286 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1287 arb_bs.add(0, new TreeSet<int[]>(compar));
1288 arb_bs.add(1, new TreeSet<int[]>(compar));
1289 // if (dtxt!=null) dtxt.println("ROW init");
1290 lastcommod = thiscommod;
1292 for (int bs = 0; bs < 2; bs++) {
1293 String pricestr = row.get(bs*2 + 2);
1294 if (pricestr == null)
1296 int[] entry = new int[2];
1297 // if (dtxt!=null) dtxt.println("ROW BS "+bs);
1298 entry[0] = parseQty(pricestr);
1299 entry[1] = parseQty(row.get(bs*2 + 3));
1300 arb_bs.get(bs).add(entry);
1303 arbitrage += calculateArbitrageCommodity(arb_bs);
1304 if (arbitrage != 0) {
1305 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage
1308 arbitrageResult.setText("no arbitrage");