networkanalyzer.NetworkAnalyzer.java Source code

Java tutorial

Introduction

Here is the source code for networkanalyzer.NetworkAnalyzer.java

Source

package networkanalyzer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.Timer;
import static networkanalyzer.Pinger.count;
import org.jfree.chart.ChartUtilities;

/*
 * 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.
 */

/**
 *
 * @author Kaeny
 */

public class NetworkAnalyzer extends javax.swing.JFrame implements ActionListener {
    //timer to refresh every second
    private final Timer timer = new Timer(1000, this);
    String host;
    boolean isRunning = true;
    DynamicPing pinger = new DynamicPing();

    /**
     * Creates new form NetworkAnalyzerwindow
     * @param title
     */

    static int min = 0, max = 0, avg = 0, ping = 0;

    public NetworkAnalyzer(final String title) {
        super(title);
        initComponents();

    }

    /**
     * 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.
     */

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        hostName = new javax.swing.JTextField();
        maxPing = new javax.swing.JLabel();
        minPing = new javax.swing.JLabel();
        avgPing = new javax.swing.JLabel();
        pingPanel = new javax.swing.JPanel();
        startButton = new javax.swing.JButton();
        saveCheck = new javax.swing.JCheckBox();
        saveLoc = new javax.swing.JTextField();
        nameLabel = new javax.swing.JLabel();
        browse = new javax.swing.JButton();
        savePng = new javax.swing.JButton();
        pngText = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAutoRequestFocus(false);
        setBackground(new java.awt.Color(255, 255, 255));
        setForeground(java.awt.Color.white);

        hostName.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        hostName.setText("Enter domain");
        hostName.setToolTipText("");

        maxPing.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        maxPing.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        maxPing.setText("Max: ms");
        maxPing.setToolTipText("Ping");

        minPing.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        minPing.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        minPing.setText("Min: ms");

        avgPing.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        avgPing.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        avgPing.setText("Avg: ms");

        pingPanel.setBackground(new java.awt.Color(255, 255, 255));
        pingPanel.setLayout(new java.awt.BorderLayout());
        pingPanel.add(pinger.getChartPanel());

