All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.mcs.jmeasurement.gui.ReportViewer Maven / Gradle / Ivy

There is a newer version: 1.1.226
Show newest version
/*
 * MCS Media Computer Software Copyright (c) 2006 by MCS
 * -------------------------------------- Created on 07.08.2006 by w.klaas
 * 
 * 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 de.mcs.jmeasurement.gui;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Paint;
import java.awt.Point;
import java.awt.TexturePaint;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.InvalidPropertiesFormatException;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.ProgressMonitorInputStream;
import javax.swing.ScrollPaneLayout;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import org.jdesktop.swingx.IncidentInfo;
import org.jdesktop.swingx.JXErrorDialog;
import org.xml.sax.SAXException;

import de.mcs.jmeasurement.MeasureFactory;
import de.mcs.jmeasurement.MeasurePoint;
import de.mcs.jmeasurement.exception.MeasurementException;

/**
 * @author w.klaas
 * 
 */
public class ReportViewer extends JFrame {
  /**
   * Image panel for about dialog.
   * 
   * @author w.klaas
   * 
   */
  public static final class ImagePanel extends JPanel {
    /**
     * 
     */
    private static final long serialVersionUID = -1949615036773091661L;

    /** the texture. */
    private transient Paint texture;

    /**
     * constructiong a image panel.
     * 
     * @param name
     *            name of the image to load with resourceFrom Stream.
     */
    public ImagePanel(final String name) {
      BufferedImage image;
      try {
        image = ImageIO.read(getClass().getResourceAsStream(name));
        Rectangle2D r = new Rectangle2D.Double(0, 0, image.getWidth(), image.getHeight());
        texture = new TexturePaint(image, r);
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    /**
     * paint hte image panel.
     * 
     * @param g
     *            the graphics
     * @see JPanel#paint(Graphics)
     */
    public void paint(final Graphics g) {
      Graphics2D g2 = (Graphics2D) g;
      super.paint(g);
      g2.setPaint(texture);
      g2.fillRect(0, 0, getWidth(), getHeight());
    }
  }

  /**
   * 
   */
  private static final long serialVersionUID = -3627139012406024384L;

  /** action names. */
  private static final String FILE_EXIT = "file/exit"; //$NON-NLS-1$

  /** action names. */
  private static final String FILE_OPEN = "file/open"; //$NON-NLS-1$

  /** action names. */
  private static final String FILTER_PROCESS = "filter/process"; //$NON-NLS-1$

  /** action names. */
  private static final String FILE_OPEN_URL = "file/open/url"; //$NON-NLS-1$

  /** action names. */
  private static final String FILE_REFRESH_URL = "file/refresh/url"; //$NON-NLS-1$

  /** action names. */
  private static final String EXTRA_OPTIONS = "extra/options"; //$NON-NLS-1$

  /** action names. */
  private static final String HELP_ABOUT = "help/about";

  /** component. */
  private JPanel contentPane = null;

  /** component. */
  private JMenuBar jMenuBar = null;

  /** component. */
  private JMenu fileMenu = null;

  /** component. */
  // private JMenu editMenu = null;

  /** component. */
  private JMenu helpMenu = null;

  /** component. */
  private JMenuItem exitMenuItem = null;

  /** component. */
  private JMenuItem aboutMenuItem = null;

  /** component. */
  // private JMenuItem cutMenuItem = null;

  /** component. */
  // private JMenuItem copyMenuItem = null;

  /** component. */
  // private JMenuItem pasteMenuItem = null;

  /** component. */
  private JMenuItem openMenuItem = null;

  /** component. */
  private JToolBar toolBar;

  /** component. */
  private JPanel centerPane;

  /** component. */
  private JPanel filterPane;

  /** component. */
  private JComboBox jcFilter;

  /** component. */
  private JTable grid;

  /** the data model forthe table. */
  private MeasureTableModel model;

  /** the sorter model. */
  private TableSorter tableModel;

  /** map with all actions. */
  private HashMap actions;

  /** panel for status messages and the progress bar. */
  private JPanel statusPane;

  /** label for status messages. */
  private JLabel statusText;

  /** the progress bar. */
  private JProgressBar progressBar;

  /** menu item. */
  private JMenuItem openUrlMenuItem;

  /** the singelton application. */
  private static ReportViewer application;

  /** url of the report data if set. */
  private URL url = null;

  /** configuration data. */
  private StoreProperties config;

  /** list of all used urls. */
  private ArrayList urllist;

  /** the combobox with the snapshots. */
  private JComboBox jcSnapShot;

  /** menu item. */
  private JMenuItem reloadMenuItem;

  /** button for refresh, when url is loaded. */
  private JButton jbRefresh;

  /** timer for the about box. */
  private transient Timer timer;

  // private JMenu extraMenu;

  // private JMenuItem optionsMenuItem;

  private JButton jbOptions;

  /**
   * @param args
   *            commandline arguments first argument is the file to show
   * @throws UnsupportedLookAndFeelException
   *             if something goes wrong.
   * @throws IllegalAccessException
   *             if something goes wrong.
   * @throws InstantiationException
   *             if something goes wrong.
   * @throws ClassNotFoundException
   *             if something goes wrong.
   * @throws MeasurementException
   *             if something goes wrong.
   * @throws SAXException
   *             if something goes wrong.
   * @throws IOException
   *             if something goes wrong.
   */
  public static void main(final String[] args) throws ClassNotFoundException, InstantiationException,
      IllegalAccessException, UnsupportedLookAndFeelException, IOException, SAXException, MeasurementException {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    JFrame.setDefaultLookAndFeelDecorated(true);
    application = new ReportViewer();
    if (args.length > 0) {
      File reportData = new File(args[0]);
      application.loadReport(reportData);
    }
    application.setVisible(true);
  }

  /**
   * This is the default constructor.
   */
  public ReportViewer() {
    super();
    urllist = new ArrayList();
    initialize();
  }

  /**
   * This method initializes this.
   * 
   */
  private void initialize() {
    actions = new HashMap();
    addStandardActions();

    loadConfigurationData();
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setJMenuBar(getMyMenuBar());
    this.setContentPane(getJContentPane());
    this.setTitle(Messages.getString("ReportViewer.APPLICATION.TITLE")); //$NON-NLS-1$

    addWindowListener(new WindowAdapter() {

      /*
       * (non-Javadoc)
       * 
       * @see java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent)
       */
      @Override
      public void windowClosing(final WindowEvent e) {
        super.windowClosing(e);
        saveConfigurationData();
      }

    });
    jbRefresh.setEnabled(false);
    showAbout();
  }

  /** adding standard sctions like file/exit help. */
  private void addStandardActions() {
    actions.put(FILE_EXIT, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        saveConfigurationData();
        exit();
      }

    });
    actions.put(FILE_OPEN, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        openReport();
      }

    });
    actions.put(FILE_OPEN_URL, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        openReportURL();
      }

    });
    actions.put(FILE_REFRESH_URL, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        if (null != url) {
          try {
            loadReportFromURL(url);
          } catch (Exception e1) {
            showException(e1);
          }
        }
      }
    });
    actions.put(FILTER_PROCESS, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        doFilter();
      }

    });
    actions.put(EXTRA_OPTIONS, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        showOptions();
      }

    });
    actions.put(HELP_ABOUT, new AbstractAction() {

      private static final long serialVersionUID = 1L;

      public void actionPerformed(final ActionEvent e) {
        showAbout();
      }

    });
  }

  protected void showOptions() {
    // TODO Auto-generated method stub
    System.out.println("show options");
  }

  /**
   * showing the about dialog.
   * 
   */
  protected final void showAbout() {
    final JDialog aboutDialog = new JDialog(ReportViewer.this, Messages.getString("ReportViewer.ABOUT.TITLE"), false); //$NON-NLS-1$
    // final JFrame aboutDialog = new JFrame(Messages
    // .getString("ReportViewer.ABOUT.TITLE")); //$NON-NLS-1$
    aboutDialog.setResizable(false);
    ImagePanel imagePanel = new ImagePanel("/de/mcs/jmeasurement/gui/images/logo_mcs.jpg");
    imagePanel.setLayout(new BorderLayout());
    imagePanel.addMouseListener(new MouseAdapter() {

      /*
       * (non-Javadoc)
       * 
       * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
       */
      @Override
      public void mouseClicked(final MouseEvent e) {
        if (aboutDialog.isVisible()) {
          aboutDialog.setVisible(false);
        }
      }

    });

    aboutDialog.getContentPane().add(imagePanel);
    Dimension dimension = new Dimension(400, 320);
    Point point = getCenterWindowPosition(dimension);
    aboutDialog.setAlwaysOnTop(true);
    aboutDialog.setLocation(point);
    aboutDialog.setSize(dimension);
    aboutDialog.setVisible(true);
    timer = new Timer("about");
    timer.schedule(new TimerTask() {

      @Override
      public void run() {
        if (aboutDialog.isVisible()) {
          aboutDialog.setVisible(false);
        }
      }

    }, 5000);
    // aboutDialog.pack();
  }

  /**
   * getting one action from the action map.
   * 
   * @param actionName
   *            action to get.
   * @return ActionListener
   */
  private ActionListener getAction(final String actionName) {
    return actions.get(actionName);
  }

  /**
   * This method initializes jContentPane.
   * 
   * @return javax.swing.JPanel
   */
  private JPanel getJContentPane() {
    if (contentPane == null) {
      contentPane = new JPanel();
      contentPane.setLayout(new BorderLayout());
      contentPane.add(BorderLayout.NORTH, getToolBar());
      contentPane.add(BorderLayout.CENTER, getCenterPane());
    }
    return contentPane;
  }

  /**
   * This method initializes center pane.
   * 
   * @return javax.swing.JPanel
   */
  private JPanel getCenterPane() {
    if (centerPane == null) {
      centerPane = new JPanel();
      centerPane.setLayout(new BorderLayout());
      centerPane.add(BorderLayout.NORTH, getFilterPane());
      centerPane.add(BorderLayout.CENTER, getMeasureGrid());
      centerPane.add(BorderLayout.SOUTH, getStatusPane());
    }
    return centerPane;
  }

  /**
   * This method initializes filter pane.
   * 
   * @return javax.swing.JPanel
   */
  private JPanel getStatusPane() {
    if (statusPane == null) {
      statusPane = new JPanel();
      GridBagLayout gbl = new GridBagLayout();
      gbl.columnWidths = new int[] { 300, 60 };
      statusPane.setLayout(gbl);
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      statusText = new JLabel(""); //$NON-NLS-1$
      statusPane.add(statusText, gbc);

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 1;

      progressBar = new JProgressBar(0, 100);
      statusPane.add(progressBar, gbc);
    }
    return statusPane;
  }

  /**
   * This method initializes filter pane.
   * 
   * @return javax.swing.JPanel
   */
  private JPanel getFilterPane() {
    if (filterPane == null) {
      filterPane = new JPanel();
      GridBagLayout gbl = new GridBagLayout();
      gbl.columnWidths = new int[] { 60, 300, 60, 120 };
      filterPane.setLayout(gbl);
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      filterPane.add(new JLabel(Messages.getString("ReportViewer.Filter")), gbc); //$NON-NLS-1$

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 1;
      filterPane.add(getFilterCombo(), gbc);

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridx = 2;
      gbc.insets = new Insets(0, 5, 0, 0);
      filterPane.add(new JLabel(Messages.getString("ReportViewer.Snapshots")), gbc); //$NON-NLS-1$

      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.gridwidth = GridBagConstraints.REMAINDER;
      gbc.gridx = 3;
      filterPane.add(getSnapShotCombo(), gbc);
    }
    return filterPane;
  }

  /**
   * This method initializes filter combo box.
   * 
   * @return JComboBox
   */
  private JComboBox getSnapShotCombo() {
    if (jcSnapShot == null) {
      jcSnapShot = new JComboBox();
      // String[] items = config.getFilterItems();
      // if (items != null) {
      // for (int i = 0; i < items.length; i++) {
      // jcSnapShot.addItem(items[i]);
      // }
      // }

      jcSnapShot.setEditable(false);
      jcSnapShot.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {
          if (model != null) {
            String selection = (String) jcSnapShot.getSelectedItem();
            if (selection != null) {
              if (jcSnapShot.getSelectedIndex() == 0) {
                model.setSnapshot(null);
              } else {
                model.setSnapshot(selection);
              }
            }
          }
        }

      });
    }
    return jcSnapShot;
  }

  /**
   * This method initializes filter combo box.
   * 
   * @return JComboBox
   */
  private JComboBox getFilterCombo() {
    if (jcFilter == null) {
      jcFilter = new JComboBox();
      String[] items = config.getFilterItems();
      if (items != null) {
        for (int i = 0; i < items.length; i++) {
          jcFilter.addItem(items[i]);
        }
      }

      jcFilter.setEditable(true);
      jcFilter.addActionListener(new ActionListener() {

        public void actionPerformed(final ActionEvent e) {
          String selection = (String) jcFilter.getSelectedItem();
          for (int i = 0; i < jcFilter.getItemCount(); i++) {
            String string = (String) jcFilter.getItemAt(i);
            if (string.equals(selection)) {
              doFilter();
              return;
            }
          }
          jcFilter.insertItemAt(selection, 0);
          while (jcFilter.getItemCount() > 10) {
            jcFilter.removeItemAt(jcFilter.getItemCount() - 1);
          }
          doFilter();
        }

      });
    }
    return jcFilter;
  }

  /**
   * This method initializes the measure grid.
   * 
   * @return Component
   */
  private Component getMeasureGrid() {
    if (null != model) {
      grid = new JTable(tableModel) {
        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        // Implement table header tool tips.
        protected JTableHeader createDefaultTableHeader() {
          return new JTableHeader(columnModel) {
            /**
             * 
             */
            private static final long serialVersionUID = 1L;

            public String getToolTipText(final MouseEvent e) {
              java.awt.Point p = e.getPoint();
              int index = columnModel.getColumnIndexAtX(p.x);
              int realIndex = columnModel.getColumn(index).getModelIndex();
              return model.getColumnDescription(realIndex);
            }
          };
        }
      };
      initGrid();
    } else {
      grid = new JTable();
    }
    grid.addMouseListener(new MouseAdapter() {

      /**
       * @see java.awt.event.MouseAdapter#mouseClicked(java.awt.event.MouseEvent)
       */
      @Override
      public void mouseClicked(final MouseEvent e) {
        if (e.getClickCount() > 1) {
          showSelectedPoint();
        }
      }

    });

    JScrollPane pane = new JScrollPane(grid);
    pane.setLayout(new ScrollPaneLayout());
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

    return pane;
  }

  /**
   * This method initializes the toolbar.
   * 
   * @return JToolBar
   */
  private JToolBar getToolBar() {
    toolBar = new JToolBar();
    toolBar.setRollover(true);

    JButton jbExit = new JButton(
    // Messages.getString("ReportViewer.BUTTON.EXIT"),
        Messages.getImage( //$NON-NLS-1$
            "misc_goto", true)); //$NON-NLS-1$

    jbExit.addActionListener(actions.get(FILE_EXIT));
    jbExit.setHorizontalTextPosition(SwingConstants.CENTER);
    jbExit.setVerticalTextPosition(SwingConstants.BOTTOM);
    jbExit.setToolTipText(Messages.getString("ReportViewer.BUTTON.EXIT"));
    toolBar.add(jbExit);

    JButton jbAbout = new JButton(
    // Messages.getString("ReportViewer.BUTTON.ABOUT"),
        Messages.getImage( //$NON-NLS-1$
            "win_info", true)); //$NON-NLS-1$

    jbAbout.addActionListener(actions.get(HELP_ABOUT));
    jbAbout.setHorizontalTextPosition(SwingConstants.CENTER);
    jbAbout.setVerticalTextPosition(SwingConstants.BOTTOM);
    jbAbout.setToolTipText(Messages.getString("ReportViewer.BUTTON.ABOUT"));
    toolBar.add(jbAbout);

    toolBar.addSeparator();

    JButton jbOpen = new JButton(
    // Messages.getString("ReportViewer.BUTTON.OPEN"),
        Messages.getImage( //$NON-NLS-1$
            "win_fileopen", true)); //$NON-NLS-1$
    jbOpen.addActionListener(getAction(FILE_OPEN));
    jbOpen.setHorizontalTextPosition(SwingConstants.CENTER);
    jbOpen.setVerticalTextPosition(SwingConstants.BOTTOM);
    jbOpen.setToolTipText(Messages.getString("ReportViewer.BUTTON.OPEN"));
    toolBar.add(jbOpen);

    jbRefresh = new JButton(
    // Messages.getString("ReportViewer.BUTTON.REFRESH"),
        Messages.getImage( //$NON-NLS-1$
            "db_refresh", true));
    jbRefresh.addActionListener(getAction(FILE_REFRESH_URL));
    jbRefresh.setHorizontalTextPosition(SwingConstants.CENTER);
    jbRefresh.setVerticalTextPosition(SwingConstants.BOTTOM);
    jbRefresh.setToolTipText(Messages.getString("ReportViewer.BUTTON.REFRESH"));
    toolBar.add(jbRefresh);

    jbOptions = new JButton(
    // Messages.getString("ReportViewer.BUTTON.OPTIONS"),
        Messages.getImage( //$NON-NLS-1$
            "db_refresh", true));
    jbOptions.addActionListener(getAction(EXTRA_OPTIONS));
    jbOptions.setHorizontalTextPosition(SwingConstants.CENTER);
    jbOptions.setVerticalTextPosition(SwingConstants.BOTTOM);
    jbOptions.setToolTipText(Messages.getString("ReportViewer.BUTTON.OPTIONS"));
    // toolBar.add(jbOptions);
    return toolBar;
  }

  /**
   * This method initializes MenuBar.
   * 
   * @return javax.swing.JMenuBar
   */
  private JMenuBar getMyMenuBar() {
    if (jMenuBar == null) {
      jMenuBar = new JMenuBar();
      jMenuBar.add(getFileMenu());
      // jMenuBar.add(getEditMenu());
      // jMenuBar.add(getExtraMenu());
      jMenuBar.add(getHelpMenu());
    }
    return jMenuBar;
  }

  /**
   * This method initializes file menu.
   * 
   * @return javax.swing.JMenu
   */
  private JMenu getFileMenu() {
    if (fileMenu == null) {
      fileMenu = new JMenu();
      fileMenu.setText(Messages.getString("ReportViewer.MENU.FILE")); //$NON-NLS-1$
      fileMenu.add(getOpenMenuItem());
      fileMenu.addSeparator();
      fileMenu.add(getOpenURLMenuItem());
      fileMenu.add(getReloadMenuItem());
      fileMenu.addSeparator();
      fileMenu.add(getExitMenuItem());
    }
    return fileMenu;
  }

  /**
   * This method initializes edit menu.
   * 
   * @return javax.swing.JMenu
   */
  // private JMenu getEditMenu() {
  // if (editMenu == null) {
  // editMenu = new JMenu();
  //      editMenu.setText(Messages.getString("ReportViewer.MENU.EDIT")); //$NON-NLS-1$
  // editMenu.add(getCutMenuItem());
  // editMenu.add(getCopyMenuItem());
  // editMenu.add(getPasteMenuItem());
  // }
  // return editMenu;
  // }

  /**
   * This method initializes edit menu.
   * 
   * @return javax.swing.JMenu
   */
  // private JMenu getExtraMenu() {
  // if (extraMenu == null) {
  // extraMenu = new JMenu();
  //      extraMenu.setText(Messages.getString("ReportViewer.MENU.EXTRA")); //$NON-NLS-1$
  // extraMenu.add(getOptionsMenuItem());
  // }
  // return extraMenu;
  // }

  /**
   * This method initializes exit menu item.
   * 
   * @return javax.swing.JMenuItem
   */
  // private JMenuItem getOptionsMenuItem() {
  // if (optionsMenuItem == null) {
  // optionsMenuItem = new JMenuItem();
  //      optionsMenuItem.setText(Messages.getString("ReportViewer.MENU.EXTRA.OPTIONS")); //$NON-NLS-1$
  // optionsMenuItem.addActionListener(actions.get(EXTRA_OPTIONS));
  // }
  // return optionsMenuItem;
  // }

  /**
   * This method initializes help menu.
   * 
   * @return javax.swing.JMenu
   */
  private JMenu getHelpMenu() {
    if (helpMenu == null) {
      helpMenu = new JMenu();
      helpMenu.setText(Messages.getString("ReportViewer.MENU.HELP")); //$NON-NLS-1$
      helpMenu.add(getAboutMenuItem());
    }
    return helpMenu;
  }

  /**
   * This method initializes exit menu item.
   * 
   * @return javax.swing.JMenuItem
   */
  private JMenuItem getExitMenuItem() {
    if (exitMenuItem == null) {
      exitMenuItem = new JMenuItem();
      exitMenuItem.setText(Messages.getString("ReportViewer.MENU.FILE.EXIT")); //$NON-NLS-1$
      exitMenuItem.addActionListener(actions.get(FILE_EXIT));
    }
    return exitMenuItem;
  }

  /**
   * This method initializes about menu item.
   * 
   * @return javax.swing.JMenuItem
   */
  private JMenuItem getAboutMenuItem() {
    if (aboutMenuItem == null) {
      aboutMenuItem = new JMenuItem();
      aboutMenuItem.setText(Messages.getString("ReportViewer.MENU.HELP.ABOUT")); //$NON-NLS-1$
      aboutMenuItem.addActionListener(actions.get(HELP_ABOUT));
    }
    return aboutMenuItem;
  }

  /**
   * getting the center position of a dialog.
   * 
   * @param dimension
   *            dimensions of the dialog.
   * @return Point the location the dialog must have.
   */
  public static final Point getCenterWindowPosition(final Dimension dimension) {
    int divx = dimension.width / 2;
    int divy = dimension.height / 2;
    /** size of the screen. */
    Dimension screensize = Toolkit.getDefaultToolkit().getScreenSize();

    return new Point((screensize.width / 2) - divx, (screensize.height / 2) - divy);
  }

  /**
   * This method initializes jMenuItem.
   * 
   * @return javax.swing.JMenuItem
   */
  // private JMenuItem getCutMenuItem() {
  // if (cutMenuItem == null) {
  // cutMenuItem = new JMenuItem();
  //      cutMenuItem.setText(Messages.getString("ReportViewer.7")); //$NON-NLS-1$
  // cutMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK, true));
  // }
  // return cutMenuItem;
  // }

  /**
   * This method initializes jMenuItem.
   * 
   * @return javax.swing.JMenuItem
   */
  // private JMenuItem getCopyMenuItem() {
  // if (copyMenuItem == null) {
  // copyMenuItem = new JMenuItem();
  //      copyMenuItem.setText(Messages.getString("ReportViewer.8")); //$NON-NLS-1$
  // copyMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK, true));
  // }
  // return copyMenuItem;
  // }

  /**
   * This method initializes jMenuItem.
   * 
   * @return javax.swing.JMenuItem
   */
  // private JMenuItem getPasteMenuItem() {
  // if (pasteMenuItem == null) {
  // pasteMenuItem = new JMenuItem();
  //      pasteMenuItem.setText(Messages.getString("ReportViewer.9")); //$NON-NLS-1$
  // pasteMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK, true));
  // }
  // return pasteMenuItem;
  // }

  /**
   * This method initializes open menu item.
   * 
   * @return javax.swing.JMenuItem
   */
  private JMenuItem getOpenMenuItem() {
    if (openMenuItem == null) {
      openMenuItem = new JMenuItem();
      openMenuItem.setText(Messages.getString("ReportViewer.MENU.FILE.OPEN")); //$NON-NLS-1$
      openMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK, true));
      openMenuItem.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
        public void propertyChange(final java.beans.PropertyChangeEvent e) {
          if ((e.getPropertyName().equals("accelerator"))) { //$NON-NLS-1$
            System.out.println("propertyChange(accelerator)"); //$NON-NLS-1$
          }
        }
      });
      openMenuItem.addActionListener(getAction(FILE_OPEN));

    }
    return openMenuItem;
  }

  /**
   * This method initializes open menu item.
   * 
   * @return javax.swing.JMenuItem
   */
  private JMenuItem getOpenURLMenuItem() {
    if (openUrlMenuItem == null) {
      openUrlMenuItem = new JMenuItem();
      openUrlMenuItem.setText(Messages.getString("ReportViewer.MENU.FILE.OPEN.URL")); //$NON-NLS-1$)
      openUrlMenuItem.addActionListener(getAction(FILE_OPEN_URL));
    }
    return openUrlMenuItem;
  }

  /**
   * This method initializes open menu item.
   * 
   * @return javax.swing.JMenuItem
   */
  private JMenuItem getReloadMenuItem() {
    if (reloadMenuItem == null) {
      reloadMenuItem = new JMenuItem();
      reloadMenuItem.setText(Messages.getString("ReportViewer.MENU.FILE.RELOAD")); //$NON-NLS-1$)
      reloadMenuItem.addActionListener(getAction(FILE_REFRESH_URL));
    }
    return reloadMenuItem;
  }

  /**
   * open a report with dialog.
   * 
   */
  private void openReport() {
    JFileChooser chooser = new JFileChooser(new File("").getAbsoluteFile());
    chooser.addChoosableFileFilter(new FileFilter() {

      @Override
      public boolean accept(final File f) {
        if (f.isDirectory()) {
          return true;
        }
        return f.getName().toLowerCase().endsWith(".xml"); //$NON-NLS-1$
      }

      @Override
      public String getDescription() {
        // TODO Auto-generated method stub
        return Messages.getString("ReportViewer.XMLFILE"); //$NON-NLS-1$
      }

    });
    chooser.setMultiSelectionEnabled(false);
    chooser.setDialogTitle(Messages.getString("ReportViewer.DIALOG.OPEN.TITLE")); //$NON-NLS-1$
    chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
      try {
        loadReport(chooser.getSelectedFile());
      } catch (IOException e) {
        e.printStackTrace();
      } catch (SAXException e) {
        e.printStackTrace();
      } catch (MeasurementException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * open a report with dialog.
   * 
   */
  private void openReportURL() {
    String value = "";
    if (urllist.size() > 0) {
      value = urllist.get(urllist.size() - 1);
    }
    String urlString = (String) JOptionPane.showInputDialog(this, Messages.getString("ReportViewer.URL.Text"), value); //$NON-NLS-1$
    urlString = urlString.trim();
    if (!urllist.contains(urlString)) {
      urllist.add(urlString);
    }
    try {
      URL tmpurl = new URL(urlString);
      loadReportFromURL(tmpurl);
      url = tmpurl;
    } catch (Exception e) {
      url = null;
      showException(e);
    }
  }

  /**
   * loading the desired report.
   * 
   * @param reportData
   *            the report file to load.
   * @throws IOException
   *             if something goes wrong.
   * @throws SAXException
   *             if something goes wrong.
   * @throws MeasurementException
   *             if something goes wrong.
   */
  private void loadReportFromStream(final InputStream reportData) throws IOException, SAXException,
      MeasurementException {
    MeasureFactory.clear();
    Runnable run = new Runnable() {

      public void run() {
        try {
          InputStream in = new BufferedInputStream(new ProgressMonitorInputStream(application,
              Messages.getString("ReportViewer.Progress.Reading") + reportData, reportData)); //$NON-NLS-1$
          MeasureFactory.loadFromXMLStream(in, true);
          in.close();
          String[] snapshotNames = MeasureFactory.getSnapShotNames();
          jcSnapShot.removeAllItems();
          for (int i = 0; i < snapshotNames.length; i++) {
            jcSnapShot.addItem(snapshotNames[i]);
          }
          jcSnapShot.insertItemAt("Main", 0);
          jcSnapShot.setSelectedIndex(0);
          model = new MeasureTableModel();
          if (null == tableModel) {
            tableModel = new TableSorter(model);
          } else {
            tableModel.setTableModel(model);
          }
          if (null != grid) {
            grid.setModel(tableModel);
            initGrid();
          }
          if (getFilter() != null) {
            model.setFilter(getFilter());
          }
          if (url != null) {
            jbRefresh.setEnabled(true);
          }
        } catch (Exception e) {
          showException(e);
        }
      }

    };
    Thread thread = new Thread(run);
    thread.start();
  }

  /**
   * loading the desired report.
   * 
   * @param reportData
   *            the report file to load.
   * @throws IOException
   *             if something goes wrong.
   * @throws SAXException
   *             if something goes wrong.
   * @throws MeasurementException
   *             if something goes wrong.
   */
  private void loadReport(final File reportData) throws IOException, SAXException, MeasurementException {
    loadReportFromStream(new FileInputStream(reportData));
    this.setTitle(Messages.getString("ReportViewer.APPLICATION.TITLE") //$NON-NLS-1$
        + " - " + reportData.getName()); //$NON-NLS-1$
  }

  /**
   * loading the report from a url.
   * 
   * @param aUrl
   *            where to load the report from.
   * @throws IOException
   *             if something goes wrong
   * @throws SAXException
   *             if something goes wrong
   * @throws MeasurementException
   *             if something goes wrong
   */
  private void loadReportFromURL(final URL aUrl) throws IOException, SAXException, MeasurementException {
    loadReportFromStream(aUrl.openStream());
    this.setTitle(Messages.getString("ReportViewer.APPLICATION.TITLE") //$NON-NLS-1$
        + " - " + aUrl.toExternalForm()); //$NON-NLS-1$
  }

  /**
   * initialise the grid.
   */
  private void initGrid() {
    grid.doLayout();
    grid.updateUI();
    initColumnSizes(grid);
    grid.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    tableModel.setTableHeader(grid.getTableHeader());
  }

  /**
   * showing the point dialog for the point selected in the grid.
   * 
   */
  private void showSelectedPoint() {
    int rowpos = grid.getSelectedRow();
    int colpos = 0;
    for (int i = 0; i < grid.getColumnCount(); i++) {
      String headerName = (String) grid.getColumnName(i);
      if (headerName.equalsIgnoreCase("pointname")) {
        colpos = i;
        break;
      }
    }
    String pointName = (String) grid.getValueAt(rowpos, colpos);
    MeasurePoint point = model.getMeasurePoint(pointName);
    showPointData(point);
  }

  /**
   * showing the dialog for a measure point. Restore the last position and
   * size of this dialog.
   * 
   * @param point
   *            the point to show.
   */
  private void showPointData(final MeasurePoint point) {
    PointDataDialog pointDataDialog = new PointDataDialog(point);
    pointDataDialog.setAlwaysOnTop(true);
    pointDataDialog.setModal(true);
    pointDataDialog.setSize(config.getPointDialogDimesions());
    pointDataDialog.setLocation(config.getPointDialogLocation());

    pointDataDialog.setVisible(true);
    config.setPointDialogDimesions(pointDataDialog.getSize());
    config.setPointDialogLocation(pointDataDialog.getLocation());
    pointDataDialog.dispose();
    System.out.println("hide it.");
  }

  /**
   * doing the filter.
   * 
   */
  private void doFilter() {
    model.setFilter(getFilter());
  }

  /**
   * @return string the filter string.
   * 
   */
  private String getFilter() {
    if (null == jcFilter) {
      return null;
    }
    return (String) jcFilter.getSelectedItem();
  }

  /**
   * initilise the column width, default or from the configuration.
   * 
   * @param table
   *            the table to use.
   */
  private void initColumnSizes(final JTable table) {
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    Object[] longValues = model.getLongValues();
    TableCellRenderer headerRenderer = table.getTableHeader().getDefaultRenderer();

    int[] sizes = config.getColumnSizes();
    for (int i = 0; i < table.getColumnModel().getColumnCount(); i++) {
      column = table.getColumnModel().getColumn(i);
      try {
        if ((sizes == null) || (sizes.length <= i) || (sizes[i] == 0)) {
          comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
          headerWidth = comp.getPreferredSize().width;

          comp = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, longValues[i],
              false, false, 0, i);
          cellWidth = comp.getPreferredSize().width;

          column.setPreferredWidth(Math.max(headerWidth, cellWidth));
        } else {
          column.setPreferredWidth(sizes[i]);
        }
      } catch (Exception e) {
        // nothing to do here.
      }
    }
    // : listener that watches the width of a column
    PropertyChangeListener pcl = new PropertyChangeListener() {
      public void propertyChange(final PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals("preferredWidth")) {
          saveColumnWidths();
        }
      }
    };

    // : add the column width lister to each column
    for (Enumeration e = table.getColumnModel().getColumns(); e.hasMoreElements();) {
      TableColumn tc = e.nextElement();
      tc.addPropertyChangeListener(pcl);
    }
  }

  /**
   * loading the configuration data from a config.xml file in the working
   * directory.
   * 
   */
  private void loadConfigurationData() {
    if (config == null) {
      config = new StoreProperties();
    }
    File configFile = new File("config.xml"); //$NON-NLS-1$
    if (configFile.exists()) {
      try {
        config.loadFromXML(new FileInputStream(configFile));
      } catch (InvalidPropertiesFormatException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    this.setSize(config.getWindowDimesions());
    this.setLocation(config.getWindowLocation());
    String[] urlValue = config.getUrlList();
    if (urlValue != null) {
      urllist = new ArrayList(Arrays.asList(urlValue));
    }
  }

  /**
   * saving the configuration data to a config.xml file in the working
   * directory.
   * 
   */
  private void saveConfigurationData() {
    config.setWindowDimesions(this.getSize());
    config.setWindowoLocation(this.getLocation());
    String[] items = new String[jcFilter.getItemCount()];
    for (int i = 0; i < jcFilter.getItemCount(); i++) {
      items[i] = (String) jcFilter.getItemAt(i);
    }
    config.setFilterItems(items);
    config.setUrlList((String[]) urllist.toArray(new String[0]));
    saveColumnWidths();
    File configFile = new File("config.xml"); //$NON-NLS-1$
    try {
      config.storeToXML(new FileOutputStream(configFile), ""); //$NON-NLS-1$
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

  /**
   * saving the column width of the grid.
   * 
   */
  private void saveColumnWidths() {
    int[] colwidth = new int[grid.getColumnModel().getColumnCount()];
    TableColumn column = null;
    for (int i = 0; i < grid.getColumnModel().getColumnCount(); i++) {
      column = grid.getColumnModel().getColumn(i);
      colwidth[i] = column.getWidth();
    }
    config.setColumnSizes(colwidth);
  }

  /**
   * showing an error dialog.
   * 
   * @param e
   *            exception to show.
   */
  public final void showException(final Throwable e) {
    IncidentInfo ii = new IncidentInfo(Messages.getString("ReportViewer.Error.Title"), //$NON-NLS-1$
        Messages.getString("ReportViewer.Error.Text"), null, e); //$NON-NLS-1$
    JXErrorDialog.showDialog(null, ii);
  }

  /**
   * exit this application.
   * 
   */
  private void exit() {
    System.exit(0);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy