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;
23 import com.tedpearson.util.update.*;
27 allow adding new islands
28 allow adding new oceans
32 * MarketUploader is a class that handles the uploading of market data from
33 * Yohoho! Puzzle Pirates. Currently, it must be launched in the save Java
34 * Virtual Machine as YPP. This is handled by a sister "helper" class,
35 * {@link MarketUploaderRunner}.
37 * MarketUploader initializes after the main YPP window has initialized. It
38 * provides a simple window with a "Capture Market Data" button displayed.
39 * Upon clicking this button, a progress dialog is displayed, and the data
40 * is processed and submitted to the Pirate Commodities Trader with Bleach (PCTB)
41 * web server. If any errors occur, an error dialog is shown, and processing
42 * returns, the button becoming re-enabled.
44 * @see MarketUploaderRunner
46 public class MarketUploader implements TopLevelWindowListener, GUIInitializedListener {
47 private JFrame frame = null;
48 private Window window = null;
49 private JButton findMarket = null;
51 private final static String PCTB_LIVE_HOST_URL = "http://pctb.crabdance.com/";
52 private final static String PCTB_TEST_HOST_URL = "http://pctb.ilk.org/";
53 private String PCTB_HOST_URL;
55 // Yarrg protocol parameters
56 private final static String YARRG_CLIENTNAME = "jpctb greenend";
57 private final static String YARRG_CLIENTVERSION = "0.1";
58 private final static String YARRG_CLIENTFIXES = "";
59 private final static String YARRG_LIVE_URL = "http://upload.yarrg.chiark.net/commod-update-receiver";
60 private final static String YARRG_TEST_URL = "http://upload.yarrg.chiark.net/test/commod-update-receiver";
61 private String YARRG_URL;
63 private boolean uploadToYarrg;
64 private boolean uploadToPCTB;
66 private String islandName = null;
67 private String oceanName = null;
68 private java.util.concurrent.CountDownLatch latch = null;
70 private AccessibleContext sidePanel;
71 private HashMap<String,Integer> commodMap;
72 private HashMap<String,String> islandNumbers = new HashMap<String,String>();
74 String[] nums = new String[]
75 {"","Viridian","Midnight","Hunter","Cobalt","Sage","Ice","Malachite","Crimson","Opal"};
76 for(int i=1;i<nums.length;i++) {
77 islandNumbers.put(nums[i],""+i);
80 private PropertyChangeListener changeListener = new PropertyChangeListener() {
81 public void propertyChange(PropertyChangeEvent e) {
82 if(e.getNewValue() != null &&
83 e.getPropertyName().equals(AccessibleContext.ACCESSIBLE_CHILD_PROPERTY)) {
84 Accessible islandInfo = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0,0,1,2});;
85 String text = islandInfo.getAccessibleContext().getAccessibleText().getAtIndex(AccessibleText.SENTENCE,0);
86 int index = text.indexOf(":");
87 String name = text.substring(0,index);
89 //System.out.println(islandName);
90 sidePanel.removePropertyChangeListener(this);
97 * An abstract market offer, entailing a commodity being bought or sold by
98 * a shoppe, for a certain price in a certain quantity. Not instantiable.
103 abstract class Offer {
104 public int commodity, price, quantity, shoppe;
106 * Create an offer from <code>record</code>, determining the shoppe Id from
107 * <code>stallMap</code> and the commodity Id from <code>commodMap</code>.
108 * <code>priceIndex</code> should be the index of the price in the record
109 * (the quantity will be <code>priceIndex + 1</code>).
111 * @param record the record with data to create the offer from
112 * @param stallMap a map containing the ids of the various stalls
113 * @param commodMap a map containing the ids of the various commodities
114 * @param priceIndex the index of the price in the record
116 public Offer(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap,
118 Integer commodId = commodMap.get(record.get(0));
119 if(commodId == null) {
120 throw new IllegalArgumentException();
122 commodity = commodId.intValue();
123 price = Integer.parseInt(record.get(priceIndex));
124 String qty = record.get(priceIndex+1);
125 if(qty.equals(">1000")) {
128 quantity = Integer.parseInt(record.get(priceIndex+1));
130 shoppe = stallMap.get(record.get(1)).intValue();
134 * Returns a human-readable version of this offer, useful for debugging
136 * @return human-readable offer
138 public String toString() {
139 return "[C:" + commodity + ",$" + price + ",Q:" + quantity + ",S:" + shoppe + "]";
144 * An offer from a shoppe or stall to buy a certain quantity of a commodity
145 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
146 * then by buy price descending, and finally by stall id ascending.
148 class Buy extends Offer implements Comparable<Buy> {
150 * Creates a new <code>Buy</code> offer from the given <code>record</code>
151 * using the other parameters to determine stall id and commodity id of the offer.
153 * @param record the record with data to create the offer from
154 * @param stallMap a map containing the ids of the various stalls
155 * @param commodMap a map containing the ids of the various commodities
157 public Buy(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
158 super(record,stallMap,commodMap,2);
162 * Sorts by commodity index ascending, then price descending, then stall id ascending.
164 public int compareTo(Buy buy) {
165 // organize by: commodity index, price, stall index
166 if(commodity == buy.commodity) {
167 // organize by price, then by stall index
168 if(price == buy.price) {
169 // organize by stall index
170 return shoppe>buy.shoppe ? 1 : -1;
171 } else if(price > buy.price) {
176 } else if(commodity > buy.commodity) {
185 * An offer from a shoppe or stall to sell a certain quantity of a commodity
186 * for a certain price. If placed in an ordered Set, sorts by commodity index ascending,
187 * then by sell price ascending, and finally by stall id ascending.
189 class Sell extends Offer implements Comparable<Sell> {
191 * Creates a new <code>Sell</code> offer from the given <code>record</code>
192 * using the other parameters to determine stall id and commodity id of the offer.
194 * @param record the record with data to create the offer from
195 * @param stallMap a map containing the ids of the various stalls
196 * @param commodMap a map containing the ids of the various commodities
198 public Sell(ArrayList<String> record, LinkedHashMap<String,Integer> stallMap, HashMap<String,Integer> commodMap) {
199 super(record,stallMap,commodMap,4);
203 * Sorts by commodity index ascending, then price ascending, then stall id ascending.
205 public int compareTo(Sell sell) {
206 // organize by: commodity index, price, stall index
207 if(commodity == sell.commodity) {
208 // organize by price, then by stall index
209 if(price == sell.price) {
210 // organize by stall index
211 return shoppe>sell.shoppe ? 1 : -1;
212 } else if(price > sell.price) {
217 } else if(commodity > sell.commodity) {
226 * Entry point. Remove modified files and replace with backups.
227 * Register the jar file we are running from to be deleted upon quit.
228 * Finally, conditionally set up the GUI.
230 public MarketUploader() {
231 // check if we've been turned off in the control panel
232 Preferences prefs = Preferences.userNodeForPackage(getClass());
233 boolean launch = prefs.getBoolean("launchAtStartup", true);
238 if (prefs.getBoolean("useLiveServers", false)) {
239 YARRG_URL = YARRG_LIVE_URL;
240 PCTB_HOST_URL = PCTB_LIVE_HOST_URL;
242 YARRG_URL = YARRG_TEST_URL;
243 PCTB_HOST_URL = PCTB_TEST_HOST_URL;
246 uploadToYarrg=prefs.getBoolean("uploadToYarrg", true);
247 uploadToPCTB=prefs.getBoolean("uploadToPCTB", true);
249 EventQueueMonitor.addTopLevelWindowListener(this);
250 if (EventQueueMonitor.isGUIInitialized()) {
253 EventQueueMonitor.addGUIInitializedListener(this);
258 * Set up the GUI, with its window and one-button interface. Only initialize
259 * if we're running alongside a Window named "Puzzle Pirates" though.
261 private void createGUI() {
262 if (frame != null && window != null) {
263 if (window.getAccessibleContext().getAccessibleName().equals("Puzzle Pirates")) frame.setVisible(true);
266 frame = new JFrame("MarketUploader");
267 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
268 frame.getContentPane().setLayout(new FlowLayout());
269 //frame.setPreferredSize(new Dimension(200, 60));
271 findMarket = new JButton("Upload Market Data");
272 findMarket.addActionListener(new ActionListener() {
273 public void actionPerformed(ActionEvent e) {
274 findMarket.setEnabled(false);
279 } catch(Exception e) {
283 if(sidePanel != null) {
284 // remove it if it's still attached
285 sidePanel.removePropertyChangeListener(changeListener);
289 findMarket.setEnabled(true);
294 frame.add(findMarket);
299 * Finds the island name from the /who tab, sets global islandName variable
301 private void getIsland() {
303 // If the league tracker is there, we can skip the faff
304 // and ask for its tooltip, since we're on a boat
306 Accessible leagueTracker = descendNodes(window,new int[] {0,1,0,0,2,1,1,1});
308 latch = new java.util.concurrent.CountDownLatch(0);
309 islandName = ((JLabel)leagueTracker).getToolTipText();
310 } catch (NullPointerException e) {
312 // evidently we're actually on an island
315 AccessibleContext chatArea = descendNodes(window,new int[] {0,1,0,0,0,2,0,0,2}).getAccessibleContext();
316 // attach the property change listener to the outer sunshine panel if the "ahoy" tab
317 // is not active, otherwise attach it to the scroll panel in the "ahoy" tab.
318 if(!"com.threerings.piracy.client.AttentionListPanel".
319 equals(descendNodes(window,new int[] {0,1,0,0,2,2,0}).getClass().getCanonicalName())) {
320 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2}).getAccessibleContext();
322 sidePanel = descendNodes(window,new int[] {0,1,0,0,2,2,0,0,0}).getAccessibleContext();
324 sidePanel.addPropertyChangeListener(changeListener);
325 latch = new java.util.concurrent.CountDownLatch(1);
326 // make the Players Online ("/who") panel appear
327 AccessibleEditableText chat = chatArea.getAccessibleEditableText();
328 chat.setTextContents("/w");
329 int c = chatArea.getAccessibleAction().getAccessibleActionCount();
330 for(int i=0;i<c;i++) {
331 if("notify-field-accept".equals(chatArea.getAccessibleAction().getAccessibleActionDescription(i))) {
332 chatArea.getAccessibleAction().doAccessibleAction(i);
336 // if we don't find the island name, hopefully the server will
340 * Find the ocean name from the window title, and set global oceanName variable
342 private void getOcean() {
344 AccessibleContext topwindow = window.getAccessibleContext();
345 oceanName = topwindow.getAccessibleName().replaceAll(".*on the (\\w+) ocean", "$1");
350 * Shows a dialog with the error <code>msg</code>.
352 * @param msg a String describing the error that occured.
354 private void error(String msg) {
355 JOptionPane.showMessageDialog(frame,msg,"Error",JOptionPane.ERROR_MESSAGE);
359 * Run the data collection process, and upload the results. This is the method
360 * that calls most of the other worker methods for the process. If an error occurs,
361 * the method will call the error method and return early, freeing up the button
362 * to be clicked again.
364 * @exception Exception if an error we didn't expect occured
366 private void runPCTB() throws Exception {
368 ProgressMonitor pm = new ProgressMonitor(frame,"Processing Market Data","Getting table data",0,100);
369 pm.setMillisToDecideToPopup(0);
370 pm.setMillisToPopup(0);
373 yarrgts = getYarrgTimestamp();
376 AccessibleTable t = findMarketTable();
378 error("Market table not found! Please open the Buy/Sell Commodities interface.");
381 if(t.getAccessibleRowCount() == 0) {
382 error("No data found, please wait for the table to have data first!");
385 if(!isDisplayAll()) {
386 error("Please select \"All\" from the Display: popup menu.");
393 latch.await(2, java.util.concurrent.TimeUnit.SECONDS);
395 ArrayList<ArrayList<String>> data = getData(t);
398 pm.setNote("Preparing data for Yarrg");
401 StringBuilder yarrgsb = new StringBuilder();
402 String yarrgdata; // string containing what we'll feed to yarrg
404 for (ArrayList<String> row : data) {
405 if (row.size() > 6) {
408 for (String rowitem : row) {
409 yarrgsb.append(rowitem != null ? rowitem : "");
410 yarrgsb.append("\t");
412 yarrgsb.setLength(yarrgsb.length()-1); // chop
413 yarrgsb.append("\n");
416 yarrgdata = yarrgsb.toString();
418 pm.setNote("Uploading to Yarrg");
420 if (islandName != null) {
421 runYarrg(yarrgts, oceanName, islandName, yarrgdata);
423 System.out.println("Couldn't upload to Yarrg - no island name found");
427 pm.setNote("Getting stall names");
429 if(pm.isCanceled()) {
432 TreeSet<Offer> buys = new TreeSet<Offer>();
433 TreeSet<Offer> sells = new TreeSet<Offer>();
434 LinkedHashMap<String,Integer> stallMap = getStallMap(data);
436 pm.setNote("Sorting offers");
437 if(pm.isCanceled()) {
442 HashMap<String,Integer> commodMap = getCommodMap();
443 if(commodMap == null) {
446 int[] offerCount = getBuySellMaps(data,buys,sells,stallMap,commodMap);
447 //println(buys.toString());
448 //System.out.println(sells);
449 //System.out.println("\n\n\n"+buys);
452 ByteArrayOutputStream outStream = new ByteArrayOutputStream();
454 pm.setNote("Sending data");
455 if(pm.isCanceled()) {
458 GZIPOutputStream out = new GZIPOutputStream(outStream);
459 //FileOutputStream out = new FileOutputStream(new File("output.text"));
460 DataOutputStream dos = new DataOutputStream(out);
461 dos.writeBytes("005\n");
462 dos.writeBytes(stallMap.size()+"\n");
463 dos.writeBytes(getAbbrevStallList(stallMap));
464 writeBuySellOffers(buys,sells,offerCount,out);
466 InputStream in = sendInitialData(new ByteArrayInputStream(outStream.toByteArray()));
468 if(pm.isCanceled()) {
471 pm.setNote("Waiting for PCTB...");
478 * Get the offer data out of the table and cache it in an <code>ArrayList</code>.
480 * @param table the <code>AccessibleTable</code> containing the market data
481 * @return an array of record arrays, each representing a row of the table
483 private ArrayList<ArrayList<String>> getData(AccessibleTable table) {
484 ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
485 for (int i = 0; i < table.getAccessibleRowCount(); i++) {
486 ArrayList<String> row = new ArrayList<String>();
487 for (int j = 0; j < table.getAccessibleColumnCount(); j++) {
488 row.add(table.getAccessibleAt(i, j).getAccessibleContext().getAccessibleName());
496 * @return the table containing market data if it exists, otherwise <code>null</code>
498 public AccessibleTable findMarketTable() {
499 Accessible node1 = window;
500 Accessible node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,0,1,0,0}); // commod market
501 // 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})
502 //System.out.println(node);
503 if (!(node instanceof JTable)) {
504 node = descendNodes(node1,new int[] {0,1,0,0,0,0,1,0,1,0,0,1,0,0}); // commod market
506 if (!(node instanceof JTable)) return null;
507 AccessibleTable table = node.getAccessibleContext().getAccessibleTable();
508 //System.out.println(table);
513 * Utility method to descend through several levels of Accessible children
516 * @param parent the node on which to start the descent
517 * @param path an array of ints, each int being the index of the next
518 * accessible child to descend.
519 * @return the <code>Accessible</code> reached by following the descent path,
520 * or <code>null</code> if the desired path was invalid.
522 private Accessible descendNodes(Accessible parent, int[] path) {
523 for(int i=0;i<path.length;i++) {
524 if (null == (parent = descend(parent, path[i]))) return null;
525 // System.out.println(parent.getClass());
531 * Descends one level to the specified child of the parent <code>Accessible</code> "node".
533 * @param parent the node with children
534 * @param childNum the index of the child of <code>parent</code> to return
535 * @return the <code>childNum</code> child of <code>parent</code> or <code>null</code>
536 * if the child is not found.
538 private Accessible descend(Accessible parent, int childNum) {
539 if (childNum >= parent.getAccessibleContext().getAccessibleChildrenCount()) return null;
540 return parent.getAccessibleContext().getAccessibleChild(childNum);
543 public static void main(String[] args) {
544 new MarketUploader();
548 * Set the global window variable after the YPP window is created,
549 * remove the top level window listener, and start the GUI
551 public void topLevelWindowCreated(Window w) {
553 EventQueueMonitor.removeTopLevelWindowListener(this);
558 * Returns true if the "Display:" menu on the commodities interface in YPP is set to "All"
560 * @return <code>true</code> if all commodities are displayed, otherwise <code>false</code>
562 private boolean isDisplayAll() {
563 Accessible button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,0,0,1});
564 if(!(button instanceof JButton)) {
565 button = descendNodes(window,new int[] {0,1,0,0,0,0,1,0,1,0,0,0,1});
567 String display = button.getAccessibleContext().getAccessibleName();
568 if(!display.equals("All")) {
574 public void topLevelWindowDestroyed(Window w) {}
576 public void guiInitialized() {
581 * Gets the list of commodities and their associated commodity ids.
582 * On the first run, the data is downloaded from the PCTB server.
583 * After the first run, the data is cached using <code>Preferences</code>.
585 * Potential issues: When more commodities are added to the server, this
586 * program will currently break unless the user deletes the preferences
587 * file or we give them a new release with a slighly different storage
588 * location for the data.
590 * @return a map where the key is the commodity and the value is the commodity id.
592 private HashMap<String,Integer> getCommodMap() {
593 if(commodMap != null) {
596 HashMap<String,Integer> map = new HashMap<String,Integer>();
597 Preferences prefs = Preferences.userNodeForPackage(getClass());
600 URL host = new URL(PCTB_HOST_URL + "commodmap.php");
601 BufferedReader br = new BufferedReader(new InputStreamReader(host.openStream()));
602 StringBuilder sb = new StringBuilder();
604 while((str = br.readLine()) != null) {
607 int first = sb.indexOf("<pre>") + 5;
608 int last = sb.indexOf("</body>");
609 xml = sb.substring(first,last);
610 //System.out.println(xml);
611 Reader reader = new CharArrayReader(xml.toCharArray());
612 Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(reader));
613 NodeList maps = d.getElementsByTagName("c");
614 for(int i=0;i<maps.getLength();i++) {
615 NodeList content = maps.item(i).getChildNodes();
616 Integer num = Integer.parseInt(content.item(1).getTextContent());
617 map.put(content.item(0).getTextContent(),num);
619 } catch(Exception e) {
621 error("Unable to load Commodity list from server!");
629 * Given the list of offers, this method will find all the unique stall names
630 * and return them in a <code>LinkedHashMap</code> where the key is the stall name
631 * and the value is the generated stall id (position in the list).
633 * The reason this method returns a LinkedHashMap instead of a simple HashMap is the need
634 * for iterating over the stall names in insertion order for output to the server.
636 * @param offers the list of records from the commodity buy/sell interface
637 * @return an iterable ordered map of the stall names and generated stall ids
639 private LinkedHashMap<String,Integer> getStallMap(ArrayList<ArrayList<String>> offers) {
641 LinkedHashMap<String,Integer> map = new LinkedHashMap<String,Integer>();
642 for(ArrayList<String> offer : offers) {
643 String shop = offer.get(1);
644 if(!map.containsKey(shop)) {
653 * Gets a sorted list of Buys and Sells from the list of records. <code>buys</code> and <code>sells</code>
654 * should be pre-initialized and passed into the method to receive the data.
655 * Returns a 2-length int array with the number of buys and sells found.
657 * @param offers the data found from the market table in-game
658 * @param buys an empty initialized <code>TreeSet<Offer></code> to
659 * hold the Buy offers.
660 * @param sells an empty initialized <code>TreeSet<Offer></code> to
661 * hold the Sell offers.
662 * @param stalls the map of stalls to their ids
663 * @param commodMap the map of commodities to their ids
664 * @return a 2-length int[] array containing the number of buys and sells, respectively
666 private int[] getBuySellMaps(ArrayList<ArrayList<String>> offers, TreeSet<Offer> buys,
667 TreeSet<Offer> sells, LinkedHashMap<String,Integer> stalls, HashMap<String,Integer> commodMap) {
668 int[] buySellCount = new int[2];
669 for(ArrayList<String> offer : offers) {
671 if(offer.get(2) != null) {
672 buys.add(new Buy(offer,stalls,commodMap));
675 if(offer.get(4) != null) {
676 sells.add(new Sell(offer,stalls,commodMap));
679 } catch(IllegalArgumentException e) {
680 // System.err.println("Error: Unsupported Commodity \"" + offer.get(0) + "\"");
687 * Prepares the list of stalls for writing to the output stream.
688 * The <code>String</code> returned by this method is ready to be written
689 * directly to the stream.
691 * All shoppe names are left as they are. Stall names are abbreviated just before the
692 * apostrophe in the possessive, with an "^" and a letter matching the stall's type
693 * appended. Example: "Burninator's Ironworking Stall" would become "Burninator^I".
695 * @param stallMap the map of stalls and stall ids in an iterable order
696 * @return a <code>String</code> containing the list of stalls in format ready
697 * to be written to the output stream.
699 private String getAbbrevStallList(LinkedHashMap<String,Integer> stallMap) {
700 // set up some mapping
701 HashMap<String,String> types = new HashMap<String,String>();
702 types.put("Apothecary Stall", "A");
703 types.put("Distilling Stall", "D");
704 types.put("Furnishing Stall", "F");
705 types.put("Ironworking Stall", "I");
706 types.put("Shipbuilding Stall", "S");
707 types.put("Tailoring Stall", "T");
708 types.put("Weaving Stall", "W");
710 StringBuilder sb = new StringBuilder();
711 for(String name : stallMap.keySet()) {
712 int index = name.indexOf("'s");
713 String finalName = name;
716 finalName = name.substring(0,index);
717 if(index + 2 < name.length()) {
718 String end = name.substring(index+2,name.length()).trim();
719 type = types.get(end);
723 sb.append(name+"\n");
725 sb.append(finalName+"^"+type+"\n");
728 return sb.toString();
732 * Writes a list of offers in correct format to the output stream.
734 * The format is thus: (all numbers are 2-byte integers in little-endian format)
735 * (number of offers of this type, aka buy/sell)
736 * (commodity ID) (number of offers for this commodity) [shopID price qty][shopID price qty]...
738 * @param out the output stream to write the data to
739 * @param offers the offers to write
741 private void writeOffers(OutputStream out, TreeSet<Offer> offers) throws IOException {
742 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
743 if(offers.size() == 0) {
744 // nothing to write, and "0" has already been written
747 int commodity = offers.first().commodity;
749 for(Offer offer : offers) {
750 if(commodity != offer.commodity) {
752 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
754 commodity = offer.commodity;
757 writeLEShort(offer.shoppe,buffer); // stall index
758 writeLEShort(offer.price,buffer); // buy price
759 writeLEShort(offer.quantity,buffer); // buy qty
762 writeBufferedOffers(out,buffer.toByteArray(),commodity,count);
766 * Writes the buffered data to the output strea for one commodity.
768 * @param out the stream to write to
769 * @param buffer the buffered data to write
770 * @param commodity the commmodity id to write before the buffered data
771 * @param count the number of offers for this commodity to write before the data
773 private void writeBufferedOffers(OutputStream out, byte[] buffer, int commodity, int count) throws IOException {
774 writeLEShort(commodity,out); // commod index
775 writeLEShort(count,out); // offer count
776 out.write(buffer); // the buffered offers
780 * Writes the buy and sell offers to the outputstream by calling other methods.
782 * @param buys list of Buy offers to write
783 * @param sells list of Sell offers to write
784 * @param offerCount 2-length int array containing the number of buys and sells to write out
785 * @param out the stream to write to
787 private void writeBuySellOffers(TreeSet<Offer> buys,
788 TreeSet<Offer> sells, int[] offerCount, OutputStream out) throws IOException {
790 writeLEShort(offerCount[0],out);
791 writeOffers(out,buys);
793 writeLEShort(offerCount[1],out);
794 writeOffers(out,sells);
798 * Sends the data to the server via multipart-formdata POST,
799 * with the gzipped data as a file upload.
801 * @param file an InputStream open to the gzipped data we want to send
803 private InputStream sendInitialData(InputStream file) throws IOException {
804 ClientHttpRequest http = new ClientHttpRequest(PCTB_HOST_URL + "upload.php");
805 http.setParameter("marketdata","marketdata.gz",file,"application/gzip");
810 * Utility method to write a 2-byte int in little-endian form to an output stream.
812 * @param num an integer to write
813 * @param out stream to write to
815 private void writeLEShort(int num, OutputStream out) throws IOException {
816 out.write(num & 0xFF);
817 out.write((num >>> 8) & 0xFF);
821 * Reads the response from the server, and selects the correct parameters
822 * which are sent in a GET request to the server asking it to confirm
823 * the upload and accept the data into the database. Notably, the island id
824 * and ocean id are determined, while other parameter such as the filename
825 * are determined from the hidden form fields.
827 * @param in stream of data from the server to read
829 private void finishUpload(InputStream in) throws IOException {
830 StringBuilder sb = new StringBuilder();
831 BufferedReader br = new BufferedReader(new InputStreamReader(in));
833 while((str = br.readLine()) != null) {
836 String html = sb.toString();
837 //System.out.println(html);
838 String topIsland = "0", ocean, islandNum, action, forceReload, filename;
840 Pattern whoIsland = Pattern.compile("<option value=\"\\d+\">" + islandName + ", ([^<]+)</ocean>");
841 m = whoIsland.matcher(html);
843 // the server agrees with us
844 ocean = islandNumbers.get(m.group(1));
846 // if the server doesn't agree with us:
847 Pattern island = Pattern.compile("<option value=\"(\\d+)\">([^,]+), ([^<]+)</ocean>");
848 m = island.matcher(html);
850 // server doesn't know what island. if we do, let's select it.
851 if(islandName != null && !islandName.equals("")) {
852 // find the island name in the list as many times as it occurs
853 // if more than once, present a dialog
854 // set the ocean, we have the islandname, topIsland = 0
855 Pattern myIsland = Pattern.compile("islands\\[(\\d+)\\]\\[\\d+\\]=new Option\\(\"" + islandName +
857 Matcher m1 = myIsland.matcher(html);
858 ArrayList<Integer> myOceanNums = new ArrayList<Integer>();
860 myOceanNums.add(new Integer(m1.group(1)));
862 if(myOceanNums.size() > 0) {
863 if(myOceanNums.size() > 1) {
864 String[] myOceansList = new String[myOceanNums.size()];
866 for(int myOcean : myOceanNums) {
867 Pattern oceanNumPat = Pattern.compile("<option value=\"\\" + myOcean + "\">([^<]+)</option>");
868 m1 = oceanNumPat.matcher(html);
870 myOceansList[i++] = m1.group(1);
873 Object option = JOptionPane.showInputDialog(null,"We found islands named \"" +
874 islandName +"\" on " + myOceansList.length + " oceans:","Choose Ocean",
875 JOptionPane.QUESTION_MESSAGE, null, myOceansList, null);
877 error("Unable to determine the current island!");
880 ocean = islandNumbers.get(option).toString();
882 ocean = myOceanNums.get(0).toString();
885 error("Unknown island!");
889 error("Unable to determine island name from the client!");
893 topIsland = m.group(1);
894 islandName = m.group(2);
895 ocean = islandNumbers.get(m.group(3));
898 Pattern oceanIslandNum = Pattern.compile("islands\\[" + ocean + "\\]\\[\\d+\\]=new Option\\(\"" + islandName + "\",(\\d+)");
899 m = oceanIslandNum.matcher(html);
901 error("This does not seem to be a valid island! Unable to upload.");
904 islandNum = m.group(1);
905 Pattern params = Pattern.compile("(?s)<input type=\"hidden\" name=\"action\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"forcereload\" value=\"([^\"]+)\" />.+?<input type=\"hidden\" name=\"filename\" value=\"([^\"]+)\" />");
906 m = params.matcher(html);
908 error("The PCTB server returned unusual data. Maybe you're using an old version of the uploader?");
912 forceReload = m.group(2);
913 filename = m.group(3);
914 URL get = new URL(PCTB_HOST_URL + "upload.php?topisland=" + topIsland + "&ocean=" + ocean + "&island="
915 + islandNum + "&action=" + action + "&forcereload=" + forceReload + "&filename=" + filename);
916 // System.out.println(get);
917 BufferedReader br2 = new BufferedReader(new InputStreamReader(get.openStream()));
918 sb = new StringBuilder();
919 while((str = br2.readLine()) != null) {
922 Pattern done = Pattern.compile("Your data has been integrated into the database. Thank you!");
923 m = done.matcher(sb.toString());
925 //System.out.println("FILE upload successful!!!");
927 error("Something was wrong with the final upload parameters!");
928 System.err.println(sb.toString());
929 System.err.println(html);
933 private String getYarrgTimestamp() throws IOException {
934 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
935 http.setParameter("clientname", YARRG_CLIENTNAME);
936 http.setParameter("clientversion", YARRG_CLIENTVERSION);
937 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
938 http.setParameter("requesttimestamp", "y");
939 InputStream in = http.post();
940 BufferedReader br = new BufferedReader(new InputStreamReader(in));
941 String tsresult = br.readLine();
942 return tsresult.substring(3, tsresult.length()-1);
945 private void runYarrg(String timestamp, String ocean, String island, String yarrgdata) throws IOException {
946 ByteArrayOutputStream bos = new ByteArrayOutputStream();
947 BufferedOutputStream bufos = new BufferedOutputStream(new GZIPOutputStream(bos));
948 bufos.write(yarrgdata.getBytes() );
950 ByteArrayInputStream file = new ByteArrayInputStream(bos.toByteArray());
952 ClientHttpRequest http = new ClientHttpRequest (YARRG_URL);
953 http.setParameter("clientname", YARRG_CLIENTNAME);
954 http.setParameter("clientversion", YARRG_CLIENTVERSION);
955 http.setParameter("clientfixes", YARRG_CLIENTFIXES);
956 http.setParameter("timestamp", timestamp);
957 http.setParameter("ocean", ocean);
958 http.setParameter("island", island);
959 http.setParameter("data", "deduped.tsv.gz", file, "application/octet-stream");
960 InputStream in = http.post();
961 BufferedReader br = new BufferedReader(new InputStreamReader(in));
963 while((yarrgresult = br.readLine()) != null) {
964 System.out.println(yarrgresult);