        startButton.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        startButton.setText("Start");
        startButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                startButtonMouseClicked(evt);
            }
        });

        saveCheck.setText("Save data");
        saveCheck.setToolTipText("");
        saveCheck.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveCheckMouseClicked(evt);
            }
        });

        saveLoc.setToolTipText("");
        saveLoc.setEnabled(false);

        nameLabel.setText("File name");
        nameLabel.setToolTipText("");
        nameLabel.setEnabled(false);

        browse.setText("browse...");
        browse.setEnabled(false);
        browse.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                browseMouseClicked(evt);
            }
        });

        savePng.setText("Save as png");
        savePng.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                savePngMouseClicked(evt);
            }
        });

        pngText.setText(".png");
        pngText.setToolTipText("");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(hostName, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                                .addComponent(maxPing, javax.swing.GroupLayout.Alignment.TRAILING,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(minPing, javax.swing.GroupLayout.Alignment.TRAILING,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(avgPing, 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)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(saveCheck, javax.swing.GroupLayout.PREFERRED_SIZE, 135,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(31, 31, 31).addComponent(nameLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(saveLoc, javax.swing.GroupLayout.PREFERRED_SIZE, 200,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(browse))
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout
                                                .createSequentialGroup()
                                                .addComponent(startButton, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(96, 96, 96).addComponent(pngText).addGap(18, 18, 18)
                                                .addComponent(savePng, javax.swing.GroupLayout.PREFERRED_SIZE, 100,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(pingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 495,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(61, Short.MAX_VALUE)));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(41, 41, 41)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(hostName, javax.swing.GroupLayout.DEFAULT_SIZE, 32, Short.MAX_VALUE)
                                .addComponent(startButton, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(savePng, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(pngText))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(maxPing, javax.swing.GroupLayout.PREFERRED_SIZE, 111,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(minPing, javax.swing.GroupLayout.PREFERRED_SIZE, 120,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(avgPing, javax.swing.GroupLayout.PREFERRED_SIZE, 128,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup()
                                        .addComponent(pingPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 339,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(saveCheck)
                                                .addComponent(saveLoc, javax.swing.GroupLayout.PREFERRED_SIZE, 23,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(nameLabel, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                .addComponent(browse))))
                        .addGap(41, 41, 41)));

        hostName.getAccessibleContext().setAccessibleName("");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void startButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_startButtonMouseClicked

        if (startButton.getText().equals("Start")) {
            try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("disconnectLog.txt", true)))) {
                java.util.Date startTime = new java.util.Date();
                out.println(startTime + " Connecting to: " + hostName.getText() + "...");
            } catch (IOException ex) {
                Logger.getLogger(NetworkAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
            }
            timer.start();
            startButton.setText("Stop");
        } else {
            timer.stop();
            startButton.setText("Start");
        }

    }//GEN-LAST:event_startButtonMouseClicked

    private void browseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_browseMouseClicked
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Browse the folder to process");
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        chooser.setAcceptAllFileFilterUsed(true);

        if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
            String fileName = chooser.getSelectedFile().toString();
            saveLoc.setText(fileName);
        }

    }//GEN-LAST:event_browseMouseClicked

    private void saveCheckMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveCheckMouseClicked
        if (saveCheck.isSelected()) {
            saveLoc.setEnabled(true);
            nameLabel.setEnabled(true);
            browse.setEnabled(true);
        }
        if (!saveCheck.isSelected()) {
            saveLoc.setEnabled(false);
            nameLabel.setEnabled(false);
            browse.setEnabled(false);
        }
    }//GEN-LAST:event_saveCheckMouseClicked

    private void savePngMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_savePngMouseClicked

        File png = new File(pngText.getText());
        try {
            ChartUtilities.saveChartAsPNG(png, pinger.getChart(), 503, 346);
        } catch (IOException ex) {
            Logger.getLogger(NetworkAnalyzer.class.getName()).log(Level.SEVERE, null, ex);
        }

    }//GEN-LAST:event_savePngMouseClicked

    @Override
    public void actionPerformed(ActionEvent e) {
        host = hostName.getText();

        try {
            ping = Pinger.pingCheck(host);
            //max ping       
            if (count == 1 || ping >= max)
                max = ping;
            //min ping
            if (count == 1 || ping <= min)
                min = ping;
            //avg ping
            if (count > 0)
                avg = (avg * (count - 1) + ping) / count;

            maxPing.setText("Max: " + max + "ms");
            minPing.setText("Min: " + min + "ms");
            avgPing.setText("Avg: " + avg + "ms");

            DynamicPing.pingData(ping);

        } catch (IOException ex) {
            Logger.getLogger(NetworkAnalyzer.class.getName()).log(Level.SEVERE, null, ex);

        }

    }

    /**
     * @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(NetworkAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(NetworkAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(NetworkAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NetworkAnalyzer.class.getName()).log(java.util.logging.Level.SEVERE,
                    null, ex);
        }
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NetworkAnalyzer("").setVisible(true);

            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    public static javax.swing.JLabel avgPing;
    public static javax.swing.JButton browse;
    public static javax.swing.JTextField hostName;
    public static javax.swing.JLabel maxPing;
    public static javax.swing.JLabel minPing;
    public static javax.swing.JLabel nameLabel;
    public static javax.swing.JPanel pingPanel;
    public static javax.swing.JTextField pngText;
    public static javax.swing.JCheckBox saveCheck;
    public static javax.swing.JTextField saveLoc;
    public static javax.swing.JButton savePng;
    public static javax.swing.JButton startButton;
    // End of variables declaration//GEN-END:variables

}