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 //System.out.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 long now = new Date().getTime();
96 System.out.println("progress "+(now - startTime)+"ms "+s);
99 private void progressNote(ProgressMonitor pm, String s) {
101 if (arbitrageResult != null)
102 arb = arbitrageResult.getText();
103 if (arb != null && arb.length() != 0)
104 s = "<html>" + arb + "<br>" + s;
109 * An abstract market offer, entailing a commodity being bought or sold by
110 * a shoppe, for a certain price in a certain quantity. Not instantiable.
115 abstract class Offer {
116 public int commodity, price, quantity, shoppe;
118 * Create an offer from <code>record</code>, determining the shoppe Id from
119 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
120 * <code>priceIndex</code> should be the index of the price in the record
121 * (the quantity will be <code>priceIndex + 1</code>).
123 * @param record the record with data to create the offer from
124 * @param stallMap a map containing the ids of the various stalls
125 * @param commodMap a map containing the ids of the various commodities
126 * @param priceIndex the index of the price in the record
128 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
130 Integer commodId = commodMap.get(record.get(0));
131 if(commodId == null) {
132 throw new IllegalArgumentException();
134 commodity = commodId.intValue();
135 price = Integer.parseInt(record.get(priceIndex));
136 String qty = record.get(priceIndex+1);
137 quantity = parseQty(qty);
138 shoppe = stallMap.get(record.get(1)).intValue();
142 * Returns a human-readable version of this offer, useful for debugging
144 * @return human-readable offer
146 public String toString() {
147 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
152 * An offer from a shoppe or stall to buy a certain quantity of a commodity
153 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
154 * then by buy price descending, and finally by stall id ascending.
156 class Buy extends Offer implements Comparable<Buy> {
158 * Creates a new <code>Buy</code> offer from the given <code>record</code>
159 * using the other parameters to determine stall id and commodity id of the offer.
161 * @param record the record with data to create the offer from
162 * @param stallMap a map containing the ids of the various stalls
163 * @param commodMap a map containing the ids of the various commodities
165 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
166 super(record,stallMap,commodMap,2);
170 * Sorts by commodity index ascending, then price descending, then stall id ascending.
172 public int compareTo(Buy buy) {
173 // organize by: commodity index, price, stall index
174 if(commodity == buy.commodity) {
175 // organize by price, then by stall index
176 if(price == buy.price) {
177 // organize by stall index
178 return shoppe>buy.shoppe ? 1 : -1;
179 } else if(price > buy.price) {
184 } else if(commodity > buy.commodity) {
193 * An offer from a shoppe or stall to sell a certain quantity of a commodity
194 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
195 * then by sell price ascending, and finally by stall id ascending.
197 class Sell extends Offer implements Comparable<Sell> {
199 * Creates a new <code>Sell</code> offer from the given <code>record</code>
200 * using the other parameters to determine stall id and commodity id of the offer.
202 * @param record the record with data to create the offer from
203 * @param stallMap a map containing the ids of the various stalls
204 * @param commodMap a map containing the ids of the various commodities
206 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
207 super(record,stallMap,commodMap,4);
211 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
213 public int compareTo(Sell sell) {
214 // organize by: commodity index, price, stall index
215 if(commodity == sell.commodity) {
216 // organize by price, then by stall index
217 if(price == sell.price) {
218 // organize by stall index
219 return shoppe>sell.shoppe ? 1 : -1;
220 } else if(price > sell.price) {
225 } else if(commodity > sell.commodity) {
234 * Entry point. Read our preferences.
236 public MarketUploader() {
237 // check if we've been turned off in the control panel
238 Preferences prefs = Preferences.userNodeForPackage(getClass());
240 if (prefs.getBoolean("writeDebugFiles", false)) {
242 dtxt = new PrintStream(new File("jarrg-debug-log.txt"));
243 } catch (java.io.FileNotFoundException e) {
244 System.err.println("JARRG: Error opening debug log: "+e);
248 if (prefs.getBoolean("useLiveServers", false)) {
249 YARRG_URL = YARRG_LIVE_URL;
250 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
252 YARRG_URL = YARRG_TEST_URL;
253 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
256 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
257 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
258 showArbitrage=prefs.getBoolean("showArbitrage", true);
260 EventQueueMonitor.addTopLevelWindowListener(this);
261 if (EventQueueMonitor.isGUIInitialized()) {
264 EventQueueMonitor.addGUIInitializedListener(this);
269 * Set up the GUI, with its window and one-button
270 * interface. Only initialize if we're running alongside
271 * a Window named "Puzzle Pirates" though.
273 private void createGUI() {
274 if (frame != null && window != null) {
275 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
278 frame = new JFrame("Jarrg Uploader");
279 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
280 GridLayout layout = new GridLayout(2,1);
281 frame.getContentPane().setLayout(layout);
282 //frame.setPreferredSize(new Dimension(200, 60));
284 findMarket = new JButton("Upload Market Data");
285 findMarket.addActionListener(new ActionListener() {
286 public void actionPerformed(ActionEvent e) {
287 findMarket.setEnabled(false);
290 startTime = new Date().getTime();
291 resultSummary.setText("");
292 arbitrageResult.setText("");
295 } catch(Exception e) {
298 resultSummary.setText("failed");
300 if(sidePanel != null) {
301 // remove it if it's still attached
302 sidePanel.removePropertyChangeListener(changeListener);
306 findMarket.setEnabled(true);
311 frame.add(findMarket);
313 resultSummary = new JLabel("ready");
314 frame.add(resultSummary);
316 arbitrageResult = new JLabel("");
319 layout.setRows(layout.getRows() + 1);
320 frame.add(arbitrageResult);
327 * Finds the island name from the /who tab, sets global islandName variable
329 private void getIsland() {
331 // If the league tracker is there, we can skip the faff
332 // and ask for its tooltip, since we're on a boat
334 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
336 islandName = ((JLabel)leagueTracker).getToolTipText();
337 } catch (NullPointerException e) {
338 // evidently we're actually on an island
341 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
342 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
343 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
344 if(!"com.threerings.piracy.client.AttentionListPanel".
345 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
346 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
348 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
350 sidePanel.addPropertyChangeListener(changeListener);
351 latch = new java.util.concurrent.CountDownLatch(1);
352 // make the Players Online ("/who") panel appear
353 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
354 chat.setTextContents("/w");
355 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
356 for(int i=0;i<c;i++) {
357 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
358 chatArea.getAccessibleAction().doAccessibleAction(i);
362 // if we don't find the island name, hopefully the server will
366 * Find the ocean name from the window title, and set global oceanName variable
368 private void getOcean() {
370 AccessibleContext topwindow = window.getAccessibleContext();
371 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
376 * Shows a dialog with the error <code>msg</code>.
378 * @param msg a String describing the error that occured.
380 private void error(String msg) {
381 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
384 private void error_html(String msg, String html) {
385 //System.err.println("===" + html + "===");
387 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
388 Matcher m = body.matcher(html);
391 Pattern fixup = Pattern.compile("<(\\w+) */>");;
392 m = fixup.matcher(html);
393 html = m.replaceAll("<$1>");
394 m = Pattern.compile("[\\r\\n]+").matcher(html);
395 html = m.replaceAll(" ");
397 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
398 System.err.println("###" + whole_msg + "###");
400 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
404 * Run the data collection process, and upload the results. This is the method
405 * that calls most of the other worker methods for the process. If an error occurs,
406 * the method will call the error method and return early, freeing up the button
407 * to be clicked again.
409 * @exception Exception if an error we didn't expect occured
411 private void runUpload() throws Exception {
412 progresslog("starting");
415 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
416 pm.setMillisToDecideToPopup(0);
417 pm.setMillisToPopup(0);
418 boolean doneyarrg = false, donepctb = false;
421 progresslog("yarrg timestamp...");
422 yarrgts = getYarrgTimestamp();
423 progresslog("yarrg timestamp done.");
426 AccessibleTable accesstable = findMarketTable();
427 if(accesstable == null) {
428 error("Market table not found! Please open the Buy/Sell Commodities interface.");
431 if(accesstable.getAccessibleRowCount() == 0) {
432 error("No data found, please wait for the table to have data first!");
435 if(!isDisplayAll()) {
436 error("Please select \"All\" from the Display: popup menu.");
440 progresslog("getisland...");
442 progresslog("getocean...");
444 progresslog("getocean done");
447 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
450 if (islandName == null) {
451 error("Could not find island name in YPP user interface.");
455 progresslog("table check...");
457 String headings_expected[] = new String[]
458 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
459 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
460 if (headers.size() != 1) {
461 error("Table headings not one row! " + headers.toString());
464 if (headers.get(0).size() != 6) {
465 error("Table headings not six columns! " + headers.toString());
468 for (int col=0; col<headings_expected.length; col++) {
469 String expd = headings_expected[col];
470 String got = headers.get(0).get(col);
471 if (expd.compareTo(got) != 0) {
472 error("Table heading for column "+col
473 +" is not \""+expd+"\" but \""+got+"\".\n\n"
474 +"Please do not reorder the table when using this tool.");
479 progresslog("table read...");
481 ArrayList<ArrayList<String>> data = getData(accesstable);
484 progresslog("arbitrage...");
485 calculateArbitrage(data);
486 progresslog("arbitrage done.");
489 if (uploadToYarrg && yarrgts != null) {
490 progresslog("yarrg prepare...");
491 progressNote(pm, "Yarrg: Preparing data");
494 StringBuilder yarrgsb = new StringBuilder();
495 String yarrgdata; // string containing what we'll feed to yarrg
497 for (ArrayList<String> row : data) {
498 if (row.size() > 6) {
501 for (String rowitem : row) {
502 yarrgsb.append(rowitem != null ? rowitem : "");
503 yarrgsb.append("\t");
505 yarrgsb.setLength(yarrgsb.length()-1); // chop
506 yarrgsb.append("\n");
509 yarrgdata = yarrgsb.toString();
511 progressNote(pm, "Yarrg: Uploading");
512 progresslog("yarrg upload...");
514 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
515 progresslog("yarrg done.");
519 progresslog("pctb prepare...");
520 progressNote(pm, "PCTB: Getting stall names");
522 if(pm.isCanceled()) {
525 TreeSet<Offer> buys = new TreeSet<Offer>();
526 TreeSet<Offer> sells = new TreeSet<Offer>();
527 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
529 progressNote(pm, "PCTB: Sorting offers");
530 if(pm.isCanceled()) {
535 HashMap<String,Integer> commodMap = getCommodMap();
536 if(commodMap == null) {
539 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
540 //println(buys.toString());
541 //System.out.println(sells);
542 //System.out.println("\n\n\n"+buys);
544 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
546 progressNote(pm, "PCTB: Sending data");
547 if(pm.isCanceled()) {
550 GZIPOutputStream out = new GZIPOutputStream(outStream);
551 //FileOutputStream out = new FileOutputStream(new File("output.text"));
552 DataOutputStream dos = new DataOutputStream(out);
553 dos.writeBytes("005y\n");
554 dos.writeBytes(stallMap.size()+"\n");
555 dos.writeBytes(getAbbrevStallList(stallMap));
556 writeBuySellOffers(buys,sells,offerCount,out);
558 progresslog("pctb send...");
559 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
560 progresslog("pctb sent.");
561 if (in == null) return;
563 if(pm.isCanceled()) {
566 progressNote(pm, "PCTB: Waiting ...");
567 progresslog("pctb finish...");
568 donepctb = finishUpload(in);
569 progresslog("pctb done.");
573 if ((uploadToPCTB && !donepctb) ||
574 (uploadToYarrg && !doneyarrg)) {
575 resultSummary.setText("trouble");
576 } else if (donepctb || doneyarrg) {
577 resultSummary.setText("Done " + islandName);
579 resultSummary.setText("uploaded nowhere!");
581 progresslog("done.");
585 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
587 * @param table the <code>AccessibleTable</code> containing the market data
588 * @return an array of record arrays, each representing a row of the table
590 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
591 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
592 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
593 ArrayList<String> row = new ArrayList<String>();
594 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
595 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
603 * @return the table containing market data if it exists, otherwise <code>null</code>
605 public AccessibleTable findMarketTable() {
606 Accessible node1 = window;
607 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
608 // 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})
609 //System.out.println(node);
610 if (!(node instanceof JTable)) {
611 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
613 if (!(node instanceof JTable)) return null;
614 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
615 //System.out.println(table);
620 * Utility method to descend through several levels of Accessible children
623 * @param parent the node on which to start the descent
624 * @param path an array of ints, each int being the index of the next
625 * accessible child to descend.
626 * @return the <code>Accessible</code> reached by following the descent path,
627 * or <code>null</code> if the desired path was invalid.
629 private Accessible descendNodes(Accessible parent, int[] path) {
630 for(int i=0;i<path.length;i++) {
631 if (null == (parent = descend(parent, path[i]))) return null;
632 // System.out.println(parent.getClass());
638 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
640 * @param parent the node with children
641 * @param childNum the index of the child of <code>parent</code> to return
642 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
643 * if the child is not found.
645 private Accessible descend(Accessible parent, int childNum) {
646 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
647 return parent.getAccessibleContext().getAccessibleChild(childNum);
650 public static void main(String[] args) {
651 new MarketUploader();
655 * Set the global window variable after the YPP window is created,
656 * remove the top level window listener, and start the GUI
658 public void topLevelWindowCreated(Window w) {
660 EventQueueMonitor.removeTopLevelWindowListener(this);
665 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
667 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
669 private boolean isDisplayAll() {
670 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
671 if(!(button instanceof JButton)) {
672 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
674 String display = button.getAccessibleContext().getAccessibleName();
675 if(!display.equals("All")) {
681 public void topLevelWindowDestroyed(Window w) {}
683 public void guiInitialized() {
688 * Gets the list of commodities and their associated commodity ids.
689 * On the first run, the data is downloaded from the PCTB server.
690 * After the first run, the data is cached using <code>Preferences</code>.
692 * Potential issues: When more commodities are added to the server, this
693 * program will currently break unless the user deletes the preferences
694 * file or we give them a new release with a slighly different storage
695 * location for the data.
697 * @return a map where the key is the commodity and the value is the commodity id.
699 private HashMap<String,Integer> getCommodMap() {
700 if(commodMap != null) {
703 HashMap<String,Integer> map = new HashMap<String,Integer>();
704 Preferences prefs = Preferences.userNodeForPackage(getClass());
707 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
708 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
709 StringBuilder sb = new StringBuilder();
711 while((str = br.readLine()) != null) {
714 int first = sb.indexOf("<pre>") + 5;
715 int last = sb.indexOf("</body>");
716 xml = sb.substring(first,last);
718 // dtxt.println(">>");
719 // dtxt.println(sb);;
720 // dtxt.println("||");
721 // dtxt.println(xml);
722 // dtxt.println("<<");
724 //System.out.println(xml);
725 Reader reader = new CharArrayReader(xml.toCharArray());
726 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
727 NodeList maps = d.getElementsByTagName("CommodMap");
728 for(int i=0;i<maps.getLength();i++) {
729 NodeList content = maps.item(i).getChildNodes();
730 Integer num = Integer.parseInt(content.item(1).getTextContent());
731 map.put(content.item(0).getTextContent(),num);
733 } catch(Exception e) {
735 error("Unable to load Commodity list from server!");
743 * Given the list of offers, this method will find all the unique stall names
744 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
745 * and the value is the generated stall id (position in the list).
747 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
748 * for iterating over the stall names in insertion order for output to the server.
750 * @param offers the list of records from the commodity buy/sell interface
751 * @return an iterable ordered map of the stall names and generated stall ids
753 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
755 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
756 for(ArrayList<String> offer : offers) {
757 String shop = offer.get(1);
758 if(!map.containsKey(shop)) {
767 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
768 * should be pre-initialized and passed into the method to receive the data.
769 * Returns a 2-length int array with the number of buys and sells found.
771 * @param offers the data found from the market table in-game
772 * @param buys an empty initialized <code>TreeSet<Offer></code> to
773 * hold the Buy offers.
774 * @param sells an empty initialized <code>TreeSet<Offer></code> to
775 * hold the Sell offers.
776 * @param stalls the map of stalls to their ids
777 * @param commodMap the map of commodities to their ids
778 * @return a 2-length int[] array containing the number of buys and sells, respectively
780 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
781 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
782 int[] buySellCount = new int[2];
783 for(ArrayList<String> offer : offers) {
785 if(offer.get(2) != null) {
786 buys.add(new Buy(offer,stalls,commodMap));
789 if(offer.get(4) != null) {
790 sells.add(new Sell(offer,stalls,commodMap));
793 } catch(IllegalArgumentException e) {
794 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
797 if (buySellCount[0]==0 && buySellCount[1]==0) {
798 error("No (valid) offers for PCTB?!");
799 throw new IllegalArgumentException();
805 * Prepares the list of stalls for writing to the output stream.
806 * The <code>String</code> returned by this method is ready to be written
807 * directly to the stream.
809 * All shoppe names are left as they are. Stall names are abbreviated just before the
810 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
811 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
813 * @param stallMap the map of stalls and stall ids in an iterable order
814 * @return a <code>String</code> containing the list of stalls in format ready
815 * to be written to the output stream.
817 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
818 // set up some mapping
819 HashMap<String,String> types = new HashMap<String,String>();
820 types.put("Apothecary Stall", "A");
821 types.put("Distilling Stall", "D");
822 types.put("Furnishing Stall", "F");
823 types.put("Ironworking Stall", "I");
824 types.put("Shipbuilding Stall", "S");
825 types.put("Tailoring Stall", "T");
826 types.put("Weaving Stall", "W");
828 StringBuilder sb = new StringBuilder();
829 for(String name : stallMap.keySet()) {
830 int index = name.indexOf("'s");
831 String finalName = name;
834 finalName = name.substring(0,index);
835 if(index + 2 < name.length()) {
836 String end = name.substring(index+2,name.length()).trim();
837 type = types.get(end);
841 sb.append(name+"\n");
843 sb.append(finalName+"^"+type+"\n");
846 return sb.toString();
850 * Writes a list of offers in correct format to the output stream.
852 * The format is thus: (all numbers are 2-byte integers in little-endian format)
853 * (number of offers of this type, aka buy/sell)
854 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
856 * @param out the output stream to write the data to
857 * @param offers the offers to write
859 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
860 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
861 if(offers.size() == 0) {
862 // nothing to write, and "0" has already been written
865 int commodity = offers.first().commodity;
867 for(Offer offer : offers) {
868 if(commodity != offer.commodity) {
870 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
872 commodity = offer.commodity;
875 writeLEShort(offer.shoppe,buffer); // stall index
876 writeLEShort(offer.price,buffer); // buy price
877 writeLEShort(offer.quantity,buffer); // buy qty
880 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
884 * Writes the buffered data to the output strea for one commodity.
886 * @param out the stream to write to
887 * @param buffer the buffered data to write
888 * @param commodity the commmodity id to write before the buffered data
889 * @param count the number of offers for this commodity to write before the data
891 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
892 writeLEShort(commodity,out); // commod index
893 writeLEShort(count,out); // offer count
894 out.write(buffer); // the buffered offers
898 * Writes the buy and sell offers to the outputstream by calling other methods.
900 * @param buys list of Buy offers to write
901 * @param sells list of Sell offers to write
902 * @param offerCount 2-length int array containing the number of buys and sells to write out
903 * @param out the stream to write to
905 private void writeBuySellOffers(TreeSet<Offer> buys,
906 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
908 writeLEShort(offerCount[0],out);
909 writeOffers(out,buys);
911 writeLEShort(offerCount[1],out);
912 writeOffers(out,sells);
915 private String readstreamstring(InputStream in) throws IOException {
916 StringBuilder sb = new StringBuilder();
917 BufferedReader br = new BufferedReader(new InputStreamReader(in));
919 while((str = br.readLine()) != null) {
922 return sb.toString();
926 * Sends the data to the server via multipart-formdata POST,
927 * with the gzipped data as a file upload.
929 * @param file an InputStream open to the gzipped data we want to send
931 private InputStream sendInitialData(InputStream file) throws IOException {
932 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
933 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
935 String err = readstreamstring(http.resultstream());
936 error("Error sending initial data:\n"+err);
939 return http.resultstream();
943 * Utility method to write a 2-byte int in little-endian form to an output stream.
945 * @param num an integer to write
946 * @param out stream to write to
948 private void writeLEShort(int num, OutputStream out) throws IOException {
949 out.write(num & 0xFF);
950 out.write((num >>> 8) & 0xFF);
954 * Reads the response from the server, and selects the correct parameters
955 * which are sent in a GET request to the server asking it to confirm
956 * the upload and accept the data into the database. Notably, the island id
957 * and ocean id are determined, while other parameter such as the filename
958 * are determined from the hidden form fields.
960 * @param in stream of data from the server to read
962 private boolean finishUpload(InputStream in) throws IOException {
963 String html = readstreamstring(in);
964 //System.out.println(html);
967 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
968 m = params.matcher(html);
970 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
974 String forceReload = m.group(1);
975 String filename = m.group(2);
977 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
978 m = oceanNumPat.matcher(html);
980 error_html("Unable to find the ocean in the server's list of oceans!", html);
983 String oceanNum = m.group(1);
985 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
986 m = oceanIslandNum.matcher(html);
988 error_html("This does not seem to be a valid island! Unable to upload.", html);
991 String islandNum = m.group(1);
993 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
994 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
995 String complete = readstreamstring(get.openStream());
996 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
997 m = done.matcher(complete);
999 System.out.println("FILE upload successful!!!");
1002 error_html("Something was wrong with the final upload parameters!", complete);
1007 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
1009 String err = readstreamstring(http.resultstream());
1010 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
1013 return http.resultstream();
1016 private String getYarrgTimestamp() throws IOException {
1017 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1018 http.setParameter("clientname", YARRG_CLIENTNAME);
1019 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1020 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1021 http.setParameter("requesttimestamp", "y");
1022 InputStream in = post_for_yarrg(http);
1023 if (in == null) return null;
1024 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1025 String tsresult = br.readLine();
1026 return tsresult.substring(3, tsresult.length()-1);
1029 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
1030 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1031 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
1032 bufos.write(yarrgdata.getBytes() );
1034 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
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("timestamp", timestamp);
1041 http.setParameter("ocean", ocean);
1042 http.setParameter("island", island);
1043 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
1044 InputStream in = post_for_yarrg(http);
1045 if (in == null) return false;
1046 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1048 while((yarrgresult = br.readLine()) != null) {
1049 System.out.println(yarrgresult);
1054 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1055 //System.out.println("ARBITRAGE?");
1057 SortedSet<int[]> buys = arb_bs.get(0);
1058 SortedSet<int[]> sells = arb_bs.get(1);
1062 // NB "sell" means they sell, ie we buy
1063 sell = sells.last();
1065 } catch (NoSuchElementException e) {
1069 int unitprofit = buy[0] - sell[0];
1070 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1071 //System.out.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1072 // +" => x"+count+" @"+unitprofit);
1074 if (unitprofit <= 0)
1077 profit += count * unitprofit;
1080 if (buy[1]==0) buys.remove(buy);
1081 if (sell[1]==0) sells.remove(sell);
1083 //System.out.println(" PROFIT "+profit);
1087 private class arbitrageOfferComparator implements Comparator {
1088 public int compare(Object o1, Object o2) {
1089 int p1 = ((int[])o1)[0];
1090 int p2 = ((int[])o2)[0];
1095 private @SuppressWarnings("unchecked")
1096 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1098 ArrayList<SortedSet<int[]>> arb_bs = null;
1099 String lastcommod = null;
1100 Comparator compar = new arbitrageOfferComparator();
1102 for (ArrayList<String> row : data) {
1103 String thiscommod = row.get(0);
1104 //System.out.println("ROW "+row.toString());
1105 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1106 if (lastcommod != null)
1107 arbitrage += calculateArbitrageCommodity(arb_bs);
1108 //System.out.println("ROW rdy");
1109 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1110 arb_bs.add(0, new TreeSet<int[]>(compar));
1111 arb_bs.add(1, new TreeSet<int[]>(compar));
1112 //System.out.println("ROW init");
1113 lastcommod = thiscommod;
1115 for (int bs = 0; bs < 2; bs++) {
1116 String pricestr = row.get(bs*2 + 2);
1117 if (pricestr == null)
1119 int[] entry = new int[2];
1120 //System.out.println("ROW BS "+bs);
1121 entry[0] = parseQty(pricestr);
1122 entry[1] = parseQty(row.get(bs*2 + 3));
1123 arb_bs.get(bs).add(entry);
1126 arbitrage += calculateArbitrageCommodity(arb_bs);
1127 if (arbitrage != 0) {
1128 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1130 arbitrageResult.setText("no arbitrage");