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);
83 * An abstract market offer, entailing a commodity being bought or sold by
84 * a shoppe, for a certain price in a certain quantity. Not instantiable.
89 abstract class Offer {
90 public int commodity, price, quantity, shoppe;
92 * Create an offer from <code>record</code>, determining the shoppe Id from
93 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
94 * <code>priceIndex</code> should be the index of the price in the record
95 * (the quantity will be <code>priceIndex + 1</code>).
97 * @param record the record with data to create the offer from
98 * @param stallMap a map containing the ids of the various stalls
99 * @param commodMap a map containing the ids of the various commodities
100 * @param priceIndex the index of the price in the record
102 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
104 Integer commodId = commodMap.get(record.get(0));
105 if(commodId == null) {
106 throw new IllegalArgumentException();
108 commodity = commodId.intValue();
109 price = Integer.parseInt(record.get(priceIndex));
110 String qty = record.get(priceIndex+1);
111 if(qty.equals(">1000")) {
114 quantity = Integer.parseInt(record.get(priceIndex+1));
116 shoppe = stallMap.get(record.get(1)).intValue();
120 * Returns a human-readable version of this offer, useful for debugging
122 * @return human-readable offer
124 public String toString() {
125 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
130 * An offer from a shoppe or stall to buy a certain quantity of a commodity
131 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
132 * then by buy price descending, and finally by stall id ascending.
134 class Buy extends Offer implements Comparable<Buy> {
136 * Creates a new <code>Buy</code> offer from the given <code>record</code>
137 * using the other parameters to determine stall id and commodity id of the offer.
139 * @param record the record with data to create the offer from
140 * @param stallMap a map containing the ids of the various stalls
141 * @param commodMap a map containing the ids of the various commodities
143 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
144 super(record,stallMap,commodMap,2);
148 * Sorts by commodity index ascending, then price descending, then stall id ascending.
150 public int compareTo(Buy buy) {
151 // organize by: commodity index, price, stall index
152 if(commodity == buy.commodity) {
153 // organize by price, then by stall index
154 if(price == buy.price) {
155 // organize by stall index
156 return shoppe>buy.shoppe ? 1 : -1;
157 } else if(price > buy.price) {
162 } else if(commodity > buy.commodity) {
171 * An offer from a shoppe or stall to sell a certain quantity of a commodity
172 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
173 * then by sell price ascending, and finally by stall id ascending.
175 class Sell extends Offer implements Comparable<Sell> {
177 * Creates a new <code>Sell</code> offer from the given <code>record</code>
178 * using the other parameters to determine stall id and commodity id of the offer.
180 * @param record the record with data to create the offer from
181 * @param stallMap a map containing the ids of the various stalls
182 * @param commodMap a map containing the ids of the various commodities
184 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
185 super(record,stallMap,commodMap,4);
189 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
191 public int compareTo(Sell sell) {
192 // organize by: commodity index, price, stall index
193 if(commodity == sell.commodity) {
194 // organize by price, then by stall index
195 if(price == sell.price) {
196 // organize by stall index
197 return shoppe>sell.shoppe ? 1 : -1;
198 } else if(price > sell.price) {
203 } else if(commodity > sell.commodity) {
212 * Entry point. Read our preferences.
214 public MarketUploader() {
215 // check if we've been turned off in the control panel
216 Preferences prefs = Preferences.userNodeForPackage(getClass());
218 if (prefs.getBoolean("useLiveServers", false)) {
219 YARRG_URL = YARRG_LIVE_URL;
220 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
222 YARRG_URL = YARRG_TEST_URL;
223 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
226 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
227 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
229 EventQueueMonitor.addTopLevelWindowListener(this);
230 if (EventQueueMonitor.isGUIInitialized()) {
233 EventQueueMonitor.addGUIInitializedListener(this);
238 * Set up the GUI, with its window and one-button
239 * interface. Only initialize if we're running alongside
240 * a Window named "Puzzle Pirates" though.
242 private void createGUI() {
243 if (frame != null && window != null) {
244 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
247 frame = new JFrame("MarketUploader");
248 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
249 frame.getContentPane().setLayout(new GridLayout(2,1));
250 //frame.setPreferredSize(new Dimension(200, 60));
252 findMarket = new JButton("Upload Market Data");
253 findMarket.addActionListener(new ActionListener() {
254 public void actionPerformed(ActionEvent e) {
255 findMarket.setEnabled(false);
258 resultSummary.setText("");
261 } catch(Exception e) {
264 resultSummary.setText("failed");
266 if(sidePanel != null) {
267 // remove it if it's still attached
268 sidePanel.removePropertyChangeListener(changeListener);
272 findMarket.setEnabled(true);
277 frame.add(findMarket);
279 resultSummary = new JLabel("ready");
280 frame.add(resultSummary);
286 * Finds the island name from the /who tab, sets global islandName variable
288 private void getIsland() {
290 // If the league tracker is there, we can skip the faff
291 // and ask for its tooltip, since we're on a boat
293 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
295 islandName = ((JLabel)leagueTracker).getToolTipText();
296 } catch (NullPointerException e) {
297 // evidently we're actually on an island
300 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
301 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
302 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
303 if(!"com.threerings.piracy.client.AttentionListPanel".
304 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
305 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
307 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
309 sidePanel.addPropertyChangeListener(changeListener);
310 latch = new java.util.concurrent.CountDownLatch(1);
311 // make the Players Online ("/who") panel appear
312 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
313 chat.setTextContents("/w");
314 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
315 for(int i=0;i<c;i++) {
316 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
317 chatArea.getAccessibleAction().doAccessibleAction(i);
321 // if we don't find the island name, hopefully the server will
325 * Find the ocean name from the window title, and set global oceanName variable
327 private void getOcean() {
329 AccessibleContext topwindow = window.getAccessibleContext();
330 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
335 * Shows a dialog with the error <code>msg</code>.
337 * @param msg a String describing the error that occured.
339 private void error(String msg) {
340 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
343 private void error_html(String msg, String html) {
344 //System.err.println("===" + html + "===");
346 Pattern body = Pattern.compile("<body>(.*)</body>", Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
347 Matcher m = body.matcher(html);
350 Pattern fixup = Pattern.compile("<(\\w+) */>");;
351 m = fixup.matcher(html);
352 html = m.replaceAll("<$1>");
353 m = Pattern.compile("[\\r\\n]+").matcher(html);
354 html = m.replaceAll(" ");
356 String whole_msg = "<html><h1>Error</h1>"+msg+"<h1>PCTB Server said:</h1><blockquote>"+html+"</blockquote>";
357 System.err.println("###" + whole_msg + "###");
359 JOptionPane.showMessageDialog(frame,whole_msg,"Error",JOptionPane.ERROR_MESSAGE);
363 * Run the data collection process, and upload the results. This is the method
364 * that calls most of the other worker methods for the process. If an error occurs,
365 * the method will call the error method and return early, freeing up the button
366 * to be clicked again.
368 * @exception Exception if an error we didn't expect occured
370 private void runPCTB() throws Exception {
372 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
373 pm.setMillisToDecideToPopup(0);
374 pm.setMillisToPopup(0);
375 boolean doneyarrg = false, donepctb = false;
378 yarrgts = getYarrgTimestamp();
381 AccessibleTable accesstable = findMarketTable();
382 if(accesstable == null) {
383 error("Market table not found! Please open the Buy/Sell Commodities interface.");
386 if(accesstable.getAccessibleRowCount() == 0) {
387 error("No data found, please wait for the table to have data first!");
390 if(!isDisplayAll()) {
391 error("Please select \"All\" from the Display: popup menu.");
399 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
402 String headings_expected[] = new String[]
403 { "Commodity", "Trading outlet", "Buy price", "Will buy", "Sell price", "Will sell" };
404 ArrayList<ArrayList<String>> headers = getData(accesstable.getAccessibleColumnHeader());
405 if (headers.size() != 1) {
406 error("Table headings not one row! " + headers.toString());
409 if (headers.get(0).size() != 6) {
410 error("Table headings not six columns! " + headers.toString());
413 for (int col=0; col<headings_expected.length; col++) {
414 String expd = headings_expected[col];
415 String got = headers.get(0).get(col);
416 if (expd.compareTo(got) != 0) {
417 error("Table heading for column "+col
418 +" is not \""+expd+"\" but \""+got+"\".\n\n"
419 +"Please do not reorder the table when using this tool.");
424 ArrayList<ArrayList<String>> data = getData(accesstable);
426 if (uploadToYarrg && yarrgts != null) {
427 pm.setNote("Yarrg: Preparing data");
430 StringBuilder yarrgsb = new StringBuilder();
431 String yarrgdata; // string containing what we'll feed to yarrg
433 for (ArrayList<String> row : data) {
434 if (row.size() > 6) {
437 for (String rowitem : row) {
438 yarrgsb.append(rowitem != null ? rowitem : "");
439 yarrgsb.append("\t");
441 yarrgsb.setLength(yarrgsb.length()-1); // chop
442 yarrgsb.append("\n");
445 yarrgdata = yarrgsb.toString();
447 pm.setNote("Yarrg: Uploading");
449 if (islandName != null) {
450 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
452 System.out.println("Couldn't upload to Yarrg - no island name found");
457 pm.setNote("PCTB: Getting stall names");
459 if(pm.isCanceled()) {
462 TreeSet<Offer> buys = new TreeSet<Offer>();
463 TreeSet<Offer> sells = new TreeSet<Offer>();
464 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
466 pm.setNote("PCTB: Sorting offers");
467 if(pm.isCanceled()) {
472 HashMap<String,Integer> commodMap = getCommodMap();
473 if(commodMap == null) {
476 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
477 //println(buys.toString());
478 //System.out.println(sells);
479 //System.out.println("\n\n\n"+buys);
481 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
483 pm.setNote("PCTB: Sending data");
484 if(pm.isCanceled()) {
487 GZIPOutputStream out = new GZIPOutputStream(outStream);
488 //FileOutputStream out = new FileOutputStream(new File("output.text"));
489 DataOutputStream dos = new DataOutputStream(out);
490 dos.writeBytes("005y\n");
491 dos.writeBytes(stallMap.size()+"\n");
492 dos.writeBytes(getAbbrevStallList(stallMap));
493 writeBuySellOffers(buys,sells,offerCount,out);
495 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
496 if (in == null) return;
498 if(pm.isCanceled()) {
501 pm.setNote("PCTB: Waiting ...");
502 donepctb = finishUpload(in);
506 if ((uploadToPCTB && !donepctb) ||
507 (uploadToYarrg && !doneyarrg)) {
508 resultSummary.setText("trouble");
509 } else if (donepctb || doneyarrg) {
510 resultSummary.setText("Done " + islandName);
512 resultSummary.setText("uploaded nowhere!");
517 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
519 * @param table the <code>AccessibleTable</code> containing the market data
520 * @return an array of record arrays, each representing a row of the table
522 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
523 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
524 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
525 ArrayList<String> row = new ArrayList<String>();
526 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
527 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
535 * @return the table containing market data if it exists, otherwise <code>null</code>
537 public AccessibleTable findMarketTable() {
538 Accessible node1 = window;
539 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
540 // 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})
541 //System.out.println(node);
542 if (!(node instanceof JTable)) {
543 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
545 if (!(node instanceof JTable)) return null;
546 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
547 //System.out.println(table);
552 * Utility method to descend through several levels of Accessible children
555 * @param parent the node on which to start the descent
556 * @param path an array of ints, each int being the index of the next
557 * accessible child to descend.
558 * @return the <code>Accessible</code> reached by following the descent path,
559 * or <code>null</code> if the desired path was invalid.
561 private Accessible descendNodes(Accessible parent, int[] path) {
562 for(int i=0;i<path.length;i++) {
563 if (null == (parent = descend(parent, path[i]))) return null;
564 // System.out.println(parent.getClass());
570 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
572 * @param parent the node with children
573 * @param childNum the index of the child of <code>parent</code> to return
574 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
575 * if the child is not found.
577 private Accessible descend(Accessible parent, int childNum) {
578 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
579 return parent.getAccessibleContext().getAccessibleChild(childNum);
582 public static void main(String[] args) {
583 new MarketUploader();
587 * Set the global window variable after the YPP window is created,
588 * remove the top level window listener, and start the GUI
590 public void topLevelWindowCreated(Window w) {
592 EventQueueMonitor.removeTopLevelWindowListener(this);
597 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
599 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
601 private boolean isDisplayAll() {
602 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
603 if(!(button instanceof JButton)) {
604 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
606 String display = button.getAccessibleContext().getAccessibleName();
607 if(!display.equals("All")) {
613 public void topLevelWindowDestroyed(Window w) {}
615 public void guiInitialized() {
620 * Gets the list of commodities and their associated commodity ids.
621 * On the first run, the data is downloaded from the PCTB server.
622 * After the first run, the data is cached using <code>Preferences</code>.
624 * Potential issues: When more commodities are added to the server, this
625 * program will currently break unless the user deletes the preferences
626 * file or we give them a new release with a slighly different storage
627 * location for the data.
629 * @return a map where the key is the commodity and the value is the commodity id.
631 private HashMap<String,Integer> getCommodMap() {
632 if(commodMap != null) {
635 HashMap<String,Integer> map = new HashMap<String,Integer>();
636 Preferences prefs = Preferences.userNodeForPackage(getClass());
639 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
640 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
641 StringBuilder sb = new StringBuilder();
643 while((str = br.readLine()) != null) {
646 int first = sb.indexOf("<pre>") + 5;
647 int last = sb.indexOf("</body>");
648 xml = sb.substring(first,last);
649 //System.out.println(xml);
650 Reader reader = new CharArrayReader(xml.toCharArray());
651 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
652 NodeList maps = d.getElementsByTagName("CommodMap");
653 for(int i=0;i<maps.getLength();i++) {
654 NodeList content = maps.item(i).getChildNodes();
655 Integer num = Integer.parseInt(content.item(1).getTextContent());
656 map.put(content.item(0).getTextContent(),num);
658 } catch(Exception e) {
660 error("Unable to load Commodity list from server!");
668 * Given the list of offers, this method will find all the unique stall names
669 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
670 * and the value is the generated stall id (position in the list).
672 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
673 * for iterating over the stall names in insertion order for output to the server.
675 * @param offers the list of records from the commodity buy/sell interface
676 * @return an iterable ordered map of the stall names and generated stall ids
678 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
680 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
681 for(ArrayList<String> offer : offers) {
682 String shop = offer.get(1);
683 if(!map.containsKey(shop)) {
692 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
693 * should be pre-initialized and passed into the method to receive the data.
694 * Returns a 2-length int array with the number of buys and sells found.
696 * @param offers the data found from the market table in-game
697 * @param buys an empty initialized <code>TreeSet<Offer></code> to
698 * hold the Buy offers.
699 * @param sells an empty initialized <code>TreeSet<Offer></code> to
700 * hold the Sell offers.
701 * @param stalls the map of stalls to their ids
702 * @param commodMap the map of commodities to their ids
703 * @return a 2-length int[] array containing the number of buys and sells, respectively
705 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
706 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
707 int[] buySellCount = new int[2];
708 for(ArrayList<String> offer : offers) {
710 if(offer.get(2) != null) {
711 buys.add(new Buy(offer,stalls,commodMap));
714 if(offer.get(4) != null) {
715 sells.add(new Sell(offer,stalls,commodMap));
718 } catch(IllegalArgumentException e) {
719 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
722 if (buySellCount[0]==0 && buySellCount[1]==0) {
723 error("No (valid) offers for PCTB?!");
724 throw new IllegalArgumentException();
730 * Prepares the list of stalls for writing to the output stream.
731 * The <code>String</code> returned by this method is ready to be written
732 * directly to the stream.
734 * All shoppe names are left as they are. Stall names are abbreviated just before the
735 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
736 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
738 * @param stallMap the map of stalls and stall ids in an iterable order
739 * @return a <code>String</code> containing the list of stalls in format ready
740 * to be written to the output stream.
742 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
743 // set up some mapping
744 HashMap<String,String> types = new HashMap<String,String>();
745 types.put("Apothecary Stall", "A");
746 types.put("Distilling Stall", "D");
747 types.put("Furnishing Stall", "F");
748 types.put("Ironworking Stall", "I");
749 types.put("Shipbuilding Stall", "S");
750 types.put("Tailoring Stall", "T");
751 types.put("Weaving Stall", "W");
753 StringBuilder sb = new StringBuilder();
754 for(String name : stallMap.keySet()) {
755 int index = name.indexOf("'s");
756 String finalName = name;
759 finalName = name.substring(0,index);
760 if(index + 2 < name.length()) {
761 String end = name.substring(index+2,name.length()).trim();
762 type = types.get(end);
766 sb.append(name+"\n");
768 sb.append(finalName+"^"+type+"\n");
771 return sb.toString();
775 * Writes a list of offers in correct format to the output stream.
777 * The format is thus: (all numbers are 2-byte integers in little-endian format)
778 * (number of offers of this type, aka buy/sell)
779 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
781 * @param out the output stream to write the data to
782 * @param offers the offers to write
784 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
785 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
786 if(offers.size() == 0) {
787 // nothing to write, and "0" has already been written
790 int commodity = offers.first().commodity;
792 for(Offer offer : offers) {
793 if(commodity != offer.commodity) {
795 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
797 commodity = offer.commodity;
800 writeLEShort(offer.shoppe,buffer); // stall index
801 writeLEShort(offer.price,buffer); // buy price
802 writeLEShort(offer.quantity,buffer); // buy qty
805 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
809 * Writes the buffered data to the output strea for one commodity.
811 * @param out the stream to write to
812 * @param buffer the buffered data to write
813 * @param commodity the commmodity id to write before the buffered data
814 * @param count the number of offers for this commodity to write before the data
816 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
817 writeLEShort(commodity,out); // commod index
818 writeLEShort(count,out); // offer count
819 out.write(buffer); // the buffered offers
823 * Writes the buy and sell offers to the outputstream by calling other methods.
825 * @param buys list of Buy offers to write
826 * @param sells list of Sell offers to write
827 * @param offerCount 2-length int array containing the number of buys and sells to write out
828 * @param out the stream to write to
830 private void writeBuySellOffers(TreeSet<Offer> buys,
831 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
833 writeLEShort(offerCount[0],out);
834 writeOffers(out,buys);
836 writeLEShort(offerCount[1],out);
837 writeOffers(out,sells);
840 private String readstreamstring(InputStream in) throws IOException {
841 StringBuilder sb = new StringBuilder();
842 BufferedReader br = new BufferedReader(new InputStreamReader(in));
844 while((str = br.readLine()) != null) {
847 return sb.toString();
851 * Sends the data to the server via multipart-formdata POST,
852 * with the gzipped data as a file upload.
854 * @param file an InputStream open to the gzipped data we want to send
856 private InputStream sendInitialData(InputStream file) throws IOException {
857 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
858 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
860 String err = readstreamstring(http.resultstream());
861 error("Error sending initial data:\n"+err);
864 return http.resultstream();
868 * Utility method to write a 2-byte int in little-endian form to an output stream.
870 * @param num an integer to write
871 * @param out stream to write to
873 private void writeLEShort(int num, OutputStream out) throws IOException {
874 out.write(num & 0xFF);
875 out.write((num >>> 8) & 0xFF);
879 * Reads the response from the server, and selects the correct parameters
880 * which are sent in a GET request to the server asking it to confirm
881 * the upload and accept the data into the database. Notably, the island id
882 * and ocean id are determined, while other parameter such as the filename
883 * are determined from the hidden form fields.
885 * @param in stream of data from the server to read
887 private boolean finishUpload(InputStream in) throws IOException {
888 String html = readstreamstring(in);
889 //System.out.println(html);
892 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
893 m = params.matcher(html);
895 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
899 String forceReload = m.group(1);
900 String filename = m.group(2);
902 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
903 m = oceanNumPat.matcher(html);
905 error_html("Unable to find the ocean in the server's list of oceans!", html);
908 String oceanNum = m.group(1);
910 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
911 m = oceanIslandNum.matcher(html);
913 error_html("This does not seem to be a valid island! Unable to upload.", html);
916 String islandNum = m.group(1);
918 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
919 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
920 String complete = readstreamstring(get.openStream());
921 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
922 m = done.matcher(complete);
924 System.out.println("FILE upload successful!!!");
927 error_html("Something was wrong with the final upload parameters!", complete);
932 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
934 String err = readstreamstring(http.resultstream());
935 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
938 return http.resultstream();
941 private String getYarrgTimestamp() throws IOException {
942 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
943 http.setParameter("clientname", YARRG_CLIENTNAME);
944 http.setParameter("clientversion", YARRG_CLIENTVERSION);
945 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
946 http.setParameter("requesttimestamp", "y");
947 InputStream in = post_for_yarrg(http);
948 if (in == null) return null;
949 BufferedReader br = new BufferedReader(new InputStreamReader(in));
950 String tsresult = br.readLine();
951 return tsresult.substring(3, tsresult.length()-1);
954 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
955 ByteArrayOutputStream bos = new ByteArrayOutputStream();
956 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
957 bufos.write(yarrgdata.getBytes() );
959 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
961 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
962 http.setParameter("clientname", YARRG_CLIENTNAME);
963 http.setParameter("clientversion", YARRG_CLIENTVERSION);
964 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
965 http.setParameter("timestamp", timestamp);
966 http.setParameter("ocean", ocean);
967 http.setParameter("island", island);
968 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
969 InputStream in = post_for_yarrg(http);
970 if (in == null) return false;
971 BufferedReader br = new BufferedReader(new InputStreamReader(in));
973 while((yarrgresult = br.readLine()) != null) {
974 System.out.println(yarrgresult);