Package org.pentaho.reporting.ui.datasources.jdbc.ui

Source Code of org.pentaho.reporting.ui.datasources.jdbc.ui.JdbcDataSourceDialog$QueryTextFieldActivationHandler

/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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 Lesser General Public License for more details.
*
* Copyright (c) 2008 - 2009 Pentaho Corporation, .  All rights reserved.
*/

package org.pentaho.reporting.ui.datasources.jdbc.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.net.URL;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListDataEvent;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import nickyb.sqleonardo.querybuilder.QueryBuilder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException;
import org.pentaho.reporting.engine.classic.core.designtime.DesignTimeContext;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.ExceptionDialog;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.KeyedComboBoxModel;
import org.pentaho.reporting.engine.classic.core.modules.gui.commonswing.SwingUtil;
import org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.ConnectionProvider;
import org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.DriverConnectionProvider;
import org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.JndiConnectionProvider;
import org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.SQLReportDataFactory;
import org.pentaho.reporting.libraries.base.util.LinkedMap;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
import org.pentaho.reporting.libraries.base.util.ResourceBundleSupport;
import org.pentaho.reporting.libraries.designtime.swing.BorderlessButton;
import org.pentaho.reporting.libraries.designtime.swing.background.DataPreviewDialog;
import org.pentaho.reporting.ui.datasources.jdbc.JdbcDataSourceModule;
import org.pentaho.reporting.ui.datasources.jdbc.connection.DriverConnectionDefinition;
import org.pentaho.reporting.ui.datasources.jdbc.connection.JdbcConnectionDefinition;
import org.pentaho.reporting.ui.datasources.jdbc.connection.JndiConnectionDefinition;

/**
* @author David Kincade
*/
public class JdbcDataSourceDialog extends JDialog
{

  private class PreviewAction extends AbstractAction implements PropertyChangeListener
  {
    private PreviewAction()
    {
      putValue(Action.NAME, getBundleSupport().getString("JdbcDataSourceDialog.Preview"));
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      setEnabled(dialogModel.isConnectionSelected() && dialogModel.isQuerySelected());
    }

    public void propertyChange(final PropertyChangeEvent evt)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      setEnabled(dialogModel.isConnectionSelected() && dialogModel.isQuerySelected());
    }

    public void actionPerformed(final ActionEvent evt)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      final JdbcConnectionDefinition connectionDefinition = (JdbcConnectionDefinition) dialogModel.getConnections().getSelectedItem();
      if (connectionDefinition == null)
      {
        return;
      }

