Package sk.netmap.gui

Source Code of sk.netmap.gui.MainFrame

/*
* GNU General Public License
*
* Copyright (C) 2006 Matej Zachar <mzachar@users.sourceforge.net>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id: MainFrame.java 55 2006-04-23 20:43:49 +0000 (Ne, 23 apr 2006) mzachar $
*/
package sk.netmap.gui;

import java.awt.AWTException;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.io.File;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.prefs.Preferences;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;

import sk.netmap.bo.Group;
import sk.netmap.bo.Server;
import sk.netmap.bo.SharedFolder;
import sk.netmap.gui.componets.DynamicTree;
import sk.netmap.gui.componets.IPropertyChangeListener;
import sk.netmap.gui.controller.DataController;
import sk.netmap.gui.controller.PopupMenuController;
import sk.netmap.util.CommonUtill;
import sk.netmap.util.Encrypter;
import sk.netmap.util.Global;
import sk.netmap.util.PackUtill;
import sk.netmap.util.PreferencesConfig;
import sk.netmap.util.SpringUtil;

import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.looks.BorderStyle;
import com.jgoodies.looks.HeaderStyle;
import com.jgoodies.looks.Options;
import com.jgoodies.looks.plastic.PlasticLookAndFeel;

/**
* Main frame of aplication
*
* @author Matej Zachar, $Date: 2006-04-23 20:43:49 +0000 (Ne, 23 apr 2006) $
*/
public class MainFrame extends JFrame implements ActionListener, TreeSelectionListener, IPropertyChangeListener {

  /**
   * ID
   */
  private static final long serialVersionUID = -5107406103417573333L;

  /**
   * Logger
   */
  private static final Logger logger = Logger.getLogger(MainFrame.class);

  /**
   * Resources for languge file
   */
  private static ResourceBundle resources;

  /**
   * Tray icon (java se6 mustang)
   */
  private SystemTray tray = SystemTray.getSystemTray();

  private DynamicTree dynamicTree;

  private JButton mapOrUnmapButton;
  /**
   * Main dialogs
   */
  private SettingDialog settingDialog;

  private PreferencesDialog preferencesDialog;

  /**
   * Main Panels
   */
  private GroupPanel groupPanel;

  private ServerPanel serverPanel;

  private SharedFolderPanel sharedFolderPanel;

  /**
   * Tray componets
   */
  private TrayIcon trayIcon;
 
  /**
   * TrayIcon images
   */
  private static Image disconnectTrayIcon = CommonUtill.getImage(new File(Global.ICON_DISCONNECT));

  private static Image connectTrayIcon = CommonUtill.getImage(new File(Global.ICON_CONNECT));

  /**
   * Main Panel componet
   */
  private JPanel componentPanel;

  private JPasswordField password;

  /**
   * For startup progres...
   */
  public static boolean isInitialized = false;
  public static int percentil = 0;
 
  /**
   * Singleton instance of Main Frame
   */
  private static MainFrame instance;

  /**
   * Main method
   *
   * @param args
   */
  public static void main(String[] args) {
    try {
      resources = ResourceBundle.getBundle("netmap-names", new Locale(
          PreferencesConfig.userRoot().get(
              PreferencesConfig.KEY_LANGUAGE, "en")));
    } catch (MissingResourceException ex) {
      JOptionPane.showMessageDialog((JFrame) null,
          "Cannot find config files for application JNetMap.\n"
              + ex.getLocalizedMessage(), "Error!",
          JOptionPane.ERROR_MESSAGE);
      System.exit(1);
    }
   
    try {
      instance = new MainFrame();
      new StartupProgresBar(instance).start();
      percentil = 10;
      if (PreferencesConfig.userRoot().getBoolean(
          PreferencesConfig.KEY_LOAD_LAST_DB_ON_STARTUP, false)) {
        instance.loadLastDatabase();
      }
     
      percentil = 30;
      instance.configureUI();     
      percentil = 40;
      instance.buildInterface();

    } catch (RuntimeException e) {
      e.printStackTrace();
      System.err.println("Upsik vyskytol sa nam RuntimeException: "+e);

    } catch (Exception e) {
      e.printStackTrace();
      System.err.println("Upsik vyskytol sa nam Exception:" + e);

    } catch (Error e) {
      e.printStackTrace();
      System.err.println("Upsik vyskytol sa nam Exception:" + e);
      /*
      JOptionPane.showMessageDialog(null,
          "Database was locked by another proces",
          "Database lock error", JOptionPane.ERROR_MESSAGE);
          */
    }
  }

