vn.topmedia.monitor.form.MDIMain.java Source code

Java tutorial

Introduction

Here is the source code for vn.topmedia.monitor.form.MDIMain.java

Source

/*
 * Copyright (c) 2011 Topmedia Company
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package vn.topmedia.monitor.form;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.swing.JFrame;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import vn.topmedia.monitor.MonitorBean;
import vn.topmedia.monitor.MonitorCheck;
import vn.topmedia.monitor.bean.AddressBean;
import vn.topmedia.monitor.bean.MonitorSettingBean;
import vn.topmedia.monitor.common.MonitorLevel;
import vn.topmedia.monitor.commons.Alert;
import vn.topmedia.monitor.commons.Constants;

/**
 *
 * @author Anh Tuan <tuanta@topmedia.vn>
 */
public class MDIMain extends JFrame {

    /**
     * Creates new form MDIMain
     */
    public MDIMain() {
        initComponents();
        initConfigure();
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setSize((int) d.getWidth(), (int) d.getHeight());
    }

    private void initConfigure() {
        enableMenu(true);
        menuBar.setVisible(false);
        loadConfigFile(Constants.CFG_FILE_NAME);
        monitor();
    }

    /**
     * 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() {

        desktopPane = new javax.swing.JDesktopPane();
        jPanel1 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        jSeparator5 = new javax.swing.JToolBar.Separator();
        btnLogin = new javax.swing.JButton();
        jSeparator4 = new javax.swing.JToolBar.Separator();
        btnSettings = new javax.swing.JButton();
        jSeparator2 = new javax.swing.JToolBar.Separator();
        menuBar = new javax.swing.JMenuBar();
        fileMenu = new javax.swing.JMenu();
        mnuItmLogin = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        mnuItmSettings = new javax.swing.JMenuItem();
        jSeparator = new javax.swing.JSeparator();
        mnuItmExit = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("ExMonitor 1.3");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        desktopPane.setBackground(new java.awt.Color(2, 113, 167));

        jToolBar1.setFloatable(false);
        jToolBar1.add(jSeparator5);

        btnLogin.setText("Login...");
        btnLogin.setFocusable(false);
        btnLogin.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnLogin.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnLoginActionPerformed(evt);
            }
        });
        jToolBar1.add(btnLogin);
        jToolBar1.add(jSeparator4);

        btnSettings.setText("Settings...");
        btnSettings.setFocusable(false);
        btnSettings.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        btnSettings.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSettingsActionPerformed(evt);
            }
        });
        jToolBar1.add(btnSettings);
        jToolBar1.add(jSeparator2);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jToolBar1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE));
        jPanel1Layout.setVerticalGroup(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jToolBar1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 25,
                        org.jdesktop.layout.GroupLayout.PREFERRED_SIZE));

        fileMenu.setText("File");

        mnuItmLogin.setText("Login...");
        mnuItmLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuItmLoginActionPerformed(evt);
            }
        });
        fileMenu.add(mnuItmLogin);
        fileMenu.add(jSeparator1);

        mnuItmSettings.setText("Settings...");
        mnuItmSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuItmSettingsActionPerformed(evt);
            }
        });
        fileMenu.add(mnuItmSettings);
        fileMenu.add(jSeparator);

        mnuItmExit.setText("Exit");
        mnuItmExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnuItmExitActionPerformed(evt);
            }
        });
        fileMenu.add(mnuItmExit);

        menuBar.add(fileMenu);

        setJMenuBar(menuBar);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
                        org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(desktopPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 518, Short.MAX_VALUE));
        layout.setVerticalGroup(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
                                org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
                                org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(desktopPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 371, Short.MAX_VALUE)));

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

    private void mnuItmLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuItmLoginActionPerformed
        // TODO add your handling code here:
        loginDlg = null;
        loginDlg = new Login(this, true);
        loginDlg.setVisible(true);
    }//GEN-LAST:event_mnuItmLoginActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        if (monitor != null) {
            monitor.doExit();
        }
    }//GEN-LAST:event_formWindowClosing

    private void mnuItmSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuItmSettingsActionPerformed
        // TODO add your handling code here:
        setting = new Settings(this, true, monitor);
        setting.setVisible(true);
    }//GEN-LAST:event_mnuItmSettingsActionPerformed

    private void mnuItmExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnuItmExitActionPerformed
        if (monitor != null) {
            monitor.doExit();
        }
        System.exit(0);
    }//GEN-LAST:event_mnuItmExitActionPerformed

    private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnLoginActionPerformed
        // TODO add your handling code here:
        loginDlg = null;
        loginDlg = new Login(this, true);
        loginDlg.setVisible(true);
    }//GEN-LAST:event_btnLoginActionPerformed

    private void btnSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSettingsActionPerformed
        // TODO add your handling code here:
        setting = new Settings(this, true, monitor);
        setting.setVisible(true);
    }//GEN-LAST:event_btnSettingsActionPerformed

    public void loadConfigFile(String fileName) {
        Properties properties = new Properties();
        System.out.println("Reading configuration file " + fileName);
        try {
            FileInputStream fin = new FileInputStream(fileName);
            properties.load(fin);
            fin.close();
            userName = properties.getProperty("rabbit-user", "monitor");
            password = properties.getProperty("rabbit-password", "monitor");
            vitualHost = properties.getProperty("rabbit-vitualhost", "/monitor");
            monServer = properties.getProperty("rabbit-server", "210.211.97.115");
            String str = properties.getProperty("rabbit-port", "5672");
            monPort = Integer.parseInt(str);
            str = properties.getProperty("mon-type", "0");
            monitorType = Integer.parseInt(str);
            str = properties.getProperty("mon-server-port", "0");
            Constants.MONITOR_SERVER_PORT = Integer.parseInt(str);
            str = properties.getProperty("alert-type", "1");
            this.alertType = Integer.parseInt(str);
            if (this.alertType < 0) {
                this.alertType = Constants.ALERT_BEEP;
            }
            str = properties.getProperty("mon-cps", "");
            if (str.length() > 0 && str.indexOf(",") > 0) {
                Constants.MONITOR_CPS = str.split(",");
            }
            str = properties.getProperty("mon-label", "");
            if (str.length() > 0 && str.indexOf(",") > 0) {
                Constants.MONITOR_LABELS = str.split(",");
            }
            str = properties.getProperty("mon-logger", "");
            if (str.length() > 0 && str.indexOf(",") > 0) {
                Constants.MONITOR_LOGGER = str.split(",");
            }
            str = properties.getProperty("mon-time-check", "5000");
            Constants.MONITOR_TIME_CHECK = Integer.parseInt(str);
            str = properties.getProperty("mon-check", "");
            String[] addtmp = str.split(",");
            address = new ArrayList<AddressBean>();
            for (String ad : addtmp) {
                String http = properties.getProperty(ad + "-http", "");
                String ip = properties.getProperty(ad + "-ip", "");
                String tmp = properties.getProperty(ad + "-port", "0");
                int port = Integer.valueOf(tmp);
                AddressBean bean = null;
                if (http.length() > 0) {
                    bean = new AddressBean(ad);
                    bean.setHttp(http);
                } else if (ip.length() > 0) {
                    bean = new AddressBean(ad);
                    bean.setIp(ip);
                    bean.setPort(port);
                }
                if (bean != null) {
                    address.add(bean);
                }
            }
        } catch (IOException ioe) {
            System.out.println("Error reading config file " + fileName + ": " + ioe);
            System.exit(0);
        }
    }

    public void updateConfigFile(MonitorSettingBean setting) {
        try {
            FileOutputStream fos = new FileOutputStream(Constants.CFG_FILE_NAME);
            String str = "";
            str += "rabbit-port=" + setting.getUserPort() + "\r\n";
            str += "rabbit-server=" + setting.getUserIP() + "\r\n";
            str += "rabbit-user=" + setting.getUserName() + "\r\n";
            str += "rabbit-password=" + setting.getPassword() + "\r\n";
            str += "rabbit-vitualhost=" + setting.getVitualHost() + "\r\n";
            str += "#0: mute, 1: beep\r\n";
            str += "alert-type=" + setting.getAlertType() + "\r\n";
            str += "#1: server, 0: client\r\n";
            str += "mon-type=" + this.monitorType + "\r\n";
            str += "mon-server-port=" + Constants.MONITOR_SERVER_PORT + "\r\n";
            str += "mon-cps=";
            int len = Constants.MONITOR_CPS.length;
            for (int i = 0; i < len; i++) {
                if (len - 1 != i) {
                    str += Constants.MONITOR_CPS[i] + ",";
                } else {
                    str += Constants.MONITOR_CPS[i] + "\r\n";
                }
            }
            str += "mon-label=";
            len = Constants.MONITOR_LABELS.length;
            for (int i = 0; i < len; i++) {
                if (len - 1 != i) {
                    str += Constants.MONITOR_LABELS[i] + ",";
                } else {
                    str += Constants.MONITOR_LABELS[i] + "\r\n";
                }
            }
            str += "mon-logger=";
            len = Constants.MONITOR_LOGGER.length;
            for (int i = 0; i < len; i++) {
                if (len - 1 != i) {
                    str += Constants.MONITOR_LOGGER[i] + ",";
                } else {
                    str += Constants.MONITOR_LOGGER[i] + "\r\n";
                }
            }
            str += "mon-time-check=";
            str += Constants.MONITOR_TIME_CHECK + "\r\n";
            str += "mon-check=";
            String addressLink = "";
            len = address.size();
            for (int i = 0; i < len; i++) {
                AddressBean ad = address.get(i);
                if (len - 1 != i) {
                    str += ad.getLink() + ",";
                } else {
                    str += ad.getLink() + "\r\n";
                }
                if (ad.getHttp() != null && ad.getHttp().length() > 0) {
                    addressLink += ad.getLink() + "-http=" + ad.getHttp() + "\r\n";
                } else if (ad.getIp() != null && ad.getIp().length() > 0) {
                    addressLink += ad.getLink() + "-ip=" + ad.getIp() + "\r\n";
                    addressLink += ad.getLink() + "-port=" + ad.getPort() + "\r\n";
                }
            }
            str += addressLink;
            fos.write(str.getBytes());
            fos.flush();
            fos.close();
        } catch (IOException ioe) {
            System.out.println("Error updateConfigFile: " + ioe);
        }
    }

    public void setMonPort(int value) {
        this.monPort = value;
    }

    public int getMonPort() {
        return this.monPort;
    }

    public void monitor() {
        mnuItmLogin.setEnabled(false);
        btnLogin.setEnabled(false);
        this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        monitor = new SMSMonitor(this);
        desktopPane.add(monitor);
        monitor.setVisible(true);
        this.setCursor(Cursor.getDefaultCursor());
        goToTray();

        if (monitorType == Constants.MONITOR_SERVER_TYPE) {
            //Check address avaiable
            monitor.loadMonitorCheck(address);
            //Neu la monitor server thi listern port mac dinh la 9200
            //Dung de nhan message thong qua socket khi Rabbit Server bi loi hoac la muon gui thong tin qua Socket
            //            monitor.startMonitoring();
        }

        //Alert setting
        Alert.setMdiMain(this);
        Alert.setMonitor(monitor);
        loadRabbitClient();
    }

    /**
     * Load configure for rabbit client to Rabbit Server
     */
    public void loadRabbitClient() {
        //        java.awt.EventQueue.invokeLater(new Runnable() {
        //
        //            public void run() {
        try {
            if (context == null) {
                context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/rabbit-client.xml");
            } else {
                context.close();
                context = new ClassPathXmlApplicationContext("classpath:META-INF/spring/rabbit-client.xml");
            }
            context.registerShutdownHook();
        } catch (Exception ex) {
            MonitorBean smsError = new MonitorBean();
            smsError.setType("Monitor Client");
            smsError.setLevel(MonitorLevel.ERROR);
            smsError.setServiceId("Logger");
            smsError.setClazz(MonitorCheck.class.getName());
            smsError.setInfo("Error start listern message from Rabbit queue: " + ex.toString());
            Alert.alert(monitor.getMonitorUser(), smsError);
        }
        //            }
        //        });
    }