      try
      {
        final String query = getQueryName();
        final DataPreviewDialog dialog = new DataPreviewDialog(JdbcDataSourceDialog.this);
        Integer maxRows = 0;
        if (maxPreviewRowsSpinner.isEnabled())
        {
          maxRows = (Integer) maxPreviewRowsSpinner.getValue();
        }
        if (maxRows == null)
        {
          maxRows = 0;
        }
        final JdbcPreviewWorker theJdbcPreviewWorker = new JdbcPreviewWorker(createDataFactory(connectionDefinition), query, 0, maxRows);
        dialog.showData(theJdbcPreviewWorker);

        final ReportDataFactoryException theException = theJdbcPreviewWorker.getException();
        if (theException != null)
        {
          ExceptionDialog.showExceptionDialog(JdbcDataSourceDialog.this,
              getBundleSupport().getString("PreviewDialog.PreviewError.Title"),
              getBundleSupport().getString("PreviewDialog.PreviewError.Message"), theException);
        }
      }
      catch (Exception e)
      {
        log.warn("QueryPanel.actionPerformed ", e);
        if (designTimeContext != null)
        {
          designTimeContext.userError(e);
        }
      }

    }
  }

  private class InvokeQueryDesignerAction extends AbstractAction implements PropertyChangeListener
  {
    private InvokeQueryDesignerAction()
    {
      final URL location = ConnectionPanel.class.getResource("/org/pentaho/reporting/ui/datasources/jdbc/resources/Edit.png");
      if (location != null)
      {
        putValue(Action.SMALL_ICON, new ImageIcon(location));
      }
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
     
      enable(dialogModel);
    }

    public void propertyChange(final PropertyChangeEvent evt)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      enable(dialogModel);
    }
   
    /**
     * Enable or disable the query editor button (SQLeonardo)
     *
     * This is currently disabled for Hadoop's Hive JDBC as not
     * enough SQL is supported by the driver.
     *
     * @param dialogModel
     * @return
     */
    private void enable(NamedDataSourceDialogModel dialogModel) {
      boolean enable = true;
     
      if(!(dialogModel.isConnectionSelected() && dialogModel.isQuerySelected())) {
        // At least one of Connection or Query is not selected
        enable = false;
      } else {
        // Fetch the currently selected connection for inspection
        Object connection = dialogModel.getConnections().getSelectedItem();
       
        if(connection instanceof DriverConnectionDefinition) {
          DriverConnectionDefinition dcd = (DriverConnectionDefinition) connection;

          // There are some instances where the DatabaseType is coming back null
          if(dcd.getDatabaseType() != null) {
            if(dcd.getDatabaseType().equalsIgnoreCase("HIVE")) { //$NON-NLS-1$
              // Disable SQLeonardo for Hadoop's Hive JDBC
              enable = false;
            }
          }
        }
      }

      setEnabled(enable);
    }

    public void actionPerformed(final ActionEvent e)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      final JdbcConnectionDefinition connectionDefinition = (JdbcConnectionDefinition) dialogModel.getConnections().getSelectedItem();
      if (connectionDefinition == null)
      {
        return;
      }

      Connection conn = null;
      try
      {
        final SQLReportDataFactory factory = createDataFactory(connectionDefinition);
        conn = factory.getConnectionProvider().createConnection(null, null);
        if (conn == null)
        {
          // TODO add proper error handling
          JOptionPane.showMessageDialog(JdbcDataSourceDialog.this,
              getBundleSupport().getString("JdbcDataSourceDialog.InvokeQueryDesignerError"),
              getBundleSupport().getString("JdbcDataSourceDialog.InvokeQueryDesignerError.Title"),
              JOptionPane.ERROR_MESSAGE);
          return;
        }

        final String schema = performQuerySchema(conn);

        final QueryBuilder queryBuilder = new QueryBuilder(conn);
        QueryBuilder.autoAlias = false;
        final JdbcQueryDesignerDialog queryDesigner = new JdbcQueryDesignerDialog(JdbcDataSourceDialog.this, queryBuilder);
        final String query = queryDesigner.designQuery(designTimeContext, factory.getConnectionProvider(), schema, getQuery());
        if (query != null)
        {
          setQuery(query);
        }
      }
      catch (SQLException e1)
      {
        log.warn("QueryPanel.actionPerformed ", e1);
        JOptionPane.showMessageDialog(JdbcDataSourceDialog.this, e1);
      }
      finally
      {
        if (conn != null)
        {
          try
          {
            conn.close();
          }
          catch (SQLException sqle)
          {
            log.warn("Could not close database connection", sqle);
          }
        }
      }
    }

    private String performQuerySchema(final Connection conn)
    {
      String schema = null;
      try
      {
        final DatabaseMetaData data = conn.getMetaData();
        final boolean isHsql = ("HSQL Database Engine".equals(data.getDatabaseProductName()));
        if (data.supportsSchemasInTableDefinitions())
        {
          final LinkedMap schemas = new LinkedMap();
          final ResultSet rs = data.getSchemas();
          while (rs.next())
          {
            final String schemaName = rs.getString(1).trim();
            if (isHsql && "INFORMATION_SCHEMA".equals(schemaName))
            {
              continue;
            }

            schemas.put(schemaName, Boolean.TRUE);
          }
          rs.close();

          // bring up dialog
          final String[] schemasArray = (String[]) schemas.keys(new String[schemas.size()]);
          if (schemas.size() > 1)
          {
            final SchemaSelectionDialog schemaSelectionDialog =
                new SchemaSelectionDialog(JdbcDataSourceDialog.this, schemasArray);
            schema = schemaSelectionDialog.getSchema();
          }
          else if (schemas.size() == 1)
          {
            schema = schemasArray[0];
          }
        }
      }
      catch (Exception ex)
      {
        log.warn("QueryPanel.actionPerformed ", ex);
      }
      return schema;
    }
  }

  private class QueryNameListSelectionListener implements ListSelectionListener
  {
    private QueryNameListSelectionListener()
    {
    }

    public void valueChanged(final ListSelectionEvent e)
    {
      getDialogModel().getQueries().setSelectedItem(queryNameList.getSelectedValue());

      final boolean querySelected = queryNameList.getSelectedIndex() != -1;
      queryNameTextField.setEnabled(querySelected);
    }
  }

  private class CancelAction extends AbstractAction
  {
    private CancelAction()
    {
      putValue(Action.NAME, getBundleSupport().getString("Button.cancel"));
    }

    public void actionPerformed(final ActionEvent e)
    {
      setConfirmed(false);
      dispose();
    }
  }

  private class ConfirmAction extends AbstractAction implements PropertyChangeListener
  {
    private ConfirmAction()
    {
      putValue(Action.NAME, getBundleSupport().getString("Button.ok"));
    }

    public void propertyChange(final PropertyChangeEvent evt)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      setEnabled(dialogModel.isConnectionSelected());
    }

    public void actionPerformed(final ActionEvent e)
    {
      setConfirmed(true);
      dispose();
    }
  }

  private class QueryAddAction extends AbstractAction
  {
    private QueryAddAction()
    {
      final URL location = ConnectionPanel.class.getResource("/org/pentaho/reporting/ui/datasources/jdbc/resources/Add.png");
      if (location != null)
      {
        putValue(Action.SMALL_ICON, new ImageIcon(location));
      }
      else
      {
        putValue(Action.NAME, bundleSupport.getString("JdbcDataSourceDialog.Add.Name"));
      }
      putValue(Action.SHORT_DESCRIPTION, bundleSupport.getString("JdbcDataSourceDialog.Add.Description"));
    }

    public void actionPerformed(final ActionEvent e)
    {
      String queryName = bundleSupport.getString("JdbcDataSourceDialog.Query");
      for (int i = 1; i < 1000; ++i)
      {
        final String newQuery = bundleSupport.getString("JdbcDataSourceDialog.Query") + " " + i;
        if (dialogModel.getQueries().findElementIndex(newQuery) == -1)
        {
          queryName = newQuery;
          break;
        }
      }

      dialogModel.addQuery(queryName, "");
      queryNameList.setSelectedValue(queryName, true);
    }
  }

  private class QueryRemoveAction extends AbstractAction implements PropertyChangeListener
  {
    private QueryRemoveAction()
    {
      final URL resource = ConnectionPanel.class.getResource("/org/pentaho/reporting/ui/datasources/jdbc/resources/Remove.png");
      if (resource != null)
      {
        putValue(Action.SMALL_ICON, new ImageIcon(resource));
      }
      else
      {
        putValue(Action.NAME, bundleSupport.getString("JdbcDataSourceDialog.Remove.Name"));
      }
      putValue(Action.SHORT_DESCRIPTION, bundleSupport.getString("JdbcDataSourceDialog.Remove.Description"));
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      setEnabled(dialogModel.isQuerySelected());
    }

    public void propertyChange(final PropertyChangeEvent evt)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      setEnabled(dialogModel.isQuerySelected());
    }

    public void actionPerformed(final ActionEvent e)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      final KeyedComboBoxModel queries = dialogModel.getQueries();
      queries.remove(queries.getSelectedItemIndex());
      queries.setSelectedItem(null);
      queryNameList.clearSelection();
    }
  }

  private class QueryNameTextFieldDocumentListener implements DocumentListener, ListDataListener
  {
    private boolean inUpdate;

    private QueryNameTextFieldDocumentListener()
    {
    }

    public void intervalAdded(final ListDataEvent e)
    {
    }

    public void intervalRemoved(final ListDataEvent e)
    {
    }

    public void contentsChanged(final ListDataEvent e)
    {
      if (inUpdate)
      {
        return;
      }
      if (e.getIndex0() != -1)
      {
        return;
      }

      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      try
      {
        inUpdate = true;
        final String currentName = getQueryName();
        final String selectedName = (String) dialogModel.getQueries().getSelectedItem();
        if (ObjectUtilities.equal(currentName, selectedName) == false)
        {
          setQueryName(selectedName);
        }

        setQuery((String) dialogModel.getQueries().getSelectedKey());
      }
      finally
      {
        inUpdate = false;
      }
    }

    public void insertUpdate(final DocumentEvent e)
    {
      update();
    }

    public void removeUpdate(final DocumentEvent e)
    {
      update();
    }

    public void changedUpdate(final DocumentEvent e)
    {
      update();
    }

    private void update()
    {
      if (inUpdate)
      {
        return;
      }
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      try
      {
        final KeyedComboBoxModel model = dialogModel.getQueries();
        final int itemIndex = model.getSelectedItemIndex();
        if (itemIndex == -1)
        {
          return;
        }

        inUpdate = true;
        model.update(itemIndex, getQuery(), getQueryName());
      }
      finally
      {
        inUpdate = false;
      }
    }
  }

  private class QueryDocumentListener implements DocumentListener
  {
    private QueryDocumentListener()
    {
    }

    public void insertUpdate(final DocumentEvent e)
    {
      update();
    }

    public void removeUpdate(final DocumentEvent e)
    {
      update();
    }

    public void changedUpdate(final DocumentEvent e)
    {
      update();
    }

    private void update()
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      final KeyedComboBoxModel model = dialogModel.getQueries();
      final int itemIndex = model.getSelectedItemIndex();
      if (itemIndex == -1)
      {
        return;
      }

      model.update(itemIndex, getQuery(), getQueryName());
    }
  }

  private class LimitRowsCheckBoxActionListener extends AbstractAction implements ItemListener
  {
    private JSpinner maxPreviewRowsSpinner;

    private LimitRowsCheckBoxActionListener(final JSpinner maxPreviewRowsSpinner)
    {
      this.maxPreviewRowsSpinner = maxPreviewRowsSpinner;
      putValue(Action.NAME, getBundleSupport().getString("QueryPanel.LimitRowsCheckBox"));
      putValue(Action.MNEMONIC_KEY, getBundleSupport().getMnemonic("QueryPanel.LimitRowsCheckBox.Mnemonic"));
      maxPreviewRowsSpinner.setEnabled(false);
    }

    public void itemStateChanged(final ItemEvent e)
    {
      final Object source = e.getSource();
      if (source instanceof AbstractButton)
      {
        final AbstractButton b = (AbstractButton) source;
        maxPreviewRowsSpinner.setEnabled(b.isSelected());
      }
    }

    public void actionPerformed(final ActionEvent e)
    {
      final Object source = e.getSource();
      if (source instanceof AbstractButton)
      {
        final AbstractButton b = (AbstractButton) source;
        maxPreviewRowsSpinner.setEnabled(b.isSelected());
      }
    }
  }

  private class QueryTextFieldActivationHandler implements PropertyChangeListener
  {
    private QueryTextFieldActivationHandler()
    {
    }

    public void propertyChange(final PropertyChangeEvent evt)
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      queryTextArea.setEnabled(dialogModel.isQuerySelected());
    }
  }

  protected static final Log log = LogFactory.getLog(JdbcDataSourceDialog.class);

  private boolean confirmed;

  private JTextField queryNameTextField;
  private RSyntaxTextArea queryTextArea;
  private JList queryNameList;
  private NamedDataSourceDialogModel dialogModel;
  private JdbcConnectionPanel connectionComponent;
  private ResourceBundleSupport bundleSupport;
  private DesignTimeContext designTimeContext;
  private JSpinner maxPreviewRowsSpinner;

  public JdbcDataSourceDialog(final DesignTimeContext designTimeContext)
  {
    this.designTimeContext = designTimeContext;
    initDialog();
  }

  public JdbcDataSourceDialog(final DesignTimeContext designTimeContext, final JDialog parent)
  {
    super(parent);
    this.designTimeContext = designTimeContext;
    initDialog();
  }

  public JdbcDataSourceDialog(final DesignTimeContext designTimeContext, final JFrame parent)
  {
    super(parent);
    this.designTimeContext = designTimeContext;
    initDialog();
  }

  /**
   * Displays the dialog and returns the newly created JNDIDataSetReportElement
   *
   * @param dataFactory the datafactory to be configured or null to create a new one
   * @return the a clone of the configured datafactory or null on cancel.
   */
  public SQLReportDataFactory performConfiguration(final SQLReportDataFactory dataFactory,
                                                   final String selectedQueryName)
  {
    confirmed = false;
    dialogModel.clear();

    // Load the data from the current report element
    if (dataFactory != null)
    {
      dialogModel.setJdbcPasswordField(dataFactory.getPasswordField());
      dialogModel.setJdbcUserField(dataFactory.getUserField());
      // Save the JNDI query information
      final String[] queryNames = dataFactory.getQueryNames();
      for (int i = 0; i < queryNames.length; i++)
      {
        final String queryName = queryNames[i];
        final String query = dataFactory.getQuery(queryName);
        dialogModel.addQuery(queryName, query);
      }

      queryNameList.setSelectedValue(selectedQueryName, true);

      final ConnectionProvider currentConnectionProvider = dataFactory.getConnectionProvider();
      final JdbcConnectionDefinition definition = connectionComponent.createConnectionDefinition(currentConnectionProvider);
      dialogModel.addConnection(definition);
      dialogModel.getConnections().setSelectedItem(definition);
    }

    // Enable the dialog
    setVisible(true);

    final JdbcConnectionDefinition connectionDefinition = (JdbcConnectionDefinition) dialogModel.getConnections().getSelectedItem();

    if (confirmed == false || connectionDefinition == null)
    {
      return null;
    }

    return createDataFactory(connectionDefinition);
  }

  private SQLReportDataFactory createDataFactory(final JdbcConnectionDefinition connectionDefinition)
  {
    final ConnectionProvider connectionProvider;
    if (connectionDefinition instanceof JndiConnectionDefinition)
    {
      final JndiConnectionDefinition jcd = (JndiConnectionDefinition) connectionDefinition;
      final JndiConnectionProvider provider = new JndiConnectionProvider();
      provider.setConnectionPath(jcd.getJndiName());
      provider.setUsername(jcd.getUsername());
      provider.setPassword(jcd.getPassword());
      connectionProvider = provider;
    }
    else if (connectionDefinition instanceof DriverConnectionDefinition)
    {
      final DriverConnectionDefinition dcd = (DriverConnectionDefinition) connectionDefinition;
      final DriverConnectionProvider provider = new DriverConnectionProvider();
      provider.setDriver(dcd.getDriverClass());
      provider.setUrl(dcd.getConnectionString());

      final Properties properties = dcd.getProperties();
      final Enumeration keys = properties.keys();
      while (keys.hasMoreElements())
      {
        final String key = (String) keys.nextElement();
        provider.setProperty(key, properties.getProperty(key));
      }
      connectionProvider = provider;
    }
    else
    {
      return null;
    }

    final SQLReportDataFactory newDataFactory = new SQLReportDataFactory(connectionProvider);
    newDataFactory.setPasswordField(dialogModel.getJdbcPasswordField());
    newDataFactory.setUserField(dialogModel.getJdbcUserField());
    final KeyedComboBoxModel queries = dialogModel.getQueries();
    for (int i = 0; i < queries.getSize(); i++)
    {
      newDataFactory.setQuery((String) queries.getElementAt(i), (String) queries.getKeyAt(i));
    }
    return newDataFactory;
  }

  /**
   * Creates the panel which holds the main content of the dialog
   */
  private void initDialog()
  {
    bundleSupport = new ResourceBundleSupport(Locale.getDefault(), JdbcDataSourceModule.MESSAGES,
        ObjectUtilities.getClassLoader(JdbcDataSourceModule.class));

    setTitle(bundleSupport.getString("JdbcDataSourceDialog.Title"));
    setModal(true);

    dialogModel = new NamedDataSourceDialogModel();
    connectionComponent = new JdbcConnectionPanel(dialogModel, designTimeContext);

    maxPreviewRowsSpinner = new JSpinner(new SpinnerNumberModel(10000, 1, Integer.MAX_VALUE, 1));

    queryNameTextField = new JTextField();
    queryNameTextField.setColumns(35);
    queryNameTextField.setEnabled(dialogModel.isQuerySelected());

    final QueryNameTextFieldDocumentListener updateHandler = new QueryNameTextFieldDocumentListener();
    queryNameTextField.getDocument().addDocumentListener(updateHandler);
    dialogModel.getQueries().addListDataListener(updateHandler);

    queryTextArea = new RSyntaxTextArea();
    queryTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_SQL);
    queryTextArea.setEnabled(dialogModel.isQuerySelected());
    queryTextArea.getDocument().addDocumentListener(new QueryDocumentListener());

    dialogModel.addPropertyChangeListener(new QueryTextFieldActivationHandler());

    queryNameList = new JList(dialogModel.getQueries());
    queryNameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    queryNameList.setVisibleRowCount(5);
    queryNameList.addListSelectionListener(new QueryNameListSelectionListener());

   
    // Create the connection panel
    final JPanel queryContentPanel = new JPanel(new BorderLayout());
    queryContentPanel.add(BorderLayout.NORTH, createQueryListPanel());
    queryContentPanel.add(BorderLayout.CENTER, createQueryDetailsPanel());

    // Create the button panel
    final ConfirmAction confirmAction = new ConfirmAction();
    dialogModel.addPropertyChangeListener(confirmAction);

    // Create the content panel
    final JPanel contentPanel = new JPanel(new BorderLayout());
    contentPanel.add(BorderLayout.WEST, connectionComponent);
    contentPanel.add(BorderLayout.CENTER, queryContentPanel);
    contentPanel.add(BorderLayout.SOUTH, createPreviewButtonsPanel());
    contentPanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 8, 8));


    final JButton okButton = new JButton(confirmAction);
    final JButton cancelButton = new JButton(new CancelAction());

    final JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
    buttonPanel.setBorder(BorderFactory.createMatteBorder(1, 0, 0, 0, Color.LIGHT_GRAY));
    buttonPanel.add(okButton);
    buttonPanel.add(cancelButton);

    // Create the center panel
    final JPanel centerPanel = new JPanel(new BorderLayout());
    centerPanel.add(BorderLayout.CENTER, contentPanel);
    centerPanel.add(BorderLayout.SOUTH, buttonPanel);

    // Return the center panel
    setContentPane(centerPanel);
    pack();
    SwingUtil.centerDialogInParent(this);
  }

  private JPanel createPreviewButtonsPanel()
  {
    final JPanel previewButtonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    previewButtonsPanel.add(new JCheckBox(new LimitRowsCheckBoxActionListener(maxPreviewRowsSpinner)));
    previewButtonsPanel.add(maxPreviewRowsSpinner);

    final PreviewAction thePreviewAction = new PreviewAction();
    dialogModel.addPropertyChangeListener(thePreviewAction);
    previewButtonsPanel.add(new JButton(thePreviewAction));
    return previewButtonsPanel;
  }

  private JPanel createQueryDetailsPanel()
  {
    final JPanel theQueryNamePanel = new JPanel(new BorderLayout());
    theQueryNamePanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 0, 8));
    theQueryNamePanel.add(new JLabel(getBundleSupport().getString("JdbcDataSourceDialog.QueryStringLabel")), BorderLayout.NORTH);
    theQueryNamePanel.add(queryNameTextField, BorderLayout.SOUTH);

    final InvokeQueryDesignerAction queryDesignerAction = new InvokeQueryDesignerAction();
    dialogModel.addPropertyChangeListener(queryDesignerAction);

    final JPanel theQueryButtonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
    theQueryButtonsPanel.add(new BorderlessButton(queryDesignerAction));

    final JPanel theQueryControlsPanel = new JPanel(new BorderLayout());
    theQueryControlsPanel.add(new JLabel(getBundleSupport().getString("JdbcDataSourceDialog.QueryDetailsLabel")), BorderLayout.WEST);
    theQueryControlsPanel.add(theQueryButtonsPanel, BorderLayout.EAST);

    final JPanel theQueryPanel = new JPanel(new BorderLayout());
    theQueryPanel.add(theQueryControlsPanel, BorderLayout.NORTH);
    theQueryPanel.add(new RTextScrollPane(500, 300, queryTextArea, true), BorderLayout.CENTER);
    theQueryPanel.setBorder(BorderFactory.createEmptyBorder(8, 8, 0, 8));

    // Create the query details panel
    final JPanel queryDetailsPanel = new JPanel(new BorderLayout());
    queryDetailsPanel.add(BorderLayout.NORTH, theQueryNamePanel);
    queryDetailsPanel.add(BorderLayout.CENTER, theQueryPanel);
    return queryDetailsPanel;
  }

  private JPanel createQueryListPanel()
  {
    // Create the query list panel
    final QueryRemoveAction queryRemoveAction = new QueryRemoveAction();
    dialogModel.addPropertyChangeListener(queryRemoveAction);

    final JPanel theQueryButtonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 5));
    theQueryButtonsPanel.add(new BorderlessButton(new QueryAddAction()));
    theQueryButtonsPanel.add(new BorderlessButton(queryRemoveAction));

    final JPanel theQueryControlsPanel = new JPanel(new BorderLayout());
    theQueryControlsPanel.add(new JLabel(getBundleSupport().getString("JdbcDataSourceDialog.AvailableQueries")), BorderLayout.WEST);
    theQueryControlsPanel.add(theQueryButtonsPanel, BorderLayout.EAST);

    final JPanel queryListPanel = new JPanel(new BorderLayout());
    queryListPanel.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 8));
    queryListPanel.add(BorderLayout.NORTH, theQueryControlsPanel);
    queryListPanel.add(BorderLayout.CENTER, new JScrollPane(queryNameList));
    return queryListPanel;
  }

  protected NamedDataSourceDialogModel getDialogModel()
  {
    return dialogModel;
  }

  protected String getQuery()
  {
    return queryTextArea.getText();
  }

  protected void setQuery(final String query)
  {
    this.queryTextArea.setText(query);
  }

  protected String getQueryName()
  {
    return queryNameTextField.getText();
  }

  protected void setQueryName(final String queryName)
  {
    this.queryNameTextField.setText(queryName);
  }

  protected ResourceBundleSupport getBundleSupport()
  {
    return bundleSupport;
  }

  public boolean isConfirmed()
  {
    return confirmed;
  }

  protected void setConfirmed(final boolean confirmed)
  {
    this.confirmed = confirmed;
  }
}
TOP

Related Classes of org.pentaho.reporting.ui.datasources.jdbc.ui.JdbcDataSourceDialog$QueryTextFieldActivationHandler

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.