Package org.pentaho.reporting.ui.datasources.mondrian

Source Code of org.pentaho.reporting.ui.datasources.mondrian.MondrianDataSourceEditor

/*
* 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) 2009 Pentaho Corporation.  All rights reserved.
*/

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


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
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.io.File;
import java.net.URL;
import java.util.Enumeration;
import java.util.Properties;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListModel;
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 javax.swing.filechooser.FileFilter;

import org.pentaho.reporting.engine.classic.core.AbstractReportDefinition;
import org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
import org.pentaho.reporting.engine.classic.core.DataFactory;
import org.pentaho.reporting.engine.classic.core.DefaultReportEnvironment;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException;
import org.pentaho.reporting.engine.classic.core.ReportEnvironment;
import org.pentaho.reporting.engine.classic.core.designtime.DesignTimeContext;
import org.pentaho.reporting.engine.classic.core.designtime.DesignTimeUtil;
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.extensions.datasources.mondrian.AbstractMDXDataFactory;
import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.AbstractNamedMDXDataFactory;
import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.CubeFileProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.DataSourceProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.DefaultCubeFileProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.DriverDataSourceProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.mondrian.JndiDataSourceProvider;
import org.pentaho.reporting.libraries.base.config.Configuration;
import org.pentaho.reporting.libraries.base.util.FilesystemFilter;
import org.pentaho.reporting.libraries.base.util.IOUtils;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
import org.pentaho.reporting.libraries.base.util.StringUtils;
import org.pentaho.reporting.libraries.designtime.swing.BorderlessButton;
import org.pentaho.reporting.libraries.designtime.swing.background.DataPreviewDialog;
import org.pentaho.reporting.libraries.designtime.swing.filechooser.CommonFileChooser;
import org.pentaho.reporting.libraries.designtime.swing.filechooser.FileChooserService;
import org.pentaho.reporting.libraries.resourceloader.ResourceKey;
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;
import org.pentaho.reporting.ui.datasources.jdbc.ui.JdbcConnectionPanel;
import org.pentaho.reporting.ui.datasources.jdbc.ui.NamedDataSourceDialogModel;

/**
* @author Michael D'Amour
*/
public abstract class MondrianDataSourceEditor extends JDialog
{
  private class BrowseAction extends AbstractAction
  {
    protected BrowseAction()
    {
      putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.Browse.Name"));
    }

    public void actionPerformed(final ActionEvent e)
    {
      final File reportContextFile = DesignTimeUtil.getContextAsFile(context.getReport());
      final File initiallySelectedFile;

      if (StringUtils.isEmpty(getFileName(), true) == false)
      {
        if (reportContextFile == null)
        {
          initiallySelectedFile = new File(getFileName());
        }
        else
        {
          initiallySelectedFile = new File(reportContextFile.getParentFile(), getFileName());
        }
      }
      else
      {
        initiallySelectedFile = null;
      }

      final FileFilter[] fileFilters = new FileFilter[]{new FilesystemFilter(new String[]{".xml"},
          Messages.getString("MondrianDataSourceEditor.FileName") + " (*.xml)", true)};


      final CommonFileChooser fileChooser = FileChooserService.getInstance().getFileChooser("mondrian");
      fileChooser.setSelectedFile(initiallySelectedFile);
      fileChooser.setFilters(fileFilters);
      if (fileChooser.showDialog(MondrianDataSourceEditor.this, JFileChooser.OPEN_DIALOG) == false)
      {
        return;
      }
      final File file = fileChooser.getSelectedFile();
      if (file == null)
      {
        return;
      }

      final String path;
      if (reportContextFile != null)
      {
        path = IOUtils.getInstance().createRelativePath(file.getPath(), reportContextFile.getAbsolutePath());
      }
      else
      {
        path = file.getPath();
      }
      setFileName(path);
    }
  }

