Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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.scriptable;
 
 import java.awt.Frame;
 import java.net.URL;
 import java.util.Map;
 
 import  org.apache.bsf.BSFManager;
 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.AbstractReportDefinition;
 import  org.pentaho.reporting.engine.classic.core.ClassicEngineBoot;
 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.util.ReportParameterValues;
 import  org.pentaho.reporting.libraries.base.config.Configuration;
 import  org.pentaho.reporting.libraries.base.util.StringUtils;
 import  org.pentaho.reporting.libraries.designtime.swing.BorderlessButton;
 import  org.pentaho.reporting.libraries.designtime.swing.CommonDialog;
 import  org.pentaho.reporting.libraries.designtime.swing.LibSwingUtil;
 import  org.pentaho.reporting.libraries.designtime.swing.background.CancelEvent;
 import  org.pentaho.reporting.libraries.designtime.swing.background.DataPreviewDialog;
 import  org.pentaho.reporting.libraries.designtime.swing.background.PreviewWorker;
 import  org.pentaho.reporting.libraries.resourceloader.ResourceKey;

Author(s):
David Kincade
 
 public class ScriptableDataSourceEditor extends CommonDialog
 {
   private class UpdateLanguageHandler implements ActionListenerListSelectionListener
   {
     private UpdateLanguageHandler()
     {
     }
 
     public void actionPerformed(final ActionEvent e)
     {
       updateComponents();
     }

    
Called whenever the value of the selection changes.

Parameters:
e the event that characterizes the change.
 
    public void valueChanged(final ListSelectionEvent e)
    {
      updateComponents();
    }
  }
  private static class InternalBSFManager extends BSFManager
  {
    private InternalBSFManager()
    {
    }
    public static String[] getRegisteredLanguages()
    {
      final ArrayList<Stringlist = new ArrayList<String>();
      final Iterator iterator = registeredEngines.entrySet().iterator();
      while (iterator.hasNext())
      {
        final Map.Entry entry = (Map.Entryiterator.next();
        final String lang = (Stringentry.getKey();
        final String className = (Stringentry.getValue();
        try
        {
          // this is how BSH will load the class
          Class.forName(classNamefalse, Thread.currentThread().getContextClassLoader());
          list.add(lang);
        }
        catch (Throwable t)
        {
          // ignored.
        }
      }
      return list.toArray(new String[list.size()]);
    }
  }
  private class QueryRemoveAction extends AbstractAction implements ListSelectionListener
  {
    private QueryRemoveAction()
    {
      final URL resource = ScriptableDataSourceEditor.class.getResource
          ("/org/pentaho/reporting/ui/datasources/scriptable/resources/Remove.png");
      if (resource != null)
      {
        putValue(.new ImageIcon(resource));
      }
      else
      {
        putValue(., Messages.getString("ScriptableDataSourceEditor.RemoveQuery.Name"));
      }
      putValue(., Messages.getString("ScriptableDataSourceEditor.RemoveQuery.Description"));
    }
    public void actionPerformed(final ActionEvent e)
    {
      final DataSetQuery query = (DataSetQuery.getSelectedValue();
      if (query != null)
      {
        .remove(query.getQueryName());
      }
       = true;
      updateQueryList();
       = false;
      updateComponents();
    }
    public void valueChanged(final ListSelectionEvent e)
    {
      setEnabled(.isSelectionEmpty() == 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 ()
      {
        return;
      }
      final String queryName = .getText();
      final DataSetQuery currentQuery = (DataSetQuery.getSelectedValue();
      if (currentQuery == null)
      {
        return;
      }
      if (queryName.equals(currentQuery.getQueryName()))
      {
        return;
      }
      if (.containsKey(queryName))
      {
        return;
      }
       = true;
      .remove(currentQuery.getQueryName());
      currentQuery.setQueryName(queryName);
      .put(currentQuery.getQueryName(), currentQuery);
      updateQueryList();
      .setSelectedValue(currentQuerytrue);
       = false;
    }
  }
  private static class QueryNameListCellRenderer extends DefaultListCellRenderer
  {
    public Component getListCellRendererComponent(final JList list,
                                                  final Object value,
                                                  final int index,
                                                  final boolean isSelected,
                                                  final boolean cellHasFocus)
    {
      final JLabel listCellRendererComponent =
          (JLabelsuper.getListCellRendererComponent(listvalueindexisSelectedcellHasFocus);
      if (value != null)
      {
        final String queryName = ((DataSetQueryvalue).getQueryName();
        if (StringUtils.isEmpty(queryName) == false)
        {
          listCellRendererComponent.setText(queryName);
        }
        else
        {
          listCellRendererComponent.setText(" ");
        }
      }
      return listCellRendererComponent;
    }
  }
  {
    public void valueChanged(final ListSelectionEvent e)
    {
      if (!)
      {
        final DataSetQuery query = (DataSetQuery.getSelectedValue();
        if (query != null)
        {
          .setText(query.getQueryName());
          .setText(query.getQuery());
          updateComponents();
        }
        else
        {
          .setText("");
          .setText("");
          updateComponents();
        }
      }
    }
  }
  private class QueryAddAction extends AbstractAction
  {
    private QueryAddAction()
    {
      final URL resource = ScriptableDataSourceEditor.class.getResource
          ("/org/pentaho/reporting/ui/datasources/scriptable/resources/Add.png");
      if (resource != null)
      {
        putValue(.new ImageIcon(resource));
      }
      else
      {
        putValue(., Messages.getString("ScriptableDataSourceEditor.AddQuery.Name"));
      }
      putValue(., Messages.getString("ScriptableDataSourceEditor.AddQuery.Description"));
    }
    public void actionPerformed(final ActionEvent e)
    {
      // Find a unique query name
      String queryName = Messages.getString("ScriptableDataSourceEditor.Query");
      for (int i = 1; i < 1000; ++i)
      {
        final String newQueryName = Messages.getString("ScriptableDataSourceEditor.Query") + ' ' + i;
        if (!.containsKey(newQueryName))
        {
          queryName = newQueryName;
          break;
        }
      }
      final DataSetQuery newQuery = new DataSetQuery(queryName"");
      .put(newQuery.getQueryName(), newQuery);
       = true;
      updateQueryList();
      .setSelectedValue(newQuerytrue);
       = false;
      updateComponents();
    }
  }
  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 DataSetQuery currentQuery = (DataSetQuery.getSelectedValue();
      if (currentQuery == null)
      {
        return;
      }
      currentQuery.setQuery(.getText());
    }
  }
  private class PreviewAction extends AbstractAction
  {
    private PreviewAction()
    {
      putValue(., Messages.getString("ScriptableDataSourceEditor.Preview.Name"));
    }
    public void actionPerformed(final ActionEvent aEvt)
    {
      try
      {
        final ScriptableDataFactory dataFactory = produceFactory();
        final AbstractReportDefinition report = .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 DataPreviewDialog previewDialog = new DataPreviewDialog(ScriptableDataSourceEditor.this);
        final ScriptablePreviewWorker worker = new ScriptablePreviewWorker(dataFactory.getText());
        previewDialog.showData(worker);
        final ReportDataFactoryException factoryException = worker.getException();
        if (factoryException != null)
        {
          ExceptionDialog.showExceptionDialog(ScriptableDataSourceEditor.this,
              Messages.getString("ScriptableDataSourceEditor.PreviewError.Title"),
              Messages.getString("ScriptableDataSourceEditor.PreviewError.Message"), factoryException);
        }
      }
      catch (Exception e)
      {
        ExceptionDialog.showExceptionDialog(ScriptableDataSourceEditor.this,
            Messages.getString("ScriptableDataSourceEditor.PreviewError.Title"),
            Messages.getString("ScriptableDataSourceEditor.PreviewError.Message"), e);
      }
    }
  }
  private static class ScriptablePreviewWorker implements PreviewWorker
  {
    private TableModel resultTableModel;
    private ReportDataFactoryException exception;
    private String query;
    private ScriptablePreviewWorker(final ScriptableDataFactory dataFactory,
                                    final String query)
    {
      if (dataFactory == null)
      {
        throw new NullPointerException();
      }
      this. = query;
      this. = dataFactory;
    }
    public ReportDataFactoryException getException()
    {
      return ;
    }
    {
      return ;
    }
    public void close()
    {
    }

    
Requests that the thread stop processing as soon as possible.
    public void cancelProcessing(final CancelEvent event)
    {
    }

    
When an object implementing interface Runnable is used to create a thread, starting the thread causes the object's run method to be called in that separately executing thread.

The general contract of the method run is that it may take any action whatsoever.

See also:
Thread.run()
    public void run()
    {
      try
      {
         = .queryData(new ReportParameterValues());
      }
      catch (ReportDataFactoryException e)
      {
         = e;
      }
      finally
      {
        .close();
      }
    }
  }
  private JList queryNameList;
  private JList languageField;
  private RSyntaxTextArea queryTextArea;
  private RSyntaxTextArea initScriptTextArea;
  private RSyntaxTextArea shutdownScriptTextArea;
  private Map<StringDataSetQueryqueries;
  private boolean inQueryNameUpdate;
  private boolean inModifyingQueryNameList;
  private DesignTimeContext designTimeContext;
  public ScriptableDataSourceEditor(final DesignTimeContext designTimeContext)
  {
    init(designTimeContext);
  }
  public ScriptableDataSourceEditor(final DesignTimeContext designTimeContextfinal Dialog owner)
  {
    super(owner);
    init(designTimeContext);
  }
  public ScriptableDataSourceEditor(final DesignTimeContext designTimeContextfinal Frame owner)
  {
    super(owner);
    init(designTimeContext);
  }
  private void init(final DesignTimeContext designTimeContext)
  {
    if (designTimeContext == null)
    {
      throw new NullPointerException();
    }
    this. = designTimeContext;
    setTitle(Messages.getString("ScriptableDataSourceEditor.Title"));
    setModal(true);
     = new PreviewAction();
     = new JTextField(null, 0);
     = new RSyntaxTextArea();
    .setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
    .getDocument().addDocumentListener(new QueryDocumentListener());
     = new RSyntaxTextArea();
    .setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
     = new RSyntaxTextArea();
    .setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
     = new JList(new DefaultComboBoxModel(InternalBSFManager.getRegisteredLanguages()));
     = new JList();
    final QueryRemoveAction removeQueryAction = new QueryRemoveAction();
    .addListSelectionListener(removeQueryAction);
    super.init();
    pack();
    LibSwingUtil.centerDialogInParent(this);
  }
  {
    final JPanel initScriptContentHolder = new JPanel(new BorderLayout());
    initScriptContentHolder.add(.new JLabel(Messages.getString("ScriptableDataSourceEditor.InitScript")));
    initScriptContentHolder.add(.new RTextScrollPane(500, 600, true));
    final JPanel shutdownScriptContentHolder = new JPanel(new BorderLayout());
    shutdownScriptContentHolder.add(.new JLabel(Messages.getString("ScriptableDataSourceEditor.ShutdownScript")));
    shutdownScriptContentHolder.add(.new RTextScrollPane(500, 600, true));
    final JPanel queryDetailsNamePanel = new JPanel(new BorderLayout());
    queryDetailsNamePanel.add(new JLabel(Messages.getString("ScriptableDataSourceEditor.QueryName")), .);
    queryDetailsNamePanel.add(.);
    final JPanel queryContentHolder = new JPanel(new BorderLayout());
    queryContentHolder.add(.new JLabel(Messages.getString("ScriptableDataSourceEditor.QueryLabel")));
    queryContentHolder.add(.new RTextScrollPane(500, 300, true));
    // Create the query details panel
    final JPanel queryDetailsPanel = new JPanel(new BorderLayout());
    queryDetailsPanel.setBorder(new EmptyBorder(0, 8, 8, 8));
    queryDetailsPanel.add(.queryDetailsNamePanel);
    queryDetailsPanel.add(.queryContentHolder);
    final JPanel previewButtonPanel = new JPanel(new FlowLayout(.));
    previewButtonPanel.add(new JButton());
    final JPanel queryContentPanel = new JPanel(new BorderLayout());
    queryContentPanel.add(.createQueryListPanel());
    queryContentPanel.add(.queryDetailsPanel);
    final JTabbedPane scriptsTabPane = new JTabbedPane();
    scriptsTabPane.addTab(Messages.getString("ScriptableDataSourceEditor.QueryTab"), queryContentPanel);
    scriptsTabPane.addTab(Messages.getString("ScriptableDataSourceEditor.InitScriptTab"), initScriptContentHolder);
    scriptsTabPane.addTab(Messages.getString("ScriptableDataSourceEditor.ShutdownScriptTab"), shutdownScriptContentHolder);
    final JLabel languageLabel = new JLabel(Messages.getString("ScriptableDataSourceEditor.Language"));
    languageLabel.setBorder(new EmptyBorder(0, 0, 3, 0));
    final JPanel languagesPanel = new JPanel(new BorderLayout());
    languagesPanel.setBorder(new EmptyBorder(8, 8, 8, 0));
    languagesPanel.add(.languageLabel);
    languagesPanel.add(.new JScrollPane());
    final JPanel contentPanel = new JPanel(new BorderLayout());
    contentPanel.add(.languagesPanel);
    contentPanel.add(.scriptsTabPane);
    contentPanel.add(.previewButtonPanel);
    return contentPanel;
  }
  {
    final QueryRemoveAction queryRemoveAction = new QueryRemoveAction();
    .addListSelectionListener(queryRemoveAction);
    final JPanel theQueryButtonsPanel = new JPanel(new FlowLayout(.));
    theQueryButtonsPanel.add(new BorderlessButton(new QueryAddAction()));
    theQueryButtonsPanel.add(new BorderlessButton(queryRemoveAction));
    final JPanel theQueryControlsPanel = new JPanel(new BorderLayout());
    theQueryControlsPanel.add(.new JLabel(Messages.getString("ScriptableDataSourceEditor.AvailableQueries")));
    theQueryControlsPanel.add(.theQueryButtonsPanel);
    final JPanel queryListPanel = new JPanel(new BorderLayout());
    queryListPanel.setBorder(BorderFactory.createEmptyBorder(0, 8, 0, 8));
    queryListPanel.add(.theQueryControlsPanel);
    queryListPanel.add(.new JScrollPane());
    return queryListPanel;
  }
  public ScriptableDataFactory performConfiguration(final ScriptableDataFactory dataFactoryfinal String selectedQuery)
  {
    // Reset the confirmed / cancel flag
    // Initialize the internal storage
     = new TreeMap<StringDataSetQuery>();
    // Load the current configuration
    if (dataFactory != null)
    {
      .setSelectedValue(dataFactory.getLanguage(), true);
      final String[] queryNames = dataFactory.getQueryNames();
      for (int i = 0; i < queryNames.lengthi++)
      {
        final String queryName = queryNames[i];
        final String query = dataFactory.getQuery(queryName);
        .put(queryNamenew DataSetQuery(queryNamequery));
      }
      .setText(dataFactory.getScript());
      .setText(dataFactory.getShutdownScript());
    }
    // Prepare the data and the enable the proper buttons
    setSelectedQuery(selectedQuery);
    // Enable the dialog
    if (!performEdit())
    {
      return null;
    }
    return produceFactory();
  }
  {
    final ScriptableDataFactory returnDataFactory = new ScriptableDataFactory();
    returnDataFactory.setLanguage((String.getSelectedValue());
    if (StringUtils.isEmpty(.getText()))
    {
      returnDataFactory.setScript(null);
    }
    else
    {
      returnDataFactory.setScript(.getText());
    }
    if (StringUtils.isEmpty(.getText()))
    {
      returnDataFactory.setShutdownScript(null);
    }
    else
    {
      returnDataFactory.setShutdownScript(.getText());
    }
    final DataSetQuery[] queries = this..values().toArray(new DataSetQuery[this..size()]);
    for (int i = 0; i < queries.lengthi++)
    {
      final DataSetQuery query = queries[i];
      returnDataFactory.setQuery(query.getQueryName(), query.getQuery());
    }
    return returnDataFactory;
  }
  protected void updateQueryList()
  {
  }
  private void setSelectedQuery(final String aQuery)
  {
    final ListModel theModel = .getModel();
    for (int i = 0; i < theModel.getSize(); i++)
    {
      final DataSetQuery theDataSet = (DataSetQuerytheModel.getElementAt(i);
      if (theDataSet.getQueryName().equals(aQuery))
      {
        .setSelectedValue(theDataSettrue);
        break;
      }
    }
  }
  protected void updateComponents()
  {
    final boolean querySelected = .getSelectedIndex() != -1;
    final boolean hasQueries = .getModel().getSize() > 0;
    .setEnabled(querySelected);
    .setEnabled(querySelected);
    getConfirmAction().setEnabled(hasQueries && .getSelectedIndex() != -1);
    .setEnabled(querySelected);
  }
  private String mapLanguageToSyntaxHighlighting(final String language)
  {
    if ("beanshell".equals(language))
    {
      return SyntaxConstants.SYNTAX_STYLE_JAVA;
    }
    if ("groovy".equals(language))
    {
      return SyntaxConstants.SYNTAX_STYLE_GROOVY;
    }
    if ("javascript".equals(language))
    {
      return SyntaxConstants.SYNTAX_STYLE_JAVASCRIPT;
    }
    if ("jython".equals(language))
    {
      return SyntaxConstants.SYNTAX_STYLE_PYTHON;
    }
    if ("xslt".equals(language))
    {
      return SyntaxConstants.SYNTAX_STYLE_XML;
    }
    return SyntaxConstants.SYNTAX_STYLE_NONE;
  }