/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Connection con = null;
    ResultSet rs = null;
    PreparedStatement pst = null;

    String user = request.getParameter("username");
    String dburl = "jdbc:mysql://localhost:3306/STOCK_APP";
    String dbuser = "******";
    String dbpassword = "******";

    try {

      con = DriverManager.getConnection(dburl, dbuser, dbpassword);
      pst = con.prepareStatement("SELECT * FROM USER_FAVORITES where USERNAME = ?");
      pst.setString(1, user);

      rs = pst.executeQuery();
      StringBuffer returnData;
      returnData = new StringBuffer("fail");
      List<String> symbolList = new ArrayList<String>();
      boolean hasResults = false;
      while (rs.next()) {
        symbolList.add(rs.getString(3));
        System.out.println(rs.getString(3));
        System.out.println("{\"user\":\"" + rs.getString(2) + "\"");
        hasResults = true;
      }

      if (hasResults) {

        returnData = new StringBuffer("{\"companies\":[");
        // Get Quote and Iterate through companies
        String[] symbols = symbolList.toArray(new String[symbolList.size()]);
        Map<String, Stock> stocks = YahooFinance.get(symbols, true);
        int count = 0;
        for (Map.Entry<String, Stock> stock : stocks.entrySet()) {
          count++;
          returnData.append(getGraphData(stock.getValue().getSymbol(), "1"));
          if (count < stocks.entrySet().size()) {
            returnData.append(",");
          }
        }
        returnData.append("]}");
      } else {
        returnData = new StringBuffer("{\"favorites\":[],");
        returnData.append("\"stats\":{}");
        returnData.append("}");
      }

      System.out.println(returnData.toString());
      response.getWriter().write(returnData.toString());

    } catch (SQLException ex) {
      Logger lgr = Logger.getLogger(Test.class.getName());
      lgr.log(Level.SEVERE, ex.getMessage(), ex);

    } finally {

      try {

        if (pst != null) {
          pst.close();
        }
        if (con != null) {
          con.close();
        }

      } catch (SQLException ex) {
        Logger lgr = Logger.getLogger(Test.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
      }
    }
  }
  private static String getGraphData(String sym, String option) {
    Stock stock = YahooFinance.get(sym);

    if (stock.getName() != null && stock.getName() != "" && !stock.getName().equals("N/A")) {
      System.out.println(stock.getName());

      ArrayList<String> dates = new ArrayList();
      ArrayList<String> values = new ArrayList();
      BigDecimal firstb = new BigDecimal(1);
      BigDecimal lastb = new BigDecimal(1);
      boolean first = true;
      if (option.equals("1")) {
        // 1 Year
        Calendar end = Calendar.getInstance();
        Calendar start = Calendar.getInstance();
        start.add(Calendar.YEAR, -1);
        List<HistoricalQuote> history = stock.getHistory(start, end, Interval.WEEKLY);
        Iterator<HistoricalQuote> historyItr = history.iterator();
        HistoricalQuote current;
        while (historyItr.hasNext()) {
          current = historyItr.next();
          if (first) { // first is last value
            lastb = current.getAdjClose();
            first = false;
          }
          if (!historyItr.hasNext()) {

            firstb = current.getAdjClose();
          }
          GregorianCalendar g = (GregorianCalendar) current.getDate();
          dates.add(
              Integer.toString(g.get(GregorianCalendar.MONTH) + 1)
                  + "/"
                  + Integer.toString(g.get(GregorianCalendar.DAY_OF_MONTH)));
          values.add(current.getAdjClose().setScale(2, RoundingMode.HALF_UP).toString());
        }
      }

      if (values.size()
          > 5) // Not sure why 5 was picked. I guess its smaller than what the smallest range would
               // be for a graph.
      {
        // Convert data to JSON
        StringBuffer returnString = new StringBuffer("{");
        // values
        returnString.append("\"values\":[");
        for (int i = values.size() - 1; i >= 0; i--) {

          returnString.append(values.get(i));

          if (i != 0) {
            returnString.append(",");
          }
        }
        returnString.append("],");

        // dates
        returnString.append("\"dates\":[");
        for (int i = values.size() - 1; i >= 0; i--) {

          returnString.append("\"" + dates.get(i) + "\"");

          //		if(!dates.get(i).equals("15") && !dates.get(i).equals("28") )
          //		{
          //			returnString.append("\"\"");
          //		}
          //		else
          //		{
          //			returnString.append(dates.get(i));
          //		}
          if (i != 0) {
            returnString.append(",");
          }
        }
        returnString.append("],");

        // diff pct
        returnString.append("\"info\":{");

        // Double firstd = firstb.doubleValue();
        // System.out.println(firstd);
        // Double lastd = lastb.doubleValue();
        // System.out.println(lastd);

        // Double d = ((lastd-firstd)/(firstd))* 100.00;
        BigDecimal oneHundred = new BigDecimal(100.0);
        double d =
            (((lastb.subtract(firstb)).divide((firstb), 4, RoundingMode.HALF_UP))
                    .multiply(oneHundred))
                .setScale(2, RoundingMode.HALF_UP)
                .doubleValue();

        switch (option) {
          case "1":
            returnString.append("\"interval\":\"Month\",");
            break;
        }
        returnString.append("\"symbol\":\"" + stock.getSymbol() + "\",");
        returnString.append("\"name\":\"" + stock.getName() + "\",");
        returnString.append("\"diff\":" + d);

        returnString.append("}");

        returnString.append("}");

        // System.out.println(returnString.toString());

        return returnString.toString();
      } else {
        return "";
      }
    }
    return "";
  }
示例#3
0
 /**
  * Sends a request with the historical quotes included at the specified interval (DAILY, WEEKLY,
  * MONTHLY). Returns null if the data can't be retrieved from Yahoo Finance.
  *
  * @param symbol the symbol of the stock for which you want to retrieve information
  * @param interval the interval of the included historical data
  * @return a {@link Stock} object containing the requested information
  * @throws IOException when there's a connection problem
  */
 public static Stock get(String symbol, Interval interval) throws IOException {
   return YahooFinance.get(
       symbol, HistQuotesRequest.DEFAULT_FROM, HistQuotesRequest.DEFAULT_TO, interval);
 }
示例#4
0
 /**
  * Sends a basic quotes request to Yahoo Finance. This will return a {@link Stock} object with its
  * {@link yahoofinance.quotes.stock.StockQuote}, {@link yahoofinance.quotes.stock.StockStats} and
  * {@link yahoofinance.quotes.stock.StockDividend} member fields filled in with the available
  * data. Returns null if the data can't be retrieved from Yahoo Finance.
  *
  * @param symbol the symbol of the stock for which you want to retrieve information
  * @return a {@link Stock} object containing the requested information
  * @throws IOException when there's a connection problem
  */
 public static Stock get(String symbol) throws IOException {
   return YahooFinance.get(symbol, false);
 }
示例#5
0
 /**
  * Sends a basic quotes request to Yahoo Finance. This will return a {@link Map} object that links
  * the symbols to their respective {@link Stock} objects. The Stock objects have their {@link
  * yahoofinance.quotes.stock.StockQuote}, {@link yahoofinance.quotes.stock.StockStats} and {@link
  * yahoofinance.quotes.stock.StockDividend} member fields filled in with the available data.
  *
  * <p>All the information is retrieved in a single request to Yahoo Finance. The returned Map only
  * includes the Stocks that could successfully be retrieved from Yahoo Finance.
  *
  * @param symbols the symbols of the stocks for which you want to retrieve information
  * @return a Map that links the symbols to their respective Stock objects
  * @throws IOException when there's a connection problem
  */
 public static Map<String, Stock> get(String[] symbols) throws IOException {
   return YahooFinance.get(symbols, false);
 }
示例#6
0
 /**
  * Sends a request with the historical quotes included starting from the specified {@link
  * Calendar} date until the specified Calendar date (to) at the default interval (monthly).
  * Returns null if the data can't be retrieved from Yahoo Finance.
  *
  * @param symbol the symbol of the stock for which you want to retrieve information
  * @param from start date of the historical data
  * @param to end date of the historical data
  * @return a {@link Stock} object containing the requested information
  * @throws IOException when there's a connection problem
  */
 public static Stock get(String symbol, Calendar from, Calendar to) throws IOException {
   return YahooFinance.get(symbol, from, to, HistQuotesRequest.DEFAULT_INTERVAL);
 }