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;
44 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
45 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
46 private String PCTB_HOST_URL;
48 // Yarrg protocol parameters
49 private final static String YARRG_CLIENTNAME = "jpctb greenend";
50 private final static String YARRG_CLIENTVERSION =
51 com.tedpearson.ypp.market.Version.version;
52 private final static String YARRG_CLIENTFIXES = "bug-094";
53 private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
54 private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
55 private String YARRG_URL;
57 private boolean uploadToYarrg;
58 private boolean uploadToPCTB;
59 private boolean showArbitrage;
61 private String islandName = null;
62 private String oceanName = null;
63 private java.util.concurrent.CountDownLatch latch = null;
65 private AccessibleContext sidePanel;
66 private HashMap<String,Integer> commodMap;
68 private PropertyChangeListener changeListener = new PropertyChangeListener() {
69 public void propertyChange(PropertyChangeEvent e) {
70 if(e.getNewValue() != null &&
71 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
72 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
73 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
74 int index = text.indexOf(":");
75 String name = text.substring(0,index);
77 //System.out.println(islandName);
78 sidePanel.removePropertyChangeListener(this);
84 private int parseQty(String str) {
85 if (str.equals(">1000")) {
88 return Integer.parseInt(str);
92 private void progressNote(ProgressMonitor pm, String s) {
94 if (arbitrageResult != null)
95 arb = arbitrageResult.getText();
96 if (arb != null && arb.length() != 0)
97 s = "<html>" + arb + "<br>" + s;
102 * An abstract market offer, entailing a commodity being bought or sold by
103 * a shoppe, for a certain price in a certain quantity. Not instantiable.
108 abstract class Offer {
109 public int commodity, price, quantity, shoppe;
111 * Create an offer from <code>record</code>, determining the shoppe Id from
112 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
113 * <code>priceIndex</code> should be the index of the price in the record
114 * (the quantity will be <code>priceIndex + 1</code>).
116 * @param record the record with data to create the offer from
117 * @param stallMap a map containing the ids of the various stalls
118 * @param commodMap a map containing the ids of the various commodities
119 * @param priceIndex the index of the price in the record
121 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
123 Integer commodId = commodMap.get(record.get(0));
124 if(commodId == null) {
125 throw new IllegalArgumentException();
127 commodity = commodId.intValue();
128 price = Integer.parseInt(record.get(priceIndex));
129 String qty = record.get(priceIndex+1);
130 quantity = parseQty(qty);
131 shoppe = stallMap.get(record.get(1)).intValue();
135 * Returns a human-readable version of this offer, useful for debugging
137 * @return human-readable offer
139 public String toString() {
140 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
145 * An offer from a shoppe or stall to buy a certain quantity of a commodity
146 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
147 * then by buy price descending, and finally by stall id ascending.
149 class Buy extends Offer implements Comparable<Buy> {
151 * Creates a new <code>Buy</code> offer from the given <code>record</code>
152 * using the other parameters to determine stall id and commodity id of the offer.
154 * @param record the record with data to create the offer from
155 * @param stallMap a map containing the ids of the various stalls
156 * @param commodMap a map containing the ids of the various commodities
158 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
159 super(record,stallMap,commodMap,2);
163 * Sorts by commodity index ascending, then price descending, then stall id ascending.
165 public int compareTo(Buy buy) {
166 // organize by: commodity index, price, stall index
167 if(commodity == buy.commodity) {
168 // organize by price, then by stall index
169 if(price == buy.price) {
170 // organize by stall index
171 return shoppe>buy.shoppe ? 1 : -1;
172 } else if(price > buy.price) {
177 } else if(commodity > buy.commodity) {
186 * An offer from a shoppe or stall to sell a certain quantity of a commodity
187 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
188 * then by sell price ascending, and finally by stall id ascending.
190 class Sell extends Offer implements Comparable<Sell> {
192 * Creates a new <code>Sell</code> offer from the given <code>record</code>
193 * using the other parameters to determine stall id and commodity id of the offer.
195 * @param record the record with data to create the offer from
196 * @param stallMap a map containing the ids of the various stalls
197 * @param commodMap a map containing the ids of the various commodities
199 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
200 super(record,stallMap,commodMap,4);
204 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
206 public int compareTo(Sell sell) {
207 // organize by: commodity index, price, stall index
208 if(commodity == sell.commodity) {
209 // organize by price, then by stall index
210 if(price == sell.price) {
211 // organize by stall index
212 return shoppe>sell.shoppe ? 1 : -1;
213 } else if(price > sell.price) {
218 } else if(commodity > sell.commodity) {
227 * Entry point. Read our preferences.
229 public MarketUploader() {
230 // check if we've been turned off in the control panel
231 Preferences prefs = Preferences.userNodeForPackage(getClass());
233 if (prefs.getBoolean("useLiveServers", false)) {
234 YARRG_URL = YARRG_LIVE_URL;
235 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
237 YARRG_URL = YARRG_TEST_URL;
238 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
241 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
242 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
243 showArbitrage=prefs.getBoolean("showArbitrage", true);
245 EventQueueMonitor.addTopLevelWindowListener(this);
246 if (EventQueueMonitor.isGUIInitialized()) {
249 EventQueueMonitor.addGUIInitializedListener(this);
254 * Set up the GUI, with its window and one-button
255 * interface. Only initialize if we're running alongside
256 * a Window named "Puzzle Pirates" though.
258 private void createGUI() {
259 if (frame != null && window != null) {
260 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
263 frame = new JFrame("Jarrg Uploader");
264 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
265 GridLayout layout = new GridLayout(2,1);
266 frame.getContentPane().setLayout(layout);
267 //frame.setPreferredSize(new Dimension(200, 60));
269 findMarket = new JButton("Upload Market Data");
270 findMarket.addActionListener(new ActionListener() {
271 public void actionPerformed(ActionEvent e) {
272 findMarket.setEnabled(false);
275 resultSummary.setText("");
276 arbitrageResult.setText("");
279 } catch(Exception e) {
282 resultSummary.setText("failed");
284 if(sidePanel != null) {
285 // remove it if it's still attached
286 sidePanel.removePropertyChangeListener(changeListener);
290 findMarket.setEnabled(true);
295 frame.add(findMarket);
297 resultSummary = new JLabel("ready");
298 frame.add(resultSummary);
300 arbitrageResult = new JLabel("");
303 layout.setRows(layout.getRows() + 1);
304 frame.add(arbitrageResult);
311 * Finds the island name from the /who tab, sets global islandName variable
313 private void getIsland() {
315 // If the league tracker is there, we can skip the faff
316 // and ask for its tooltip, since we're on a boat
318 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
320 islandName = ((JLabel)leagueTracker).getToolTipText();
321 } catch (NullPointerException e) {
322 // evidently we're actually on an island
325 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
326 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
327 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
328 if(!"com.threerings.piracy.client.AttentionListPanel".
329 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
330 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
332 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
334 sidePanel.addPropertyChangeListener(changeListener);
335 latch = new java.util.concurrent.CountDownLatch(1);
336 // make the Players Online ("/who") panel appear
337 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
338 chat.setTextContents("/w");
339 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
340 for(int i=0;i<c;i++) {
341 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
342 chatArea.getAccessibleAction().doAccessibleAction(i);
346 // if we don't find the island name, hopefully the server will
350 * Find the ocean name from the window title, and set global oceanName variable
352 private void getOcean() {
354 AccessibleContext topwindow = window.getAccessibleContext();
355 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
360 * Shows a dialog with the error <code>msg</code>.
362 * @param msg a String describing the error that occured.
364 private void error(String msg) {
365 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
368 private void error_html(String msg, String html) {
369 //System.err.println("===" + html + "===");
371 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
372 Matcher m = body.matcher(html);
375 Pattern fixup = Pattern.compile("<(\\w+) */>");;
376 m = fixup.matcher(html);
377 html = m.replaceAll("<$1>");
378 m = Pattern.compile("[\\r\\n]+").matcher(html);
379 html = m.replaceAll(" ");
381 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
382 System.err.println("###" + whole_msg + "###");
384 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
388 * Run the data collection process, and upload the results. This is the method
389 * that calls most of the other worker methods for the process. If an error occurs,
390 * the method will call the error method and return early, freeing up the button
391 * to be clicked again.
393 * @exception Exception if an error we didn't expect occured
395 private void runPCTB() throws Exception {
397 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
398 pm.setMillisToDecideToPopup(0);
399 pm.setMillisToPopup(0);
400 boolean doneyarrg = false, donepctb = false;
403 yarrgts = getYarrgTimestamp();
406 AccessibleTable accesstable = findMarketTable();
407 if(accesstable == null) {
408 error("Market table not found! Please open the Buy/Sell Commodities interface.");
411 if(accesstable.getAccessibleRowCount() == 0) {
412 error("No data found, please wait for the table to have data first!");
415 if(!isDisplayAll()) {
416 error("Please select \"All\" from the Display: popup menu.");
424 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
427 String headings_expected[] = new String[]
428 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
429 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
430 if (headers.size() != 1) {
431 error("Table headings not one row! " + headers.toString());
434 if (headers.get(0).size() != 6) {
435 error("Table headings not six columns! " + headers.toString());
438 for (int col=0; col<headings_expected.length; col++) {
439 String expd = headings_expected[col];
440 String got = headers.get(0).get(col);
441 if (expd.compareTo(got) != 0) {
442 error("Table heading for column "+col
443 +" is not \""+expd+"\" but \""+got+"\".\n\n"
444 +"Please do not reorder the table when using this tool.");
449 ArrayList<ArrayList<String>> data = getData(accesstable);
452 calculateArbitrage(data);
455 if (uploadToYarrg && yarrgts != null) {
456 progressNote(pm, "Yarrg: Preparing data");
459 StringBuilder yarrgsb = new StringBuilder();
460 String yarrgdata; // string containing what we'll feed to yarrg
462 for (ArrayList<String> row : data) {
463 if (row.size() > 6) {
466 for (String rowitem : row) {
467 yarrgsb.append(rowitem != null ? rowitem : "");
468 yarrgsb.append("\t");
470 yarrgsb.setLength(yarrgsb.length()-1); // chop
471 yarrgsb.append("\n");
474 yarrgdata = yarrgsb.toString();
476 progressNote(pm, "Yarrg: Uploading");
478 if (islandName != null) {
479 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
481 System.out.println("Couldn't upload to Yarrg - no island name found");
486 progressNote(pm, "PCTB: Getting stall names");
488 if(pm.isCanceled()) {
491 TreeSet<Offer> buys = new TreeSet<Offer>();
492 TreeSet<Offer> sells = new TreeSet<Offer>();
493 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
495 progressNote(pm, "PCTB: Sorting offers");
496 if(pm.isCanceled()) {
501 HashMap<String,Integer> commodMap = getCommodMap();
502 if(commodMap == null) {
505 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
506 //println(buys.toString());
507 //System.out.println(sells);
508 //System.out.println("\n\n\n"+buys);
510 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
512 progressNote(pm, "PCTB: Sending data");
513 if(pm.isCanceled()) {
516 GZIPOutputStream out = new GZIPOutputStream(outStream);
517 //FileOutputStream out = new FileOutputStream(new File("output.text"));
518 DataOutputStream dos = new DataOutputStream(out);
519 dos.writeBytes("005y\n");
520 dos.writeBytes(stallMap.size()+"\n");
521 dos.writeBytes(getAbbrevStallList(stallMap));
522 writeBuySellOffers(buys,sells,offerCount,out);
524 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
525 if (in == null) return;
527 if(pm.isCanceled()) {
530 progressNote(pm, "PCTB: Waiting ...");
531 donepctb = finishUpload(in);
535 if ((uploadToPCTB && !donepctb) ||
536 (uploadToYarrg && !doneyarrg)) {
537 resultSummary.setText("trouble");
538 } else if (donepctb || doneyarrg) {
539 resultSummary.setText("Done " + islandName);
541 resultSummary.setText("uploaded nowhere!");
546 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
548 * @param table the <code>AccessibleTable</code> containing the market data
549 * @return an array of record arrays, each representing a row of the table
551 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
552 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
553 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
554 ArrayList<String> row = new ArrayList<String>();
555 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
556 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
564 * @return the table containing market data if it exists, otherwise <code>null</code>
566 public AccessibleTable findMarketTable() {
567 Accessible node1 = window;
568 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
569 // 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})
570 //System.out.println(node);
571 if (!(node instanceof JTable)) {
572 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
574 if (!(node instanceof JTable)) return null;
575 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
576 //System.out.println(table);
581 * Utility method to descend through several levels of Accessible children
584 * @param parent the node on which to start the descent
585 * @param path an array of ints, each int being the index of the next
586 * accessible child to descend.
587 * @return the <code>Accessible</code> reached by following the descent path,
588 * or <code>null</code> if the desired path was invalid.
590 private Accessible descendNodes(Accessible parent, int[] path) {
591 for(int i=0;i<path.length;i++) {
592 if (null == (parent = descend(parent, path[i]))) return null;
593 // System.out.println(parent.getClass());
599 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
601 * @param parent the node with children
602 * @param childNum the index of the child of <code>parent</code> to return
603 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
604 * if the child is not found.
606 private Accessible descend(Accessible parent, int childNum) {
607 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
608 return parent.getAccessibleContext().getAccessibleChild(childNum);
611 public static void main(String[] args) {
612 new MarketUploader();
616 * Set the global window variable after the YPP window is created,
617 * remove the top level window listener, and start the GUI
619 public void topLevelWindowCreated(Window w) {
621 EventQueueMonitor.removeTopLevelWindowListener(this);
626 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
628 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
630 private boolean isDisplayAll() {
631 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
632 if(!(button instanceof JButton)) {
633 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
635 String display = button.getAccessibleContext().getAccessibleName();
636 if(!display.equals("All")) {
642 public void topLevelWindowDestroyed(Window w) {}
644 public void guiInitialized() {
649 * Gets the list of commodities and their associated commodity ids.
650 * On the first run, the data is downloaded from the PCTB server.
651 * After the first run, the data is cached using <code>Preferences</code>.
653 * Potential issues: When more commodities are added to the server, this
654 * program will currently break unless the user deletes the preferences
655 * file or we give them a new release with a slighly different storage
656 * location for the data.
658 * @return a map where the key is the commodity and the value is the commodity id.
660 private HashMap<String,Integer> getCommodMap() {
661 if(commodMap != null) {
664 HashMap<String,Integer> map = new HashMap<String,Integer>();
665 Preferences prefs = Preferences.userNodeForPackage(getClass());
668 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
669 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
670 StringBuilder sb = new StringBuilder();
672 while((str = br.readLine()) != null) {
675 int first = sb.indexOf("<pre>") + 5;
676 int last = sb.indexOf("</body>");
677 xml = sb.substring(first,last);
678 //System.out.println(xml);
679 Reader reader = new CharArrayReader(xml.toCharArray());
680 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
681 NodeList maps = d.getElementsByTagName("CommodMap");
682 for(int i=0;i<maps.getLength();i++) {
683 NodeList content = maps.item(i).getChildNodes();
684 Integer num = Integer.parseInt(content.item(1).getTextContent());
685 map.put(content.item(0).getTextContent(),num);
687 } catch(Exception e) {
689 error("Unable to load Commodity list from server!");
697 * Given the list of offers, this method will find all the unique stall names
698 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
699 * and the value is the generated stall id (position in the list).
701 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
702 * for iterating over the stall names in insertion order for output to the server.
704 * @param offers the list of records from the commodity buy/sell interface
705 * @return an iterable ordered map of the stall names and generated stall ids
707 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
709 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
710 for(ArrayList<String> offer : offers) {
711 String shop = offer.get(1);
712 if(!map.containsKey(shop)) {
721 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
722 * should be pre-initialized and passed into the method to receive the data.
723 * Returns a 2-length int array with the number of buys and sells found.
725 * @param offers the data found from the market table in-game
726 * @param buys an empty initialized <code>TreeSet<Offer></code> to
727 * hold the Buy offers.
728 * @param sells an empty initialized <code>TreeSet<Offer></code> to
729 * hold the Sell offers.
730 * @param stalls the map of stalls to their ids
731 * @param commodMap the map of commodities to their ids
732 * @return a 2-length int[] array containing the number of buys and sells, respectively
734 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
735 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
736 int[] buySellCount = new int[2];
737 for(ArrayList<String> offer : offers) {
739 if(offer.get(2) != null) {
740 buys.add(new Buy(offer,stalls,commodMap));
743 if(offer.get(4) != null) {
744 sells.add(new Sell(offer,stalls,commodMap));
747 } catch(IllegalArgumentException e) {
748 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
751 if (buySellCount[0]==0 && buySellCount[1]==0) {
752 error("No (valid) offers for PCTB?!");
753 throw new IllegalArgumentException();
759 * Prepares the list of stalls for writing to the output stream.
760 * The <code>String</code> returned by this method is ready to be written
761 * directly to the stream.
763 * All shoppe names are left as they are. Stall names are abbreviated just before the
764 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
765 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
767 * @param stallMap the map of stalls and stall ids in an iterable order
768 * @return a <code>String</code> containing the list of stalls in format ready
769 * to be written to the output stream.
771 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
772 // set up some mapping
773 HashMap<String,String> types = new HashMap<String,String>();
774 types.put("Apothecary Stall", "A");
775 types.put("Distilling Stall", "D");
776 types.put("Furnishing Stall", "F");
777 types.put("Ironworking Stall", "I");
778 types.put("Shipbuilding Stall", "S");
779 types.put("Tailoring Stall", "T");
780 types.put("Weaving Stall", "W");
782 StringBuilder sb = new StringBuilder();
783 for(String name : stallMap.keySet()) {
784 int index = name.indexOf("'s");
785 String finalName = name;
788 finalName = name.substring(0,index);
789 if(index + 2 < name.length()) {
790 String end = name.substring(index+2,name.length()).trim();
791 type = types.get(end);
795 sb.append(name+"\n");
797 sb.append(finalName+"^"+type+"\n");
800 return sb.toString();
804 * Writes a list of offers in correct format to the output stream.
806 * The format is thus: (all numbers are 2-byte integers in little-endian format)
807 * (number of offers of this type, aka buy/sell)
808 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
810 * @param out the output stream to write the data to
811 * @param offers the offers to write
813 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
814 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
815 if(offers.size() == 0) {
816 // nothing to write, and "0" has already been written
819 int commodity = offers.first().commodity;
821 for(Offer offer : offers) {
822 if(commodity != offer.commodity) {
824 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
826 commodity = offer.commodity;
829 writeLEShort(offer.shoppe,buffer); // stall index
830 writeLEShort(offer.price,buffer); // buy price
831 writeLEShort(offer.quantity,buffer); // buy qty
834 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
838 * Writes the buffered data to the output strea for one commodity.
840 * @param out the stream to write to
841 * @param buffer the buffered data to write
842 * @param commodity the commmodity id to write before the buffered data
843 * @param count the number of offers for this commodity to write before the data
845 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
846 writeLEShort(commodity,out); // commod index
847 writeLEShort(count,out); // offer count
848 out.write(buffer); // the buffered offers
852 * Writes the buy and sell offers to the outputstream by calling other methods.
854 * @param buys list of Buy offers to write
855 * @param sells list of Sell offers to write
856 * @param offerCount 2-length int array containing the number of buys and sells to write out
857 * @param out the stream to write to
859 private void writeBuySellOffers(TreeSet<Offer> buys,
860 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
862 writeLEShort(offerCount[0],out);
863 writeOffers(out,buys);
865 writeLEShort(offerCount[1],out);
866 writeOffers(out,sells);
869 private String readstreamstring(InputStream in) throws IOException {
870 StringBuilder sb = new StringBuilder();
871 BufferedReader br = new BufferedReader(new InputStreamReader(in));
873 while((str = br.readLine()) != null) {
876 return sb.toString();
880 * Sends the data to the server via multipart-formdata POST,
881 * with the gzipped data as a file upload.
883 * @param file an InputStream open to the gzipped data we want to send
885 private InputStream sendInitialData(InputStream file) throws IOException {
886 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
887 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
889 String err = readstreamstring(http.resultstream());
890 error("Error sending initial data:\n"+err);
893 return http.resultstream();
897 * Utility method to write a 2-byte int in little-endian form to an output stream.
899 * @param num an integer to write
900 * @param out stream to write to
902 private void writeLEShort(int num, OutputStream out) throws IOException {
903 out.write(num & 0xFF);
904 out.write((num >>> 8) & 0xFF);
908 * Reads the response from the server, and selects the correct parameters
909 * which are sent in a GET request to the server asking it to confirm
910 * the upload and accept the data into the database. Notably, the island id
911 * and ocean id are determined, while other parameter such as the filename
912 * are determined from the hidden form fields.
914 * @param in stream of data from the server to read
916 private boolean finishUpload(InputStream in) throws IOException {
917 String html = readstreamstring(in);
918 //System.out.println(html);
921 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
922 m = params.matcher(html);
924 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
928 String forceReload = m.group(1);
929 String filename = m.group(2);
931 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
932 m = oceanNumPat.matcher(html);
934 error_html("Unable to find the ocean in the server's list of oceans!", html);
937 String oceanNum = m.group(1);
939 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
940 m = oceanIslandNum.matcher(html);
942 error_html("This does not seem to be a valid island! Unable to upload.", html);
945 String islandNum = m.group(1);
947 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
948 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
949 String complete = readstreamstring(get.openStream());
950 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
951 m = done.matcher(complete);
953 System.out.println("FILE upload successful!!!");
956 error_html("Something was wrong with the final upload parameters!", complete);
961 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
963 String err = readstreamstring(http.resultstream());
964 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
967 return http.resultstream();
970 private String getYarrgTimestamp() throws IOException {
971 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
972 http.setParameter("clientname", YARRG_CLIENTNAME);
973 http.setParameter("clientversion", YARRG_CLIENTVERSION);
974 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
975 http.setParameter("requesttimestamp", "y");
976 InputStream in = post_for_yarrg(http);
977 if (in == null) return null;
978 BufferedReader br = new BufferedReader(new InputStreamReader(in));
979 String tsresult = br.readLine();
980 return tsresult.substring(3, tsresult.length()-1);
983 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
984 ByteArrayOutputStream bos = new ByteArrayOutputStream();
985 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
986 bufos.write(yarrgdata.getBytes() );
988 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
990 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
991 http.setParameter("clientname", YARRG_CLIENTNAME);
992 http.setParameter("clientversion", YARRG_CLIENTVERSION);
993 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
994 http.setParameter("timestamp", timestamp);
995 http.setParameter("ocean", ocean);
996 http.setParameter("island", island);
997 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
998 InputStream in = post_for_yarrg(http);
999 if (in == null) return false;
1000 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1002 while((yarrgresult = br.readLine()) != null) {
1003 System.out.println(yarrgresult);
1008 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
1009 //System.out.println("ARBITRAGE?");
1011 SortedSet<int[]> buys = arb_bs.get(0);
1012 SortedSet<int[]> sells = arb_bs.get(1);
1016 // NB "sell" means they sell, ie we buy
1017 sell = sells.last();
1019 } catch (NoSuchElementException e) {
1023 int unitprofit = buy[0] - sell[0];
1024 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1025 //System.out.println(" sell @"+sell[0]+" x"+sell[1]+" buy @"+buy[0]+" x"+buy[1]
1026 // +" => x"+count+" @"+unitprofit);
1028 if (unitprofit <= 0)
1031 profit += count * unitprofit;
1034 if (buy[1]==0) buys.remove(buy);
1035 if (sell[1]==0) sells.remove(sell);
1037 //System.out.println(" PROFIT "+profit);
1041 private class arbitrageOfferComparator implements Comparator {
1042 public int compare(Object o1, Object o2) {
1043 int p1 = ((int[])o1)[0];
1044 int p2 = ((int[])o2)[0];
1049 private @SuppressWarnings("unchecked")
1050 void calculateArbitrage(ArrayList<ArrayList<String>> data) {
1052 ArrayList<SortedSet<int[]>> arb_bs = null;
1053 String lastcommod = null;
1054 Comparator compar = new arbitrageOfferComparator();
1056 for (ArrayList<String> row : data) {
1057 String thiscommod = row.get(0);
1058 //System.out.println("ROW "+row.toString());
1059 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1060 if (lastcommod != null)
1061 arbitrage += calculateArbitrageCommodity(arb_bs);
1062 //System.out.println("ROW rdy");
1063 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1064 arb_bs.add(0, new TreeSet<int[]>(compar));
1065 arb_bs.add(1, new TreeSet<int[]>(compar));
1066 //System.out.println("ROW init");
1067 lastcommod = thiscommod;
1069 for (int bs = 0; bs < 2; bs++) {
1070 String pricestr = row.get(bs*2 + 2);
1071 if (pricestr == null)
1073 int[] entry = new int[2];
1074 //System.out.println("ROW BS "+bs);
1075 entry[0] = parseQty(pricestr);
1076 entry[1] = parseQty(row.get(bs*2 + 3));
1077 arb_bs.get(bs).add(entry);
1080 arbitrage += calculateArbitrageCommodity(arb_bs);
1081 if (arbitrage != 0) {
1082 arbitrageResult.setText("<html><strong>arbitrage: "+arbitrage+" poe</strong>");
1084 arbitrageResult.setText("no arbitrage");