    public void goToTray() {
        if (SystemTray.isSupported()) {
            SystemTray tray = SystemTray.getSystemTray();
            normal = Toolkit.getDefaultToolkit().getImage("normal.gif");
            MouseListener mouseListener = new MouseListener() {

                public void mouseClicked(MouseEvent e) {
                    //                    System.out.println("Tray Icon - Mouse clicked!");                 
                }

                public void mouseEntered(MouseEvent e) {
                    //                    System.out.println("Tray Icon - Mouse entered!");                 
                }

                public void mouseExited(MouseEvent e) {
                    //                    System.out.println("Tray Icon - Mouse exited!");                 
                }

                public void mousePressed(MouseEvent e) {
                    //                    System.out.println("Tray Icon - Mouse pressed!"); 
                    showMonitor(0);
                }

                public void mouseReleased(MouseEvent e) {
                    //                    System.out.println("Tray Icon - Mouse released!");                 
                }
            };

            ActionListener exitListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    System.out.println("Exiting...");
                    mnuItmExit.doClick();
                }
            };

            ActionListener showMonitorListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    showMonitor(2);
                }
            };

            popup = new PopupMenu();
            //---------------------------            
            MenuItem showItem;
            showItem = new MenuItem("Show");
            showItem.addActionListener(showMonitorListener);
            popup.add(showItem);
            //-----------------            
            popup.addSeparator();
            //------------------------            
            MenuItem defaultItem = new MenuItem("Exit");
            defaultItem.addActionListener(exitListener);
            popup.add(defaultItem);
            //------------------------
            trayIcon = new TrayIcon(normal, "ExMonitor 1.3", popup);

            ActionListener actionListener = new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    showMonitor(2);
                }
            };

            trayIcon.setImageAutoSize(true);
            trayIcon.addActionListener(actionListener);
            trayIcon.addMouseListener(mouseListener);

            try {
                tray.add(trayIcon);
            } catch (AWTException e) {
                System.err.println("TrayIcon could not be added.");
            }

        } else {
            //  System Tray is not supported
        }

    }

    public void showTrayTip(String title, String info) {
        trayIcon.displayMessage(title, info, TrayIcon.MessageType.INFO);
    }

    public void showTrayTip(String title, String info, String lf) {
        String[] str = info.split(lf);
        String s = "";
        for (int i = 0; i < str.length; i++) {
            s = s + str[i] + "\n";
        }
        trayIcon.displayMessage(title, s, TrayIcon.MessageType.INFO);
    }

    public void showMonitor(int force) {
        if (force == 0) {
            if (this.isVisible()) {
                popup.getItem(0).setLabel("Hide");
            } else {
                popup.getItem(0).setLabel("Show");
            }
        } else if (force == 1) {
            this.setVisible(true);
            this.setState(JFrame.NORMAL);
            popup.getItem(0).setLabel("Hide");
        } else {
            if (!this.isVisible()) {
                this.setVisible(true);
                this.setState(JFrame.NORMAL);
                popup.getItem(0).setLabel("Hide");
            } else {
                this.setVisible(false);
                popup.getItem(0).setLabel("Show");
            }
        }
    }

    public void enableMenu(boolean value) {
        mnuItmSettings.setEnabled(value);
        btnSettings.setEnabled(value);
    }

    public void setUserName(String value) {
        this.userName = value;
    }

    public String getUserName() {
        return this.userName;
    }

    public void setPassword(String value) {
        this.password = value;
    }

    public String getPassword() {
        return this.password;
    }

    //    public void setLogin(boolean value) {
    //        this.login = value;
    //    }
    //
    //    public boolean getLogin() {
    //        return this.login;
    //    }
    //    public void setMonActive(boolean value) {
    //        this.monActive = value;
    //    }
    //    public boolean getMonActive() {
    //        return this.monActive;
    //    }
    //    public void setMonReport(boolean value) {
    //        this.monReport = value;
    //    }
    //
    //    public boolean getMonReport() {
    //        return this.monReport;
    //    }
    public String getVitualHost() {
        return vitualHost;
    }

    public void setVitualHost(String vitualHost) {
        this.vitualHost = vitualHost;
    }

    public TrayIcon getTrayIcon() {
        return this.trayIcon;
    }

    public void addComponent(javax.swing.JComponent comp) {
        desktopPane.add(comp);
    }

    public int getAlertType() {
        return alertType;
    }

    public String getMonServer() {
        return this.monServer;
    }

    public SMSMonitor getSMSMonitor() {
        return this.monitor;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnLogin;
    private javax.swing.JButton btnSettings;
    private javax.swing.JDesktopPane desktopPane;
    private javax.swing.JMenu fileMenu;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JToolBar.Separator jSeparator2;
    private javax.swing.JToolBar.Separator jSeparator4;
    private javax.swing.JToolBar.Separator jSeparator5;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JMenuItem mnuItmExit;
    private javax.swing.JMenuItem mnuItmLogin;
    private javax.swing.JMenuItem mnuItmSettings;
    // End of variables declaration//GEN-END:variables
    private int monPort;
    private Login loginDlg;
    private String userName;
    private String password;
    private String vitualHost;
    //    private boolean login;//login successful?
    //    private boolean monActive;//active monitoring?
    //    private boolean monReport;//duty report made?
    //    private SMSMonitor monitor;
    private SMSMonitor monitor;
    private Settings setting;
    private TrayIcon trayIcon;
    private Image normal;
    //    private int alertFlag;//=0: for client, view only; 1: monitor
    private int alertType;//=1: beep
    private String monServer;//used to check monServer when alert=0
    private PopupMenu popup;
    private int monitorType = 0;
    //    private MonitorCheck[] checkAddress;
    private List<AddressBean> address;
    private AbstractApplicationContext context;
}