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 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 int unknownPCTBcommods = 0;
44 private long startTime = 0;
46 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
47 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
48 private String PCTB_HOST_URL;
50 // Yarrg protocol parameters
51 private final static String YARRG_CLIENTNAME = "jpctb greenend";
52 private final static String YARRG_CLIENTVERSION =
53 net.chiark.yarrg.Version.version;
54 private final static String YARRG_CLIENTFIXES = "bug-094";
55 private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
56 private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
57 private String YARRG_URL;
59 private boolean uploadToYarrg;
60 private boolean uploadToPCTB;
61 private boolean showArbitrage;
63 private String islandName = null;
64 private String oceanName = null;
65 private java.util.concurrent.CountDownLatch latch = null;
67 private AccessibleContext sidePanel;
68 private HashMap<String,Integer> commodMap;
69 public PrintStream dtxt = null;
71 private PropertyChangeListener changeListener = new PropertyChangeListener() {
72 public void propertyChange(PropertyChangeEvent e) {
73 if(e.getNewValue() != null &&
74 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
75 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
76 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
77 int index = text.indexOf(":");
78 String name = text.substring(0,index);
80 // if (dtxt!=null) dtxt.println(islandName);
81 sidePanel.removePropertyChangeListener(this);
87 private int parseQty(String str) {
88 if (str.equals(">1000")) {
91 return Integer.parseInt(str);
95 private void progresslog(String s) {
96 if (dtxt == null) return;
97 long now = new Date().getTime();
98 dtxt.println("progress "+(now - startTime)+"ms "+s);
101 private void debug_write_stringdata(String what, String data) throws FileNotFoundException,IOException {
102 if (dtxt==null) return;
103 PrintStream strm = new PrintStream(new File("jarrg-debug-"+what));
108 private void debug_write_bytes(String what, byte[] data) throws FileNotFoundException,IOException {
109 if (dtxt==null) return;
110 FileOutputStream strm = new FileOutputStream(new File("jarrg-debug-"+what));
115 private void progressNote(ProgressMonitor pm, String s) {
117 if (arbitrageResult != null)
118 arb = arbitrageResult.getText();
119 if (arb != null && arb.length() != 0)
120 s = "<html>" + arb + "<br>" + s;
125 * An abstract market offer, entailing a commodity being bought or sold by
126 * a shoppe, for a certain price in a certain quantity. Not instantiable.
131 abstract class Offer {
132 public int commodity, price, quantity, shoppe;
134 * Create an offer from <code>record</code>, determining the shoppe Id from
135 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
136 * <code>priceIndex</code> should be the index of the price in the record
137 * (the quantity will be <code>priceIndex + 1</code>).
139 * @param record the record with data to create the offer from
140 * @param stallMap a map containing the ids of the various stalls
141 * @param commodMap a map containing the ids of the various commodities
142 * @param priceIndex the index of the price in the record
144 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
146 Integer commodId = commodMap.get(record.get(0));
147 if(commodId == null) {
148 throw new IllegalArgumentException();
150 commodity = commodId.intValue();
151 price = Integer.parseInt(record.get(priceIndex));
152 String qty = record.get(priceIndex+1);
153 quantity = parseQty(qty);
154 shoppe = stallMap.get(record.get(1)).intValue();
158 * Returns a human-readable version of this offer, useful for debugging
160 * @return human-readable offer
162 public String toString() {
163 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
168 * An offer from a shoppe or stall to buy a certain quantity of a commodity
169 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
170 * then by buy price descending, and finally by stall id ascending.
172 class Buy extends Offer implements Comparable<Buy> {
174 * Creates a new <code>Buy</code> offer from the given <code>record</code>
175 * using the other parameters to determine stall id and commodity id of the offer.
177 * @param record the record with data to create the offer from
178 * @param stallMap a map containing the ids of the various stalls
179 * @param commodMap a map containing the ids of the various commodities
181 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
182 super(record,stallMap,commodMap,2);
186 * Sorts by commodity index ascending, then price descending, then stall id ascending.
188 public int compareTo(Buy buy) {
189 // organize by: commodity index, price, stall index
190 if(commodity == buy.commodity) {
191 // organize by price, then by stall index
192 if(price == buy.price) {
193 // organize by stall index
194 return shoppe>buy.shoppe ? 1 : -1;
195 } else if(price > buy.price) {
200 } else if(commodity > buy.commodity) {
209 * An offer from a shoppe or stall to sell a certain quantity of a commodity
210 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
211 * then by sell price ascending, and finally by stall id ascending.
213 class Sell extends Offer implements Comparable<Sell> {
215 * Creates a new <code>Sell</code> offer from the given <code>record</code>
216 * using the other parameters to determine stall id and commodity id of the offer.
218 * @param record the record with data to create the offer from
219 * @param stallMap a map containing the ids of the various stalls
220 * @param commodMap a map containing the ids of the various commodities
222 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
223 super(record,stallMap,commodMap,4);
227 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
229 public int compareTo(Sell sell) {
230 // organize by: commodity index, price, stall index
231 if(commodity == sell.commodity) {
232 // organize by price, then by stall index
233 if(price == sell.price) {
234 // organize by stall index
235 return shoppe>sell.shoppe ? 1 : -1;
236 } else if(price > sell.price) {
241 } else if(commodity > sell.commodity) {
250 * Entry point. Read our preferences.
252 public MarketUploader() {
253 Preferences prefs = Preferences.userNodeForPackage(getClass());
255 if (prefs.getBoolean("writeDebugFiles", false)) {
257 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
258 } catch (java.io.FileNotFoundException e) {
259 System.err.println("JARRG: Error opening debug log: "+e);
263 if (prefs.getBoolean("useLiveServers", true)) {
264 YARRG_URL = YARRG_LIVE_URL;
265 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
267 YARRG_URL = YARRG_TEST_URL;
268 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
271 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
272 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
273 showArbitrage=prefs.getBoolean("showArbitrage", true);
275 EventQueueMonitor.addTopLevelWindowListener(this);
276 if (EventQueueMonitor.isGUIInitialized()) {
279 EventQueueMonitor.addGUIInitializedListener(this);
284 * Set up the GUI, with its window and one-button
285 * interface. Only initialize if we're running alongside
286 * a Window named "Puzzle Pirates" though.
288 private void createGUI() {
289 if (frame != null && window != null) {
290 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
293 frame = new JFrame("Jarrg Uploader");
294 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
295 GridLayout layout = new GridLayout(2,1);
296 frame.getContentPane().setLayout(layout);
297 //frame.setPreferredSize(new Dimension(200, 60));
299 findMarket = new JButton("Upload Market Data");
300 findMarket.addActionListener(new ActionListener() {
301 public void actionPerformed(ActionEvent e) {
302 findMarket.setEnabled(false);
305 startTime = new Date().getTime();
306 resultSummary.setText("");
307 arbitrageResult.setText("");
308 unknownPCTBcommods = 0;
311 } catch(Exception e) {
314 resultSummary.setText("failed");
316 if(sidePanel != null) {
317 // remove it if it's still attached
318 sidePanel.removePropertyChangeListener(changeListener);
321 findMarket.setEnabled(true);
326 frame.add(findMarket);
328 resultSummary = new JLabel("ready");
329 frame.add(resultSummary);
331 arbitrageResult = new JLabel("");
334 layout.setRows(layout.getRows() + 1);
335 frame.add(arbitrageResult);
342 * Finds the island name from the /who tab, sets global islandName variable
344 private void getIsland() {
346 // If the league tracker is there, we can skip the faff
347 // and ask for its tooltip, since we're on a boat
349 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
351 islandName = ((JLabel)leagueTracker).getToolTipText();
352 } catch (NullPointerException e) {
353 // evidently we're actually on an island
356 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
357 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
358 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
359 if(!"com.threerings.piracy.client.AttentionListPanel".
360 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
361 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
363 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
365 sidePanel.addPropertyChangeListener(changeListener);
366 latch = new java.util.concurrent.CountDownLatch(1);
367 // make the Players Online ("/who") panel appear
368 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
369 chat.setTextContents("/w");
370 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
371 for(int i=0;i<c;i++) {
372 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
373 chatArea.getAccessibleAction().doAccessibleAction(i);
380 * Find the ocean name from the window title, and set global oceanName variable
382 private void getOcean() {
384 AccessibleContext topwindow = window.getAccessibleContext();
385 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
390 * Shows a dialog with the error <code>msg</code>.
392 * @param msg a String describing the error that occured.
394 private void error(String msg) {
395 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
398 private void error_html(String msg, String html) {
399 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
400 Matcher m = body.matcher(html);
403 Pattern fixup = Pattern.compile("<(\\w+) */>");;
404 m = fixup.matcher(html);
405 html = m.replaceAll("<$1>");
406 m = Pattern.compile("[\\r\\n]+").matcher(html);
407 html = m.replaceAll(" ");
409 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
410 if (dtxt!=null) dtxt.println("###" + whole_msg + "###");
412 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
416 * Run the data collection process, and upload the results. This is the method
417 * that calls most of the other worker methods for the process. If an error occurs,
418 * the method will call the error method and return early, freeing up the button
419 * to be clicked again.
421 * @exception Exception if an error we didn't expect occured
423 private class YarrgTimestampFetcher extends Thread {
424 public String ts = null;
427 ts = getYarrgTimestamp();
428 progresslog("(async) yarrg timestamp ready.");
429 } catch(Exception e) {
430 error("Error getting YARRG timestamp: "+e);
435 private void runUpload() throws Exception {
436 progresslog("starting");
438 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
439 pm.setMillisToDecideToPopup(0);
440 pm.setMillisToPopup(0);
441 boolean doneyarrg = false, donepctb = false;
442 YarrgTimestampFetcher yarrgts_thread = null;
445 progresslog("(async) yarrg timestamp...");
446 yarrgts_thread = new YarrgTimestampFetcher();
447 yarrgts_thread.start();
450 AccessibleTable accesstable = findMarketTable();
451 if(accesstable == null) {
452 error("Market table not found! Please open the Buy/Sell Commodities interface.");
455 if(accesstable.getAccessibleRowCount() == 0) {
456 error("No data found, please wait for the table to have data first!");
459 if(!isDisplayAll()) {
460 error("Please select \"All\" from the Display: popup menu.");
464 progresslog("(async) getisland...");
466 progresslog("getocean...");
468 progresslog("getocean done");
471 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
473 progresslog("(async) getisland done");
475 String yarrgts = null;
476 if (yarrgts_thread != null) {
477 progresslog("(async) yarrg timestamp join...");
478 yarrgts_thread.join();
479 progresslog("(async) yarrg timestamp joined.");
480 yarrgts = yarrgts_thread.ts;
483 if (islandName == null) {
484 error("Could not find island name in YPP user interface.");
488 progresslog("table check...");
490 String headings_expected[] = new String[]
491 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
492 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
493 if (headers.size() != 1) {
494 error("Table headings not one row! " + headers.toString());
497 if (headers.get(0).size() < 6 ||
498 headers.get(0).size() > 7) {
499 error("Table headings not six or seven columns! " + headers.toString());
502 for (int col=0; col<headings_expected.length; col++) {
503 String expd = headings_expected[col];
504 String got = headers.get(0).get(col);
505 if (expd.compareTo(got) != 0) {
506 error("Table heading for column "+col
507 +" is not \""+expd+"\" but \""+got+"\".\n\n"
508 +"Please do not reorder the table when using this tool.");
513 progresslog("table read...");
515 ArrayList<ArrayList<String>> data = getData(accesstable);
518 progresslog("arbitrage...");
519 calculateArbitrage(data);
520 progresslog("arbitrage done.");
523 if (uploadToYarrg && yarrgts != null) {
524 progresslog("yarrg prepare...");
525 progressNote(pm, "Yarrg: Preparing data");
528 StringBuilder yarrgsb = new StringBuilder();
529 String yarrgdata; // string containing what we'll feed to yarrg
531 for (ArrayList<String> row : data) {
532 if (row.size() > 6) {
535 for (String rowitem : row) {
536 yarrgsb.append(rowitem != null ? rowitem : "");
537 yarrgsb.append("\t");
539 yarrgsb.setLength(yarrgsb.length()-1); // chop
540 yarrgsb.append("\n");
543 yarrgdata = yarrgsb.toString();
545 progressNote(pm, "Yarrg: Uploading");
546 progresslog("yarrg upload...");
548 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
549 progresslog("yarrg done.");
553 progresslog("pctb prepare...");
554 progressNote(pm, "PCTB: Getting stall names");
556 if(pm.isCanceled()) {
559 TreeSet<Offer> buys = new TreeSet<Offer>();
560 TreeSet<Offer> sells = new TreeSet<Offer>();
561 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
563 progressNote(pm, "PCTB: Sorting offers");
564 if(pm.isCanceled()) {
569 progresslog("pctb commodmap...");
570 HashMap<String,Integer> commodMap = getCommodMap();
571 if(commodMap == null) {
574 progresslog("pctb commodmap done.");
575 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
576 // if (dtxt!=null) dtxt.println(sells);
577 // if (dtxt!=null) dtxt.println("\n\n\n"+buys);
579 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
581 progressNote(pm, "PCTB: Sending data");
582 if(pm.isCanceled()) {
585 GZIPOutputStream out = new GZIPOutputStream(outStream);
586 DataOutputStream dos = new DataOutputStream(out);
587 dos.writeBytes("005y\n");
588 dos.writeBytes(stallMap.size()+"\n");
589 dos.writeBytes(getAbbrevStallList(stallMap));
590 writeBuySellOffers(buys,sells,offerCount,out);
592 progresslog("pctb send...");
594 byte[] ba = outStream.toByteArray();
595 debug_write_bytes("pctb-marketdata.gz", ba);
597 InputStream in = sendInitialData(new ByteArrayInputStream(ba));
598 progresslog("pctb sent.");
599 if (in == null) return;
601 if(pm.isCanceled()) {
604 progressNote(pm, "PCTB: Waiting ...");
605 progresslog("pctb finish...");
606 donepctb = finishUpload(in);
607 progresslog("pctb done.");
611 if ((uploadToPCTB && !donepctb) ||
612 (uploadToYarrg && !doneyarrg)) {
613 resultSummary.setText("trouble");
614 } else if (unknownPCTBcommods != 0) {
615 resultSummary.setText("PCTB lacks "+unknownPCTBcommods+" commod");
616 } else if (donepctb || doneyarrg) {
617 resultSummary.setText("Done " + islandName);
619 resultSummary.setText("uploaded nowhere!");
621 progresslog("done.");
625 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
627 * @param table the <code>AccessibleTable</code> containing the market data
628 * @return an array of record arrays, each representing a row of the table
630 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
631 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
632 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
633 ArrayList<String> row = new ArrayList<String>();
634 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
635 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
643 * @return the table containing market data if it exists, otherwise <code>null</code>
645 public AccessibleTable findMarketTable() {
646 Accessible node1 = window;
647 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
648 // 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})
649 // if (dtxt!=null) dtxt.println(node);
650 if (!(node instanceof JTable)) {
651 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
653 if (!(node instanceof JTable)) return null;
654 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
655 // if (dtxt!=null) dtxt.println(table);
660 * Utility method to descend through several levels of Accessible children
663 * @param parent the node on which to start the descent
664 * @param path an array of ints, each int being the index of the next
665 * accessible child to descend.
666 * @return the <code>Accessible</code> reached by following the descent path,
667 * or <code>null</code> if the desired path was invalid.
669 private Accessible descendNodes(Accessible parent, int[] path) {
670 for(int i=0;i<path.length;i++) {
671 if (null == (parent = descend(parent, path[i]))) return null;
672 // if (dtxt!=null) dtxt.println(parent.getClass());
678 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
680 * @param parent the node with children
681 * @param childNum the index of the child of <code>parent</code> to return
682 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
683 * if the child is not found.
685 private Accessible descend(Accessible parent, int childNum) {
686 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
687 return parent.getAccessibleContext().getAccessibleChild(childNum);
690 public static void main(String[] args) {
691 new MarketUploader();
695 * Set the global window variable after the YPP window is created,
696 * remove the top level window listener, and start the GUI
698 public void topLevelWindowCreated(Window w) {
700 EventQueueMonitor.removeTopLevelWindowListener(this);
705 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
707 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
709 private boolean isDisplayAll() {
710 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
711 if(!(button instanceof JButton)) {
712 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
714 String display = button.getAccessibleContext().getAccessibleName();
715 if(!display.equals("All")) {
721 public void topLevelWindowDestroyed(Window w) {}
723 public void guiInitialized() {
728 * Gets the list of commodities and their associated commodity ids.
730 * @return a map where the key is the commodity and the value is the commodity id.
732 private HashMap<String,Integer> getCommodMap() {
733 if(commodMap != null) {
736 HashMap<String,Integer> map = new HashMap<String,Integer>();
739 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
740 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
741 StringBuilder sb = new StringBuilder();
743 while((str = br.readLine()) != null) {
746 if (dtxt != null) debug_write_stringdata("pctb-commodmap.xmlish", sb.toString());
747 int first = sb.indexOf("<pre>") + 5;
748 int last = sb.indexOf("</body>");
749 xml = sb.substring(first,last);
750 Reader reader = new CharArrayReader(xml.toCharArray());
751 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
752 NodeList maps = d.getElementsByTagName("CommodMap");
753 for(int i=0;i<maps.getLength();i++) {
754 NodeList content = maps.item(i).getChildNodes();
755 Integer num = Integer.parseInt(content.item(1).getTextContent());
756 map.put(content.item(0).getTextContent(),num);
758 } catch(Exception e) {
760 error("Unable to load Commodity list from server!");
768 * Given the list of offers, this method will find all the unique stall names
769 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
770 * and the value is the generated stall id (position in the list).
772 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
773 * for iterating over the stall names in insertion order for output to the server.
775 * @param offers the list of records from the commodity buy/sell interface
776 * @return an iterable ordered map of the stall names and generated stall ids
778 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
780 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
781 for(ArrayList<String> offer : offers) {
782 String shop = offer.get(1);
783 if(!map.containsKey(shop)) {
792 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
793 * should be pre-initialized and passed into the method to receive the data.
794 * Returns a 2-length int array with the number of buys and sells found.
796 * @param offers the data found from the market table in-game
797 * @param buys an empty initialized <code>TreeSet<Offer></code> to
798 * hold the Buy offers.
799 * @param sells an empty initialized <code>TreeSet<Offer></code> to
800 * hold the Sell offers.
801 * @param stalls the map of stalls to their ids
802 * @param commodMap the map of commodities to their ids
803 * @return a 2-length int[] array containing the number of buys and sells, respectively
805 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
806 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
807 int[] buySellCount = new int[2];
808 for(ArrayList<String> offer : offers) {
810 if(offer.get(2) != null) {
811 buys.add(new Buy(offer,stalls,commodMap));
814 if(offer.get(4) != null) {
815 sells.add(new Sell(offer,stalls,commodMap));
818 } catch(IllegalArgumentException e) {
819 unknownPCTBcommods++;
820 if (dtxt!=null) dtxt.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
823 if (buySellCount[0]==0 && buySellCount[1]==0) {
824 error("No (valid) offers for PCTB?!");
825 throw new IllegalArgumentException();
831 * Prepares the list of stalls for writing to the output stream.
832 * The <code>String</code> returned by this method is ready to be written
833 * directly to the stream.
835 * All shoppe names are left as they are. Stall names are abbreviated just before the
836 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
837 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
839 * @param stallMap the map of stalls and stall ids in an iterable order
840 * @return a <code>String</code> containing the list of stalls in format ready
841 * to be written to the output stream.
843 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
844 // set up some mapping
845 HashMap<String,String> types = new HashMap<String,String>();
846 types.put("Apothecary Stall", "A");
847 types.put("Distilling Stall", "D");
848 types.put("Furnishing Stall", "F");
849 types.put("Ironworking Stall", "I");
850 types.put("Shipbuilding Stall", "S");
851 types.put("Tailoring Stall", "T");
852 types.put("Weaving Stall", "W");
854 StringBuilder sb = new StringBuilder();
855 for(String name : stallMap.keySet()) {
856 int index = name.indexOf("'s");
857 String finalName = name;
860 finalName = name.substring(0,index);
861 if(index + 2 < name.length()) {
862 String end = name.substring(index+2,name.length()).trim();
863 type = types.get(end);
867 sb.append(name+"\n");
869 sb.append(finalName+"^"+type+"\n");
872 return sb.toString();
876 * Writes a list of offers in correct format to the output stream.
878 * The format is thus: (all numbers are 2-byte integers in little-endian format)
879 * (number of offers of this type, aka buy/sell)
880 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
882 * @param out the output stream to write the data to
883 * @param offers the offers to write
885 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
886 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
887 if(offers.size() == 0) {
888 // nothing to write, and "0" has already been written
891 int commodity = offers.first().commodity;
893 for(Offer offer : offers) {
894 if(commodity != offer.commodity) {
896 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
898 commodity = offer.commodity;
901 writeLEShort(offer.shoppe,buffer); // stall index
902 writeLEShort(offer.price,buffer); // buy price
903 writeLEShort(offer.quantity,buffer); // buy qty
906 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
910 * Writes the buffered data to the output strea for one commodity.
912 * @param out the stream to write to
913 * @param buffer the buffered data to write
914 * @param commodity the commmodity id to write before the buffered data
915 * @param count the number of offers for this commodity to write before the data
917 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
918 writeLEShort(commodity,out); // commod index
919 writeLEShort(count,out); // offer count
920 out.write(buffer); // the buffered offers
924 * Writes the buy and sell offers to the outputstream by calling other methods.
926 * @param buys list of Buy offers to write
927 * @param sells list of Sell offers to write
928 * @param offerCount 2-length int array containing the number of buys and sells to write out
929 * @param out the stream to write to
931 private void writeBuySellOffers(TreeSet<Offer> buys,
932 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
934 writeLEShort(offerCount[0],out);
935 writeOffers(out,buys);
937 writeLEShort(offerCount[1],out);
938 writeOffers(out,sells);
941 private String readstreamstring(InputStream in) throws IOException {
942 StringBuilder sb = new StringBuilder();
943 BufferedReader br = new BufferedReader(new InputStreamReader(in));
945 while((str = br.readLine()) != null) {
948 return sb.toString();
952 * Sends the data to the server via multipart-formdata POST,
953 * with the gzipped data as a file upload.
955 * @param file an InputStream open to the gzipped data we want to send
957 private InputStream sendInitialData(InputStream file) throws IOException {
958 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
959 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
961 String err = readstreamstring(http.resultstream());
962 error("Error sending initial data:\n"+err);
965 return http.resultstream();
969 * Utility method to write a 2-byte int in little-endian form to an output stream.
971 * @param num an integer to write
972 * @param out stream to write to
974 private void writeLEShort(int num, OutputStream out) throws IOException {
975 out.write(num & 0xFF);
976 out.write((num >>> 8) & 0xFF);
980 * Reads the response from the server, and selects the correct parameters
981 * which are sent in a GET request to the server asking it to confirm
982 * the upload and accept the data into the database. Notably, the island id
983 * and ocean id are determined, while other parameter such as the filename
984 * are determined from the hidden form fields.
986 * @param in stream of data from the server to read
988 private boolean finishUpload(InputStream in) throws IOException {
989 String html = readstreamstring(in);
990 debug_write_stringdata("pctb-initial.html", html);
993 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
994 m = params.matcher(html);
996 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
1000 String forceReload = m.group(1);
1001 String filename = m.group(2);
1003 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
1004 m = oceanNumPat.matcher(html);
1006 error_html("Unable to find the ocean in the server's list of oceans!", html);
1009 String oceanNum = m.group(1);
1011 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
1012 m = oceanIslandNum.matcher(html);
1014 error_html("This does not seem to be a valid island! Unable to upload.", html);
1017 String islandNum = m.group(1);
1019 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
1020 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
1021 String complete = readstreamstring(get.openStream());
1022 debug_write_stringdata("pctb-final.html", complete);
1023 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
1024 m = done.matcher(complete);
1028 error_html("Something was wrong with the final upload parameters!", complete);
1033 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
1035 String err = readstreamstring(http.resultstream());
1036 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1039 return http.resultstream();
1042 private String getYarrgTimestamp() throws IOException {
1043 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1044 http.setParameter("clientname", YARRG_CLIENTNAME);
1045 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1046 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1047 http.setParameter("requesttimestamp", "y");
1048 InputStream in = post_for_yarrg(http);
1049 if (in == null) return null;
1050 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1051 String tsresult = br.readLine();
1052 return tsresult.substring(3, tsresult.length()-1);
1055 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
1056 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1057 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
1058 bufos.write(yarrgdata.getBytes() );
1060 byte[] compressed = bos.toByteArray();
1061 debug_write_bytes("yarrg-deduped.tsv.gz", compressed);
1062 ByteArrayInputStream file = new ByteArrayInputStream(compressed);
1064 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1065 http.setParameter("clientname", YARRG_CLIENTNAME);
1066 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1067 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1068 http.setParameter("timestamp", timestamp);
1069 http.setParameter("ocean", ocean);
1070 http.setParameter("island", island);
1071 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
1072 InputStream in = post_for_yarrg(http);
1073 if (in == null) return false;
1074 String output = readstreamstring(in);
1075 if (!output.startsWith("OK")) {
1076 error("<html><h1>Unexpected output from YARRG server</h1>\n" + output);
1079 debug_write_stringdata("yarrg-result.txt", output);
1083 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1084 // if (dtxt!=null) dtxt.println("ARBITRAGE?");
1086 SortedSet<int[]> buys = arb_bs.get(0);
1087 SortedSet<int[]> sells = arb_bs.get(1);
1091 // NB "sell" means they sell, ie we buy
1092 sell = sells.last();
1094 } catch (NoSuchElementException e) {
1098 int unitprofit = buy[0] - sell[0];
1099 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1100 // if (dtxt!=null) dtxt.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1101 // +" => x"+count+" @"+unitprofit);
1103 if (unitprofit <= 0)
1106 profit += count * unitprofit;
1109 if (buy[1]==0) buys.remove(buy);
1110 if (sell[1]==0) sells.remove(sell);
1112 // if (dtxt!=null) dtxt.println(" PROFIT "+profit);
1116 private class arbitrageOfferComparator implements Comparator {
1117 public int compare(Object o1, Object o2) {
1118 int p1 = ((int[])o1)[0];
1119 int p2 = ((int[])o2)[0];
1124 private @SuppressWarnings("unchecked")
1125 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1127 ArrayList<SortedSet<int[]>> arb_bs = null;
1128 String lastcommod = null;
1129 Comparator compar = new arbitrageOfferComparator();
1131 for (ArrayList<String> row : data) {
1132 String thiscommod = row.get(0);
1133 // if (dtxt!=null) dtxt.println("ROW "+row.toString());
1134 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1135 if (lastcommod != null)
1136 arbitrage += calculateArbitrageCommodity(arb_bs);
1137 // if (dtxt!=null) dtxt.println("ROW rdy");
1138 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1139 arb_bs.add(0, new TreeSet<int[]>(compar));
1140 arb_bs.add(1, new TreeSet<int[]>(compar));
1141 // if (dtxt!=null) dtxt.println("ROW init");
1142 lastcommod = thiscommod;
1144 for (int bs = 0; bs < 2; bs++) {
1145 String pricestr = row.get(bs*2 + 2);
1146 if (pricestr == null)
1148 int[] entry = new int[2];
1149 // if (dtxt!=null) dtxt.println("ROW BS "+bs);
1150 entry[0] = parseQty(pricestr);
1151 entry[1] = parseQty(row.get(bs*2 + 3));
1152 arb_bs.get(bs).add(entry);
1155 arbitrage += calculateArbitrageCommodity(arb_bs);
1156 if (arbitrage != 0) {
1157 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1159 arbitrageResult.setText("no arbitrage");