1 package com.tedpearson.ypp.market;
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 implements TopLevelWindowListener, GUIInitializedListener {
38 private JFrame frame = null;
39 private Window window = null;
40 private JButton findMarket = null;
41 private JLabel resultSummary = null;
42 private JLabel arbitrageResult = null;
43 private long startTime = 0;
45 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
46 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
47 private String PCTB_HOST_URL;
49 // Yarrg protocol parameters
50 private final static String YARRG_CLIENTNAME = "jpctb greenend";
51 private final static String YARRG_CLIENTVERSION =
52 com.tedpearson.ypp.market.Version.version;
53 private final static String YARRG_CLIENTFIXES = "bug-094";
54 private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
55 private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
56 private String YARRG_URL;
58 private boolean uploadToYarrg;
59 private boolean uploadToPCTB;
60 private boolean showArbitrage;
62 private String islandName = null;
63 private String oceanName = null;
64 private java.util.concurrent.CountDownLatch latch = null;
66 private AccessibleContext sidePanel;
67 private HashMap<String,Integer> commodMap;
68 public PrintStream dtxt = null;
70 private PropertyChangeListener changeListener = new PropertyChangeListener() {
71 public void propertyChange(PropertyChangeEvent e) {
72 if(e.getNewValue() != null &&
73 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
74 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
75 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
76 int index = text.indexOf(":");
77 String name = text.substring(0,index);
79 // if (dtxt!=null) dtxt.println(islandName);
80 sidePanel.removePropertyChangeListener(this);
86 private int parseQty(String str) {
87 if (str.equals(">1000")) {
90 return Integer.parseInt(str);
94 private void progresslog(String s) {
95 if (dtxt == null) return;
96 long now = new Date().getTime();
97 dtxt.println("progress "+(now - startTime)+"ms "+s);
100 private void debug_write_stringdata(String what, String data) throws FileNotFoundException,IOException {
101 if (dtxt==null) return;
102 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
107 private void progressNote(ProgressMonitor pm, String s) {
109 if (arbitrageResult != null)
110 arb = arbitrageResult.getText();
111 if (arb != null && arb.length() != 0)
112 s = "<html>" + arb + "<br>" + s;
117 * An abstract market offer, entailing a commodity being bought or sold by
118 * a shoppe, for a certain price in a certain quantity. Not instantiable.
123 abstract class Offer {
124 public int commodity, price, quantity, shoppe;
126 * Create an offer from <code>record</code>, determining the shoppe Id from
127 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
128 * <code>priceIndex</code> should be the index of the price in the record
129 * (the quantity will be <code>priceIndex + 1</code>).
131 * @param record the record with data to create the offer from
132 * @param stallMap a map containing the ids of the various stalls
133 * @param commodMap a map containing the ids of the various commodities
134 * @param priceIndex the index of the price in the record
136 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
138 Integer commodId = commodMap.get(record.get(0));
139 if(commodId == null) {
140 throw new IllegalArgumentException();
142 commodity = commodId.intValue();
143 price = Integer.parseInt(record.get(priceIndex));
144 String qty = record.get(priceIndex+1);
145 quantity = parseQty(qty);
146 shoppe = stallMap.get(record.get(1)).intValue();
150 * Returns a human-readable version of this offer, useful for debugging
152 * @return human-readable offer
154 public String toString() {
155 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
160 * An offer from a shoppe or stall to buy a certain quantity of a commodity
161 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
162 * then by buy price descending, and finally by stall id ascending.
164 class Buy extends Offer implements Comparable<Buy> {
166 * Creates a new <code>Buy</code> offer from the given <code>record</code>
167 * using the other parameters to determine stall id and commodity id of the offer.
169 * @param record the record with data to create the offer from
170 * @param stallMap a map containing the ids of the various stalls
171 * @param commodMap a map containing the ids of the various commodities
173 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
174 super(record,stallMap,commodMap,2);
178 * Sorts by commodity index ascending, then price descending, then stall id ascending.
180 public int compareTo(Buy buy) {
181 // organize by: commodity index, price, stall index
182 if(commodity == buy.commodity) {
183 // organize by price, then by stall index
184 if(price == buy.price) {
185 // organize by stall index
186 return shoppe>buy.shoppe ? 1 : -1;
187 } else if(price > buy.price) {
192 } else if(commodity > buy.commodity) {
201 * An offer from a shoppe or stall to sell a certain quantity of a commodity
202 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
203 * then by sell price ascending, and finally by stall id ascending.
205 class Sell extends Offer implements Comparable<Sell> {
207 * Creates a new <code>Sell</code> offer from the given <code>record</code>
208 * using the other parameters to determine stall id and commodity id of the offer.
210 * @param record the record with data to create the offer from
211 * @param stallMap a map containing the ids of the various stalls
212 * @param commodMap a map containing the ids of the various commodities
214 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
215 super(record,stallMap,commodMap,4);
219 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
221 public int compareTo(Sell sell) {
222 // organize by: commodity index, price, stall index
223 if(commodity == sell.commodity) {
224 // organize by price, then by stall index
225 if(price == sell.price) {
226 // organize by stall index
227 return shoppe>sell.shoppe ? 1 : -1;
228 } else if(price > sell.price) {
233 } else if(commodity > sell.commodity) {
242 * Entry point. Read our preferences.
244 public MarketUploader() {
245 Preferences prefs = Preferences.userNodeForPackage(getClass());
247 if (prefs.getBoolean("writeDebugFiles", false)) {
249 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
250 } catch (java.io.FileNotFoundException e) {
251 System.err.println("JARRG: Error opening debug log: "+e);
255 if (prefs.getBoolean("useLiveServers", false)) {
256 YARRG_URL = YARRG_LIVE_URL;
257 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
259 YARRG_URL = YARRG_TEST_URL;
260 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
263 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
264 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
265 showArbitrage=prefs.getBoolean("showArbitrage", true);
267 EventQueueMonitor.addTopLevelWindowListener(this);
268 if (EventQueueMonitor.isGUIInitialized()) {
271 EventQueueMonitor.addGUIInitializedListener(this);
276 * Set up the GUI, with its window and one-button
277 * interface. Only initialize if we're running alongside
278 * a Window named "Puzzle Pirates" though.
280 private void createGUI() {
281 if (frame != null && window != null) {
282 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
285 frame = new JFrame("Jarrg Uploader");
286 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
287 GridLayout layout = new GridLayout(2,1);
288 frame.getContentPane().setLayout(layout);
289 //frame.setPreferredSize(new Dimension(200, 60));
291 findMarket = new JButton("Upload Market Data");
292 findMarket.addActionListener(new ActionListener() {
293 public void actionPerformed(ActionEvent e) {
294 findMarket.setEnabled(false);
297 startTime = new Date().getTime();
298 resultSummary.setText("");
299 arbitrageResult.setText("");
302 } catch(Exception e) {
305 resultSummary.setText("failed");
307 if(sidePanel != null) {
308 // remove it if it's still attached
309 sidePanel.removePropertyChangeListener(changeListener);
312 findMarket.setEnabled(true);
317 frame.add(findMarket);
319 resultSummary = new JLabel("ready");
320 frame.add(resultSummary);
322 arbitrageResult = new JLabel("");
325 layout.setRows(layout.getRows() + 1);
326 frame.add(arbitrageResult);
333 * Finds the island name from the /who tab, sets global islandName variable
335 private void getIsland() {
337 // If the league tracker is there, we can skip the faff
338 // and ask for its tooltip, since we're on a boat
340 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
342 islandName = ((JLabel)leagueTracker).getToolTipText();
343 } catch (NullPointerException e) {
344 // evidently we're actually on an island
347 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
348 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
349 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
350 if(!"com.threerings.piracy.client.AttentionListPanel".
351 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
352 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
354 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
356 sidePanel.addPropertyChangeListener(changeListener);
357 latch = new java.util.concurrent.CountDownLatch(1);
358 // make the Players Online ("/who") panel appear
359 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
360 chat.setTextContents("/w");
361 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
362 for(int i=0;i<c;i++) {
363 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
364 chatArea.getAccessibleAction().doAccessibleAction(i);
371 * Find the ocean name from the window title, and set global oceanName variable
373 private void getOcean() {
375 AccessibleContext topwindow = window.getAccessibleContext();
376 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
381 * Shows a dialog with the error <code>msg</code>.
383 * @param msg a String describing the error that occured.
385 private void error(String msg) {
386 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
389 private void error_html(String msg, String html) {
390 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
391 Matcher m = body.matcher(html);
394 Pattern fixup = Pattern.compile("<(\\w+) */>");;
395 m = fixup.matcher(html);
396 html = m.replaceAll("<$1>");
397 m = Pattern.compile("[\\r\\n]+").matcher(html);
398 html = m.replaceAll(" ");
400 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
401 if (dtxt!=null) dtxt.println("###" + whole_msg + "###");
403 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
407 * Run the data collection process, and upload the results. This is the method
408 * that calls most of the other worker methods for the process. If an error occurs,
409 * the method will call the error method and return early, freeing up the button
410 * to be clicked again.
412 * @exception Exception if an error we didn't expect occured
414 private class YarrgTimestampFetcher extends Thread {
415 public String ts = null;
418 ts = getYarrgTimestamp();
419 progresslog("(async) yarrg timestamp ready.");
420 } catch(Exception e) {
421 error("Error getting YARRG timestamp: "+e);
426 private void runUpload() throws Exception {
427 progresslog("starting");
429 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
430 pm.setMillisToDecideToPopup(0);
431 pm.setMillisToPopup(0);
432 boolean doneyarrg = false, donepctb = false;
433 YarrgTimestampFetcher yarrgts_thread = null;
436 progresslog("(async) yarrg timestamp...");
437 yarrgts_thread = new YarrgTimestampFetcher();
438 yarrgts_thread.start();
441 AccessibleTable accesstable = findMarketTable();
442 if(accesstable == null) {
443 error("Market table not found! Please open the Buy/Sell Commodities interface.");
446 if(accesstable.getAccessibleRowCount() == 0) {
447 error("No data found, please wait for the table to have data first!");
450 if(!isDisplayAll()) {
451 error("Please select \"All\" from the Display: popup menu.");
455 progresslog("(async) getisland...");
457 progresslog("getocean...");
459 progresslog("getocean done");
462 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
464 progresslog("(async) getisland done");
466 String yarrgts = null;
467 if (yarrgts_thread != null) {
468 progresslog("(async) yarrg timestamp join...");
469 yarrgts_thread.join();
470 progresslog("(async) yarrg timestamp joined.");
471 yarrgts = yarrgts_thread.ts;
474 if (islandName == null) {
475 error("Could not find island name in YPP user interface.");
479 progresslog("table check...");
481 String headings_expected[] = new String[]
482 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
483 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
484 if (headers.size() != 1) {
485 error("Table headings not one row! " + headers.toString());
488 if (headers.get(0).size() != 6) {
489 error("Table headings not six columns! " + headers.toString());
492 for (int col=0; col<headings_expected.length; col++) {
493 String expd = headings_expected[col];
494 String got = headers.get(0).get(col);
495 if (expd.compareTo(got) != 0) {
496 error("Table heading for column "+col
497 +" is not \""+expd+"\" but \""+got+"\".\n\n"
498 +"Please do not reorder the table when using this tool.");
503 progresslog("table read...");
505 ArrayList<ArrayList<String>> data = getData(accesstable);
508 progresslog("arbitrage...");
509 calculateArbitrage(data);
510 progresslog("arbitrage done.");
513 if (uploadToYarrg && yarrgts != null) {
514 progresslog("yarrg prepare...");
515 progressNote(pm, "Yarrg: Preparing data");
518 StringBuilder yarrgsb = new StringBuilder();
519 String yarrgdata; // string containing what we'll feed to yarrg
521 for (ArrayList<String> row : data) {
522 if (row.size() > 6) {
525 for (String rowitem : row) {
526 yarrgsb.append(rowitem != null ? rowitem : "");
527 yarrgsb.append("\t");
529 yarrgsb.setLength(yarrgsb.length()-1); // chop
530 yarrgsb.append("\n");
533 yarrgdata = yarrgsb.toString();
535 progressNote(pm, "Yarrg: Uploading");
536 progresslog("yarrg upload...");
538 debug_write_stringdata("yarrg-deduped.tsv", yarrgdata);
540 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
541 progresslog("yarrg done.");
545 progresslog("pctb prepare...");
546 progressNote(pm, "PCTB: Getting stall names");
548 if(pm.isCanceled()) {
551 TreeSet<Offer> buys = new TreeSet<Offer>();
552 TreeSet<Offer> sells = new TreeSet<Offer>();
553 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
555 progressNote(pm, "PCTB: Sorting offers");
556 if(pm.isCanceled()) {
561 progresslog("pctb commodmap...");
562 HashMap<String,Integer> commodMap = getCommodMap();
563 if(commodMap == null) {
566 progresslog("pctb commodmap done.");
567 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
568 // if (dtxt!=null) dtxt.println(sells);
569 // if (dtxt!=null) dtxt.println("\n\n\n"+buys);
571 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
573 progressNote(pm, "PCTB: Sending data");
574 if(pm.isCanceled()) {
577 GZIPOutputStream out = new GZIPOutputStream(outStream);
578 DataOutputStream dos = new DataOutputStream(out);
579 dos.writeBytes("005y\n");
580 dos.writeBytes(stallMap.size()+"\n");
581 dos.writeBytes(getAbbrevStallList(stallMap));
582 writeBuySellOffers(buys,sells,offerCount,out);
584 progresslog("pctb send...");
586 byte[] ba = outStream.toByteArray();
588 FileOutputStream dbgdata = new FileOutputStream(new File("jarrg-debug-pctb-marketdata.gz"));
593 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
594 progresslog("pctb sent.");
595 if (in == null) return;
597 if(pm.isCanceled()) {
600 progressNote(pm, "PCTB: Waiting ...");
601 progresslog("pctb finish...");
602 donepctb = finishUpload(in);
603 progresslog("pctb done.");
607 if ((uploadToPCTB && !donepctb) ||
608 (uploadToYarrg && !doneyarrg)) {
609 resultSummary.setText("trouble");
610 } else if (donepctb || doneyarrg) {
611 resultSummary.setText("Done " + islandName);
613 resultSummary.setText("uploaded nowhere!");
615 progresslog("done.");
619 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
621 * @param table the <code>AccessibleTable</code> containing the market data
622 * @return an array of record arrays, each representing a row of the table
624 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
625 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
626 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
627 ArrayList<String> row = new ArrayList<String>();
628 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
629 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
637 * @return the table containing market data if it exists, otherwise <code>null</code>
639 public AccessibleTable findMarketTable() {
640 Accessible node1 = window;
641 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
642 // 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})
643 // if (dtxt!=null) dtxt.println(node);
644 if (!(node instanceof JTable)) {
645 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
647 if (!(node instanceof JTable)) return null;
648 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
649 // if (dtxt!=null) dtxt.println(table);
654 * Utility method to descend through several levels of Accessible children
657 * @param parent the node on which to start the descent
658 * @param path an array of ints, each int being the index of the next
659 * accessible child to descend.
660 * @return the <code>Accessible</code> reached by following the descent path,
661 * or <code>null</code> if the desired path was invalid.
663 private Accessible descendNodes(Accessible parent, int[] path) {
664 for(int i=0;i<path.length;i++) {
665 if (null == (parent = descend(parent, path[i]))) return null;
666 // if (dtxt!=null) dtxt.println(parent.getClass());
672 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
674 * @param parent the node with children
675 * @param childNum the index of the child of <code>parent</code> to return
676 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
677 * if the child is not found.
679 private Accessible descend(Accessible parent, int childNum) {
680 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
681 return parent.getAccessibleContext().getAccessibleChild(childNum);
684 public static void main(String[] args) {
685 new MarketUploader();
689 * Set the global window variable after the YPP window is created,
690 * remove the top level window listener, and start the GUI
692 public void topLevelWindowCreated(Window w) {
694 EventQueueMonitor.removeTopLevelWindowListener(this);
699 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
701 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
703 private boolean isDisplayAll() {
704 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
705 if(!(button instanceof JButton)) {
706 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
708 String display = button.getAccessibleContext().getAccessibleName();
709 if(!display.equals("All")) {
715 public void topLevelWindowDestroyed(Window w) {}
717 public void guiInitialized() {
722 * Gets the list of commodities and their associated commodity ids.
724 * @return a map where the key is the commodity and the value is the commodity id.
726 private HashMap<String,Integer> getCommodMap() {
727 if(commodMap != null) {
730 HashMap<String,Integer> map = new HashMap<String,Integer>();
733 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
734 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
735 StringBuilder sb = new StringBuilder();
737 while((str = br.readLine()) != null) {
740 if (dtxt != null) debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
741 int first = sb.indexOf("<pre>") + 5;
742 int last = sb.indexOf("</body>");
743 xml = sb.substring(first,last);
744 Reader reader = new CharArrayReader(xml.toCharArray());
745 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
746 NodeList maps = d.getElementsByTagName("CommodMap");
747 for(int i=0;i<maps.getLength();i++) {
748 NodeList content = maps.item(i).getChildNodes();
749 Integer num = Integer.parseInt(content.item(1).getTextContent());
750 map.put(content.item(0).getTextContent(),num);
752 } catch(Exception e) {
754 error("Unable to load Commodity list from server!");
762 * Given the list of offers, this method will find all the unique stall names
763 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
764 * and the value is the generated stall id (position in the list).
766 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
767 * for iterating over the stall names in insertion order for output to the server.
769 * @param offers the list of records from the commodity buy/sell interface
770 * @return an iterable ordered map of the stall names and generated stall ids
772 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
774 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
775 for(ArrayList<String> offer : offers) {
776 String shop = offer.get(1);
777 if(!map.containsKey(shop)) {
786 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
787 * should be pre-initialized and passed into the method to receive the data.
788 * Returns a 2-length int array with the number of buys and sells found.
790 * @param offers the data found from the market table in-game
791 * @param buys an empty initialized <code>TreeSet<Offer></code> to
792 * hold the Buy offers.
793 * @param sells an empty initialized <code>TreeSet<Offer></code> to
794 * hold the Sell offers.
795 * @param stalls the map of stalls to their ids
796 * @param commodMap the map of commodities to their ids
797 * @return a 2-length int[] array containing the number of buys and sells, respectively
799 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
800 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
801 int[] buySellCount = new int[2];
802 for(ArrayList<String> offer : offers) {
804 if(offer.get(2) != null) {
805 buys.add(new Buy(offer,stalls,commodMap));
808 if(offer.get(4) != null) {
809 sells.add(new Sell(offer,stalls,commodMap));
812 } catch(IllegalArgumentException e) {
813 if (dtxt!=null) dtxt.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
816 if (buySellCount[0]==0 && buySellCount[1]==0) {
817 error("No (valid) offers for PCTB?!");
818 throw new IllegalArgumentException();
824 * Prepares the list of stalls for writing to the output stream.
825 * The <code>String</code> returned by this method is ready to be written
826 * directly to the stream.
828 * All shoppe names are left as they are. Stall names are abbreviated just before the
829 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
830 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
832 * @param stallMap the map of stalls and stall ids in an iterable order
833 * @return a <code>String</code> containing the list of stalls in format ready
834 * to be written to the output stream.
836 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
837 // set up some mapping
838 HashMap<String,String> types = new HashMap<String,String>();
839 types.put("Apothecary Stall", "A");
840 types.put("Distilling Stall", "D");
841 types.put("Furnishing Stall", "F");
842 types.put("Ironworking Stall", "I");
843 types.put("Shipbuilding Stall", "S");
844 types.put("Tailoring Stall", "T");
845 types.put("Weaving Stall", "W");
847 StringBuilder sb = new StringBuilder();
848 for(String name : stallMap.keySet()) {
849 int index = name.indexOf("'s");
850 String finalName = name;
853 finalName = name.substring(0,index);
854 if(index + 2 < name.length()) {
855 String end = name.substring(index+2,name.length()).trim();
856 type = types.get(end);
860 sb.append(name+"\n");
862 sb.append(finalName+"^"+type+"\n");
865 return sb.toString();
869 * Writes a list of offers in correct format to the output stream.
871 * The format is thus: (all numbers are 2-byte integers in little-endian format)
872 * (number of offers of this type, aka buy/sell)
873 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
875 * @param out the output stream to write the data to
876 * @param offers the offers to write
878 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
879 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
880 if(offers.size() == 0) {
881 // nothing to write, and "0" has already been written
884 int commodity = offers.first().commodity;
886 for(Offer offer : offers) {
887 if(commodity != offer.commodity) {
889 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
891 commodity = offer.commodity;
894 writeLEShort(offer.shoppe,buffer); // stall index
895 writeLEShort(offer.price,buffer); // buy price
896 writeLEShort(offer.quantity,buffer); // buy qty
899 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
903 * Writes the buffered data to the output strea for one commodity.
905 * @param out the stream to write to
906 * @param buffer the buffered data to write
907 * @param commodity the commmodity id to write before the buffered data
908 * @param count the number of offers for this commodity to write before the data
910 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
911 writeLEShort(commodity,out); // commod index
912 writeLEShort(count,out); // offer count
913 out.write(buffer); // the buffered offers
917 * Writes the buy and sell offers to the outputstream by calling other methods.
919 * @param buys list of Buy offers to write
920 * @param sells list of Sell offers to write
921 * @param offerCount 2-length int array containing the number of buys and sells to write out
922 * @param out the stream to write to
924 private void writeBuySellOffers(TreeSet<Offer> buys,
925 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
927 writeLEShort(offerCount[0],out);
928 writeOffers(out,buys);
930 writeLEShort(offerCount[1],out);
931 writeOffers(out,sells);
934 private String readstreamstring(InputStream in) throws IOException {
935 StringBuilder sb = new StringBuilder();
936 BufferedReader br = new BufferedReader(new InputStreamReader(in));
938 while((str = br.readLine()) != null) {
941 return sb.toString();
945 * Sends the data to the server via multipart-formdata POST,
946 * with the gzipped data as a file upload.
948 * @param file an InputStream open to the gzipped data we want to send
950 private InputStream sendInitialData(InputStream file) throws IOException {
951 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
952 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
954 String err = readstreamstring(http.resultstream());
955 error("Error sending initial data:\n"+err);
958 return http.resultstream();
962 * Utility method to write a 2-byte int in little-endian form to an output stream.
964 * @param num an integer to write
965 * @param out stream to write to
967 private void writeLEShort(int num, OutputStream out) throws IOException {
968 out.write(num & 0xFF);
969 out.write((num >>> 8) & 0xFF);
973 * Reads the response from the server, and selects the correct parameters
974 * which are sent in a GET request to the server asking it to confirm
975 * the upload and accept the data into the database. Notably, the island id
976 * and ocean id are determined, while other parameter such as the filename
977 * are determined from the hidden form fields.
979 * @param in stream of data from the server to read
981 private boolean finishUpload(InputStream in) throws IOException {
982 String html = readstreamstring(in);
983 debug_write_stringdata("pctb-initial.html", html);
986 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
987 m = params.matcher(html);
989 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
993 String forceReload = m.group(1);
994 String filename = m.group(2);
996 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
997 m = oceanNumPat.matcher(html);
999 error_html("Unable to find the ocean in the server's list of oceans!", html);
1002 String oceanNum = m.group(1);
1004 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
1005 m = oceanIslandNum.matcher(html);
1007 error_html("This does not seem to be a valid island! Unable to upload.", html);
1010 String islandNum = m.group(1);
1012 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
1013 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
1014 String complete = readstreamstring(get.openStream());
1015 debug_write_stringdata("pctb-final.html", complete);
1016 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
1017 m = done.matcher(complete);
1021 error_html("Something was wrong with the final upload parameters!", complete);
1026 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
1028 String err = readstreamstring(http.resultstream());
1029 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1032 return http.resultstream();
1035 private String getYarrgTimestamp() throws IOException {
1036 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1037 http.setParameter("clientname", YARRG_CLIENTNAME);
1038 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1039 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1040 http.setParameter("requesttimestamp", "y");
1041 InputStream in = post_for_yarrg(http);
1042 if (in == null) return null;
1043 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1044 String tsresult = br.readLine();
1045 return tsresult.substring(3, tsresult.length()-1);
1048 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
1049 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1050 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
1051 bufos.write(yarrgdata.getBytes() );
1053 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
1055 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1056 http.setParameter("clientname", YARRG_CLIENTNAME);
1057 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1058 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1059 http.setParameter("timestamp", timestamp);
1060 http.setParameter("ocean", ocean);
1061 http.setParameter("island", island);
1062 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
1063 InputStream in = post_for_yarrg(http);
1064 if (in == null) return false;
1065 String output = readstreamstring(in);
1066 if (!output.startsWith("OK")) {
1067 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1070 debug_write_stringdata("yarrg-result.txt", output);
1074 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1075 // if (dtxt!=null) dtxt.println("ARBITRAGE?");
1077 SortedSet<int[]> buys = arb_bs.get(0);
1078 SortedSet<int[]> sells = arb_bs.get(1);
1082 // NB "sell" means they sell, ie we buy
1083 sell = sells.last();
1085 } catch (NoSuchElementException e) {
1089 int unitprofit = buy[0] - sell[0];
1090 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1091 // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1092 // +" => x"+count+" @"+unitprofit);
1094 if (unitprofit <= 0)
1097 profit += count * unitprofit;
1100 if (buy[1]==0) buys.remove(buy);
1101 if (sell[1]==0) sells.remove(sell);
1103 // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
1107 private class arbitrageOfferComparator implements Comparator {
1108 public int compare(Object o1, Object o2) {
1109 int p1 = ((int[])o1)[0];
1110 int p2 = ((int[])o2)[0];
1115 private @SuppressWarnings("unchecked")
1116 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1118 ArrayList<SortedSet<int[]>> arb_bs = null;
1119 String lastcommod = null;
1120 Comparator compar = new arbitrageOfferComparator();
1122 for (ArrayList<String> row : data) {
1123 String thiscommod = row.get(0);
1124 // if (dtxt!=null) dtxt.println("ROW "+row.toString());
1125 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1126 if (lastcommod != null)
1127 arbitrage += calculateArbitrageCommodity(arb_bs);
1128 // if (dtxt!=null) dtxt.println("ROW rdy");
1129 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1130 arb_bs.add(0, new TreeSet<int[]>(compar));
1131 arb_bs.add(1, new TreeSet<int[]>(compar));
1132 // if (dtxt!=null) dtxt.println("ROW init");
1133 lastcommod = thiscommod;
1135 for (int bs = 0; bs < 2; bs++) {
1136 String pricestr = row.get(bs*2 + 2);
1137 if (pricestr == null)
1139 int[] entry = new int[2];
1140 // if (dtxt!=null) dtxt.println("ROW BS "+bs);
1141 entry[0] = parseQty(pricestr);
1142 entry[1] = parseQty(row.get(bs*2 + 3));
1143 arb_bs.get(bs).add(entry);
1146 arbitrage += calculateArbitrageCommodity(arb_bs);
1147 if (arbitrage != 0) {
1148 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1150 arbitrageResult.setText("no arbitrage");