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 heimerdinger; import java.awt.Toolkit; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * * @author Alfredo */ public class HeimerdingerFrame extends javax.swing.JFrame { private Connection conn; private Statement stmt; private int totalGames; private int totalGamesProcessed; private int totalGamesProcessedThisSession; private int totalPlayerStatsCaptured; private int totalPlayerStatsCapturedThisSession; private int timeRunning; private boolean isRunning; /** * Creates new form HeimerdingerFrame */ public HeimerdingerFrame() { initComponents(); if (!connectDB()) { JOptionPane.showMessageDialog(null, "Could not connect to database. Check LOG for more infomation.", "ERROR", JOptionPane.ERROR_MESSAGE); System.exit(0); } this.setLocation((Toolkit.getDefaultToolkit().getScreenSize().width / 2) - (this.getWidth() / 2), (Toolkit.getDefaultToolkit().getScreenSize().height / 2) - (this.getHeight() / 2)); initLastSession(); } /** * 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() { jLabelTotalGamesProcessed = new javax.swing.JLabel(); jLabelTotalGamesProcessedThisSession = new javax.swing.JLabel(); jLabelTotalPlayerStatsCaptured = new javax.swing.JLabel(); jLabelTotalPlayerStatsCapturedThisSession = new javax.swing.JLabel(); jLabelTimeRunning = new javax.swing.JLabel(); jLabelStatus = new javax.swing.JLabel(); jButtonStart = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Heimerdinger"); setResizable(false); jLabelTotalGamesProcessed.setText("Total games processed:"); jLabelTotalGamesProcessedThisSession.setText("Total games processed this session:"); jLabelTotalPlayerStatsCaptured.setText("Total player stats captured:"); jLabelTotalPlayerStatsCapturedThisSession.setText("Total player stats captured this session:"); jLabelTimeRunning.setText("Time running:"); jLabelStatus.setText("Status:"); jButtonStart.setText("Start"); jButtonStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabelTotalGamesProcessed) .addComponent(jLabelTotalGamesProcessedThisSession) .addComponent(jLabelTotalPlayerStatsCaptured) .addComponent(jLabelTotalPlayerStatsCapturedThisSession) .addComponent(jLabelTimeRunning).addComponent(jLabelStatus)) .addGap(0, 108, Short.MAX_VALUE))) .addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabelTotalGamesProcessed) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelTotalGamesProcessedThisSession) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelTotalPlayerStatsCaptured) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelTotalPlayerStatsCapturedThisSession) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelTimeRunning) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelStatus) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonStart) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed isRunning = true; new TimeRunning().start(); new ProcessGames().start(); jButtonStart.setEnabled(false); }//GEN-LAST:event_jButtonStartActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Windows".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(HeimerdingerFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(HeimerdingerFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(HeimerdingerFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(HeimerdingerFrame.class.getName()) .log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new HeimerdingerFrame().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonStart; private javax.swing.JLabel jLabelStatus; private javax.swing.JLabel jLabelTimeRunning; private javax.swing.JLabel jLabelTotalGamesProcessed; private javax.swing.JLabel jLabelTotalGamesProcessedThisSession; private javax.swing.JLabel jLabelTotalPlayerStatsCaptured; private javax.swing.JLabel jLabelTotalPlayerStatsCapturedThisSession; // End of variables declaration//GEN-END:variables private boolean connectDB() { try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection( "jdbc:mysql://" + GlobalDef.DEF_HOSTNAME + "/" + GlobalDef.DEF_DATABASE, GlobalDef.DEF_USERNAME, GlobalDef.DEF_PASSWORD); stmt = conn.createStatement(); return true; } catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); return false; } } private void initLastSession() { try { ResultSet rs = stmt.executeQuery("SELECT count(*) as total FROM tbl_match"); if (rs.next()) { totalGames = rs.getInt("total"); } rs = stmt.executeQuery("SELECT count(distinct id_match) as total FROM tbl_playerstats"); if (rs.next()) { totalGamesProcessed = rs.getInt("total"); totalGamesProcessedThisSession = 0; } rs = stmt.executeQuery("SELECT count(*) as total FROM tbl_playerstats"); if (rs.next()) { totalPlayerStatsCaptured = rs.getInt("total"); totalPlayerStatsCapturedThisSession = 0; } updateLabels(); updateStatus("Waiting..."); } catch (SQLException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } } private void updateLabels() { jLabelTotalGamesProcessed.setText("Total games processed: " + totalGamesProcessed + "/" + totalGames + " ~ " + ((totalGamesProcessed * 100) / totalGames) + "% Done"); jLabelTotalGamesProcessedThisSession .setText("Total games processed this session: " + totalGamesProcessedThisSession + "/" + totalGames + " ~ " + ((totalGamesProcessedThisSession * 100) / totalGames) + "% Done"); jLabelTotalPlayerStatsCaptured.setText("Total player stats captured: " + totalPlayerStatsCaptured); jLabelTotalPlayerStatsCapturedThisSession .setText("Total player stats captured this session: " + totalPlayerStatsCapturedThisSession); jLabelTimeRunning.setText("Time running: " + (timeRunning / 60) + "m " + (timeRunning % 60) + "s"); } private void updateStatus(String status) { jLabelStatus.setText("Status: " + status); } class ProcessGames extends Thread { private ArrayList<Integer> getMatchIds() { ArrayList<Integer> idList = new ArrayList<>(); try { ResultSet rs = stmt .executeQuery("SELECT id FROM tbl_match WHERE status = 'Not processed' LIMIT 1;"); int matchIdDelete = 0; if (rs.next()) { matchIdDelete = rs.getInt("id"); } stmt.execute("DELETE FROM tbl_playerstats WHERE id_match = " + matchIdDelete); rs = stmt.executeQuery("SELECT id FROM tbl_match WHERE status = 'Not processed'"); while (rs.next()) { idList.add(rs.getInt("id")); } } catch (SQLException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } return idList; } private long calculateScore(long champLevel, long minionsKilled, long goldEarned, long totalDamageTaken, long totalDamageDealtToChampions, long totalTimeCrowdControlDealt, long totalHeal, long wardsPlaced, long wardsKilled, long kills, long deaths, long assists, boolean winner, long matchDuration) { double score = (champLevel * 100) + (minionsKilled * 100) + (goldEarned) + (totalDamageTaken * 0.5) + (totalDamageDealtToChampions * 0.75) + (totalTimeCrowdControlDealt * 10) + (totalHeal * 0.8) + (wardsPlaced * 100) + (wardsKilled * 150) + (kills * 500) - (deaths * 500) + (assists * 600); score = (winner) ? score * 1.5 : score; score += ((50000 - matchDuration) * 13) < 0 ? 0 : (50000 - (matchDuration * 13)); return (long) score; } @Override public void run() { ArrayList<Integer> idList = getMatchIds(); for (int id : idList) { try { updateStatus("Processing game[" + id + "]..."); URL url = new URL("https://na.api.pvp.net/api/lol/na/v2.2/match/" + id + "?api_key=" + GlobalDef.DEF_API_KEY); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); String linea; linea = br.readLine(); JSONObject obj = new JSONObject(linea); JSONArray participants = obj.getJSONArray("participants"); for (int i = 0; i < participants.length(); i++) { JSONObject stats = participants.getJSONObject(i).getJSONObject("stats"); try { String insert = "INSERT INTO tbl_playerstats (id_match, " + "id_summoner, " + "id_champion, " + "level, " + "minionsKilled, " + "goldEarned, " + "totalDamageTaken, " + "totalDamageDealtToChampions, " + "totalTimeCrowdControlDealt, " + "totalHeal, " + "wardPlaced, " + "wardKilled, " + "kills, " + "deaths, " + "assists, " + "win, " + "timePlayed, " + "score) VALUES(" + id + ", " + (i + 1) + ", " + participants.getJSONObject(i).getInt("championId") + ", " + stats.getLong("champLevel") + ", " + stats.getLong("minionsKilled") + ", " + stats.getLong("goldEarned") + ", " + stats.getLong("totalDamageTaken") + ", " + stats.getLong("totalDamageDealtToChampions") + ", " + stats.getLong("totalTimeCrowdControlDealt") + ", " + stats.getLong("totalHeal") + ", " + stats.getLong("wardsPlaced") + ", " + stats.getLong("wardsKilled") + ", " + stats.getLong("kills") + ", " + stats.getLong("deaths") + ", " + stats.getLong("assists") + ", " + stats.getBoolean("winner") + ", " + obj.getLong("matchDuration") + ", " + calculateScore(stats.getLong("champLevel"), stats.getLong("minionsKilled"), stats.getLong("goldEarned"), stats.getLong("totalDamageTaken"), stats.getLong("totalDamageDealtToChampions"), stats.getLong("totalTimeCrowdControlDealt"), stats.getLong("totalHeal"), stats.getLong("wardsPlaced"), stats.getLong("wardsKilled"), stats.getLong("kills"), stats.getLong("deaths"), stats.getLong("assists"), stats.getBoolean("winner"), obj.getLong("matchDuration")) + ")"; stmt.execute(insert); stmt.execute("UPDATE tbl_champion SET pickRate = pickRate + 1 WHERE id = " + participants.getJSONObject(i).getInt("championId")); totalPlayerStatsCaptured++; totalPlayerStatsCapturedThisSession++; } catch (SQLException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } } try { JSONArray teams = obj.getJSONArray("teams"); for (int j = 0; j < teams.length(); j++) { try { JSONArray bans = teams.getJSONObject(j).getJSONArray("bans"); for (int h = 0; h < bans.length(); h++) { stmt.execute("UPDATE tbl_champion SET banRate = banRate + 1 WHERE id = " + bans.getJSONObject(h).getInt("championId")); } } catch (JSONException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } } stmt.execute("UPDATE tbl_match SET status = 'Processed' WHERE id = " + id); } catch (SQLException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } totalGamesProcessed++; totalGamesProcessedThisSession++; Thread.sleep(1500); } catch (MalformedURLException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } } } } class TimeRunning extends Thread { @Override public void run() { while (isRunning) { try { timeRunning++; updateLabels(); Thread.sleep(1000); } catch (InterruptedException ex) { Logger.getLogger(HeimerdingerFrame.class.getName()).log(Level.SEVERE, null, ex); } } } } }