  /**
   * Singletom of MainFrame
   *
   * @return
   */
  public static MainFrame getInstance() {
    return instance;
  }

 
  /**
   * Sets visual variables and look and feel for application
   */
  private void configureUI() {
    UIManager.put(Options.USE_SYSTEM_FONTS_APP_KEY, Boolean.TRUE);
    Options.setDefaultIconSize(new Dimension(18, 18));

    // com.jgoodies.looks.windows.WindowsLookAndFeel
    // com.jgoodies.looks.plastic.PlasticXPLookAndFeel
    try {
      UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    } catch (Exception e) {
      logger.fatal(resString("CannotSetLookAndFeel"), e);
      throw new RuntimeException(e);
    }
  }

  private void configurePreferences() {
    if (PreferencesConfig.userRoot().getBoolean(
        PreferencesConfig.KEY_PROMT_PASSWORD_ON_STARTUP, false) == false) {
      Encrypter.getInstance().setDefaultPassPhrase();
    } else {
      reEnterPassword();
    }
    percentil = 65;
  }

  /**
   * Configue application
   */
  private void buildInterface() {
    configurePreferences();
    setTitle(resString("MainFrameTitle"));
    setJMenuBar(buildMenuBar());
    percentil = 75;
    setContentPane(buildContentPane());
    setSize(600, 430);
    locateOnScreen(this);
    setVisible(false);

    percentil = 85;
    try {
      tray.add(trayIcon);
      trayIcon.displayMessage("JNetMap(c) 2006 by Matej Zachar",
          "   e-mail: zachar.matej@gmail.com",
          TrayIcon.MessageType.INFO);
     
      percentil = 90;
    } catch (AWTException e) {
      throw new RuntimeException(e);
    }
   
    DataController.getInstance().addPropertyChangeListener(this);
   
    percentil = 100;
    isInitialized = true; //for progressbar
  }

  /**
   * Builds menu bar and configure its components.
   *
   * @return menubar
   */
  private JMenuBar buildMenuBar() {
    JMenu menu;
    JMenuBar menuBar = new JMenuBar();
    menuBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE);
    menuBar.putClientProperty(PlasticLookAndFeel.BORDER_STYLE_KEY,
        BorderStyle.SEPARATOR);

    // menu File
    menu = new JMenu(resString("File"));

    JMenuItem reEnterPassword = new JMenuItem(resString("ReEnterPassword"));
    reEnterPassword.setIcon(Global.iconRELock);
    reEnterPassword.addActionListener(this);
    menu.add(reEnterPassword);

    JMenuItem changePassword = new JMenuItem(resString("ChangePassword"));
    changePassword.setIcon(Global.iconLock);
    changePassword.addActionListener(this);
    menu.add(changePassword);

    menu.addSeparator();
    JMenuItem load = new JMenuItem(resString("Load"));
    load.addActionListener(this);
    menu.add(load);

    JMenuItem save = new JMenuItem(resString("Save"));
    save.setIcon(Global.iconSave);
    save.addActionListener(this);
    menu.add(save);

    menu.addSeparator();
    JMenuItem end = new JMenuItem(resString("End"));
    end.setIcon(Global.iconExit);
    end.addActionListener(this);
    menu.add(end);

    menuBar.add(menu);

    // menu Setting
    menu = new JMenu(resString("Setting"));

    JMenuItem userPreferences = new JMenuItem(resString("UserPreferences"));
    userPreferences.addActionListener(this);
    menu.add(userPreferences);

    JMenuItem systemLetters = new JMenuItem(resString("UsedSystemLetters"));
    systemLetters.addActionListener(this);
    menu.add(systemLetters);

    menuBar.add(menu);

    // menu Help
    menu = new JMenu(resString("Help"));

    JMenuItem about = new JMenuItem(resString("AboutProgram"));
    about.addActionListener(this);
    menu.add(about);

    menuBar.add(menu);

