Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package StockForecast; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.sql.ResultSet; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; import org.apache.derby.client.am.DateTime; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.json.JSONArray; import org.json.JSONObject; /** * * @author c07nw8vqg1hw */ public class Stock extends javax.swing.JFrame { /** * Creates new form Main * @throws java.lang.Exception */ public Stock() throws Exception { initComponents(); displayStockComboBox(); maxDate(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jButton1 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); dateChooserCombo1 = new datechooser.beans.DateChooserCombo(); dateChooserCombo2 = new datechooser.beans.DateChooserCombo(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jComboBox1 = new javax.swing.JComboBox<>(); jButton2 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jButton1.setText("Get Data"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jTable1.setModel( new javax.swing.table.DefaultTableModel( new Object[][] { { null, null, null, null }, { null, null, null, null }, { null, null, null, null }, { null, null, null, null } }, new String[] { "Title 1", "Title 2", "Title 3", "Title 4" })); jScrollPane1.setViewportView(jTable1); jButton3.setText("Add To DataBase"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Back"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); dateChooserCombo1.setCurrentView(new datechooser.view.appearance.AppearancesList("Light", new datechooser.view.appearance.ViewAppearance("custom", new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.ButtonPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 255), true, true, new datechooser.view.appearance.swing.ButtonPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 255), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.ButtonPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(128, 128, 128), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.LabelPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.LabelPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(255, 0, 0), false, false, new datechooser.view.appearance.swing.ButtonPainter()), (datechooser.view.BackRenderer) null, false, true))); dateChooserCombo1.setNothingAllowed(false); dateChooserCombo1.setMinDate(new java.util.GregorianCalendar(2014, 6, 1)); dateChooserCombo2.setCurrentView(new datechooser.view.appearance.AppearancesList("Light", new datechooser.view.appearance.ViewAppearance("custom", new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.ButtonPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 255), true, true, new datechooser.view.appearance.swing.ButtonPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 255), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.ButtonPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(128, 128, 128), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.LabelPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(0, 0, 255), false, true, new datechooser.view.appearance.swing.LabelPainter()), new datechooser.view.appearance.swing.SwingCellAppearance( new java.awt.Font("Lucida Grande", java.awt.Font.PLAIN, 13), new java.awt.Color(0, 0, 0), new java.awt.Color(255, 0, 0), false, false, new datechooser.view.appearance.swing.ButtonPainter()), (datechooser.view.BackRenderer) null, false, true))); dateChooserCombo2.setNothingAllowed(false); jLabel1.setText("End Date"); jLabel2.setText("Start Date"); jButton2.setText("Add"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 316, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(dateChooserCombo1, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 78, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup().addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(dateChooserCombo2, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(6, 6, 6)) .addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(layout.createSequentialGroup().addComponent(jButton4, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addComponent(jButton4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(dateChooserCombo1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 28, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton3) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout .createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(dateChooserCombo2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap())); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: try { // URL url = new URL("https://www.google.com/finance?q=%5B%28exchange+%3D%3D+%22IDX%22%29%5D"); URL url = new URL( "https://www.google.com/finance?q=%5B%28exchange+%3D%3D+%22IDX%22%29%5D&restype=company&noIL=1&num=1000&ei=u5VEVoCjHtWA0gSNvIfQCQ"); // URL url = new URL("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quote"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String strTemp = ""; while (null != (strTemp = br.readLine())) { System.out.println(strTemp); } } catch (Exception e) { System.out.println(e); } }//GEN-LAST:event_jButton1ActionPerformed private void converttoraw() throws Exception { File fileTxt = new File("RawData.txt"); FileInputStream file = new FileInputStream(new File("RawData.xls")); PrintWriter writer = new PrintWriter(fileTxt); writer.print(""); writer.close(); FileWriter fw = new FileWriter(fileTxt.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); HSSFWorkbook workbook = new HSSFWorkbook(file); HSSFSheet sheet = workbook.getSheetAt(0); Iterator<Row> rowIterator = sheet.iterator(); while (rowIterator.hasNext()) { Row row = rowIterator.next(); Iterator<Cell> cellIterator = row.cellIterator(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: // System.out.print(cell.getNumericCellValue() + ","); bw.write(cell.getNumericCellValue() + ","); break; case Cell.CELL_TYPE_STRING: // System.out.print(cell.getStringCellValue() + ","); bw.write(cell.getStringCellValue() + ","); break; } } bw.write("\n"); } bw.close(); file.close(); fw.close(); } private void displayStock() throws Exception { DefaultTableModel model = new DefaultTableModel(); jTable1.setModel(model); model.addColumn("Entity Name"); model.addColumn("Symbol"); Connect connect = new Connect(); ResultSet rs = connect.connectSelect("1", "SELECT * FROM ROOT.STOCK"); while (rs.next()) { model.addRow(new Object[] { rs.getString(1), rs.getString(2) }); } } private void displayStockComboBox() throws Exception { Connect connect = new Connect(); ResultSet rs = connect.connectSelect("1", "SELECT * FROM ROOT.STOCK"); while (rs.next()) { String s = rs.getString("symbol"); jComboBox1.addItem(s.trim()); } rs.close(); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: try { converttoraw(); FileReader fr = new FileReader("RawData.txt"); BufferedReader br = new BufferedReader(fr); LineNumberReader lnr = new LineNumberReader(new FileReader(new File("RawData.txt"))); lnr.skip(Long.MAX_VALUE); int lineNum = lnr.getLineNumber(); System.out.println(lineNum); lnr.close(); Connect connect = new Connect(); ResultSet rs = connect.connectSelect("1", "SELECT * FROM ROOT.STOCK"); ArrayList<String> stringList = new ArrayList<>(); while (rs.next()) { String sym = rs.getString("symbol"); System.out.println(sym); stringList.add(sym); } for (int i = 0; i < lineNum; i++) { String lineNumber = br.readLine(); String[] parts = lineNumber.split(","); String name = parts[0]; String symbol = parts[1]; if (stringList.contains(symbol)) { System.out.println(symbol + " : Is Already Added"); } else if (symbol.length() > 4) { System.out.println(symbol + " : Is Not a Stock Symbol"); } else { connect.connectInsert("INSERT INTO STOCK VALUES ('" + symbol + "','" + name + "')"); } } br.close(); fr.close(); } catch (Exception e) { JOptionPane.showMessageDialog(this, e.getMessage()); } try { displayStock(); } catch (Exception ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: new Login().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButton4ActionPerformed private void getHistoricalData(String stockSymbol) throws ParseException, MalformedURLException, IOException, Exception { String sym = stockSymbol; String startDate = dateChooserCombo1.getText(); String endDate = dateChooserCombo2.getText(); SimpleDateFormat oldFormat = new SimpleDateFormat("MM/dd/yy"); SimpleDateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd"); Date startDateFormat = oldFormat.parse(startDate); Date endDateFormat = oldFormat.parse(endDate); String sDate = newFormat.format(startDateFormat); String eDate = newFormat.format(endDateFormat); Connect connect = new Connect(); ResultSet rs = connect.connectSelect("1", "SELECT * FROM ROOT.STOCKDETAILS WHERE SYMBOL='" + sym + "'"); ArrayList<String> stringList = new ArrayList<>(); while (rs.next()) { String stockDate = rs.getString("stockdate"); System.out.println(stockDate); stringList.add(stockDate); } String s = "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22" + sym + ".JK%22%20and%20startDate%20%3D%20%22" + sDate + "%22%20and%20endDate%20%3D%20%22" + eDate + "%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="; URL url = new URL(s); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String a = null; String strTemp = ""; while (null != (strTemp = br.readLine())) { a = strTemp; } JSONObject obj = new JSONObject(a); JSONObject query = obj.getJSONObject("query"); int count = query.getInt("count"); System.out.println(count); if (count == 0) { JOptionPane.showMessageDialog(this, "Please Select Actual Date"); } else if (count == 1) { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); JSONObject results = query.getJSONObject("results"); JSONObject quote = results.getJSONObject("quote"); String high = quote.getString("High"); String low = quote.getString("Low"); String volume = quote.getString("Volume"); String adjClose = quote.getString("Adj_Close"); String close = quote.getString("Close"); Date date = formatter.parse(quote.getString("Date")); String open = quote.getString("Open"); System.out.println(high + ", " + low + ", " + volume + ", " + adjClose + ", " + close + ", " + formatter.format(date) + ", " + open); if (stringList.contains(date)) { System.out.println("Data on : (" + date + ") Is Already Added"); } else { connect.connectInsert("INSERT INTO STOCKDETAILS VALUES (DEFAULT,'" + sym + "','" + date + "', '" + high + "', '" + low + "', '" + volume + "', '" + adjClose + "', '" + close + "', '" + open + "')"); } } else { JSONObject results = query.getJSONObject("results"); JSONArray array = results.getJSONArray("quote"); System.out.println(array); System.out.println(array.length()); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); for (int ic = 0; ic < array.length(); ic++) { String high = array.getJSONObject(ic).getString("High"); String low = array.getJSONObject(ic).getString("Low"); String volume = array.getJSONObject(ic).getString("Volume"); String adjClose = array.getJSONObject(ic).getString("Adj_Close"); String close = array.getJSONObject(ic).getString("Close"); Date date = formatter.parse(array.getJSONObject(ic).getString("Date")); String open = array.getJSONObject(ic).getString("Open"); String exactVolume = ""; if (volume.equals("0")) { ResultSet rsPrev = connect.connectSelect("1", "SELECT * FROM ROOT.STOCK NATURAL JOIN STOCKDETAILS WHERE SYMBOL='" + sym + "'"); if (!rs.next()) { System.out.println("Coba Dimengerti"); } else { do { exactVolume = rs.getString("volume"); } while (rs.next()); } } System.out.println(high + ", " + low + ", " + volume + ", " + adjClose + ", " + close + ", " + formatter.format(date) + ", " + open); if (stringList.contains(date)) { System.out.println("Data on : (" + date + ") Is Already Added"); } else { connect.connectInsert("INSERT INTO STOCKDETAILS VALUES (DEFAULT,'" + sym + "','" + date + "', '" + high + "', '" + low + "', '" + volume + "', '" + adjClose + "', '" + close + "', '" + open + "')"); } } } br.close(); rs.close(); } private void getStock() throws IOException, MalformedURLException, Exception { String sym = jComboBox1.getSelectedItem().toString(); Connect connect = new Connect(); ResultSet rs = connect.connectSelect("1", "SELECT * FROM ROOT.STOCK"); ArrayList<String> stringList = new ArrayList<>(); while (rs.next()) { String symbol = rs.getString("symbol"); System.out.println(symbol); stringList.add(symbol); } System.out.println(stringList); System.err.println(stringList.size()); for (int i = 0; i < stringList.size(); i++) { System.out.println(stringList.get(i)); getHistoricalData(stringList.get(i)); } } private void maxDate() { DateFormat df = new SimpleDateFormat("MM/dd/yy"); Date today = Calendar.getInstance().getTime(); String reportDate = df.format(today); Calendar c = Calendar.getInstance(); c.setTime(today); c.add(Calendar.DATE, -1); dateChooserCombo1.setMaxDate(c); dateChooserCombo2.setMaxDate(c); dateChooserCombo1.setSelectedDate(c); dateChooserCombo2.setSelectedDate(c); } @SuppressWarnings("empty-statement") private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: String startDate = dateChooserCombo1.getText(); String endDate = dateChooserCombo2.getText(); if (startDate.equals(endDate)) { JOptionPane.showMessageDialog(this, "Please Select Range Date"); } else { try { getStock(); } catch (Exception ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_jButton2ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { try { new Stock().setVisible(true); } catch (Exception ex) { Logger.getLogger(Stock.class.getName()).log(Level.SEVERE, null, ex); } } // Variables declaration - do not modify//GEN-BEGIN:variables private datechooser.beans.DateChooserCombo dateChooserCombo1; private datechooser.beans.DateChooserCombo dateChooserCombo2; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JComboBox<String> jComboBox1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; // End of variables declaration//GEN-END:variables }