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 com.myjavatools.web.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;
42 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
43 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
44 private String PCTB_HOST_URL;
46 // Yarrg protocol parameters
47 private final static String YARRG_CLIENTNAME = "jpctb greenend";
48 private final static String YARRG_CLIENTVERSION =
49 com.tedpearson.ypp.market.Version.version;
50 private final static String YARRG_CLIENTFIXES = "bug-094";
51 private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
52 private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
53 private String YARRG_URL;
55 private boolean uploadToYarrg;
56 private boolean uploadToPCTB;
58 private String islandName = null;
59 private String oceanName = null;
60 private java.util.concurrent.CountDownLatch latch = null;
62 private AccessibleContext sidePanel;
63 private HashMap<String,Integer> commodMap;
64 private HashMap<String,String> islandNumbers = new HashMap<String,String>();
66 String[] nums = new String[]
67 {"","Viridian","Midnight","Hunter","Cobalt","Sage","Ice","Malachite","Crimson","Opal"};
68 for(int i=1;i<nums.length;i++) {
69 islandNumbers.put(nums[i],""+i);
72 private PropertyChangeListener changeListener = new PropertyChangeListener() {
73 public void propertyChange(PropertyChangeEvent e) {
74 if(e.getNewValue() != null &&
75 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
76 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
77 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
78 int index = text.indexOf(":");
79 String name = text.substring(0,index);
81 //System.out.println(islandName);
82 sidePanel.removePropertyChangeListener(this);
89 * An abstract market offer, entailing a commodity being bought or sold by
90 * a shoppe, for a certain price in a certain quantity. Not instantiable.
95 abstract class Offer {
96 public int commodity, price, quantity, shoppe;
98 * Create an offer from <code>record</code>, determining the shoppe Id from
99 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
100 * <code>priceIndex</code> should be the index of the price in the record
101 * (the quantity will be <code>priceIndex + 1</code>).
103 * @param record the record with data to create the offer from
104 * @param stallMap a map containing the ids of the various stalls
105 * @param commodMap a map containing the ids of the various commodities
106 * @param priceIndex the index of the price in the record
108 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
110 Integer commodId = commodMap.get(record.get(0));
111 if(commodId == null) {
112 throw new IllegalArgumentException();
114 commodity = commodId.intValue();
115 price = Integer.parseInt(record.get(priceIndex));
116 String qty = record.get(priceIndex+1);
117 if(qty.equals(">1000")) {
120 quantity = Integer.parseInt(record.get(priceIndex+1));
122 shoppe = stallMap.get(record.get(1)).intValue();
126 * Returns a human-readable version of this offer, useful for debugging
128 * @return human-readable offer
130 public String toString() {
131 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
136 * An offer from a shoppe or stall to buy a certain quantity of a commodity
137 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
138 * then by buy price descending, and finally by stall id ascending.
140 class Buy extends Offer implements Comparable<Buy> {
142 * Creates a new <code>Buy</code> offer from the given <code>record</code>
143 * using the other parameters to determine stall id and commodity id of the offer.
145 * @param record the record with data to create the offer from
146 * @param stallMap a map containing the ids of the various stalls
147 * @param commodMap a map containing the ids of the various commodities
149 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
150 super(record,stallMap,commodMap,2);
154 * Sorts by commodity index ascending, then price descending, then stall id ascending.
156 public int compareTo(Buy buy) {
157 // organize by: commodity index, price, stall index
158 if(commodity == buy.commodity) {
159 // organize by price, then by stall index
160 if(price == buy.price) {
161 // organize by stall index
162 return shoppe>buy.shoppe ? 1 : -1;
163 } else if(price > buy.price) {
168 } else if(commodity > buy.commodity) {
177 * An offer from a shoppe or stall to sell a certain quantity of a commodity
178 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
179 * then by sell price ascending, and finally by stall id ascending.
181 class Sell extends Offer implements Comparable<Sell> {
183 * Creates a new <code>Sell</code> offer from the given <code>record</code>
184 * using the other parameters to determine stall id and commodity id of the offer.
186 * @param record the record with data to create the offer from
187 * @param stallMap a map containing the ids of the various stalls
188 * @param commodMap a map containing the ids of the various commodities
190 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
191 super(record,stallMap,commodMap,4);
195 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
197 public int compareTo(Sell sell) {
198 // organize by: commodity index, price, stall index
199 if(commodity == sell.commodity) {
200 // organize by price, then by stall index
201 if(price == sell.price) {
202 // organize by stall index
203 return shoppe>sell.shoppe ? 1 : -1;
204 } else if(price > sell.price) {
209 } else if(commodity > sell.commodity) {
218 * Entry point. Read our preferences.
220 public MarketUploader() {
221 // check if we've been turned off in the control panel
222 Preferences prefs = Preferences.userNodeForPackage(getClass());
224 if (prefs.getBoolean("useLiveServers", false)) {
225 YARRG_URL = YARRG_LIVE_URL;
226 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
228 YARRG_URL = YARRG_TEST_URL;
229 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
232 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
233 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
235 EventQueueMonitor.addTopLevelWindowListener(this);
236 if (EventQueueMonitor.isGUIInitialized()) {
239 EventQueueMonitor.addGUIInitializedListener(this);
244 * Set up the GUI, with its window and one-button
245 * interface. Only initialize if we're running alongside
246 * a Window named "Puzzle Pirates" though.
248 private void createGUI() {
249 if (frame != null && window != null) {
250 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
253 frame = new JFrame("MarketUploader");
254 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
255 frame.getContentPane().setLayout(new FlowLayout());
256 //frame.setPreferredSize(new Dimension(200, 60));
258 findMarket = new JButton("Upload Market Data");
259 findMarket.addActionListener(new ActionListener() {
260 public void actionPerformed(ActionEvent e) {
261 findMarket.setEnabled(false);
266 } catch(Exception e) {
270 if(sidePanel != null) {
271 // remove it if it's still attached
272 sidePanel.removePropertyChangeListener(changeListener);
276 findMarket.setEnabled(true);
281 frame.add(findMarket);
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);
344 * Run the data collection process, and upload the results. This is the method
345 * that calls most of the other worker methods for the process. If an error occurs,
346 * the method will call the error method and return early, freeing up the button
347 * to be clicked again.
349 * @exception Exception if an error we didn't expect occured
351 private void runPCTB() throws Exception {
353 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
354 pm.setMillisToDecideToPopup(0);
355 pm.setMillisToPopup(0);
358 yarrgts = getYarrgTimestamp();
361 AccessibleTable t = findMarketTable();
363 error("Market table not found! Please open the Buy/Sell Commodities interface.");
366 if(t.getAccessibleRowCount() == 0) {
367 error("No data found, please wait for the table to have data first!");
370 if(!isDisplayAll()) {
371 error("Please select \"All\" from the Display: popup menu.");
379 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
382 ArrayList<ArrayList<String>> data = getData(t);
385 pm.setNote("Preparing data for Yarrg");
388 StringBuilder yarrgsb = new StringBuilder();
389 String yarrgdata; // string containing what we'll feed to yarrg
391 for (ArrayList<String> row : data) {
392 if (row.size() > 6) {
395 for (String rowitem : row) {
396 yarrgsb.append(rowitem != null ? rowitem : "");
397 yarrgsb.append("\t");
399 yarrgsb.setLength(yarrgsb.length()-1); // chop
400 yarrgsb.append("\n");
403 yarrgdata = yarrgsb.toString();
405 pm.setNote("Uploading to Yarrg");
407 if (islandName != null) {
408 runYarrg(yarrgts, oceanName, islandName, yarrgdata);
410 System.out.println("Couldn't upload to Yarrg - no island name found");
414 pm.setNote("Getting stall names");
416 if(pm.isCanceled()) {
419 TreeSet<Offer> buys = new TreeSet<Offer>();
420 TreeSet<Offer> sells = new TreeSet<Offer>();
421 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
423 pm.setNote("Sorting offers");
424 if(pm.isCanceled()) {
429 HashMap<String,Integer> commodMap = getCommodMap();
430 if(commodMap == null) {
433 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
434 //println(buys.toString());
435 //System.out.println(sells);
436 //System.out.println("\n\n\n"+buys);
439 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
441 pm.setNote("Sending data");
442 if(pm.isCanceled()) {
445 GZIPOutputStream out = new GZIPOutputStream(outStream);
446 //FileOutputStream out = new FileOutputStream(new File("output.text"));
447 DataOutputStream dos = new DataOutputStream(out);
448 dos.writeBytes("005y\n");
449 dos.writeBytes(stallMap.size()+"\n");
450 dos.writeBytes(getAbbrevStallList(stallMap));
451 writeBuySellOffers(buys,sells,offerCount,out);
453 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
455 if(pm.isCanceled()) {
458 pm.setNote("Waiting for PCTB...");
465 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
467 * @param table the <code>AccessibleTable</code> containing the market data
468 * @return an array of record arrays, each representing a row of the table
470 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
471 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
472 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
473 ArrayList<String> row = new ArrayList<String>();
474 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
475 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
483 * @return the table containing market data if it exists, otherwise <code>null</code>
485 public AccessibleTable findMarketTable() {
486 Accessible node1 = window;
487 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
488 // 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})
489 //System.out.println(node);
490 if (!(node instanceof JTable)) {
491 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
493 if (!(node instanceof JTable)) return null;
494 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
495 //System.out.println(table);
500 * Utility method to descend through several levels of Accessible children
503 * @param parent the node on which to start the descent
504 * @param path an array of ints, each int being the index of the next
505 * accessible child to descend.
506 * @return the <code>Accessible</code> reached by following the descent path,
507 * or <code>null</code> if the desired path was invalid.
509 private Accessible descendNodes(Accessible parent, int[] path) {
510 for(int i=0;i<path.length;i++) {
511 if (null == (parent = descend(parent, path[i]))) return null;
512 // System.out.println(parent.getClass());
518 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
520 * @param parent the node with children
521 * @param childNum the index of the child of <code>parent</code> to return
522 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
523 * if the child is not found.
525 private Accessible descend(Accessible parent, int childNum) {
526 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
527 return parent.getAccessibleContext().getAccessibleChild(childNum);
530 public static void main(String[] args) {
531 new MarketUploader();
535 * Set the global window variable after the YPP window is created,
536 * remove the top level window listener, and start the GUI
538 public void topLevelWindowCreated(Window w) {
540 EventQueueMonitor.removeTopLevelWindowListener(this);
545 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
547 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
549 private boolean isDisplayAll() {
550 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
551 if(!(button instanceof JButton)) {
552 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
554 String display = button.getAccessibleContext().getAccessibleName();
555 if(!display.equals("All")) {
561 public void topLevelWindowDestroyed(Window w) {}
563 public void guiInitialized() {
568 * Gets the list of commodities and their associated commodity ids.
569 * On the first run, the data is downloaded from the PCTB server.
570 * After the first run, the data is cached using <code>Preferences</code>.
572 * Potential issues: When more commodities are added to the server, this
573 * program will currently break unless the user deletes the preferences
574 * file or we give them a new release with a slighly different storage
575 * location for the data.
577 * @return a map where the key is the commodity and the value is the commodity id.
579 private HashMap<String,Integer> getCommodMap() {
580 if(commodMap != null) {
583 HashMap<String,Integer> map = new HashMap<String,Integer>();
584 Preferences prefs = Preferences.userNodeForPackage(getClass());
587 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
588 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
589 StringBuilder sb = new StringBuilder();
591 while((str = br.readLine()) != null) {
594 int first = sb.indexOf("<pre>") + 5;
595 int last = sb.indexOf("</body>");
596 xml = sb.substring(first,last);
597 //System.out.println(xml);
598 Reader reader = new CharArrayReader(xml.toCharArray());
599 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
600 NodeList maps = d.getElementsByTagName("c");
601 for(int i=0;i<maps.getLength();i++) {
602 NodeList content = maps.item(i).getChildNodes();
603 Integer num = Integer.parseInt(content.item(1).getTextContent());
604 map.put(content.item(0).getTextContent(),num);
606 } catch(Exception e) {
608 error("Unable to load Commodity list from server!");
616 * Given the list of offers, this method will find all the unique stall names
617 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
618 * and the value is the generated stall id (position in the list).
620 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
621 * for iterating over the stall names in insertion order for output to the server.
623 * @param offers the list of records from the commodity buy/sell interface
624 * @return an iterable ordered map of the stall names and generated stall ids
626 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
628 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
629 for(ArrayList<String> offer : offers) {
630 String shop = offer.get(1);
631 if(!map.containsKey(shop)) {
640 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
641 * should be pre-initialized and passed into the method to receive the data.
642 * Returns a 2-length int array with the number of buys and sells found.
644 * @param offers the data found from the market table in-game
645 * @param buys an empty initialized <code>TreeSet<Offer></code> to
646 * hold the Buy offers.
647 * @param sells an empty initialized <code>TreeSet<Offer></code> to
648 * hold the Sell offers.
649 * @param stalls the map of stalls to their ids
650 * @param commodMap the map of commodities to their ids
651 * @return a 2-length int[] array containing the number of buys and sells, respectively
653 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
654 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
655 int[] buySellCount = new int[2];
656 for(ArrayList<String> offer : offers) {
658 if(offer.get(2) != null) {
659 buys.add(new Buy(offer,stalls,commodMap));
662 if(offer.get(4) != null) {
663 sells.add(new Sell(offer,stalls,commodMap));
666 } catch(IllegalArgumentException e) {
667 // System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
674 * Prepares the list of stalls for writing to the output stream.
675 * The <code>String</code> returned by this method is ready to be written
676 * directly to the stream.
678 * All shoppe names are left as they are. Stall names are abbreviated just before the
679 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
680 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
682 * @param stallMap the map of stalls and stall ids in an iterable order
683 * @return a <code>String</code> containing the list of stalls in format ready
684 * to be written to the output stream.
686 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
687 // set up some mapping
688 HashMap<String,String> types = new HashMap<String,String>();
689 types.put("Apothecary Stall", "A");
690 types.put("Distilling Stall", "D");
691 types.put("Furnishing Stall", "F");
692 types.put("Ironworking Stall", "I");
693 types.put("Shipbuilding Stall", "S");
694 types.put("Tailoring Stall", "T");
695 types.put("Weaving Stall", "W");
697 StringBuilder sb = new StringBuilder();
698 for(String name : stallMap.keySet()) {
699 int index = name.indexOf("'s");
700 String finalName = name;
703 finalName = name.substring(0,index);
704 if(index + 2 < name.length()) {
705 String end = name.substring(index+2,name.length()).trim();
706 type = types.get(end);
710 sb.append(name+"\n");
712 sb.append(finalName+"^"+type+"\n");
715 return sb.toString();
719 * Writes a list of offers in correct format to the output stream.
721 * The format is thus: (all numbers are 2-byte integers in little-endian format)
722 * (number of offers of this type, aka buy/sell)
723 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
725 * @param out the output stream to write the data to
726 * @param offers the offers to write
728 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
729 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
730 if(offers.size() == 0) {
731 // nothing to write, and "0" has already been written
734 int commodity = offers.first().commodity;
736 for(Offer offer : offers) {
737 if(commodity != offer.commodity) {
739 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
741 commodity = offer.commodity;
744 writeLEShort(offer.shoppe,buffer); // stall index
745 writeLEShort(offer.price,buffer); // buy price
746 writeLEShort(offer.quantity,buffer); // buy qty
749 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
753 * Writes the buffered data to the output strea for one commodity.
755 * @param out the stream to write to
756 * @param buffer the buffered data to write
757 * @param commodity the commmodity id to write before the buffered data
758 * @param count the number of offers for this commodity to write before the data
760 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
761 writeLEShort(commodity,out); // commod index
762 writeLEShort(count,out); // offer count
763 out.write(buffer); // the buffered offers
767 * Writes the buy and sell offers to the outputstream by calling other methods.
769 * @param buys list of Buy offers to write
770 * @param sells list of Sell offers to write
771 * @param offerCount 2-length int array containing the number of buys and sells to write out
772 * @param out the stream to write to
774 private void writeBuySellOffers(TreeSet<Offer> buys,
775 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
777 writeLEShort(offerCount[0],out);
778 writeOffers(out,buys);
780 writeLEShort(offerCount[1],out);
781 writeOffers(out,sells);
785 * Sends the data to the server via multipart-formdata POST,
786 * with the gzipped data as a file upload.
788 * @param file an InputStream open to the gzipped data we want to send
790 private InputStream sendInitialData(InputStream file) throws IOException {
791 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
792 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
797 * Utility method to write a 2-byte int in little-endian form to an output stream.
799 * @param num an integer to write
800 * @param out stream to write to
802 private void writeLEShort(int num, OutputStream out) throws IOException {
803 out.write(num & 0xFF);
804 out.write((num >>> 8) & 0xFF);
808 * Reads the response from the server, and selects the correct parameters
809 * which are sent in a GET request to the server asking it to confirm
810 * the upload and accept the data into the database. Notably, the island id
811 * and ocean id are determined, while other parameter such as the filename
812 * are determined from the hidden form fields.
814 * @param in stream of data from the server to read
816 private void finishUpload(InputStream in) throws IOException {
817 StringBuilder sb = new StringBuilder();
818 BufferedReader br = new BufferedReader(new InputStreamReader(in));
820 while((str = br.readLine()) != null) {
823 String html = sb.toString();
824 //System.out.println(html);
825 String topIsland = "0", ocean, islandNum, action, forceReload, filename;
827 Pattern whoIsland = Pattern.compile("<option value=\"\\d+\">" + islandName + ", ([^<]+)</ocean>");
828 m = whoIsland.matcher(html);
830 // the server agrees with us
831 ocean = islandNumbers.get(m.group(1));
833 // if the server doesn't agree with us:
834 Pattern island = Pattern.compile("<option value=\"(\\d+)\">([^,]+), ([^<]+)</ocean>");
835 m = island.matcher(html);
837 // server doesn't know what island. if we do, let's select it.
838 if(islandName != null && !islandName.equals("")) {
839 // find the island name in the list as many times as it occurs
840 // if more than once, present a dialog
841 // set the ocean, we have the islandname, topIsland = 0
842 Pattern myIsland = Pattern.compile("islands\\[(\\d+)\\]\\[\\d+\\]=new Option\\(\"" + islandName +
844 Matcher m1 = myIsland.matcher(html);
845 ArrayList<Integer> myOceanNums = new ArrayList<Integer>();
847 myOceanNums.add(new Integer(m1.group(1)));
849 if(myOceanNums.size() > 0) {
850 if(myOceanNums.size() > 1) {
851 String[] myOceansList = new String[myOceanNums.size()];
853 for(int myOcean : myOceanNums) {
854 Pattern oceanNumPat = Pattern.compile("<option value=\"\\" + myOcean + "\">([^<]+)</option>");
855 m1 = oceanNumPat.matcher(html);
857 myOceansList[i++] = m1.group(1);
860 Object option = JOptionPane.showInputDialog(null,"We found islands named \"" +
861 islandName +"\" on " + myOceansList.length + " oceans:","Choose Ocean",
862 JOptionPane.QUESTION_MESSAGE, null, myOceansList, null);
864 error("Unable to determine the current island!");
867 ocean = islandNumbers.get(option).toString();
869 ocean = myOceanNums.get(0).toString();
872 error("Unknown island!");
876 error("Unable to determine island name from the client!");
880 topIsland = m.group(1);
881 islandName = m.group(2);
882 ocean = islandNumbers.get(m.group(3));
885 Pattern oceanIslandNum = Pattern.compile("islands\\[" + ocean + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
886 m = oceanIslandNum.matcher(html);
888 error("This does not seem to be a valid island! Unable to upload.");
891 islandNum = m.group(1);
892 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
893 m = params.matcher(html);
895 error("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?");
899 forceReload = m.group(2);
900 filename = m.group(3);
901 URL get = new URL(PCTB_HOST_URL + "upload.php?topisland=" + topIsland + "&ocean=" + ocean + "&island="
902 + islandNum + "&action=" + action + "&forcereload=" + forceReload + "&filename=" + filename);
903 // System.out.println(get);
904 BufferedReader br2 = new BufferedReader(new InputStreamReader(get.openStream()));
905 sb = new StringBuilder();
906 while((str = br2.readLine()) != null) {
909 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
910 m = done.matcher(sb.toString());
912 //System.out.println("FILE upload successful!!!");
914 error("Something was wrong with the final upload parameters!");
915 System.err.println(sb.toString());
916 System.err.println(html);
920 private String getYarrgTimestamp() throws IOException {
921 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
922 http.setParameter("clientname", YARRG_CLIENTNAME);
923 http.setParameter("clientversion", YARRG_CLIENTVERSION);
924 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
925 http.setParameter("requesttimestamp", "y");
926 InputStream in = http.post();
927 BufferedReader br = new BufferedReader(new InputStreamReader(in));
928 String tsresult = br.readLine();
929 return tsresult.substring(3, tsresult.length()-1);
932 private void 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 = http.post();
948 BufferedReader br = new BufferedReader(new InputStreamReader(in));
950 while((yarrgresult = br.readLine()) != null) {
951 System.out.println(yarrgresult);