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 wedt.project; import java.io.File; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import javax.swing.SwingWorker; import twitter4j.*; import twitter4j.conf.ConfigurationBuilder; /** * * @author revanmj */ public class MainWindow extends javax.swing.JFrame { private BayesClassifier bayesC; private SvmClassifier svmC; private Common cmn; private DefaultListModel listModel; private boolean trained = false; List<Integer> bayesErr, svmErr; /** * Creates new form MainWindow */ public MainWindow() { initComponents(); bayesC = new BayesClassifier(); svmC = new SvmClassifier(); cmn = new Common(); try { File bayesData = new File("Bayes.model"); File svmData = new File("SVM.model"); if (bayesData.exists() && svmData.exists()) { trained = true; statusLabel.setText("Dane z modelami dostepne"); } } catch (Exception e) { System.out.println("init failed"); } } /** * 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() { fileChooser = new javax.swing.JFileChooser(); parametersGroup = new javax.swing.ButtonGroup(); searchField = new javax.swing.JTextField(); searchButton = new javax.swing.JButton(); checkBoxPopular = new javax.swing.JCheckBox(); checkBoxLatest = new javax.swing.JCheckBox(); jScrollPane1 = new javax.swing.JScrollPane(); tweetsList = new javax.swing.JList(); checkTweetButton = new javax.swing.JButton(); testFromCsvButton = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); bayesLabel = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); svmLabel = new javax.swing.JLabel(); statusLabel = new javax.swing.JLabel(); learnButton = new javax.swing.JButton(); parametersField = new javax.swing.JTextField(); setParametersButton = new javax.swing.JButton(); bayesRadioButton = new javax.swing.JRadioButton(); svmRadioButton = new javax.swing.JRadioButton(); jLabel3 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBounds(new java.awt.Rectangle(0, 2, 0, 0)); searchButton.setText("Szukaj"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { searchButtonActionPerformed(evt); } }); checkBoxPopular.setText("Popularne"); checkBoxLatest.setText("Najnowsze"); checkBoxLatest.setName("checkBoxLatest"); // NOI18N jScrollPane1.setViewportView(tweetsList); checkTweetButton.setText("Oce"); checkTweetButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { checkTweetButtonActionPerformed(evt); } }); testFromCsvButton.setText("Test danymi z pliku CSV"); testFromCsvButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { testFromCsvButtonActionPerformed(evt); } }); jLabel1.setText("Bayes:"); jLabel2.setText("SVM:"); statusLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); statusLabel.setText("Status"); learnButton.setText("Uczenie"); learnButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { learnButtonActionPerformed(evt); } }); setParametersButton.setText("Ustaw"); setParametersButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { setParametersButtonActionPerformed(evt); } }); parametersGroup.add(bayesRadioButton); bayesRadioButton.setText("Bayes"); parametersGroup.add(svmRadioButton); svmRadioButton.setText("SVM"); jLabel3.setText("Parametry dla:"); 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) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(7, 7, 7).addComponent(learnButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(testFromCsvButton, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(parametersField, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup().addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bayesRadioButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(svmRadioButton))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(setParametersButton) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 632, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout .createSequentialGroup().addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bayesLabel).addGap(18, 18, 18).addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(svmLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(statusLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout .createSequentialGroup() .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, 262, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkBoxLatest) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkBoxPopular) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(searchButton, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(checkTweetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGap(0, 8, Short.MAX_VALUE))))); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup().addGap(6, 6, 6) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(learnButton).addComponent(testFromCsvButton) .addComponent(parametersField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(setParametersButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(bayesRadioButton).addComponent(svmRadioButton).addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(checkBoxLatest).addComponent(checkBoxPopular) .addComponent(searchButton).addComponent(checkTweetButton)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1).addComponent(bayesLabel).addComponent(jLabel2) .addComponent(svmLabel).addComponent(statusLabel)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed statusLabel.setText("Trwa wyszukiwanie..."); lockUI(); SwingWorker<List<Status>, Void> worker = new SwingWorker<List<Status>, Void>() { @Override protected List<Status> doInBackground() throws Exception { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("PG0vtiQ73sbKKCfp9JfqyQ") .setOAuthConsumerSecret("ITCkTQiqCh3aVZexXentwnwCJooVpUOcpkIENPKowI") .setOAuthAccessToken("89783194-z0J1KLudg6MFMhhysKmL29zB5wBjxfxWUboAh6lAI") .setOAuthAccessTokenSecret("ytOdt7t8P1OrmAI2ZCRoX30ZC3eLcDSgPY8gOa6FCwQ"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Query query = new Query(searchField.getText()); query.setCount(10); query.setLang("en"); if (checkBoxLatest.isSelected() && checkBoxPopular.isSelected()) query.setResultType(Query.ResultType.mixed); else if (checkBoxLatest.isSelected()) query.setResultType(Query.ResultType.recent); else if (checkBoxPopular.isSelected()) query.setResultType(Query.ResultType.popular); QueryResult result = twitter.search(query); return result.getTweets(); } catch (TwitterException e) { statusLabel.setText("Wyszukiwanie nie powiodlo sie"); e.printStackTrace(); //System.out.println("Failed to search tweets: " + te.getMessage()); JOptionPane.showMessageDialog(null, e.getMessage(), "Blad pobierania wynikow wyszukiwania", JOptionPane.INFORMATION_MESSAGE); } return null; } @Override protected void done() { try { List<Status> tweets = get(); listModel = new DefaultListModel(); tweetsList.setModel(listModel); tweets.stream().forEach((tweet) -> { listModel.addElement(tweet.getText()); }); statusLabel.setText("Gotowe"); } catch (Exception ex) { ex.printStackTrace(); statusLabel.setText("Wyszukiwanie nie powiodlo sie"); } unlockUI(); } }; worker.execute(); }//GEN-LAST:event_searchButtonActionPerformed private void learnButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_learnButtonActionPerformed int returnVal = fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); trained = true; statusLabel.setText("Trwa uczenie (Bayes) ..."); lockUI(); SwingWorker<Boolean, Void> workerBayes = new SwingWorker<Boolean, Void>() { @Override protected Boolean doInBackground() throws Exception { try { bayesC.train(file, cmn); return true; } catch (Exception e) { trained = false; } return false; } @Override protected void done() { try { if (get()) statusLabel.setText("Gotowe"); else statusLabel.setText("Blad"); } catch (Exception ex) { ex.printStackTrace(); statusLabel.setText("Blad"); } } }; workerBayes.execute(); statusLabel.setText("Trwa uczenie (SVM) ..."); SwingWorker<Boolean, Void> workerSvm = new SwingWorker<Boolean, Void>() { @Override protected Boolean doInBackground() throws Exception { try { svmC.train(file, cmn); return true; } catch (Exception e) { trained = false; } return false; } @Override protected void done() { try { if (get()) statusLabel.setText("Gotowe"); else statusLabel.setText("Blad"); } catch (Exception ex) { ex.printStackTrace(); statusLabel.setText("Blad"); } unlockUI(); } }; workerSvm.execute(); } }//GEN-LAST:event_learnButtonActionPerformed private void checkTweetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_checkTweetButtonActionPerformed if (trained && tweetsList.getSelectedIndex() != -1) { lockUI(); statusLabel.setText("Klasyfikacja (Bayes) w toku ..."); SwingWorker<String, Void> workerBayes = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { String result = bayesC.classifySingle(listModel.get(tweetsList.getSelectedIndex()).toString(), cmn); return result; } @Override protected void done() { try { bayesLabel.setText(get()); statusLabel.setText("Gotowe"); } catch (Exception ex) { ex.printStackTrace(); statusLabel.setText("Blad klasyfikacji"); } } }; workerBayes.execute(); statusLabel.setText("Klasyfikacja (SVM) w toku ..."); SwingWorker<String, Void> workerSvm = new SwingWorker<String, Void>() { @Override protected String doInBackground() throws Exception { String result = svmC.classifySingle(listModel.get(tweetsList.getSelectedIndex()).toString(), cmn); return result; } @Override protected void done() { try { svmLabel.setText(get()); statusLabel.setText("Gotowe"); } catch (Exception ex) { ex.printStackTrace(); statusLabel.setText("Blad klasyfikacji"); } unlockUI(); } }; workerSvm.execute(); } else if (!trained) JOptionPane.showMessageDialog(null, "Najpierw uruchom proces uczenia!", "Blad!", JOptionPane.INFORMATION_MESSAGE); else if (tweetsList.getSelectedIndex() == -1) JOptionPane.showMessageDialog(null, "Nie wybrano tweeta!", "Blad!", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_checkTweetButtonActionPerformed private void testFromCsvButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_testFromCsvButtonActionPerformed if (trained) { int returnVal = fileChooser.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); lockUI(); System.out.flush(); statusLabel.setText("Trwa klasyfikowanie (Bayes) ..."); SwingWorker<List<Integer>, Void> workerBayes = new SwingWorker<List<Integer>, Void>() { @Override protected List<Integer> doInBackground() throws Exception { statusLabel.setText("Trwa klasyfikowanie (Bayes) ..."); List<Integer> Err = bayesC.classifyFromCsv(file, cmn); return Err; } @Override protected void done() { try { System.out.println("==== Bledy Bayes ===="); bayesErr = get(); cmn.printDetailedErrors(bayesErr); statusLabel.setText("Gotowe"); showErrorSummary(); } catch (Exception ex) { System.out.println("Blad dostepu do pliku " + file.getAbsolutePath()); statusLabel.setText("Blad"); ex.printStackTrace(); } unlockUI(); } }; workerBayes.execute(); statusLabel.setText("Trwa klasyfikowanie (SVM) ..."); SwingWorker<List<Integer>, Void> workerSvm = new SwingWorker<List<Integer>, Void>() { @Override protected List<Integer> doInBackground() throws Exception { statusLabel.setText("Trwa klasyfikowanie (Bayes) ..."); List<Integer> Err = svmC.classifyFromCsv(file, cmn); return Err; } @Override protected void done() { try { System.out.println("==== Bledy SVM ===="); svmErr = get(); cmn.printDetailedErrors(svmErr); statusLabel.setText("Gotowe"); } catch (Exception ex) { System.out.println("Blad dostepu do pliku " + file.getAbsolutePath()); statusLabel.setText("Blad"); ex.printStackTrace(); } } }; workerSvm.execute(); } } else JOptionPane.showMessageDialog(null, "Najpierw uruchom proces uczenia!", "Blad!", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_testFromCsvButtonActionPerformed private void setParametersButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_setParametersButtonActionPerformed int result = 0; if (bayesRadioButton.isSelected()) result = bayesC.setParameters(parametersField.getText()); else if (svmRadioButton.isSelected()) result = svmC.setParameters(parametersField.getText()); else JOptionPane.showMessageDialog(null, "Nie wybrano klasyfikatora", "Blad!", JOptionPane.INFORMATION_MESSAGE); if (result == -1) JOptionPane.showMessageDialog(null, "Nieprawidlowe parametry!", "Blad!", JOptionPane.INFORMATION_MESSAGE); }//GEN-LAST:event_setParametersButtonActionPerformed public void lockUI() { learnButton.setEnabled(false); testFromCsvButton.setEnabled(false); parametersField.setEnabled(false); setParametersButton.setEnabled(false); bayesRadioButton.setEnabled(false); svmRadioButton.setEnabled(false); searchField.setEnabled(false); checkBoxLatest.setEnabled(false); checkBoxPopular.setEnabled(false); searchButton.setEnabled(false); checkTweetButton.setEnabled(false); tweetsList.setEnabled(false); } public void unlockUI() { learnButton.setEnabled(true); testFromCsvButton.setEnabled(true); parametersField.setEnabled(true); setParametersButton.setEnabled(true); bayesRadioButton.setEnabled(true); svmRadioButton.setEnabled(true); searchField.setEnabled(true); checkBoxLatest.setEnabled(true); checkBoxPopular.setEnabled(true); searchButton.setEnabled(true); checkTweetButton.setEnabled(true); tweetsList.setEnabled(true); } public void showErrorSummary() { JOptionPane.showMessageDialog(null, "Bledy Bayes: " + bayesErr.get(0) + "\nBledy SVM: " + svmErr.get(0), "Wynik testu", JOptionPane.INFORMATION_MESSAGE); } /** * @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 ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainWindow.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new MainWindow().setVisible(true); }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel bayesLabel; private javax.swing.JRadioButton bayesRadioButton; private javax.swing.JCheckBox checkBoxLatest; private javax.swing.JCheckBox checkBoxPopular; private javax.swing.JButton checkTweetButton; private javax.swing.JFileChooser fileChooser; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton learnButton; private javax.swing.JTextField parametersField; private javax.swing.ButtonGroup parametersGroup; private javax.swing.JButton searchButton; private javax.swing.JTextField searchField; private javax.swing.JButton setParametersButton; private javax.swing.JLabel statusLabel; private javax.swing.JLabel svmLabel; private javax.swing.JRadioButton svmRadioButton; private javax.swing.JButton testFromCsvButton; private javax.swing.JList tweetsList; // End of variables declaration//GEN-END:variables }