    return menuBar;
  }

  /**
   * Build ContentPanel with Main Panel
   *
   * @return panel
   */
  private Container buildContentPane() {
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, buildTreePanel(), buildMainPanel());
    splitPane.setOneTouchExpandable(true);
    splitPane.setContinuousLayout(true);
    return splitPane;
  }

  /**
   * Builds main panel - and configures all its components.
   *
   * @return mainpanel
   */
  private JComponent buildMainPanel() {

    FormLayout layout = new FormLayout(
        "3dlu, fill:min(100dlu;pref):grow, pref, 3dlu, pref, 3dlu",
        "3dlu, pref, 3dlu, fill:pref:grow, 3dlu, pref, 3dlu");
    layout.setColumnGroups(new int[][] { { 3, 5 } });

    PanelBuilder builder = new PanelBuilder(layout);
    builder.setDefaultDialogBorder();
    CellConstraints cc = new CellConstraints();

    trayIcon = new TrayIcon(disconnectTrayIcon, "JNetMap(c) 2006", PopupMenuController.getInstance().getPopupMenu());
    trayIcon.setImageAutoSize(true);
    trayIcon.setActionCommand("ShowMainWindow");
    trayIcon.addActionListener(this);
   

    mapOrUnmapButton = new JButton();
    mapOrUnmapButton.setEnabled(false);
    mapOrUnmapButton.setText(resString("StatusDisconnected"));
    mapOrUnmapButton.setIcon(Global.iconDisconncet);
    mapOrUnmapButton.addActionListener(this);

    componentPanel = new JPanel();
       
    groupPanel = new GroupPanel();
    serverPanel = new ServerPanel();
    sharedFolderPanel = new SharedFolderPanel();

    settingDialog = new SettingDialog(this);
    preferencesDialog = new PreferencesDialog(this);

    builder.add(componentPanel, cc.xywh(2, 2, 5, 1));

    builder.add(mapOrUnmapButton, cc.xy(5, 6));

    return builder.getPanel();
  }

  private JComponent buildTreePanel() {

    FormLayout layout = new FormLayout(
        "3dlu, fill:max(110dlu;pref):grow, 3dlu",
        "3dlu, fill:pref:grow, 3dlu");

    PanelBuilder builder = new PanelBuilder(layout);
    builder.setDefaultDialogBorder();
    CellConstraints cc = new CellConstraints();

    dynamicTree = new DynamicTree();

    JScrollPane treeScrollPane = new JScrollPane(dynamicTree.getTree());
    treeScrollPane
        .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    treeScrollPane
        .setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    builder.add(treeScrollPane, cc.xy(2, 2));

    return builder.getPanel();
  }

  /**
   * @return JFileChooser
   */
  public JFileChooser getFileChooser() {
    JFileChooser openFile = new JFileChooser();
    openFile.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
    openFile.setAcceptAllFileFilterUsed(true);
    openFile.setFileFilter(new FileFilter() {
     
      @Override
      public String getDescription() {
        return resString("JNetMapDatabaseFile");
      }

      @Override
      public boolean accept(File file) {
        if (file.isDirectory()) {
          return true;
        }

        String extension = CommonUtill.getExtension(file);
        if (extension != null) {
          if (extension.equals(Global.JNET_MAP_FILE_EXTENSION)) {
            return true;
          }
          return false;
        }

        return false;
      }

    });
    return openFile;
  }

  /**
   * Locates the frame on the screen center.
   *
   * @param frame
   */
  private void locateOnScreen(JFrame frame) {
    Dimension paneSize = frame.getSize();
    Dimension screenSize = frame.getToolkit().getScreenSize();
    frame.setLocation((screenSize.width - paneSize.width) / 2,
        (screenSize.height - paneSize.height) / 2);
  }

  /**
   * Get the resource string from the localized file
   *
   * @param key
   *            Property key
   * @return the string value
   */
  public static String resString(String key) {
    String value = "!" + key + "!";
    try {
      value = resources.getString(key);
    } catch (MissingResourceException e) {
      logger.error("resString()", e);
      throw new RuntimeException(e.getCause());
    }
    return value;
  }
 
 
  public void addToComponentPanel(DefaultPanel panel) {
    componentPanel.removeAll();
    componentPanel.add(panel);
    panel.setupFields();
    componentPanel.repaint();
  }

 
  public void clearComponentPanel() {
    componentPanel.removeAll();
    componentPanel.validate();
    componentPanel.repaint();
    logger.debug("Clear component Panel");
  }
 

  public void actionPerformed(ActionEvent e) {
    String command = e.getActionCommand();
    System.out.println(command);
    if (logger.isDebugEnabled()) {
      logger.debug("MainFrameCommand: " + command);
    }

    // frame
    if (command == resString("End")) exit();
    if (command == resString("StatusDisconnected")) DataController.getInstance().mapGroup(groupPanel.getGroup());
    if (command == resString("StatusConnected")) DataController.getInstance().unMapLastMappedGroup();

    // Tray menu
    if (command == "ShowMainWindow")setVisible(true);

    // Menu
    if (command == resString("ReEnterPassword")) reEnterPassword();
    if (command == resString("ChangePassword"))  changePassword();
    if (command == resString("Load")) loadDatabase();
    if (command == resString("Save")) saveDatabase();
    if (command == resString("UserPreferences")) preferences();
    if (command == resString("UsedSystemLetters")) settings();
    if (command == resString("AboutProgram")) about();
  }

  private void preferences() {
    preferencesDialog.shomMe();
  }

  private void changePassword() {
    JOptionPane.showMessageDialog(this, buildReEnterPanel(), resString("PromtNewPasswordHeader"), JOptionPane.INFORMATION_MESSAGE, Global.iconKeylock);
    CommonUtill.changePassword(password.getPassword());
  }

  private void reEnterPassword() {
    JOptionPane.showMessageDialog(this, buildReEnterPanel(), resString("PromtPasswordHeader"),
        JOptionPane.INFORMATION_MESSAGE, Global.iconKeylock);
    Encrypter.getInstance().setPassPhrase(password.getPassword());
    if (dynamicTree != null){
      dynamicTree.fillTree();
    }
  }

  private JComponent buildReEnterPanel() {

    FormLayout layout = new FormLayout("right:pref, 3dlu, 120dlu", // cols
        "p, 3dlu, p"); // rows

    PanelBuilder builder = new PanelBuilder(layout);
    builder.setDefaultDialogBorder();

    password = new JPasswordField();
    password.setFocusable(true);
    password.setEchoChar('�');

    CellConstraints cc = new CellConstraints();

    builder.addLabel(resString("PromptPassword"), cc.xyw(1, 1, 3));
    builder.add(password, cc.xy(3, 3));

    return builder.getPanel();
  }

  /**
   * Change tray icon in system tray bar
   */
  private void changeTrayIcoToDisconnect() {
    trayIcon.setImage(disconnectTrayIcon);
  }

  private void changeMapOrUnmapButtonStatusToDisconnect(){
    mapOrUnmapButton.setIcon(Global.iconDisconncet);
    mapOrUnmapButton.setText(resString("StatusDisconnected"));
  }
 
  /**
   * Change tray icon in system tray bar
   */
  private void changeTrayIcoToConnect() {
    trayIcon.setImage(connectTrayIcon);
  }
 
  private void changeMapOrUnmapButtonStatusToConnect() {
    mapOrUnmapButton.setIcon(Global.iconConncet);
    mapOrUnmapButton.setText(resString("StatusConnected"));
  }

 
  /**
   * Exit application
   */
  public void exit() {
    SpringUtil.closeSingletones();
    if (Preferences.userRoot().getBoolean(
        PreferencesConfig.KEY_CLEAR_DB_TEMP_FOLDER_ON_EXIT, false)) {
      CommonUtill.clearDatabaseTempFolder();
    }

    System.exit(-1);
  }


  /**
   * Open setting dialog
   */
  private void settings() {
    settingDialog.showMe();
  }

  private void loadDatabase() {

    JFileChooser choose = getFileChooser();
    choose.showOpenDialog(this);
    File file = choose.getSelectedFile();

    if (file != null) {

      SpringUtil.closeSingletones();

      PackUtill pack = new PackUtill();

      if (logger.isDebugEnabled()) {
        logger.debug("Loaded database: " + file);
        logger.debug("Path to temp database folder: " + Global.PATH_TO_DB);
      }

      pack.decompresToDir(file.getAbsolutePath(), Global.PATH_TO_DB);

      PreferencesConfig.userRoot().put(PreferencesConfig.KEY_LAST_DB_PATH, file.getAbsolutePath());
      PreferencesConfig.savePreferences();
      dynamicTree.fillTree();
      DataController.getInstance().fireDataChanged();
    }
  }

  public void loadLastDatabase() {
    String file = Preferences.userRoot().get(
        PreferencesConfig.KEY_LAST_DB_PATH, "");
    PackUtill pack = new PackUtill();

    if (logger.isDebugEnabled()) {
      logger.debug("Auto load last database: " + file);
      logger.debug("Path to temp database folder: " + Global.PATH_TO_DB);
    }

    pack.decompresToDir(file, Global.PATH_TO_DB);
  }

  private void saveDatabase() {

    JFileChooser choose = getFileChooser();
    choose.showSaveDialog(this);
    File file = choose.getSelectedFile();

    if (file != null) {
      SpringUtil.closeSingletones();

      PackUtill pack = new PackUtill();
      if (CommonUtill.getExtension(file).equals(Global.JNET_MAP_FILE_EXTENSION)){
        pack.compresFromDir(file.getAbsolutePath(), Global.PATH_TO_DB);
      } else {
        pack.compresFromDir(file.getAbsolutePath() + "."+Global.JNET_MAP_FILE_EXTENSION, Global.PATH_TO_DB);
      }
     
    }
  }

  /**
   * Show about info
   */
  private void about() {
    JOptionPane
        .showMessageDialog(
            this,
            "JNetMap\nAutor: Matej Zachar\ne-mail: zachar.matej@gmail.com\n(c)2006",
            resString("AboutProgram"),
            JOptionPane.INFORMATION_MESSAGE);
  }

  public void valueChanged(TreeSelectionEvent e) {
    TreePath path = e.getPath();
    dynamicTree.setCurrentSelectionPath(path);

    logger.debug("Selection Change: " + path.toString());

    if (dynamicTree.isRootNodeSelectedPath() == false) { // Groups node
      if (dynamicTree.isGroupNodeSelectedPath()) {
        groupPanel.setGroup((Group) dynamicTree.getCurrentNode().getUserObject());
        mapOrUnmapButton.setEnabled(true);
        mapOrUnmapButtonStatusChange();
               
        addToComponentPanel(groupPanel);
       
      } else if (dynamicTree.isServerNodeSelectedPath()) {
        serverPanel.setServer((Server) dynamicTree.getCurrentNode()
            .getUserObject());
        addToComponentPanel(serverPanel);
        mapOrUnmapButton.setEnabled(false);

      } else if (dynamicTree.isSharedFolderNodeSelectedPath()) {
        sharedFolderPanel.setSharedFolder((SharedFolder) dynamicTree
            .getCurrentNode().getUserObject());
        addToComponentPanel(sharedFolderPanel);
        mapOrUnmapButton.setEnabled(false);
      }
    } else {
      clearComponentPanel();
      mapOrUnmapButton.setEnabled(false);
    }
  }
 
  private void mapOrUnmapButtonStatusChange(){
    if (groupPanel.getGroup() == null) return;
   
    if (DataController.getInstance().isGroupMapped(groupPanel.getGroup())){
      changeMapOrUnmapButtonStatusToConnect();
      logger.debug("Status changed: to connected");
    } else {
      changeMapOrUnmapButtonStatusToDisconnect();
      logger.debug("Status changed: to DISconnected");
    }
  }

  public void propertyChange(PropertyChangeEvent event) {
    String property = event.getPropertyName();
    logger.debug("MainFrame: "+property);
   
    if (property.equals(DataController.PROPERTY_MAP_GROUP)) mapOccurres();
    if (property.equals(DataController.PROPERTY_UNMAP_GROUP))unMapOccurres();
   
    if (event.getNewValue() == null){
      clearComponentPanel();
    }
  }

  private void mapOccurres() {
    logger.debug("Map Occuress");
    changeTrayIcoToConnect();
    mapOrUnmapButtonStatusChange();
  }
 
  private void unMapOccurres() {
    logger.debug("UNMap Occuress");
    changeTrayIcoToDisconnect();
    mapOrUnmapButtonStatusChange();
  }
}
TOP

Related Classes of sk.netmap.gui.MainFrame

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.