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 t = findMarketTable();
383 error("Market table not found! Please open the Buy/Sell Commodities interface.");
386 if(t.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 ArrayList<ArrayList<String>> data = getData(t);
404 if (uploadToYarrg && yarrgts != null) {
405 pm.setNote("Yarrg: Preparing data");
408 StringBuilder yarrgsb = new StringBuilder();
409 String yarrgdata; // string containing what we'll feed to yarrg
411 for (ArrayList<String> row : data) {
412 if (row.size() > 6) {
415 for (String rowitem : row) {
416 yarrgsb.append(rowitem != null ? rowitem : "");
417 yarrgsb.append("\t");
419 yarrgsb.setLength(yarrgsb.length()-1); // chop
420 yarrgsb.append("\n");
423 yarrgdata = yarrgsb.toString();
425 pm.setNote("Yarrg: Uploading");
427 if (islandName != null) {
428 doneyarrg = runYarrg(yarrgts, oceanName, islandName, yarrgdata);
430 System.out.println("Couldn't upload to Yarrg - no island name found");
435 pm.setNote("PCTB: Getting stall names");
437 if(pm.isCanceled()) {
440 TreeSet<Offer> buys = new TreeSet<Offer>();
441 TreeSet<Offer> sells = new TreeSet<Offer>();
442 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
444 pm.setNote("PCTB: Sorting offers");
445 if(pm.isCanceled()) {
450 HashMap<String,Integer> commodMap = getCommodMap();
451 if(commodMap == null) {
454 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
455 //println(buys.toString());
456 //System.out.println(sells);
457 //System.out.println("\n\n\n"+buys);
459 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
461 pm.setNote("PCTB: Sending data");
462 if(pm.isCanceled()) {
465 GZIPOutputStream out = new GZIPOutputStream(outStream);
466 //FileOutputStream out = new FileOutputStream(new File("output.text"));
467 DataOutputStream dos = new DataOutputStream(out);
468 dos.writeBytes("005y\n");
469 dos.writeBytes(stallMap.size()+"\n");
470 dos.writeBytes(getAbbrevStallList(stallMap));
471 writeBuySellOffers(buys,sells,offerCount,out);
473 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
474 if (in == null) return;
476 if(pm.isCanceled()) {
479 pm.setNote("PCTB: Waiting ...");
480 donepctb = finishUpload(in);
484 if ((uploadToPCTB && !donepctb) ||
485 (uploadToYarrg && !doneyarrg)) {
486 resultSummary.setText("trouble");
487 } else if (donepctb || doneyarrg) {
488 resultSummary.setText("Done " + islandName);
490 resultSummary.setText("uploaded nowhere!");
495 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
497 * @param table the <code>AccessibleTable</code> containing the market data
498 * @return an array of record arrays, each representing a row of the table
500 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
501 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
502 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
503 ArrayList<String> row = new ArrayList<String>();
504 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
505 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
513 * @return the table containing market data if it exists, otherwise <code>null</code>
515 public AccessibleTable findMarketTable() {
516 Accessible node1 = window;
517 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
518 // 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})
519 //System.out.println(node);
520 if (!(node instanceof JTable)) {
521 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
523 if (!(node instanceof JTable)) return null;
524 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
525 //System.out.println(table);
530 * Utility method to descend through several levels of Accessible children
533 * @param parent the node on which to start the descent
534 * @param path an array of ints, each int being the index of the next
535 * accessible child to descend.
536 * @return the <code>Accessible</code> reached by following the descent path,
537 * or <code>null</code> if the desired path was invalid.
539 private Accessible descendNodes(Accessible parent, int[] path) {
540 for(int i=0;i<path.length;i++) {
541 if (null == (parent = descend(parent, path[i]))) return null;
542 // System.out.println(parent.getClass());
548 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
550 * @param parent the node with children
551 * @param childNum the index of the child of <code>parent</code> to return
552 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
553 * if the child is not found.
555 private Accessible descend(Accessible parent, int childNum) {
556 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
557 return parent.getAccessibleContext().getAccessibleChild(childNum);
560 public static void main(String[] args) {
561 new MarketUploader();
565 * Set the global window variable after the YPP window is created,
566 * remove the top level window listener, and start the GUI
568 public void topLevelWindowCreated(Window w) {
570 EventQueueMonitor.removeTopLevelWindowListener(this);
575 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
577 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
579 private boolean isDisplayAll() {
580 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
581 if(!(button instanceof JButton)) {
582 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
584 String display = button.getAccessibleContext().getAccessibleName();
585 if(!display.equals("All")) {
591 public void topLevelWindowDestroyed(Window w) {}
593 public void guiInitialized() {
598 * Gets the list of commodities and their associated commodity ids.
599 * On the first run, the data is downloaded from the PCTB server.
600 * After the first run, the data is cached using <code>Preferences</code>.
602 * Potential issues: When more commodities are added to the server, this
603 * program will currently break unless the user deletes the preferences
604 * file or we give them a new release with a slighly different storage
605 * location for the data.
607 * @return a map where the key is the commodity and the value is the commodity id.
609 private HashMap<String,Integer> getCommodMap() {
610 if(commodMap != null) {
613 HashMap<String,Integer> map = new HashMap<String,Integer>();
614 Preferences prefs = Preferences.userNodeForPackage(getClass());
617 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
618 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
619 StringBuilder sb = new StringBuilder();
621 while((str = br.readLine()) != null) {
624 int first = sb.indexOf("<pre>") + 5;
625 int last = sb.indexOf("</body>");
626 xml = sb.substring(first,last);
627 //System.out.println(xml);
628 Reader reader = new CharArrayReader(xml.toCharArray());
629 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
630 NodeList maps = d.getElementsByTagName("CommodMap");
631 for(int i=0;i<maps.getLength();i++) {
632 NodeList content = maps.item(i).getChildNodes();
633 Integer num = Integer.parseInt(content.item(1).getTextContent());
634 map.put(content.item(0).getTextContent(),num);
636 } catch(Exception e) {
638 error("Unable to load Commodity list from server!");
646 * Given the list of offers, this method will find all the unique stall names
647 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
648 * and the value is the generated stall id (position in the list).
650 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
651 * for iterating over the stall names in insertion order for output to the server.
653 * @param offers the list of records from the commodity buy/sell interface
654 * @return an iterable ordered map of the stall names and generated stall ids
656 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
658 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
659 for(ArrayList<String> offer : offers) {
660 String shop = offer.get(1);
661 if(!map.containsKey(shop)) {
670 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
671 * should be pre-initialized and passed into the method to receive the data.
672 * Returns a 2-length int array with the number of buys and sells found.
674 * @param offers the data found from the market table in-game
675 * @param buys an empty initialized <code>TreeSet<Offer></code> to
676 * hold the Buy offers.
677 * @param sells an empty initialized <code>TreeSet<Offer></code> to
678 * hold the Sell offers.
679 * @param stalls the map of stalls to their ids
680 * @param commodMap the map of commodities to their ids
681 * @return a 2-length int[] array containing the number of buys and sells, respectively
683 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
684 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
685 int[] buySellCount = new int[2];
686 for(ArrayList<String> offer : offers) {
688 if(offer.get(2) != null) {
689 buys.add(new Buy(offer,stalls,commodMap));
692 if(offer.get(4) != null) {
693 sells.add(new Sell(offer,stalls,commodMap));
696 } catch(IllegalArgumentException e) {
697 System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
700 if (buySellCount[0]==0 && buySellCount[1]==0) {
701 error("No (valid) offers for PCTB?!");
702 throw new IllegalArgumentException();
708 * Prepares the list of stalls for writing to the output stream.
709 * The <code>String</code> returned by this method is ready to be written
710 * directly to the stream.
712 * All shoppe names are left as they are. Stall names are abbreviated just before the
713 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
714 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
716 * @param stallMap the map of stalls and stall ids in an iterable order
717 * @return a <code>String</code> containing the list of stalls in format ready
718 * to be written to the output stream.
720 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
721 // set up some mapping
722 HashMap<String,String> types = new HashMap<String,String>();
723 types.put("Apothecary Stall", "A");
724 types.put("Distilling Stall", "D");
725 types.put("Furnishing Stall", "F");
726 types.put("Ironworking Stall", "I");
727 types.put("Shipbuilding Stall", "S");
728 types.put("Tailoring Stall", "T");
729 types.put("Weaving Stall", "W");
731 StringBuilder sb = new StringBuilder();
732 for(String name : stallMap.keySet()) {
733 int index = name.indexOf("'s");
734 String finalName = name;
737 finalName = name.substring(0,index);
738 if(index + 2 < name.length()) {
739 String end = name.substring(index+2,name.length()).trim();
740 type = types.get(end);
744 sb.append(name+"\n");
746 sb.append(finalName+"^"+type+"\n");
749 return sb.toString();
753 * Writes a list of offers in correct format to the output stream.
755 * The format is thus: (all numbers are 2-byte integers in little-endian format)
756 * (number of offers of this type, aka buy/sell)
757 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
759 * @param out the output stream to write the data to
760 * @param offers the offers to write
762 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
763 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
764 if(offers.size() == 0) {
765 // nothing to write, and "0" has already been written
768 int commodity = offers.first().commodity;
770 for(Offer offer : offers) {
771 if(commodity != offer.commodity) {
773 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
775 commodity = offer.commodity;
778 writeLEShort(offer.shoppe,buffer); // stall index
779 writeLEShort(offer.price,buffer); // buy price
780 writeLEShort(offer.quantity,buffer); // buy qty
783 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
787 * Writes the buffered data to the output strea for one commodity.
789 * @param out the stream to write to
790 * @param buffer the buffered data to write
791 * @param commodity the commmodity id to write before the buffered data
792 * @param count the number of offers for this commodity to write before the data
794 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
795 writeLEShort(commodity,out); // commod index
796 writeLEShort(count,out); // offer count
797 out.write(buffer); // the buffered offers
801 * Writes the buy and sell offers to the outputstream by calling other methods.
803 * @param buys list of Buy offers to write
804 * @param sells list of Sell offers to write
805 * @param offerCount 2-length int array containing the number of buys and sells to write out
806 * @param out the stream to write to
808 private void writeBuySellOffers(TreeSet<Offer> buys,
809 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
811 writeLEShort(offerCount[0],out);
812 writeOffers(out,buys);
814 writeLEShort(offerCount[1],out);
815 writeOffers(out,sells);
818 private String readstreamstring(InputStream in) throws IOException {
819 StringBuilder sb = new StringBuilder();
820 BufferedReader br = new BufferedReader(new InputStreamReader(in));
822 while((str = br.readLine()) != null) {
825 return sb.toString();
829 * Sends the data to the server via multipart-formdata POST,
830 * with the gzipped data as a file upload.
832 * @param file an InputStream open to the gzipped data we want to send
834 private InputStream sendInitialData(InputStream file) throws IOException {
835 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
836 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
838 String err = readstreamstring(http.resultstream());
839 error("Error sending initial data:\n"+err);
842 return http.resultstream();
846 * Utility method to write a 2-byte int in little-endian form to an output stream.
848 * @param num an integer to write
849 * @param out stream to write to
851 private void writeLEShort(int num, OutputStream out) throws IOException {
852 out.write(num & 0xFF);
853 out.write((num >>> 8) & 0xFF);
857 * Reads the response from the server, and selects the correct parameters
858 * which are sent in a GET request to the server asking it to confirm
859 * the upload and accept the data into the database. Notably, the island id
860 * and ocean id are determined, while other parameter such as the filename
861 * are determined from the hidden form fields.
863 * @param in stream of data from the server to read
865 private boolean finishUpload(InputStream in) throws IOException {
866 String html = readstreamstring(in);
867 //System.out.println(html);
870 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"setisland\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
871 m = params.matcher(html);
873 error_html("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?",
877 String forceReload = m.group(1);
878 String filename = m.group(2);
880 Pattern oceanNumPat = Pattern.compile("<option value=\"(\\d+)\">"+oceanName+"</option>");
881 m = oceanNumPat.matcher(html);
883 error_html("Unable to find the ocean in the server's list of oceans!", html);
886 String oceanNum = m.group(1);
888 Pattern oceanIslandNum = Pattern.compile("islands\\[" + oceanNum + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
889 m = oceanIslandNum.matcher(html);
891 error_html("This does not seem to be a valid island! Unable to upload.", html);
894 String islandNum = m.group(1);
896 URL get = new URL(PCTB_HOST_URL + "upload.php?action=setisland&ocean=" + oceanNum + "&island="
897 + islandNum + "&forcereload=" + forceReload + "&filename=" + filename);
898 String complete = readstreamstring(get.openStream());
899 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
900 m = done.matcher(complete);
902 System.out.println("FILE upload successful!!!");
905 error_html("Something was wrong with the final upload parameters!", complete);
910 private InputStream post_for_yarrg(ClientHttpRequest http) throws IOException {
912 String err = readstreamstring(http.resultstream());
913 error("<html><h1>Error reported by YARRG server</h1>\n" + err);
916 return http.resultstream();
919 private String getYarrgTimestamp() throws IOException {
920 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
921 http.setParameter("clientname", YARRG_CLIENTNAME);
922 http.setParameter("clientversion", YARRG_CLIENTVERSION);
923 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
924 http.setParameter("requesttimestamp", "y");
925 InputStream in = post_for_yarrg(http);
926 if (in == null) return null;
927 BufferedReader br = new BufferedReader(new InputStreamReader(in));
928 String tsresult = br.readLine();
929 return tsresult.substring(3, tsresult.length()-1);
932 private boolean runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
933 ByteArrayOutputStream bos = new ByteArrayOutputStream();
934 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
935 bufos.write(yarrgdata.getBytes() );
937 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
939 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
940 http.setParameter("clientname", YARRG_CLIENTNAME);
941 http.setParameter("clientversion", YARRG_CLIENTVERSION);
942 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
943 http.setParameter("timestamp", timestamp);
944 http.setParameter("ocean", ocean);
945 http.setParameter("island", island);
946 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
947 InputStream in = post_for_yarrg(http);
948 if (in == null) return false;
949 BufferedReader br = new BufferedReader(new InputStreamReader(in));
951 while((yarrgresult = br.readLine()) != null) {
952 System.out.println(yarrgresult);