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;
69 private PropertyChangeListener changeListener = new PropertyChangeListener() {
70 public void propertyChange(PropertyChangeEvent e) {
71 if(e.getNewValue() != null &&
72 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
73 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
74 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
75 int index = text.indexOf(":");
76 String name = text.substring(0,index);
78 //System.out.println(islandName);
79 sidePanel.removePropertyChangeListener(this);
85 private int parseQty(String str) {
86 if (str.equals(">1000")) {
89 return Integer.parseInt(str);
93 private void progresslog(String s) {
94 long now = new Date().getTime();
95 System.out.println("progress "+(now - startTime)+"ms "+s);
98 private void progressNote(ProgressMonitor pm, String s) {
100 if (arbitrageResult != null)
101 arb = arbitrageResult.getText();
102 if (arb != null && arb.length() != 0)
103 s = "<html>" + arb + "<br>" + s;
108 * An abstract market offer, entailing a commodity being bought or sold by
109 * a shoppe, for a certain price in a certain quantity. Not instantiable.
114 abstract class Offer {
115 public int commodity, price, quantity, shoppe;
117 * Create an offer from <code>record</code>, determining the shoppe Id from
118 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
119 * <code>priceIndex</code> should be the index of the price in the record
120 * (the quantity will be <code>priceIndex + 1</code>).
122 * @param record the record with data to create the offer from
123 * @param stallMap a map containing the ids of the various stalls
124 * @param commodMap a map containing the ids of the various commodities
125 * @param priceIndex the index of the price in the record
127 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
129 Integer commodId = commodMap.get(record.get(0));
130 if(commodId == null) {
131 throw new IllegalArgumentException();
133 commodity = commodId.intValue();
134 price = Integer.parseInt(record.get(priceIndex));
135 String qty = record.get(priceIndex+1);
136 quantity = parseQty(qty);
137 shoppe = stallMap.get(record.get(1)).intValue();
141 * Returns a human-readable version of this offer, useful for debugging
143 * @return human-readable offer
145 public String toString() {
146 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
151 * An offer from a shoppe or stall to buy a certain quantity of a commodity
152 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
153 * then by buy price descending, and finally by stall id ascending.
155 class Buy extends Offer implements Comparable<Buy> {
157 * Creates a new <code>Buy</code> offer from the given <code>record</code>
158 * using the other parameters to determine stall id and commodity id of the offer.
160 * @param record the record with data to create the offer from
161 * @param stallMap a map containing the ids of the various stalls
162 * @param commodMap a map containing the ids of the various commodities
164 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
165 super(record,stallMap,commodMap,2);
169 * Sorts by commodity index ascending, then price descending, then stall id ascending.
171 public int compareTo(Buy buy) {
172 // organize by: commodity index, price, stall index
173 if(commodity == buy.commodity) {
174 // organize by price, then by stall index
175 if(price == buy.price) {
176 // organize by stall index
177 return shoppe>buy.shoppe ? 1 : -1;
178 } else if(price > buy.price) {
183 } else if(commodity > buy.commodity) {
192 * An offer from a shoppe or stall to sell a certain quantity of a commodity
193 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
194 * then by sell price ascending, and finally by stall id ascending.
196 class Sell extends Offer implements Comparable<Sell> {
198 * Creates a new <code>Sell</code> offer from the given <code>record</code>
199 * using the other parameters to determine stall id and commodity id of the offer.
201 * @param record the record with data to create the offer from
202 * @param stallMap a map containing the ids of the various stalls
203 * @param commodMap a map containing the ids of the various commodities
205 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
206 super(record,stallMap,commodMap,4);
210 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
212 public int compareTo(Sell sell) {
213 // organize by: commodity index, price, stall index
214 if(commodity == sell.commodity) {
215 // organize by price, then by stall index
216 if(price == sell.price) {
217 // organize by stall index
218 return shoppe>sell.shoppe ? 1 : -1;
219 } else if(price > sell.price) {
224 } else if(commodity > sell.commodity) {
233 * Entry point. Read our preferences.
235 public MarketUploader() {
236 // check if we've been turned off in the control panel
237 Preferences prefs = Preferences.userNodeForPackage(getClass());
239 if (prefs.getBoolean("useLiveServers", false)) {
240 YARRG_URL = YARRG_LIVE_URL;
241 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
243 YARRG_URL = YARRG_TEST_URL;
244 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
247 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
248 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
249 showArbitrage=prefs.getBoolean("showArbitrage", true);
251 EventQueueMonitor.addTopLevelWindowListener(this);
252 if (EventQueueMonitor.isGUIInitialized()) {
255 EventQueueMonitor.addGUIInitializedListener(this);
260 * Set up the GUI, with its window and one-button
261 * interface. Only initialize if we're running alongside
262 * a Window named "Puzzle Pirates" though.
264 private void createGUI() {
265 if (frame != null && window != null) {
266 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
269 frame = new JFrame("Jarrg Uploader");
270 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
271 GridLayout layout = new GridLayout(2,1);
272 frame.getContentPane().setLayout(layout);
273 //frame.setPreferredSize(new Dimension(200, 60));
275 findMarket = new JButton("Upload Market Data");
276 findMarket.addActionListener(new ActionListener() {
277 public void actionPerformed(ActionEvent e) {
278 findMarket.setEnabled(false);
281 startTime = new Date().getTime();
282 resultSummary.setText("");
283 arbitrageResult.setText("");
286 } catch(Exception e) {
289 resultSummary.setText("failed");
291 if(sidePanel != null) {
292 // remove it if it's still attached
293 sidePanel.removePropertyChangeListener(changeListener);
297 findMarket.setEnabled(true);
302 frame.add(findMarket);
304 resultSummary = new JLabel("ready");
305 frame.add(resultSummary);
307 arbitrageResult = new JLabel("");
310 layout.setRows(layout.getRows() + 1);
311 frame.add(arbitrageResult);
318 * Finds the island name from the /who tab, sets global islandName variable
320 private void getIsland() {
322 // If the league tracker is there, we can skip the faff
323 // and ask for its tooltip, since we're on a boat
325 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
327 islandName = ((JLabel)leagueTracker).getToolTipText();
328 } catch (NullPointerException e) {
329 // evidently we're actually on an island
332 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
333 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
334 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
335 if(!"com.threerings.piracy.client.AttentionListPanel".
336 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
337 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
339 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
341 sidePanel.addPropertyChangeListener(changeListener);
342 latch = new java.util.concurrent.CountDownLatch(1);
343 // make the Players Online ("/who") panel appear
344 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
345 chat.setTextContents("/w");
346 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
347 for(int i=0;i<c;i++) {
348 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
349 chatArea.getAccessibleAction().doAccessibleAction(i);
353 // if we don't find the island name, hopefully the server will
357 * Find the ocean name from the window title, and set global oceanName variable
359 private void getOcean() {
361 AccessibleContext topwindow = window.getAccessibleContext();
362 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
367 * Shows a dialog with the error <code>msg</code>.
369 * @param msg a String describing the error that occured.
371 private void error(String msg) {
372 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
375 private void error_html(String msg, String html) {
376 //System.err.println("===" + html + "===");
378 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
379 Matcher m = body.matcher(html);
382 Pattern fixup = Pattern.compile("<(\\w+) */>");;
383 m = fixup.matcher(html);
384 html = m.replaceAll("<$1>");
385 m = Pattern.compile("[\\r\\n]+").matcher(html);
386 html = m.replaceAll(" ");
388 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
389 System.err.println("###" + whole_msg + "###");
391 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
395 * Run the data collection process, and upload the results. This is the method
396 * that calls most of the other worker methods for the process. If an error occurs,
397 * the method will call the error method and return early, freeing up the button
398 * to be clicked again.
400 * @exception Exception if an error we didn't expect occured
402 private void runUpload() throws Exception {
403 progresslog("starting");
406 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
407 pm.setMillisToDecideToPopup(0);
408 pm.setMillisToPopup(0);
409 boolean doneyarrg = false, donepctb = false;
412 progresslog("yarrg timestamp...");
413 yarrgts = getYarrgTimestamp();
414 progresslog("yarrg timestamp done.");
417 AccessibleTable accesstable = findMarketTable();
418 if(accesstable == null) {
419 error("Market table not found! Please open the Buy/Sell Commodities interface.");
422 if(accesstable.getAccessibleRowCount() == 0) {
423 error("No data found, please wait for the table to have data first!");
426 if(!isDisplayAll()) {
427 error("Please select \"All\" from the Display: popup menu.");
431 progresslog("getisland...");
433 progresslog("getocean...");
435 progresslog("getocean done");
438 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
441 progresslog("table check...");
443 String headings_expected[] = new String[]
444 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
445 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
446 if (headers.size() != 1) {
447 error("Table headings not one row! " + headers.toString());
450 if (headers.get(0).size() != 6) {
451 error("Table headings not six columns! " + headers.toString());
454 for (int col=0; col<headings_expected.length; col++) {
455 String expd = headings_expected[col];
456 String got = headers.get(0).get(col);
457 if (expd.compareTo(got) != 0) {
458 error("Table heading for column "+col
459 +" is not \""+expd+"\" but \""+got+"\".\n\n"
460 +"Please do not reorder the table when using this tool.");
465 progresslog("table read...");
467 ArrayList<ArrayList<String>> data = getData(accesstable);
470 progresslog("arbitrage...");
471 calculateArbitrage(data);
472 progresslog("arbitrage done.");
475 if (uploadToYarrg && yarrgts != null) {
476 progresslog("yarrg prepare...");
477 progressNote(pm, "Yarrg: Preparing data");
480 StringBuilder yarrgsb = new StringBuilder();
481 String yarrgdata; // string containing what we'll feed to yarrg
483 for (ArrayList<String> row : data) {
484 if (row.size() > 6) {
487 for (String rowitem : row) {
488 yarrgsb.append(rowitem != null ? rowitem : "");
489 yarrgsb.append("\t");
491 yarrgsb.setLength(yarrgsb.length()-1); // chop
492 yarrgsb.append("\n");
495 yarrgdata = yarrgsb.toString();
497 progressNote(pm, "Yarrg: Uploading");
498 progresslog("yarrg upload...");
500 if (islandName != null) {
501 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
503 System.out.println("Couldn't upload to Yarrg - no island name found");
505 progresslog("yarrg done.");
509 progresslog("pctb prepare...");
510 progressNote(pm, "PCTB: Getting stall names");
512 if(pm.isCanceled()) {
515 TreeSet<Offer> buys = new TreeSet<Offer>();
516 TreeSet<Offer> sells = new TreeSet<Offer>();
517 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
519 progressNote(pm, "PCTB: Sorting offers");
520 if(pm.isCanceled()) {
525 HashMap<String,Integer> commodMap = getCommodMap();
526 if(commodMap == null) {
529 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
530 //println(buys.toString());
531 //System.out.println(sells);
532 //System.out.println("\n\n\n"+buys);
534 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
536 progressNote(pm, "PCTB: Sending data");
537 if(pm.isCanceled()) {
540 GZIPOutputStream out = new GZIPOutputStream(outStream);
541 //FileOutputStream out = new FileOutputStream(new File("output.text"));
542 DataOutputStream dos = new DataOutputStream(out);
543 dos.writeBytes("005y\n");
544 dos.writeBytes(stallMap.size()+"\n");
545 dos.writeBytes(getAbbrevStallList(stallMap));
546 writeBuySellOffers(buys,sells,offerCount,out);
548 progresslog("pctb send...");
549 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
550 progresslog("pctb sent.");
551 if (in == null) return;
553 if(pm.isCanceled()) {
556 progressNote(pm, "PCTB: Waiting ...");
557 progresslog("pctb finish...");
558 donepctb = finishUpload(in);
559 progresslog("pctb done.");
563 if ((uploadToPCTB && !donepctb) ||
564 (uploadToYarrg && !doneyarrg)) {
565 resultSummary.setText("trouble");
566 } else if (donepctb || doneyarrg) {
567 resultSummary.setText("Done " + islandName);
569 resultSummary.setText("uploaded nowhere!");
571 progresslog("done.");
575 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
577 * @param table the <code>AccessibleTable</code> containing the market data
578 * @return an array of record arrays, each representing a row of the table
580 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
581 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
582 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
583 ArrayList<String> row = new ArrayList<String>();
584 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
585 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
593 * @return the table containing market data if it exists, otherwise <code>null</code>
595 public AccessibleTable findMarketTable() {
596 Accessible node1 = window;
597 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
598 // 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})
599 //System.out.println(node);
600 if (!(node instanceof JTable)) {
601 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
603 if (!(node instanceof JTable)) return null;
604 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
605 //System.out.println(table);
610 * Utility method to descend through several levels of Accessible children
613 * @param parent the node on which to start the descent
614 * @param path an array of ints, each int being the index of the next
615 * accessible child to descend.
616 * @return the <code>Accessible</code> reached by following the descent path,
617 * or <code>null</code> if the desired path was invalid.
619 private Accessible descendNodes(Accessible parent, int[] path) {
620 for(int i=0;i<path.length;i++) {
621 if (null == (parent = descend(parent, path[i]))) return null;
622 // System.out.println(parent.getClass());
628 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
630 * @param parent the node with children
631 * @param childNum the index of the child of <code>parent</code> to return
632 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
633 * if the child is not found.
635 private Accessible descend(Accessible parent, int childNum) {
636 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
637 return parent.getAccessibleContext().getAccessibleChild(childNum);
640 public static void main(String[] args) {
641 new MarketUploader();
645 * Set the global window variable after the YPP window is created,
646 * remove the top level window listener, and start the GUI
648 public void topLevelWindowCreated(Window w) {
650 EventQueueMonitor.removeTopLevelWindowListener(this);
655 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
657 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
659 private boolean isDisplayAll() {
660 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
661 if(!(button instanceof JButton)) {
662 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
664 String display = button.getAccessibleContext().getAccessibleName();
665 if(!display.equals("All")) {
671 public void topLevelWindowDestroyed(Window w) {}
673 public void guiInitialized() {
678 * Gets the list of commodities and their associated commodity ids.
679 * On the first run, the data is downloaded from the PCTB server.
680 * After the first run, the data is cached using <code>Preferences</code>.
682 * Potential issues: When more commodities are added to the server, this
683 * program will currently break unless the user deletes the preferences
684 * file or we give them a new release with a slighly different storage
685 * location for the data.
687 * @return a map where the key is the commodity and the value is the commodity id.
689 private HashMap<String,Integer> getCommodMap() {
690 if(commodMap != null) {
693 HashMap<String,Integer> map = new HashMap<String,Integer>();
694 Preferences prefs = Preferences.userNodeForPackage(getClass());
697 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
698 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
699 StringBuilder sb = new StringBuilder();
701 while((str = br.readLine()) != null) {
704 int first = sb.indexOf("<pre>") + 5;
705 int last = sb.indexOf("</body>");
706 xml = sb.substring(first,last);
707 //System.out.println(xml);
708 Reader reader = new CharArrayReader(xml.toCharArray());
709 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
710 NodeList maps = d.getElementsByTagName("CommodMap");
711 for(int i=0;i<maps.getLength();i++) {
712 NodeList content = maps.item(i).getChildNodes();
713 Integer num = Integer.parseInt(content.item(1).getTextContent());
714 map.put(content.item(0).getTextContent(),num);
716 } catch(Exception e) {
718 error("Unable to load Commodity list from server!");
726 * Given the list of offers, this method will find all the unique stall names
727 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
728 * and the value is the generated stall id (position in the list).
730 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
731 * for iterating over the stall names in insertion order for output to the server.
733 * @param offers the list of records from the commodity buy/sell interface
734 * @return an iterable ordered map of the stall names and generated stall ids
736 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
738 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
739 for(ArrayList<String> offer : offers) {
740 String shop = offer.get(1);
741 if(!map.containsKey(shop)) {
750 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
751 * should be pre-initialized and passed into the method to receive the data.
752 * Returns a 2-length int array with the number of buys and sells found.
754 * @param offers the data found from the market table in-game
755 * @param buys an empty initialized <code>TreeSet<Offer></code> to
756 * hold the Buy offers.
757 * @param sells an empty initialized <code>TreeSet<Offer></code> to
758 * hold the Sell offers.
759 * @param stalls the map of stalls to their ids
760 * @param commodMap the map of commodities to their ids
761 * @return a 2-length int[] array containing the number of buys and sells, respectively
763 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
764 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
765 int[] buySellCount = new int[2];
766 for(ArrayList<String> offer : offers) {
768 if(offer.get(2) != null) {
769 buys.add(new Buy(offer,stalls,commodMap));
772 if(offer.get(4) != null) {
773 sells.add(new Sell(offer,stalls,commodMap));
776 } catch(IllegalArgumentException e) {
777 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
780 if (buySellCount[0]==0 && buySellCount[1]==0) {
781 error("No (valid) offers for PCTB?!");
782 throw new IllegalArgumentException();
788 * Prepares the list of stalls for writing to the output stream.
789 * The <code>String</code> returned by this method is ready to be written
790 * directly to the stream.
792 * All shoppe names are left as they are. Stall names are abbreviated just before the
793 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
794 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
796 * @param stallMap the map of stalls and stall ids in an iterable order
797 * @return a <code>String</code> containing the list of stalls in format ready
798 * to be written to the output stream.
800 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
801 // set up some mapping
802 HashMap<String,String> types = new HashMap<String,String>();
803 types.put("Apothecary Stall", "A");
804 types.put("Distilling Stall", "D");
805 types.put("Furnishing Stall", "F");
806 types.put("Ironworking Stall", "I");
807 types.put("Shipbuilding Stall", "S");
808 types.put("Tailoring Stall", "T");
809 types.put("Weaving Stall", "W");
811 StringBuilder sb = new StringBuilder();
812 for(String name : stallMap.keySet()) {
813 int index = name.indexOf("'s");
814 String finalName = name;
817 finalName = name.substring(0,index);
818 if(index + 2 < name.length()) {
819 String end = name.substring(index+2,name.length()).trim();
820 type = types.get(end);
824 sb.append(name+"\n");
826 sb.append(finalName+"^"+type+"\n");
829 return sb.toString();
833 * Writes a list of offers in correct format to the output stream.
835 * The format is thus: (all numbers are 2-byte integers in little-endian format)
836 * (number of offers of this type, aka buy/sell)
837 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
839 * @param out the output stream to write the data to
840 * @param offers the offers to write
842 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
843 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
844 if(offers.size() == 0) {
845 // nothing to write, and "0" has already been written
848 int commodity = offers.first().commodity;
850 for(Offer offer : offers) {
851 if(commodity != offer.commodity) {
853 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
855 commodity = offer.commodity;
858 writeLEShort(offer.shoppe,buffer); // stall index
859 writeLEShort(offer.price,buffer); // buy price
860 writeLEShort(offer.quantity,buffer); // buy qty
863 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
867 * Writes the buffered data to the output strea for one commodity.
869 * @param out the stream to write to
870 * @param buffer the buffered data to write
871 * @param commodity the commmodity id to write before the buffered data
872 * @param count the number of offers for this commodity to write before the data
874 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
875 writeLEShort(commodity,out); // commod index
876 writeLEShort(count,out); // offer count
877 out.write(buffer); // the buffered offers
881 * Writes the buy and sell offers to the outputstream by calling other methods.
883 * @param buys list of Buy offers to write
884 * @param sells list of Sell offers to write
885 * @param offerCount 2-length int array containing the number of buys and sells to write out
886 * @param out the stream to write to
888 private void writeBuySellOffers(TreeSet<Offer> buys,
889 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
891 writeLEShort(offerCount[0],out);
892 writeOffers(out,buys);
894 writeLEShort(offerCount[1],out);
895 writeOffers(out,sells);
898 private String readstreamstring(InputStream in) throws IOException {
899 StringBuilder sb = new StringBuilder();
900 BufferedReader br = new BufferedReader(new InputStreamReader(in));
902 while((str = br.readLine()) != null) {
905 return sb.toString();
909 * Sends the data to the server via multipart-formdata POST,
910 * with the gzipped data as a file upload.
912 * @param file an InputStream open to the gzipped data we want to send
914 private InputStream sendInitialData(InputStream file) throws IOException {
915 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
916 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
918 String err = readstreamstring(http.resultstream());
919 error("Error sending initial data:\n"+err);
922 return http.resultstream();
926 * Utility method to write a 2-byte int in little-endian form to an output stream.
928 * @param num an integer to write
929 * @param out stream to write to
931 private void writeLEShort(int num, OutputStream out) throws IOException {
932 out.write(num & 0xFF);
933 out.write((num >>> 8) & 0xFF);
937 * Reads the response from the server, and selects the correct parameters
938 * which are sent in a GET request to the server asking it to confirm
939 * the upload and accept the data into the database. Notably, the island id
940 * and ocean id are determined, while other parameter such as the filename
941 * are determined from the hidden form fields.
943 * @param in stream of data from the server to read
945 private boolean finishUpload(InputStream in) throws IOException {
946 String html = readstreamstring(in);
947 //System.out.println(html);
950 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
951 m = params.matcher(html);
953 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
957 String forceReload = m.group(1);
958 String filename = m.group(2);
960 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
961 m = oceanNumPat.matcher(html);
963 error_html("Unable to find the ocean in the server's list of oceans!", html);
966 String oceanNum = m.group(1);
968 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
969 m = oceanIslandNum.matcher(html);
971 error_html("This does not seem to be a valid island! Unable to upload.", html);
974 String islandNum = m.group(1);
976 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
977 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
978 String complete = readstreamstring(get.openStream());
979 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
980 m = done.matcher(complete);
982 System.out.println("FILE upload successful!!!");
985 error_html("Something was wrong with the final upload parameters!", complete);
990 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
992 String err = readstreamstring(http.resultstream());
993 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
996 return http.resultstream();
999 private String getYarrgTimestamp() throws IOException {
1000 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1001 http.setParameter("clientname", YARRG_CLIENTNAME);
1002 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1003 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1004 http.setParameter("requesttimestamp", "y");
1005 InputStream in = post_for_yarrg(http);
1006 if (in == null) return null;
1007 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1008 String tsresult = br.readLine();
1009 return tsresult.substring(3, tsresult.length()-1);
1012 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
1013 ByteArrayOutputStream bos = new ByteArrayOutputStream();
1014 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
1015 bufos.write(yarrgdata.getBytes() );
1017 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
1019 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
1020 http.setParameter("clientname", YARRG_CLIENTNAME);
1021 http.setParameter("clientversion", YARRG_CLIENTVERSION);
1022 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
1023 http.setParameter("timestamp", timestamp);
1024 http.setParameter("ocean", ocean);
1025 http.setParameter("island", island);
1026 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
1027 InputStream in = post_for_yarrg(http);
1028 if (in == null) return false;
1029 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1031 while((yarrgresult = br.readLine()) != null) {
1032 System.out.println(yarrgresult);
1037 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1038 //System.out.println("ARBITRAGE?");
1040 SortedSet<int[]> buys = arb_bs.get(0);
1041 SortedSet<int[]> sells = arb_bs.get(1);
1045 // NB "sell" means they sell, ie we buy
1046 sell = sells.last();
1048 } catch (NoSuchElementException e) {
1052 int unitprofit = buy[0] - sell[0];
1053 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1054 //System.out.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1055 // +" => x"+count+" @"+unitprofit);
1057 if (unitprofit <= 0)
1060 profit += count * unitprofit;
1063 if (buy[1]==0) buys.remove(buy);
1064 if (sell[1]==0) sells.remove(sell);
1066 //System.out.println(" PROFIT "+profit);
1070 private class arbitrageOfferComparator implements Comparator {
1071 public int compare(Object o1, Object o2) {
1072 int p1 = ((int[])o1)[0];
1073 int p2 = ((int[])o2)[0];
1078 private @SuppressWarnings("unchecked")
1079 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1081 ArrayList<SortedSet<int[]>> arb_bs = null;
1082 String lastcommod = null;
1083 Comparator compar = new arbitrageOfferComparator();
1085 for (ArrayList<String> row : data) {
1086 String thiscommod = row.get(0);
1087 //System.out.println("ROW "+row.toString());
1088 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1089 if (lastcommod != null)
1090 arbitrage += calculateArbitrageCommodity(arb_bs);
1091 //System.out.println("ROW rdy");
1092 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1093 arb_bs.add(0, new TreeSet<int[]>(compar));
1094 arb_bs.add(1, new TreeSet<int[]>(compar));
1095 //System.out.println("ROW init");
1096 lastcommod = thiscommod;
1098 for (int bs = 0; bs < 2; bs++) {
1099 String pricestr = row.get(bs*2 + 2);
1100 if (pricestr == null)
1102 int[] entry = new int[2];
1103 //System.out.println("ROW BS "+bs);
1104 entry[0] = parseQty(pricestr);
1105 entry[1] = parseQty(row.get(bs*2 + 3));
1106 arb_bs.get(bs).add(entry);
1109 arbitrage += calculateArbitrageCommodity(arb_bs);
1110 if (arbitrage != 0) {
1111 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1113 arbitrageResult.setText("no arbitrage");