/*
* 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.pmd;
import java.awt.BorderLayout;
import java.awt.Component;
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.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
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.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileFilter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.pentaho.commons.metadata.mqleditor.editor.SwingMqlEditor;
import org.pentaho.metadata.repository.IMetadataDomainRepository;
import org.pentaho.metadata.repository.InMemoryMetadataDomainRepository;
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.extensions.datasources.pmd.PmdConnectionProvider;
import org.pentaho.reporting.engine.classic.extensions.datasources.pmd.PmdDataFactory;
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.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.VerticalLayout;
import org.pentaho.reporting.libraries.designtime.swing.background.BackgroundCancellableProcessHelper;
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.libraries.resourceloader.ResourceManager;
import org.pentaho.reporting.ui.datasources.jdbc.ui.NamedDataSourceDialogModel;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
/**
* @author David Kincade
*/
public class PmdDataSourceEditor extends CommonDialog
{
private class BrowseAction extends AbstractAction
{
protected BrowseAction()
{
putValue(Action.NAME, Messages.getString("PmdDataSourceEditor.Browse.Name"));
}
public void actionPerformed(final ActionEvent e)
{
final File initiallySelectedFile;
final File reportContextFile = DesignTimeUtil.getContextAsFile(context.getReport());
if (StringUtils.isEmpty(filenameField.getText(), true) == false)
{
if (reportContextFile != null)
{
initiallySelectedFile = new File(reportContextFile.getParentFile(), filenameField.getText());
}
else
{
initiallySelectedFile = new File(filenameField.getText());
}
}
else
{
initiallySelectedFile = null; // NON-NLS
}
final FileFilter[] fileFilters = new FileFilter[]{new FilesystemFilter(new String[]{".xmi"}, // NON-NLS
Messages.getString("PmdDataSourceEditor.XmiFileName") + " (*.xmi)", true)}; // NON-NLS
final CommonFileChooser fileChooser = FileChooserService.getInstance().getFileChooser("xmifile");
fileChooser.setSelectedFile(initiallySelectedFile);
fileChooser.setFilters(fileFilters);
if (fileChooser.showDialog(PmdDataSourceEditor.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();
}
filenameField.setText(path);
}
}
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 = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (value != null)
{
final String queryName = ((DataSetQuery) value).getQueryName();
if (!"".equals(queryName))
{
listCellRendererComponent.setText(queryName);
}
else
{
listCellRendererComponent.setText(" ");
}
}
return listCellRendererComponent;
}
}
private class QueryNameListSelectionListener implements ListSelectionListener
{
public void valueChanged(final ListSelectionEvent e)
{
if (!inQueryNameUpdate)
{
final DataSetQuery query = (DataSetQuery) queryNameList.getSelectedValue();
if (query != null)
{
queryNameTextField.setText(query.getQueryName());
queryTextArea.setText(query.getQuery());
updateComponents();
}
else
{
queryNameTextField.setText("");
queryTextArea.setText("");
updateComponents();
}
}
}
}
private class AddQueryAction extends AbstractAction
{
public AddQueryAction()
{
final URL resource = PmdDataSourceEditor.class.getResource
("/org/pentaho/reporting/ui/datasources/pmd/resources/Add.png"); // NON-NLS
if (resource != null)
{
putValue(Action.SMALL_ICON, new ImageIcon(resource));
}
else
{
putValue(Action.NAME, Messages.getString("PmdDataSourceEditor.AddQuery.Name"));
}
putValue(Action.SHORT_DESCRIPTION, Messages.getString("PmdDataSourceEditor.AddQuery.Description"));
}
public void actionPerformed(final ActionEvent e)
{
// Find a unique query name
// Find a unique query name
String queryName = "PmdDataSourceEditor.Query";
for (int i = 1; i < 1000; ++i)
{
final String newQueryName = Messages.getString("PmdDataSourceEditor.Query") + " " + i;
if (!queries.containsKey(newQueryName))
{
queryName = newQueryName;
break;
}
}
final DataSetQuery newQuery = new DataSetQuery(queryName, "");
queries.put(newQuery.getQueryName(), newQuery);
inModifyingQueryNameList = true;
updateQueryList();
queryNameList.setSelectedValue(newQuery, true);
inModifyingQueryNameList = false;
updateComponents();
}
}
private class CreateMqlEditorTask implements Runnable
{
private IMetadataDomainRepository repository;
private CreateMqlEditorTask(final IMetadataDomainRepository repository)
{
this.repository = repository;
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p/>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
public void run()
{
try
{
final SwingMqlEditor mqlEditor = new SwingMqlEditor(repository);
final String theQueryKey = queryNameTextField.getText();
final DataSetQuery theSelectedQuery = queries.get(theQueryKey);
final String theQueryXml = theSelectedQuery.getQuery();
if (StringUtils.isEmpty(theQueryXml) == false)
{
mqlEditor.setQuery(theQueryXml);
}
mqlEditor.hidePreview();
mqlEditor.show();
if (mqlEditor.getOkClicked())
{
final String theQuery = mqlEditor.getQuery();
if (theQuery != null)
{
theSelectedQuery.setQuery(theQuery);
queryTextArea.setText(theQuery);
}
}
}
catch (Exception exc)
{
context.error(exc);
}
}
}
private class PrepareAndInvokeMqlEditorTask implements Runnable
{
private PrepareAndInvokeMqlEditorTask()
{
}
public void run()
{
try
{
final LoadRepositoryRunnable loadRepositoryRunnable = new LoadRepositoryRunnable();
final Thread loadRepositoryThread = new Thread(loadRepositoryRunnable);
BackgroundCancellableProcessHelper.executeProcessWithCancelDialog(loadRepositoryThread, null, PmdDataSourceEditor.this);
final IMetadataDomainRepository repository = loadRepositoryRunnable.getRepository();
if (repository == null)
{
return;
}
SwingUtilities.invokeLater(new CreateMqlEditorTask(repository));
}
catch (Exception exc)
{
context.error(exc);
}
}
}
private class LoadRepositoryRunnable implements Runnable
{
private IMetadataDomainRepository repository;
private LoadRepositoryRunnable()
{
}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p/>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
public void run()
{
repository = buildDomainRepository();
}
public IMetadataDomainRepository getRepository()
{
return repository;
}
}
private class QueryDesignerAction extends AbstractAction
{
public QueryDesignerAction()
{
final URL resource = PmdDataSourceModule.class.getResource
("/org/pentaho/reporting/ui/datasources/pmd/resources/Edit.png"); // NON-NLS
if (resource != null)
{
putValue(Action.SMALL_ICON, new ImageIcon(resource));
}
else
{
putValue(Action.NAME, Messages.getString("PmdDataSourceEditor.EditQuery.Name"));
}
putValue(Action.SHORT_DESCRIPTION, Messages.getString("PmdDataSourceEditor.EditQuery.Description"));
setEnabled(false);
}
public void actionPerformed(final ActionEvent e)
{
final Thread t = new Thread(new PrepareAndInvokeMqlEditorTask());
t.start();
}
}
private class RemoveQueryAction extends AbstractAction
{
public RemoveQueryAction()
{
final URL resource = PmdDataSourceEditor.class.getResource
("/org/pentaho/reporting/ui/datasources/pmd/resources/Remove.png"); // NON-NLS
if (resource != null)
{
putValue(Action.SMALL_ICON, new ImageIcon(resource));
}
else
{
putValue(Action.NAME, Messages.getString("PmdDataSourceEditor.RemoveQuery.Name"));
}
putValue(Action.SHORT_DESCRIPTION, Messages.getString("PmdDataSourceEditor.RemoveQuery.Description"));
}
public void actionPerformed(final ActionEvent e)
{
final DataSetQuery query = (DataSetQuery) queryNameList.getSelectedValue();
if (query != null)
{
queries.remove(query.getQueryName());
}
inModifyingQueryNameList = true;
updateQueryList();
queryNameList.clearSelection();
inModifyingQueryNameList = 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 query = (DataSetQuery) queryNameList.getSelectedValue();
if (query != null)
{
query.setQuery(queryTextArea.getText());
}
}
}
private class QueryNameTextFieldDocumentListener implements DocumentListener
{
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 (inModifyingQueryNameList)
{
return;
}
final String queryName = queryNameTextField.getText();
final DataSetQuery currentQuery = (DataSetQuery) queryNameList.getSelectedValue();
if (currentQuery == null)
{
return;
}
if (queryName.equals(currentQuery.getQueryName()))
{
return;
}
if (queries.containsKey(queryName))
{
return;
}
inQueryNameUpdate = true;
queries.remove(currentQuery.getQueryName());
currentQuery.setQueryName(queryName);
queries.put(currentQuery.getQueryName(), currentQuery);
updateQueryList();
queryNameList.setSelectedValue(currentQuery, true);
inQueryNameUpdate = false;
}
}
private class DomainTextFieldDocumentListener implements DocumentListener
{
public void insertUpdate(final DocumentEvent e)
{
update();
}
public void removeUpdate(final DocumentEvent e)
{
update();
}
public void changedUpdate(final DocumentEvent e)
{
update();
}
private void update()
{
updateComponents();
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
updateQueries();
}
}
);
}
}
private class FilenameDocumentListener implements DocumentListener
{
public void insertUpdate(final DocumentEvent e)
{
updateComponents();
}
public void removeUpdate(final DocumentEvent e)
{
updateComponents();
}
public void changedUpdate(final DocumentEvent e)
{
updateComponents();
}
}
private class PreviewAction extends AbstractAction implements PropertyChangeListener
{
private PreviewAction()
{
putValue(Action.NAME, Messages.getString("PmdDataSourceEditor.Preview.Name"));
setEnabled(dialogModel.isConnectionSelected() && dialogModel.isQuerySelected());
}
public void propertyChange(final PropertyChangeEvent evt)
{
setEnabled(dialogModel.isConnectionSelected() && dialogModel.isQuerySelected());
}
public void actionPerformed(final ActionEvent evt)
{
try
{
final DataPreviewDialog previewDialog = new DataPreviewDialog(PmdDataSourceEditor.this);
final String query = queryNameTextField.getText();
Integer theMaxRows = 0;
if (maxPreviewRowsSpinner.isEnabled())
{
theMaxRows = (Integer) maxPreviewRowsSpinner.getValue();
}
final PmdDataFactory 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 PmdPreviewWorker worker = new PmdPreviewWorker(dataFactory, query, 0, theMaxRows);
previewDialog.showData(worker);
final ReportDataFactoryException factoryException = worker.getException();
if (factoryException != null)
{
ExceptionDialog.showExceptionDialog(PmdDataSourceEditor.this,
Messages.getString("PmdDataSourceEditor.PreviewError.Title"),
Messages.getString("PmdDataSourceEditor.PreviewError.Message"), factoryException);
}
}
catch (Exception e)
{
context.error(e);
ExceptionDialog.showExceptionDialog(PmdDataSourceEditor.this,
Messages.getString("PmdDataSourceEditor.PreviewError.Title"),
Messages.getString("PmdDataSourceEditor.PreviewError.Message"), e);
}
}
}
private class LimitRowsCheckBoxActionListener extends AbstractAction implements ItemListener
{
private JSpinner maxPreviewRowsSpinner;
private LimitRowsCheckBoxActionListener(final JSpinner maxPreviewRowsSpinner)
{
this.maxPreviewRowsSpinner = maxPreviewRowsSpinner;
putValue(Action.NAME, Messages.getString("PmdDataSourceEditor.LimitRowsCheckBox"));
putValue(Action.MNEMONIC_KEY, Messages.getMnemonic("PmdDataSourceEditor.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 ConnectionSelectedActionListener implements PropertyChangeListener
{
public void propertyChange(final PropertyChangeEvent aEvent)
{
updateComponents();
}
}
private JList queryNameList;
private JButton queryRemoveButton;
private JButton queryDesignerButton;
private JButton queryAddButton;
private JTextField domainIdTextField;
private JTextField queryNameTextField;
private JTextField filenameField;
private JTextArea queryTextArea;
private Map<String, DataSetQuery> queries;
private boolean inQueryNameUpdate;
private boolean inModifyingQueryNameList;
private NamedDataSourceDialogModel dialogModel;
private DesignTimeContext context;
private JSpinner maxPreviewRowsSpinner;
private JButton previewButton;
public PmdDataSourceEditor(final DesignTimeContext context)
{
init(context);
}
public PmdDataSourceEditor(final DesignTimeContext context, final Dialog owner)
{
super(owner);
init(context);
}
public PmdDataSourceEditor(final DesignTimeContext context, final Frame owner)
{
super(owner);
init(context);
}
private void init(final DesignTimeContext context)
{
if (context == null)
{
throw new NullPointerException();
}
this.context = context;
setModal(true);
setTitle(Messages.getString("PmdDataSourceEditor.Title"));
dialogModel = new NamedDataSourceDialogModel();
dialogModel.addPropertyChangeListener(new ConnectionSelectedActionListener());
filenameField = new JTextField(null, 0);
filenameField.setColumns(30);
filenameField.getDocument().addDocumentListener(new FilenameDocumentListener());
queryNameList = new JList();
queryNameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
queryNameList.setVisibleRowCount(5);
queryNameList.addListSelectionListener(new QueryNameListSelectionListener());
queryNameList.setCellRenderer(new QueryNameListCellRenderer());
queryAddButton = new BorderlessButton(new AddQueryAction());
queryRemoveButton = new BorderlessButton(new RemoveQueryAction());
queryNameTextField = new JTextField(null, 0);
queryNameTextField.setColumns(35);
queryNameTextField.getDocument().addDocumentListener(new QueryNameTextFieldDocumentListener());
domainIdTextField = new JTextField(null, 0);
domainIdTextField.setColumns(35);
domainIdTextField.getDocument().addDocumentListener(new DomainTextFieldDocumentListener());
queryTextArea = new JTextArea((String) null);
queryTextArea.setWrapStyleWord(true);
queryTextArea.setLineWrap(true);
queryTextArea.setRows(5);
queryTextArea.getDocument().addDocumentListener(new QueryDocumentListener());
queryDesignerButton = new JButton(new QueryDesignerAction());
queryDesignerButton.setEnabled(false);
queryDesignerButton.setBorder(new EmptyBorder(0, 0, 0, 0));
super.init();
pack();
LibSwingUtil.centerDialogInParent(this);
}
protected Component createContentPane()
{
final JPanel filePanel = new JPanel();
filePanel.setLayout(new BoxLayout(filePanel, BoxLayout.X_AXIS));
filePanel.add(filenameField);
filePanel.add(new JButton(new BrowseAction()));
final JPanel queryListButtonsPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
queryListButtonsPanel.add(queryAddButton);
queryListButtonsPanel.add(queryRemoveButton);
final JPanel queryListButtonsPanelWrapper = new JPanel(new BorderLayout());
queryListButtonsPanelWrapper.add(new JLabel(Messages.getString("PmdDataSourceEditor.AvailableQueries")), BorderLayout.WEST);
queryListButtonsPanelWrapper.add(queryListButtonsPanel, BorderLayout.EAST);
final JPanel queryTextAreaHeaderPanel = new JPanel(new BorderLayout());
queryTextAreaHeaderPanel.add(new JLabel(Messages.getString("PmdDataSourceEditor.QueryLabel")), BorderLayout.WEST);
queryTextAreaHeaderPanel.add(queryDesignerButton, BorderLayout.EAST);
final JPanel queryConfigurationPanel = new JPanel();
queryConfigurationPanel.setLayout(new VerticalLayout(5, VerticalLayout.BOTH, VerticalLayout.TOP));
queryConfigurationPanel.add(new JLabel(Messages.getString("PmdDataSourceEditor.XmiFileLabel")));
queryConfigurationPanel.add(filePanel);
queryConfigurationPanel.add(new JLabel(Messages.getString("PmdDataSourceEditor.DomainId")));
queryConfigurationPanel.add(domainIdTextField);
queryConfigurationPanel.add(queryListButtonsPanelWrapper);
queryConfigurationPanel.add(new JScrollPane(queryNameList));
queryConfigurationPanel.add(new JLabel(Messages.getString("PmdDataSourceEditor.QueryName")));
queryConfigurationPanel.add(queryNameTextField);
queryConfigurationPanel.add(queryTextAreaHeaderPanel);
final JPanel queryAreaPanel = new JPanel();
queryAreaPanel.setLayout(new BorderLayout());
queryAreaPanel.add(queryConfigurationPanel, BorderLayout.NORTH);
queryAreaPanel.add(new JScrollPane(queryTextArea), BorderLayout.CENTER);
final JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.add(queryAreaPanel, BorderLayout.CENTER);
contentPanel.add(createPreviewButtonsPanel(), BorderLayout.SOUTH);
contentPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
return contentPanel;
}
private JPanel createPreviewButtonsPanel()
{
maxPreviewRowsSpinner = new JSpinner(new SpinnerNumberModel(10000, 1, Integer.MAX_VALUE, 1));
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);
previewButton = new JButton(thePreviewAction);
previewButtonsPanel.add(previewButton);
return previewButtonsPanel;
}
public PmdDataFactory performConfiguration(final PmdDataFactory dataFactory, final String selectedQuery)
{
// Reset the ok / cancel flag
dialogModel.clear();
// Initialize the internal storage
queries = new TreeMap<String, DataSetQuery>();
// Load the current configuration
if (dataFactory != null)
{
filenameField.setText(dataFactory.getXmiFile());
domainIdTextField.setText(dataFactory.getDomainId());
final String[] queryNames = dataFactory.getQueryNames();
for (int i = 0; i < queryNames.length; i++)
{
final String queryName = queryNames[i];
final String query = dataFactory.getQuery(queryName);
queries.put(queryName, new DataSetQuery(queryName, query));
}
}
// Prepare the data and the enable the proper buttons
updateComponents();
updateQueryList();
setSelectedQuery(selectedQuery);
// Enable the dialog
pack();
setLocationRelativeTo(getParent());
if (!performEdit())
{
return null;
}
return createDataFactory();
}
private PmdDataFactory createDataFactory()
{
final PmdDataFactory returnDataFactory = new PmdDataFactory();
returnDataFactory.setXmiFile(filenameField.getText());
returnDataFactory.setDomainId(domainIdTextField.getText());
returnDataFactory.setConnectionProvider(new PmdConnectionProvider());
final DataSetQuery[] queries = this.queries.values().toArray(new DataSetQuery[this.queries.size()]);
for (int i = 0; i < queries.length; i++)
{
final DataSetQuery query = queries[i];
returnDataFactory.setQuery(query.getQueryName(), query.getQuery());
}
return returnDataFactory;
}
private IMetadataDomainRepository buildDomainRepository()
{
try
{
final AbstractReportDefinition report = context.getReport();
final MasterReport masterReport = DesignTimeUtil.getMasterReport(report);
final ResourceKey contentBase;
if (masterReport == null)
{
contentBase = null;
}
else
{
contentBase = masterReport.getContentBase();
}
final ResourceManager resourceManager = context.getReport().getResourceManager();
return new PmdConnectionProvider().getMetadataDomainRepository
(domainIdTextField.getText(), resourceManager, contentBase, filenameField.getText());
}
catch (Exception e)
{
context.error(e);
}
return new InMemoryMetadataDomainRepository();
}
protected void updateQueryList()
{
if (!queries.isEmpty())
{
queryNameList.setListData(queries.values().toArray(new DataSetQuery[queries.size()]));
}
else
{
queryNameList.setListData(new Object[0]);
}
}
private void setSelectedQuery(final String aQuery)
{
final ListModel theModel = queryNameList.getModel();
for (int i = 0; i < theModel.getSize(); i++)
{
final DataSetQuery theDataSet = (DataSetQuery) theModel.getElementAt(i);
if (theDataSet.getQueryName().equals(aQuery))
{
queryNameList.setSelectedValue(theDataSet, true);
break;
}
}
}
protected void updateComponents()
{
final boolean querySelected = queryNameList.getSelectedIndex() != -1;
final boolean hasQueries = queryNameList.getModel().getSize() > 0;
final boolean isFileSelected = !StringUtils.isEmpty(filenameField.getText(), true);
final boolean hasDomain = !StringUtils.isEmpty(domainIdTextField.getText(), true);
domainIdTextField.setEnabled(isFileSelected);
previewButton.setEnabled(isFileSelected && querySelected);
queryNameTextField.setEnabled(querySelected);
queryTextArea.setEnabled(querySelected);
queryRemoveButton.setEnabled(querySelected);
queryDesignerButton.setEnabled(hasDomain && querySelected && isFileSelected);
queryAddButton.setEnabled(true);
getConfirmAction().setEnabled(hasQueries && isFileSelected);
}
public void updateQueries()
{
try
{
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder documentBuilder = factory.newDocumentBuilder();
final DataSetQuery[] objects = queries.values().toArray(new DataSetQuery[queries.size()]);
for (int i = 0; i < objects.length; i++)
{
final DataSetQuery object = objects[i];
final String text = object.getQuery();
if (StringUtils.isEmpty(text, true))
{
continue;
}
try
{
final Document doc = documentBuilder.parse(new InputSource(new StringReader(text)));
final NodeList list = doc.getDocumentElement().getElementsByTagName("domain_id");
if (list.getLength() == 0)
{
continue;
}
list.item(0).setTextContent(domainIdTextField.getText());
final TransformerFactory tfactory = TransformerFactory.newInstance();
final StringWriter stringWriter = new StringWriter();
final StreamResult result = new StreamResult();
result.setWriter(stringWriter);
tfactory.newTransformer().transform(new DOMSource(doc), result);
object.setQuery(stringWriter.getBuffer().toString());
}
catch (Exception e)
{
context.error(e);
}
}
}
catch (Exception e)
{
context.error(e);
}
final Object o = queryNameList.getSelectedValue();
if (o != null)
{
final DataSetQuery q = (DataSetQuery) o;
queryTextArea.setText(q.getQuery());
}
}
}