  private class QueryNameListSelectionListener implements ListSelectionListener
  {
    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
  {
    public CancelAction()
    {
      putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.Cancel.Name"));
    }

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

  private class ConfirmAction extends AbstractAction implements PropertyChangeListener, DocumentListener
  {
    /**
     * Defines an <code>Action</code> object with a default
     * description string and default icon.
     */
    private ConfirmAction()
    {
      putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.OK.Name"));
    }

    public void propertyChange(final PropertyChangeEvent evt)
    {
      revalidate();
    }

    private void revalidate()
    {
      final NamedDataSourceDialogModel dialogModel = getDialogModel();
      setEnabled(dialogModel.isConnectionSelected() && StringUtils.isEmpty(filenameField.getText(), true) == false);
    }

    /**
     * Gives notification that there was an insert into the document.  The
     * range given by the DocumentEvent bounds the freshly inserted region.
     *
     * @param e the document event
     */
    public void insertUpdate(final DocumentEvent e)
    {
      revalidate();
    }

    /**
     * Gives notification that a portion of the document has been
     * removed.  The range is given in terms of what the view last
     * saw (that is, before updating sticky positions).
     *
     * @param e the document event
     */
    public void removeUpdate(final DocumentEvent e)
    {
      revalidate();
    }

    /**
     * Gives notification that an attribute or set of attributes changed.
     *
     * @param e the document event
     */
    public void changedUpdate(final DocumentEvent e)
    {
      revalidate();
    }

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

  private class AddQueryAction extends AbstractAction
  {
    protected AddQueryAction()
    {
      final URL resource = MondrianDataSourceEditor.class.getResource
          ("/org/pentaho/reporting/ui/datasources/mondrian/resources/Add.png");
      if (resource != null)
      {
        putValue(Action.SMALL_ICON, new ImageIcon(resource));
      }
      else
      {
        putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.AddQuery.Name"));
      }
      putValue(Action.SHORT_DESCRIPTION, Messages.getString("MondrianDataSourceEditor.AddQuery.Description"));
    }

    public void actionPerformed(final ActionEvent e)
    {
      // Find a unique query name
      String queryName = Messages.getString("MondrianDataSourceEditor.Query");
      for (int i = 1; i < 1000; ++i)
      {
        final String newQuery = Messages.getString("MondrianDataSourceEditor.Query") + " " + i;
        if (dialogModel.getQueries().findElementIndex(newQuery) == -1)
        {
          queryName = newQuery;
          break;
        }
      }

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

  private class RemoveQueryAction extends AbstractAction implements PropertyChangeListener
  {
    protected RemoveQueryAction()
    {
      final URL resource = MondrianDataSourceEditor.class.getResource
          ("/org/pentaho/reporting/ui/datasources/mondrian/resources/Remove.png");
      if (resource != null)
      {
        putValue(Action.SMALL_ICON, new ImageIcon(resource));
      }
      else
      {
        putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.RemoveQuery.Name"));
      }
      putValue(Action.SHORT_DESCRIPTION, Messages.getString("MondrianDataSourceEditor.RemoveQuery.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 LimitRowsCheckBoxActionListener extends AbstractAction implements ItemListener
  {
    private JSpinner maxPreviewRowsSpinner;

    private LimitRowsCheckBoxActionListener(final JSpinner maxPreviewRowsSpinner)
    {
      this.maxPreviewRowsSpinner = maxPreviewRowsSpinner;
      putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.LimitRowsCheckBox"));
      putValue(Action.MNEMONIC_KEY, Messages.getOptionalMnemonic("MondrianDataSourceEditor.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 PreviewAction extends AbstractAction implements PropertyChangeListener
  {
    private PreviewAction()
    {
      putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.Preview.Name"));
      setEnabled(dialogModel.isConnectionSelected() && dialogModel.isQuerySelected());
    }

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

    public void actionPerformed(final ActionEvent evt)
    {
      final JdbcConnectionDefinition connectionDefinition =
          (JdbcConnectionDefinition) dialogModel.getConnections().getSelectedItem();
      if (connectionDefinition == null)
      {
        return;
      }
      try
      {
        final String query = queryNameTextField.getText();
        Integer theMaxRows = 0;
        if (maxPreviewRowsSpinner.isEnabled())
        {
          theMaxRows = (Integer) maxPreviewRowsSpinner.getValue();
        }
        if (previewDialog == null)
        {
          previewDialog = new DataPreviewDialog(MondrianDataSourceEditor.this);
        }

        final AbstractMDXDataFactory dataFactory = createDataFactory();
        final AbstractReportDefinition report = context.getReport();
        final MasterReport masterReport = DesignTimeUtil.getMasterReport(report);
        final Configuration configuration;
        final ResourceKey contentBase;
        final ReportEnvironment reportEnvironment;
        if (masterReport == null)
        {
          contentBase = null;
          configuration = ClassicEngineBoot.getInstance().getGlobalConfig();
          reportEnvironment = new DefaultReportEnvironment(configuration);
        }
        else
        {
          contentBase = masterReport.getContentBase();
          configuration = masterReport.getConfiguration();
          reportEnvironment = masterReport.getReportEnvironment();
        }
        dataFactory.initialize(configuration,
            report.getResourceManager(), contentBase, MasterReport.computeAndInitResourceBundleFactory
                (report.getResourceBundleFactory(), reportEnvironment));

        final MondrianPreviewWorker worker = new MondrianPreviewWorker(dataFactory, query, 0, theMaxRows);
        previewDialog.showData(worker);

        final ReportDataFactoryException factoryException = worker.getException();
        if (factoryException != null)
        {
          ExceptionDialog.showExceptionDialog(MondrianDataSourceEditor.this,
              Messages.getString("MondrianDataSourceEditor.PreviewError.Title"),
              Messages.getString("MondrianDataSourceEditor.PreviewError.Message"), factoryException);
        }

      }
      catch (Exception e)
      {
        ExceptionDialog.showExceptionDialog(MondrianDataSourceEditor.this,
            Messages.getString("MondrianDataSourceEditor.PreviewError.Title"),
            Messages.getString("MondrianDataSourceEditor.PreviewError.Message"), e);
      }
    }
  }


  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 QueryTextFieldActivationHandler implements PropertyChangeListener
  {
    private QueryTextFieldActivationHandler()
    {
    }

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

  private class EditSecurityAction extends AbstractAction
  {
    /**
     * Defines an <code>Action</code> object with a default
     * description string and default icon.
     */
    private EditSecurityAction()
    {
      putValue(Action.NAME, Messages.getString("MondrianDataSourceEditor.EditSecurityAction.Name"));
    }

    /**
     * Invoked when an action occurs.
     */
    public void actionPerformed(final ActionEvent e)
    {
      securityDialog.setRoleField(roleField);
      securityDialog.setRole(roleText);
      securityDialog.setJdbcPassword(jdbcPasswordText);
      securityDialog.setJdbcPasswordField(jdbcPasswordField);
      securityDialog.setJdbcUser(jdbcUserText);
      securityDialog.setJdbcUserField(jdbcUserField);

      if (securityDialog.performEdit())
      {
        roleText = securityDialog.getRole();
        roleField = securityDialog.getRoleField();
        jdbcUserText = securityDialog.getJdbcUser();
        jdbcUserField = securityDialog.getJdbcUserField();
        jdbcPasswordText = securityDialog.getJdbcPassword();
        jdbcPasswordField = securityDialog.getJdbcPasswordField();
      }
    }
  }

  private boolean confirmed;
  private JList queryNameList;
  private JTextField queryNameTextField;
  private JTextField filenameField;
  private JTextArea queryTextArea;
  private NamedDataSourceDialogModel dialogModel;
  private JSpinner maxPreviewRowsSpinner;
  private DataPreviewDialog previewDialog;
  private DesignTimeContext context;
  private MondrianSecurityDialog securityDialog;
  private String jdbcUserText;
  private String jdbcUserField;
  private String jdbcPasswordText;
  private String jdbcPasswordField;
  private String roleText;
  private String roleField;

  public MondrianDataSourceEditor(final DesignTimeContext context)
  {
    init(context);
  }

  public MondrianDataSourceEditor(final DesignTimeContext context, final Dialog owner)
  {
    super(owner);
    init(context);
  }

  public MondrianDataSourceEditor(final DesignTimeContext context, final Frame owner)
  {
    super(owner);
    init(context);
  }

  protected void init(final DesignTimeContext context)
  {
    if (context == null)
    {
      throw new NullPointerException();
    }

    securityDialog = new MondrianSecurityDialog(this, context);

    setModal(true);

    this.context = context;

    dialogModel = new NamedDataSourceDialogModel();

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

    final ConfirmAction confirmAction = new ConfirmAction();
    dialogModel.addPropertyChangeListener(confirmAction);

    filenameField = new JTextField(null, 0);
    filenameField.setColumns(30);
    filenameField.getDocument().addDocumentListener(confirmAction);

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

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

    queryTextArea = new JTextArea((String) null);
    queryTextArea.setWrapStyleWord(true);
    queryTextArea.setLineWrap(true);
    queryTextArea.setRows(5);
    queryTextArea.getDocument().addDocumentListener(new QueryDocumentListener());

    dialogModel.addPropertyChangeListener(new QueryTextFieldActivationHandler());

    queryNameList = new JList(getDialogModel().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());

    final JPanel filePanel = new JPanel();
    filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.X_AXIS));
    filePanel.add(filenameField);
    filePanel.add(new JButton(new BrowseAction()));
    filePanel.add(Box.createHorizontalStrut(20));
    filePanel.add(Box.createHorizontalGlue());
    filePanel.add(new JButton(new EditSecurityAction()));

    final JPanel fileCarrier = new JPanel();
    fileCarrier.setLayout(new BorderLayout());
    fileCarrier.add(new JLabel(Messages.getString("MondrianDataSourceEditor.SchemaFileLabel")), BorderLayout.CENTER);
    fileCarrier.add(filePanel, BorderLayout.SOUTH);

    // Create the content panel
    final JPanel contentPanel = new JPanel(new BorderLayout());
    contentPanel.add(BorderLayout.NORTH, fileCarrier);
    contentPanel.add(BorderLayout.WEST, new JdbcConnectionPanel(dialogModel, context));
    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);
    SwingUtil.centerDialogInParent(securityDialog);
  }


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

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

    final JPanel theQueryControlsPanel = new JPanel(new BorderLayout());
    theQueryControlsPanel.add(new JLabel(Messages.getString("MondrianDataSourceEditor.AvailableQueriesLabel")), 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;
  }


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

    final JPanel theQueryControlsPanel = new JPanel(new BorderLayout());
    theQueryControlsPanel.add(new JLabel(Messages.getString("MondrianDataSourceEditor.QueryLabel")), BorderLayout.WEST);

    final JPanel theQueryPanel = new JPanel(new BorderLayout());
    theQueryPanel.add(theQueryControlsPanel, BorderLayout.NORTH);
    theQueryPanel.add(new JScrollPane(queryTextArea), 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 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;
  }

  protected abstract AbstractMDXDataFactory createDataFactory();

  public DataFactory performConfiguration(final AbstractNamedMDXDataFactory dataFactory, final String selectedQueryName)
  {
    // Reset the ok / cancel flag
    setConfirmed(false);
    getDialogModel().clear();
    roleText = null;
    roleField = null;
    jdbcUserText = null;
    jdbcUserField = null;
    jdbcPasswordText = null;
    jdbcPasswordField = null;

    // Load the current configuration
    if (dataFactory != null)
    {
      roleText = dataFactory.getRole();
      roleField = dataFactory.getRoleField();
      jdbcUserText = dataFactory.getJdbcUser();
      jdbcUserField = dataFactory.getJdbcUserField();
      jdbcPasswordText = dataFactory.getJdbcPassword();
      jdbcPasswordField = dataFactory.getJdbcPasswordField();

      final CubeFileProvider fileProvider = dataFactory.getCubeFileProvider();
      if (fileProvider != null)
      {
        setSchemaFileName(fileProvider.getDesignTimeFile());
      }
      else
      {
        setSchemaFileName("");
      }

      final String[] queryNames = dataFactory.getQueryNames();
      for (int i = 0; i < queryNames.length; i++)
      {
        final String queryName = queryNames[i];
        final String query = dataFactory.getQuery(queryName);
        getDialogModel().addQuery(queryName, query);
      }

      final JdbcConnectionDefinition definition = createConnectionDefinition(dataFactory);
      getDialogModel().addConnection(definition);
      getDialogModel().getConnections().setSelectedItem(definition);
    }

    // Prepare the data and the enable the proper buttons
    setSelectedQuery(selectedQueryName);

    // Enable the dialog
    pack();
    setLocationRelativeTo(getParent());
    setVisible(true);

    if (!isConfirmed())
    {
      return null;
    }

    return createDataFactory();
  }

  protected JdbcConnectionDefinition createConnectionDefinition(final AbstractMDXDataFactory dataFactory)
  {
    if (dataFactory == null)
    {
      throw new NullPointerException();
    }

    String customName = dataFactory.getDesignTimeName();
    if (customName == null)
    {
      customName = Messages.getString("MondrianDataSourceEditor.CustomConnection");
    }

    final DataSourceProvider provider = dataFactory.getDataSourceProvider();
    if (provider instanceof DriverDataSourceProvider)
    {
      final DriverDataSourceProvider dcp = (DriverDataSourceProvider) provider;
      final ListModel model = dialogModel.getConnections();
      for (int i = 0; i < model.getSize(); i++)
      {
        final JdbcConnectionDefinition definition = (JdbcConnectionDefinition) model.getElementAt(i);
        if (definition instanceof DriverConnectionDefinition == false)
        {
          continue;
        }

        final DriverConnectionDefinition dcd = (DriverConnectionDefinition) definition;
        if (ObjectUtilities.equal(dcd.getDriverClass(), dcp.getDriver()) &&
            ObjectUtilities.equal(dcd.getUsername(), dcp.getProperty("user")) &&
            ObjectUtilities.equal(dcd.getPassword(), dcp.getProperty("password")) &&
            ObjectUtilities.equal(dcd.getConnectionString(), dcp.getUrl()) &&
            ObjectUtilities.equal(dcd.getName(), dcp.getProperty("::pentaho-reporting::name")))
        {
          return definition;
        }
      }

      final String[] strings = dcp.getPropertyNames();
      final Properties p = new Properties();
      for (int i = 0; i < strings.length; i++)
      {
        final String string = strings[i];
        p.put(string, dcp.getProperty(string));
      }

      return new DriverConnectionDefinition
          (customName, dcp.getDriver(), dcp.getUrl(), null, null,
              dcp.getProperty("::pentaho-reporting::hostname"),
              dcp.getProperty("::pentaho-reporting::database-name"),
              dcp.getProperty("::pentaho-reporting::database-type"),
              dcp.getProperty("::pentaho-reporting::port"),
              p);
    }
    else if (provider instanceof JndiDataSourceProvider)
    {
      final JndiDataSourceProvider jcp = (JndiDataSourceProvider) provider;
      final ListModel model = dialogModel.getConnections();
      for (int i = 0; i < model.getSize(); i++)
      {
        final JdbcConnectionDefinition definition = (JdbcConnectionDefinition) model.getElementAt(i);
        if (definition instanceof JndiConnectionDefinition == false)
        {
          continue;
        }
        final JndiConnectionDefinition dcd = (JndiConnectionDefinition) definition;

        if (ObjectUtilities.equal(dcd.getJndiName(), jcp.getConnectionPath()))
        {
          return dcd;
        }
      }
      return new JndiConnectionDefinition(customName, jcp.getConnectionPath(), null, null, null);
    }

    return null;
  }

  protected String getFileName()
  {
    return filenameField.getText();
  }

  public void setFileName(final String fileName)
  {
    filenameField.setText(fileName);
  }

  protected NamedDataSourceDialogModel getDialogModel()
  {
    return dialogModel;
  }

  protected boolean isConfirmed()
  {
    return confirmed;
  }

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

  protected void setSchemaFileName(final String schema)
  {
    this.filenameField.setText(schema);
  }

  protected String getSchemaFileName()
  {
    return this.filenameField.getText();
  }

  protected void configureConnection(final AbstractMDXDataFactory dataFactory)
  {
    dataFactory.setCubeFileProvider(new DefaultCubeFileProvider(getSchemaFileName()));
    dataFactory.setRole(roleText);
    dataFactory.setRoleField(roleField);
    dataFactory.setJdbcUser(jdbcUserText);
    dataFactory.setJdbcUserField(jdbcUserField);
    dataFactory.setJdbcPassword(jdbcPasswordText);
    dataFactory.setJdbcPasswordField(jdbcPasswordField);

    final JdbcConnectionDefinition connectionDefinition =
        (JdbcConnectionDefinition) getDialogModel().getConnections().getSelectedItem();
    dataFactory.setDesignTimeName(connectionDefinition.getName());

    if (connectionDefinition instanceof DriverConnectionDefinition)
    {
      final DriverConnectionDefinition dcd = (DriverConnectionDefinition) connectionDefinition;
      final DriverDataSourceProvider dataSourceProvider = new DriverDataSourceProvider();
      dataSourceProvider.setUrl(dcd.getConnectionString());
      dataSourceProvider.setDriver(dcd.getDriverClass());
      final Properties properties = dcd.getProperties();
      final Enumeration keys = properties.keys();
      while (keys.hasMoreElements())
      {
        final String key = (String) keys.nextElement();
        dataSourceProvider.setProperty(key, properties.getProperty(key));
      }
      dataFactory.setDataSourceProvider(dataSourceProvider);
    }
    else
    {
      final JndiConnectionDefinition jcd = (JndiConnectionDefinition) connectionDefinition;
      dataFactory.setDataSourceProvider(new JndiDataSourceProvider(jcd.getJndiName()));
    }
  }


  protected void setSelectedQuery(final String aQuery)
  {
    getDialogModel().getQueries().setSelectedItem(aQuery);
  }

  protected void configureQueries(final AbstractNamedMDXDataFactory returnDataFactory)
  {
    final KeyedComboBoxModel queries = getDialogModel().getQueries();
    for (int i = 0; i < queries.getSize(); i++)
    {
      final String queryName = (String) queries.getElementAt(i);
      final String queryText = (String) queries.getKeyAt(i);
      returnDataFactory.setQuery(queryName, queryText);
    }
  }


  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);
  }

}
TOP

Related Classes of org.pentaho.reporting.ui.datasources.mondrian.MondrianDataSourceEditor

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.