import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.StringTokenizer;
public class YahooStock {
private String ticker;
public YahooStock(String inTicker) {
ticker = inTicker;
}
private String retrieveQuote() {
StringBuffer buf = new StringBuffer();
try {
URL page = new URL("http://quote.yahoo.com/d/quotes.csv?s=" + ticker + "&f=sl1d1t1c1ohgv&e=.csv");
String line;
URLConnection conn = page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader data = new BufferedReader(in);
while ((line = data.readLine()) != null) {
buf.append(line + "\n");
}
} catch (MalformedURLException urle) {
System.out.println("Bad URL: " + urle.toString());
} catch (IOException ioe) {
System.out.println("Error: " + ioe.toString());
}
return buf.toString();
}
private void storeQuote(String data) {
StringTokenizer tokens = new StringTokenizer(data, ",");
String[] fields = new String[9];
for (int i = 0; i < fields.length; i++) {
fields[i] = stripQuotes(tokens.nextToken());
}
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://XXXX.X.X.XX:3306/QuoteData", "xxx", "xxx");
PreparedStatement prep2 = conn.prepareStatement("INSERT INTO yahoo(ticker, price, quoteDate, change, open, high, low, volume) VALUES(?,?,?,?,?,?,?,?)");
prep2.setString(1, fields[0]);
prep2.setString(2, fields[1]);
prep2.setString(3, fields[2]);
prep2.setString(4, fields[3]);
prep2.setString(5, fields[4]);
prep2.setString(6, fields[5]);
prep2.setString(7, fields[6]);
prep2.setString(8, fields[7]);
prep2.executeUpdate();
conn.close();
} catch (SQLException sqle) {
System.out.println("SQL Error: " + sqle.toString());
} catch (ClassNotFoundException cnfe) {
System.out.println("Error: " + cnfe.toString());
}
}
private String stripQuotes(String nextToken) {
StringBuffer output = new StringBuffer();
for (int i = 0; i < nextToken.length(); i++) {
if (nextToken.charAt(i) != '\"') {
output.append(nextToken.charAt(i));
}
}
return output.toString();
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("Usage: java YahooStock tickerSymbol");
System.exit(1);
}
YahooStock ys = new YahooStock(args[0]);
String data = ys.retrieveQuote();
ys.storeQuote(data);
}
}