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;
43 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
44 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
45 private String PCTB_HOST_URL;
47 // Yarrg protocol parameters
48 private final static String YARRG_CLIENTNAME = "jpctb greenend";
49 private final static String YARRG_CLIENTVERSION =
50 com.tedpearson.ypp.market.Version.version;
51 private final static String YARRG_CLIENTFIXES = "bug-094";
52 private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
53 private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
54 private String YARRG_URL;
56 private boolean uploadToYarrg;
57 private boolean uploadToPCTB;
59 private String islandName = null;
60 private String oceanName = null;
61 private java.util.concurrent.CountDownLatch latch = null;
63 private AccessibleContext sidePanel;
64 private HashMap<String,Integer> commodMap;
66 private PropertyChangeListener changeListener = new PropertyChangeListener() {
67 public void propertyChange(PropertyChangeEvent e) {
68 if(e.getNewValue() != null &&
69 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
70 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
71 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
72 int index = text.indexOf(":");
73 String name = text.substring(0,index);
75 //System.out.println(islandName);
76 sidePanel.removePropertyChangeListener(this);
82 private int parseQty(String str) {
83 if (str.equals(">1000")) {
86 return Integer.parseInt(str);
91 * An abstract market offer, entailing a commodity being bought or sold by
92 * a shoppe, for a certain price in a certain quantity. Not instantiable.
97 abstract class Offer {
98 public int commodity, price, quantity, shoppe;
100 * Create an offer from <code>record</code>, determining the shoppe Id from
101 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
102 * <code>priceIndex</code> should be the index of the price in the record
103 * (the quantity will be <code>priceIndex + 1</code>).
105 * @param record the record with data to create the offer from
106 * @param stallMap a map containing the ids of the various stalls
107 * @param commodMap a map containing the ids of the various commodities
108 * @param priceIndex the index of the price in the record
110 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
112 Integer commodId = commodMap.get(record.get(0));
113 if(commodId == null) {
114 throw new IllegalArgumentException();
116 commodity = commodId.intValue();
117 price = Integer.parseInt(record.get(priceIndex));
118 String qty = record.get(priceIndex+1);
119 quantity = parseQty(qty);
120 shoppe = stallMap.get(record.get(1)).intValue();
124 * Returns a human-readable version of this offer, useful for debugging
126 * @return human-readable offer
128 public String toString() {
129 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
134 * An offer from a shoppe or stall to buy a certain quantity of a commodity
135 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
136 * then by buy price descending, and finally by stall id ascending.
138 class Buy extends Offer implements Comparable<Buy> {
140 * Creates a new <code>Buy</code> offer from the given <code>record</code>
141 * using the other parameters to determine stall id and commodity id of the offer.
143 * @param record the record with data to create the offer from
144 * @param stallMap a map containing the ids of the various stalls
145 * @param commodMap a map containing the ids of the various commodities
147 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
148 super(record,stallMap,commodMap,2);
152 * Sorts by commodity index ascending, then price descending, then stall id ascending.
154 public int compareTo(Buy buy) {
155 // organize by: commodity index, price, stall index
156 if(commodity == buy.commodity) {
157 // organize by price, then by stall index
158 if(price == buy.price) {
159 // organize by stall index
160 return shoppe>buy.shoppe ? 1 : -1;
161 } else if(price > buy.price) {
166 } else if(commodity > buy.commodity) {
175 * An offer from a shoppe or stall to sell a certain quantity of a commodity
176 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
177 * then by sell price ascending, and finally by stall id ascending.
179 class Sell extends Offer implements Comparable<Sell> {
181 * Creates a new <code>Sell</code> offer from the given <code>record</code>
182 * using the other parameters to determine stall id and commodity id of the offer.
184 * @param record the record with data to create the offer from
185 * @param stallMap a map containing the ids of the various stalls
186 * @param commodMap a map containing the ids of the various commodities
188 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
189 super(record,stallMap,commodMap,4);
193 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
195 public int compareTo(Sell sell) {
196 // organize by: commodity index, price, stall index
197 if(commodity == sell.commodity) {
198 // organize by price, then by stall index
199 if(price == sell.price) {
200 // organize by stall index
201 return shoppe>sell.shoppe ? 1 : -1;
202 } else if(price > sell.price) {
207 } else if(commodity > sell.commodity) {
216 * Entry point. Read our preferences.
218 public MarketUploader() {
219 // check if we've been turned off in the control panel
220 Preferences prefs = Preferences.userNodeForPackage(getClass());
222 if (prefs.getBoolean("useLiveServers", false)) {
223 YARRG_URL = YARRG_LIVE_URL;
224 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
226 YARRG_URL = YARRG_TEST_URL;
227 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
230 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
231 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
233 EventQueueMonitor.addTopLevelWindowListener(this);
234 if (EventQueueMonitor.isGUIInitialized()) {
237 EventQueueMonitor.addGUIInitializedListener(this);
242 * Set up the GUI, with its window and one-button
243 * interface. Only initialize if we're running alongside
244 * a Window named "Puzzle Pirates" though.
246 private void createGUI() {
247 if (frame != null && window != null) {
248 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
251 frame = new JFrame("MarketUploader");
252 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
253 frame.getContentPane().setLayout(new GridLayout(2,1));
254 //frame.setPreferredSize(new Dimension(200, 60));
256 findMarket = new JButton("Upload Market Data");
257 findMarket.addActionListener(new ActionListener() {
258 public void actionPerformed(ActionEvent e) {
259 findMarket.setEnabled(false);
262 resultSummary.setText("");
265 } catch(Exception e) {
268 resultSummary.setText("failed");
270 if(sidePanel != null) {
271 // remove it if it's still attached
272 sidePanel.removePropertyChangeListener(changeListener);
276 findMarket.setEnabled(true);
281 frame.add(findMarket);
283 resultSummary = new JLabel("ready");
284 frame.add(resultSummary);
290 * Finds the island name from the /who tab, sets global islandName variable
292 private void getIsland() {
294 // If the league tracker is there, we can skip the faff
295 // and ask for its tooltip, since we're on a boat
297 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
299 islandName = ((JLabel)leagueTracker).getToolTipText();
300 } catch (NullPointerException e) {
301 // evidently we're actually on an island
304 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
305 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
306 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
307 if(!"com.threerings.piracy.client.AttentionListPanel".
308 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
309 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
311 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
313 sidePanel.addPropertyChangeListener(changeListener);
314 latch = new java.util.concurrent.CountDownLatch(1);
315 // make the Players Online ("/who") panel appear
316 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
317 chat.setTextContents("/w");
318 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
319 for(int i=0;i<c;i++) {
320 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
321 chatArea.getAccessibleAction().doAccessibleAction(i);
325 // if we don't find the island name, hopefully the server will
329 * Find the ocean name from the window title, and set global oceanName variable
331 private void getOcean() {
333 AccessibleContext topwindow = window.getAccessibleContext();
334 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
339 * Shows a dialog with the error <code>msg</code>.
341 * @param msg a String describing the error that occured.
343 private void error(String msg) {
344 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
347 private void error_html(String msg, String html) {
348 //System.err.println("===" + html + "===");
350 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
351 Matcher m = body.matcher(html);
354 Pattern fixup = Pattern.compile("<(\\w+) */>");;
355 m = fixup.matcher(html);
356 html = m.replaceAll("<$1>");
357 m = Pattern.compile("[\\r\\n]+").matcher(html);
358 html = m.replaceAll(" ");
360 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
361 System.err.println("###" + whole_msg + "###");
363 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
367 * Run the data collection process, and upload the results. This is the method
368 * that calls most of the other worker methods for the process. If an error occurs,
369 * the method will call the error method and return early, freeing up the button
370 * to be clicked again.
372 * @exception Exception if an error we didn't expect occured
374 private void runPCTB() throws Exception {
376 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
377 pm.setMillisToDecideToPopup(0);
378 pm.setMillisToPopup(0);
379 boolean doneyarrg = false, donepctb = false;
382 yarrgts = getYarrgTimestamp();
385 AccessibleTable accesstable = findMarketTable();
386 if(accesstable == null) {
387 error("Market table not found! Please open the Buy/Sell Commodities interface.");
390 if(accesstable.getAccessibleRowCount() == 0) {
391 error("No data found, please wait for the table to have data first!");
394 if(!isDisplayAll()) {
395 error("Please select \"All\" from the Display: popup menu.");
403 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
406 String headings_expected[] = new String[]
407 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
408 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
409 if (headers.size() != 1) {
410 error("Table headings not one row! " + headers.toString());
413 if (headers.get(0).size() != 6) {
414 error("Table headings not six columns! " + headers.toString());
417 for (int col=0; col<headings_expected.length; col++) {
418 String expd = headings_expected[col];
419 String got = headers.get(0).get(col);
420 if (expd.compareTo(got) != 0) {
421 error("Table heading for column "+col
422 +" is not \""+expd+"\" but \""+got+"\".\n\n"
423 +"Please do not reorder the table when using this tool.");
428 ArrayList<ArrayList<String>> data = getData(accesstable);
431 calculateArbitrage(data);
434 if (uploadToYarrg && yarrgts != null) {
435 pm.setNote("Yarrg: Preparing data");
438 StringBuilder yarrgsb = new StringBuilder();
439 String yarrgdata; // string containing what we'll feed to yarrg
441 for (ArrayList<String> row : data) {
442 if (row.size() > 6) {
445 for (String rowitem : row) {
446 yarrgsb.append(rowitem != null ? rowitem : "");
447 yarrgsb.append("\t");
449 yarrgsb.setLength(yarrgsb.length()-1); // chop
450 yarrgsb.append("\n");
453 yarrgdata = yarrgsb.toString();
455 pm.setNote("Yarrg: Uploading");
457 if (islandName != null) {
458 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
460 System.out.println("Couldn't upload to Yarrg - no island name found");
465 pm.setNote("PCTB: Getting stall names");
467 if(pm.isCanceled()) {
470 TreeSet<Offer> buys = new TreeSet<Offer>();
471 TreeSet<Offer> sells = new TreeSet<Offer>();
472 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
474 pm.setNote("PCTB: Sorting offers");
475 if(pm.isCanceled()) {
480 HashMap<String,Integer> commodMap = getCommodMap();
481 if(commodMap == null) {
484 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
485 //println(buys.toString());
486 //System.out.println(sells);
487 //System.out.println("\n\n\n"+buys);
489 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
491 pm.setNote("PCTB: Sending data");
492 if(pm.isCanceled()) {
495 GZIPOutputStream out = new GZIPOutputStream(outStream);
496 //FileOutputStream out = new FileOutputStream(new File("output.text"));
497 DataOutputStream dos = new DataOutputStream(out);
498 dos.writeBytes("005y\n");
499 dos.writeBytes(stallMap.size()+"\n");
500 dos.writeBytes(getAbbrevStallList(stallMap));
501 writeBuySellOffers(buys,sells,offerCount,out);
503 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
504 if (in == null) return;
506 if(pm.isCanceled()) {
509 pm.setNote("PCTB: Waiting ...");
510 donepctb = finishUpload(in);
514 if ((uploadToPCTB && !donepctb) ||
515 (uploadToYarrg && !doneyarrg)) {
516 resultSummary.setText("trouble");
517 } else if (donepctb || doneyarrg) {
518 resultSummary.setText("Done " + islandName);
520 resultSummary.setText("uploaded nowhere!");
525 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
527 * @param table the <code>AccessibleTable</code> containing the market data
528 * @return an array of record arrays, each representing a row of the table
530 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
531 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
532 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
533 ArrayList<String> row = new ArrayList<String>();
534 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
535 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
543 * @return the table containing market data if it exists, otherwise <code>null</code>
545 public AccessibleTable findMarketTable() {
546 Accessible node1 = window;
547 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
548 // 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})
549 //System.out.println(node);
550 if (!(node instanceof JTable)) {
551 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
553 if (!(node instanceof JTable)) return null;
554 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
555 //System.out.println(table);
560 * Utility method to descend through several levels of Accessible children
563 * @param parent the node on which to start the descent
564 * @param path an array of ints, each int being the index of the next
565 * accessible child to descend.
566 * @return the <code>Accessible</code> reached by following the descent path,
567 * or <code>null</code> if the desired path was invalid.
569 private Accessible descendNodes(Accessible parent, int[] path) {
570 for(int i=0;i<path.length;i++) {
571 if (null == (parent = descend(parent, path[i]))) return null;
572 // System.out.println(parent.getClass());
578 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
580 * @param parent the node with children
581 * @param childNum the index of the child of <code>parent</code> to return
582 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
583 * if the child is not found.
585 private Accessible descend(Accessible parent, int childNum) {
586 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
587 return parent.getAccessibleContext().getAccessibleChild(childNum);
590 public static void main(String[] args) {
591 new MarketUploader();
595 * Set the global window variable after the YPP window is created,
596 * remove the top level window listener, and start the GUI
598 public void topLevelWindowCreated(Window w) {
600 EventQueueMonitor.removeTopLevelWindowListener(this);
605 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
607 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
609 private boolean isDisplayAll() {
610 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
611 if(!(button instanceof JButton)) {
612 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
614 String display = button.getAccessibleContext().getAccessibleName();
615 if(!display.equals("All")) {
621 public void topLevelWindowDestroyed(Window w) {}
623 public void guiInitialized() {
628 * Gets the list of commodities and their associated commodity ids.
629 * On the first run, the data is downloaded from the PCTB server.
630 * After the first run, the data is cached using <code>Preferences</code>.
632 * Potential issues: When more commodities are added to the server, this
633 * program will currently break unless the user deletes the preferences
634 * file or we give them a new release with a slighly different storage
635 * location for the data.
637 * @return a map where the key is the commodity and the value is the commodity id.
639 private HashMap<String,Integer> getCommodMap() {
640 if(commodMap != null) {
643 HashMap<String,Integer> map = new HashMap<String,Integer>();
644 Preferences prefs = Preferences.userNodeForPackage(getClass());
647 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
648 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
649 StringBuilder sb = new StringBuilder();
651 while((str = br.readLine()) != null) {
654 int first = sb.indexOf("<pre>") + 5;
655 int last = sb.indexOf("</body>");
656 xml = sb.substring(first,last);
657 //System.out.println(xml);
658 Reader reader = new CharArrayReader(xml.toCharArray());
659 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
660 NodeList maps = d.getElementsByTagName("CommodMap");
661 for(int i=0;i<maps.getLength();i++) {
662 NodeList content = maps.item(i).getChildNodes();
663 Integer num = Integer.parseInt(content.item(1).getTextContent());
664 map.put(content.item(0).getTextContent(),num);
666 } catch(Exception e) {
668 error("Unable to load Commodity list from server!");
676 * Given the list of offers, this method will find all the unique stall names
677 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
678 * and the value is the generated stall id (position in the list).
680 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
681 * for iterating over the stall names in insertion order for output to the server.
683 * @param offers the list of records from the commodity buy/sell interface
684 * @return an iterable ordered map of the stall names and generated stall ids
686 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
688 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
689 for(ArrayList<String> offer : offers) {
690 String shop = offer.get(1);
691 if(!map.containsKey(shop)) {
700 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
701 * should be pre-initialized and passed into the method to receive the data.
702 * Returns a 2-length int array with the number of buys and sells found.
704 * @param offers the data found from the market table in-game
705 * @param buys an empty initialized <code>TreeSet<Offer></code> to
706 * hold the Buy offers.
707 * @param sells an empty initialized <code>TreeSet<Offer></code> to
708 * hold the Sell offers.
709 * @param stalls the map of stalls to their ids
710 * @param commodMap the map of commodities to their ids
711 * @return a 2-length int[] array containing the number of buys and sells, respectively
713 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
714 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
715 int[] buySellCount = new int[2];
716 for(ArrayList<String> offer : offers) {
718 if(offer.get(2) != null) {
719 buys.add(new Buy(offer,stalls,commodMap));
722 if(offer.get(4) != null) {
723 sells.add(new Sell(offer,stalls,commodMap));
726 } catch(IllegalArgumentException e) {
727 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
730 if (buySellCount[0]==0 && buySellCount[1]==0) {
731 error("No (valid) offers for PCTB?!");
732 throw new IllegalArgumentException();
738 * Prepares the list of stalls for writing to the output stream.
739 * The <code>String</code> returned by this method is ready to be written
740 * directly to the stream.
742 * All shoppe names are left as they are. Stall names are abbreviated just before the
743 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
744 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
746 * @param stallMap the map of stalls and stall ids in an iterable order
747 * @return a <code>String</code> containing the list of stalls in format ready
748 * to be written to the output stream.
750 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
751 // set up some mapping
752 HashMap<String,String> types = new HashMap<String,String>();
753 types.put("Apothecary Stall", "A");
754 types.put("Distilling Stall", "D");
755 types.put("Furnishing Stall", "F");
756 types.put("Ironworking Stall", "I");
757 types.put("Shipbuilding Stall", "S");
758 types.put("Tailoring Stall", "T");
759 types.put("Weaving Stall", "W");
761 StringBuilder sb = new StringBuilder();
762 for(String name : stallMap.keySet()) {
763 int index = name.indexOf("'s");
764 String finalName = name;
767 finalName = name.substring(0,index);
768 if(index + 2 < name.length()) {
769 String end = name.substring(index+2,name.length()).trim();
770 type = types.get(end);
774 sb.append(name+"\n");
776 sb.append(finalName+"^"+type+"\n");
779 return sb.toString();
783 * Writes a list of offers in correct format to the output stream.
785 * The format is thus: (all numbers are 2-byte integers in little-endian format)
786 * (number of offers of this type, aka buy/sell)
787 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
789 * @param out the output stream to write the data to
790 * @param offers the offers to write
792 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
793 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
794 if(offers.size() == 0) {
795 // nothing to write, and "0" has already been written
798 int commodity = offers.first().commodity;
800 for(Offer offer : offers) {
801 if(commodity != offer.commodity) {
803 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
805 commodity = offer.commodity;
808 writeLEShort(offer.shoppe,buffer); // stall index
809 writeLEShort(offer.price,buffer); // buy price
810 writeLEShort(offer.quantity,buffer); // buy qty
813 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
817 * Writes the buffered data to the output strea for one commodity.
819 * @param out the stream to write to
820 * @param buffer the buffered data to write
821 * @param commodity the commmodity id to write before the buffered data
822 * @param count the number of offers for this commodity to write before the data
824 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
825 writeLEShort(commodity,out); // commod index
826 writeLEShort(count,out); // offer count
827 out.write(buffer); // the buffered offers
831 * Writes the buy and sell offers to the outputstream by calling other methods.
833 * @param buys list of Buy offers to write
834 * @param sells list of Sell offers to write
835 * @param offerCount 2-length int array containing the number of buys and sells to write out
836 * @param out the stream to write to
838 private void writeBuySellOffers(TreeSet<Offer> buys,
839 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
841 writeLEShort(offerCount[0],out);
842 writeOffers(out,buys);
844 writeLEShort(offerCount[1],out);
845 writeOffers(out,sells);
848 private String readstreamstring(InputStream in) throws IOException {
849 StringBuilder sb = new StringBuilder();
850 BufferedReader br = new BufferedReader(new InputStreamReader(in));
852 while((str = br.readLine()) != null) {
855 return sb.toString();
859 * Sends the data to the server via multipart-formdata POST,
860 * with the gzipped data as a file upload.
862 * @param file an InputStream open to the gzipped data we want to send
864 private InputStream sendInitialData(InputStream file) throws IOException {
865 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
866 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
868 String err = readstreamstring(http.resultstream());
869 error("Error sending initial data:\n"+err);
872 return http.resultstream();
876 * Utility method to write a 2-byte int in little-endian form to an output stream.
878 * @param num an integer to write
879 * @param out stream to write to
881 private void writeLEShort(int num, OutputStream out) throws IOException {
882 out.write(num & 0xFF);
883 out.write((num >>> 8) & 0xFF);
887 * Reads the response from the server, and selects the correct parameters
888 * which are sent in a GET request to the server asking it to confirm
889 * the upload and accept the data into the database. Notably, the island id
890 * and ocean id are determined, while other parameter such as the filename
891 * are determined from the hidden form fields.
893 * @param in stream of data from the server to read
895 private boolean finishUpload(InputStream in) throws IOException {
896 String html = readstreamstring(in);
897 //System.out.println(html);
900 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
901 m = params.matcher(html);
903 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
907 String forceReload = m.group(1);
908 String filename = m.group(2);
910 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
911 m = oceanNumPat.matcher(html);
913 error_html("Unable to find the ocean in the server's list of oceans!", html);
916 String oceanNum = m.group(1);
918 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
919 m = oceanIslandNum.matcher(html);
921 error_html("This does not seem to be a valid island! Unable to upload.", html);
924 String islandNum = m.group(1);
926 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
927 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
928 String complete = readstreamstring(get.openStream());
929 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
930 m = done.matcher(complete);
932 System.out.println("FILE upload successful!!!");
935 error_html("Something was wrong with the final upload parameters!", complete);
940 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
942 String err = readstreamstring(http.resultstream());
943 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
946 return http.resultstream();
949 private String getYarrgTimestamp() throws IOException {
950 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
951 http.setParameter("clientname", YARRG_CLIENTNAME);
952 http.setParameter("clientversion", YARRG_CLIENTVERSION);
953 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
954 http.setParameter("requesttimestamp", "y");
955 InputStream in = post_for_yarrg(http);
956 if (in == null) return null;
957 BufferedReader br = new BufferedReader(new InputStreamReader(in));
958 String tsresult = br.readLine();
959 return tsresult.substring(3, tsresult.length()-1);
962 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
963 ByteArrayOutputStream bos = new ByteArrayOutputStream();
964 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
965 bufos.write(yarrgdata.getBytes() );
967 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
969 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
970 http.setParameter("clientname", YARRG_CLIENTNAME);
971 http.setParameter("clientversion", YARRG_CLIENTVERSION);
972 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
973 http.setParameter("timestamp", timestamp);
974 http.setParameter("ocean", ocean);
975 http.setParameter("island", island);
976 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
977 InputStream in = post_for_yarrg(http);
978 if (in == null) return false;
979 BufferedReader br = new BufferedReader(new InputStreamReader(in));
981 while((yarrgresult = br.readLine()) != null) {
982 System.out.println(yarrgresult);
987 private int calculateArbitrageCommodity(ArrayList<SortedSet<int[]>> arb_bs) {
988 System.out.println("ARBITRAGE?");
990 SortedSet<int[]> buys = arb_bs.get(0);
991 SortedSet<int[]> sells = arb_bs.get(1);
997 } catch (NoSuchElementException e) {
1000 int count = buy[1] < sell[1] ? buy[1] : sell[1];
1001 System.out.println(" buy @"+buy[0]+" x"+buy[1]+" sell @"+sell[0]+" x"+sell[1]+" => x"+count);
1002 profit += count * (buy[0] - sell[0]);
1005 if (buy[1]==0) buys.remove(buy);
1006 if (sell[1]==0) buys.remove(sell);
1011 private class arbitrageOfferComparator implements Comparator {
1012 public int compare(Object o1, Object o2) {
1013 int p1 = ((int[])o1)[0];
1014 int p2 = ((int[])o2)[0];
1019 private @SuppressWarnings("unchecked") void calculateArbitrage(ArrayList<ArrayList<String>> data)
1022 ArrayList<SortedSet<int[]>> arb_bs = null;
1023 String lastcommod = null;
1024 Comparator compar = new arbitrageOfferComparator();
1026 for (ArrayList<String> row : data) {
1027 String thiscommod = row.get(0);
1028 System.out.println("ROW "+row.toString());
1029 if (lastcommod == null || !thiscommod.equals(lastcommod)) {
1030 if (lastcommod != null)
1031 arbitrage += calculateArbitrageCommodity(arb_bs);
1032 //System.out.println("ROW rdy");
1033 arb_bs = new ArrayList<SortedSet<int[]>>(2);
1034 arb_bs.add(0, new TreeSet<int[]>(compar));
1035 arb_bs.add(1, new TreeSet<int[]>(compar));
1036 System.out.println("ROW init");
1037 lastcommod = thiscommod;
1039 for (int bs = 0; bs < 2; bs++) {
1040 String pricestr = row.get(bs*2 + 2);
1041 if (pricestr == null)
1043 int[] entry = new int[2];
1044 //System.out.println("ROW BS "+bs);
1045 entry[0] = parseQty(pricestr);
1046 entry[1] = parseQty(row.get(bs*2 + 3));
1047 arb_bs.get(bs).add(entry);
1050 arbitrage += calculateArbitrageCommodity(arb_bs);