001: /*
002: * Copyright 2006-2007 Pentaho Corporation. All rights reserved.
003: * This software was developed by Pentaho Corporation and is provided under the terms
004: * of the Mozilla Public License, Version 1.1, or any later version. You may not use
005: * this file except in compliance with the license. If you need a copy of the license,
006: * please go to http://www.mozilla.org/MPL/MPL-1.1.txt.
007: *
008: * Software distributed under the Mozilla Public License is distributed on an "AS IS"
009: * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to
010: * the license for the specific language governing your rights and limitations.
011: *
012: * Additional Contributor(s): Martin Schmid gridvision engineering GmbH
013: */
014: package org.pentaho.reportdesigner.crm.report.datasetplugin.jdbc;
015:
016: import com.jgoodies.forms.layout.CellConstraints;
017: import com.jgoodies.forms.layout.FormLayout;
018: import org.jetbrains.annotations.NonNls;
019: import org.jetbrains.annotations.NotNull;
020: import org.jetbrains.annotations.Nullable;
021: import org.pentaho.reportdesigner.crm.report.components.ProgressListener;
022: import org.pentaho.reportdesigner.crm.report.connection.ColumnInfo;
023: import org.pentaho.reportdesigner.crm.report.connection.JDBCConnection;
024: import org.pentaho.reportdesigner.crm.report.connection.MetaDataService;
025: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.JDBCAnalyzer;
026: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.JDBCColumnInfo;
027: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.JDBCGraph;
028: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.JDBCVertex;
029: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.NoAffectedTablesException;
030: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.NoSuitableRootException;
031: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.QueryComposer;
032: import org.pentaho.reportdesigner.crm.report.datasetplugin.composer.QueryComposerColumn;
033: import org.pentaho.reportdesigner.crm.report.settings.WorkspaceSettings;
034: import org.pentaho.reportdesigner.crm.report.util.JOptionPaneHelper;
035: import org.pentaho.reportdesigner.lib.client.components.CenterPanelDialog;
036: import org.pentaho.reportdesigner.lib.client.components.ComponentFactory;
037: import org.pentaho.reportdesigner.lib.client.components.ProgressDialog;
038: import org.pentaho.reportdesigner.lib.client.components.TextComponentHelper;
039: import org.pentaho.reportdesigner.lib.client.i18n.TranslationManager;
040: import org.pentaho.reportdesigner.lib.client.util.CooltipManager;
041: import org.pentaho.reportdesigner.lib.client.util.GUIUtils;
042: import org.pentaho.reportdesigner.lib.client.util.TableUtils;
043: import org.pentaho.reportdesigner.lib.client.util.UncaughtExcpetionsModel;
044: import org.pentaho.reportdesigner.lib.client.util.UndoHelper;
045: import org.pentaho.reportdesigner.lib.client.util.WindowUtils;
046:
047: import javax.swing.*;
048: import javax.swing.event.DocumentEvent;
049: import javax.swing.event.DocumentListener;
050: import javax.swing.event.ListSelectionEvent;
051: import javax.swing.event.ListSelectionListener;
052: import javax.swing.table.DefaultTableCellRenderer;
053: import javax.swing.text.BadLocationException;
054: import javax.swing.tree.TreePath;
055: import java.awt.*;
056: import java.awt.event.ActionEvent;
057: import java.awt.event.ActionListener;
058: import java.awt.event.MouseAdapter;
059: import java.awt.event.MouseEvent;
060: import java.beans.PropertyChangeListener;
061: import java.beans.PropertyChangeSupport;
062: import java.util.ArrayList;
063: import java.util.Collections;
064: import java.util.LinkedHashMap;
065: import java.util.logging.Level;
066: import java.util.logging.Logger;
067:
068: /**
069: * User: Martin
070: * Date: 13.02.2006
071: * Time: 07:47:56
072: */
073: public class SQLQueryConfigurationPanel extends JPanel {
074: @NonNls
075: @NotNull
076: private static final Logger LOG = Logger
077: .getLogger(SQLQueryConfigurationPanel.class.getName());
078:
079: private static final int MAX_QUERY_HISTORY_SIZE = 30;
080: private static final int DEFAULT_MAX_ROWS = 100;
081:
082: @NotNull
083: public static final String OK = "ok";
084:
085: @NotNull
086: private PropertyChangeSupport propertyChangeSupport;
087:
088: @NotNull
089: private ArrayList<ColumnInfo> columnInfos;
090: @NotNull
091: private ArrayList<ColumnInfo> availableColumnInfos;
092:
093: @NotNull
094: private ArrayList<String> oldQueries = new ArrayList<String>();
095:
096: @NotNull
097: @NonNls
098: private JTextArea sqlQueryTextArea;
099: @NotNull
100: private JTextField maxResultsTextField;
101:
102: @NotNull
103: private JScrollPane schemaTreeScrollPane;
104:
105: private boolean ok;
106: @NotNull
107: private Component parent;
108: @NotNull
109: private WorkspaceSettings workspaceSettings;
110: @Nullable
111: private MetaDataService metaDataService;
112:
113: @NotNull
114: private JButton testQueryButton;
115: @NotNull
116: private JButton sqlHistoryButton;
117:
118: //caching
119: @Nullable
120: private JDBCGraph graph;
121:
122: public SQLQueryConfigurationPanel(@NotNull
123: Component parent, @NotNull
124: final WorkspaceSettings workspaceSettings) {
125: //noinspection ConstantConditions
126: if (parent == null) {
127: throw new IllegalArgumentException(
128: "parent must not be null");
129: }
130: //noinspection ConstantConditions
131: if (workspaceSettings == null) {
132: throw new IllegalArgumentException(
133: "workspaceSettings must not be null");
134: }
135:
136: this .parent = parent;
137: this .workspaceSettings = workspaceSettings;
138:
139: setLayout(new BorderLayout());
140:
141: propertyChangeSupport = new PropertyChangeSupport(this );
142:
143: ok = false;
144:
145: @NonNls
146: CellConstraints cc = new CellConstraints();
147:
148: schemaTreeScrollPane = new JScrollPane();
149:
150: @NonNls
151: FormLayout formLayout = new FormLayout(
152: "0dlu, fill:default:grow, 4dlu, fill:default, 4dlu, fill:default, 4dlu, fill:default, 0dlu",
153: "0dlu, " + "fill:10dlu:grow, " + "4dlu, " + "pref, "
154: + "0dlu");
155:
156: JPanel bottomPanel = new JPanel(formLayout);
157:
158: sqlQueryTextArea = new JTextArea();
159: sqlQueryTextArea.getDocument().addDocumentListener(
160: new DocumentListener() {
161: public void insertUpdate(@NotNull
162: DocumentEvent e) {
163: sqlQueryTextArea.requestFocusInWindow();
164: }
165:
166: public void removeUpdate(@NotNull
167: DocumentEvent e) {
168: sqlQueryTextArea.requestFocusInWindow();
169: }
170:
171: public void changedUpdate(@NotNull
172: DocumentEvent e) {
173: sqlQueryTextArea.requestFocusInWindow();
174: }
175: });
176: UndoHelper.installUndoSupport(sqlQueryTextArea);
177: TextComponentHelper.installDefaultPopupMenu(sqlQueryTextArea);
178: /*
179: "SELECT * FROM customer JOIN\n" +
180: "shopping_cart ON customer.customer_id=shopping_cart.customer_id JOIN\n" +
181: "item ON shopping_cart.item_id=item.item_id"
182: */
183:
184: JSplitPane splitPane = new JSplitPane(
185: JSplitPane.HORIZONTAL_SPLIT, true);
186: splitPane.setTopComponent(schemaTreeScrollPane);
187:
188: splitPane.setDividerLocation(200);
189: bottomPanel.add(splitPane, cc.xyw(2, 2, 7, "fill, fill"));
190:
191: JScrollPane scrollPane = new JScrollPane(sqlQueryTextArea);
192: scrollPane.setPreferredSize(new Dimension(10, 10));
193: splitPane.setBottomComponent(scrollPane);
194:
195: JLabel maxResultsLabel = new JLabel(TranslationManager
196: .getInstance().getTranslation("R",
197: "WizardPageDatabaseConnection.MaxResultsLabel"));
198: maxResultsTextField = new JTextField(String
199: .valueOf(DEFAULT_MAX_ROWS), 5);
200: bottomPanel.add(maxResultsLabel, cc.xy(2, 4, "right, center"));
201: bottomPanel.add(maxResultsTextField, cc.xy(4, 4));
202:
203: testQueryButton = ComponentFactory.createButton("R",
204: "WizardPageDatabaseConnection.PreviewButton");
205: bottomPanel.add(testQueryButton, cc.xy(6, 4));
206:
207: testQueryButton.setEnabled(false);
208:
209: testQueryButton.addActionListener(new ActionListener() {
210: public void actionPerformed(@NotNull
211: ActionEvent e) {
212: try {
213: final String query = sqlQueryTextArea.getText();
214: final int maxRows = Integer
215: .parseInt(maxResultsTextField.getText());
216:
217: final DefaultListModel defaultListModel = new DefaultListModel();
218: columnInfos.clear();
219:
220: final ProgressDialog progressDialog = ProgressDialog
221: .createProgressDialog(
222: SQLQueryConfigurationPanel.this ,
223: TranslationManager
224: .getInstance()
225: .getTranslation("R",
226: "SQLQueryConfigurationPanel.ExecutingQueryDialog.Title"),
227: "");
228:
229: Thread t = new Thread(new Runnable() {
230: public void run() {
231: final ColumnInfo[] queryMetaData;
232: final ReportDataTableModel reportDataTableModel;
233: try {
234: MetaDataService mds = metaDataService;
235: if (mds != null) {
236: ArrayList<ArrayList<Object>> queryData = mds
237: .getQueryData(maxRows,
238: query);
239: queryMetaData = mds
240: .getQueryMetaData(query);
241: reportDataTableModel = new ReportDataTableModel(
242: queryMetaData, queryData);
243:
244: EventQueue
245: .invokeLater(new Runnable() {
246: public void run() {
247: for (ColumnInfo columnInfo : queryMetaData) {
248: defaultListModel
249: .addElement(columnInfo);
250: columnInfos
251: .add(columnInfo);
252: }
253:
254: progressDialog
255: .dispose();
256:
257: showPreviewDialog(reportDataTableModel);
258:
259: availableColumnInfos
260: .clear();
261: availableColumnInfos
262: .addAll(columnInfos);
263:
264: ok = true;
265: propertyChangeSupport
266: .firePropertyChange(
267: OK,
268: Boolean.FALSE,
269: Boolean.TRUE);
270: }
271: });
272: }
273: } catch (final Throwable e1) {
274: EventQueue.invokeLater(new Runnable() {
275: public void run() {
276: progressDialog.dispose();
277: ok = false;
278: propertyChangeSupport
279: .firePropertyChange(OK,
280: Boolean.TRUE,
281: Boolean.FALSE);
282:
283: if (LOG.isLoggable(Level.FINE))
284: LOG
285: .log(
286: Level.FINE,
287: "WizardPageDatabaseConnection.actionPerformed ",
288: e1);
289: Throwable t = e1;
290: if (e1.getCause() != null) {
291: t = e1.getCause();
292: }
293: JOptionPaneHelper
294: .showMessageDialog(
295: SQLQueryConfigurationPanel.this ,
296: TranslationManager
297: .getInstance()
298: .getTranslation(
299: "R",
300: "Database.CouldNotFetchData")
301: + " ("
302: + (t == null ? ""
303: : t
304: .getMessage())
305: + ")",
306: TranslationManager
307: .getInstance()
308: .getTranslation(
309: "R",
310: "Error.Title"),
311: JOptionPaneHelper.ERROR_MESSAGE,
312: CenterPanelDialog.ModalityType.DOCUMENT_MODAL);
313: }
314: });
315: }
316: }
317: });
318:
319: t.setDaemon(true);
320: t.start();
321:
322: if (t.isAlive()) {
323: progressDialog.setVisible(true);
324: } else {
325: progressDialog.dispose();
326: }
327: } catch (Exception e1) {
328: ok = false;
329: propertyChangeSupport.firePropertyChange(OK,
330: Boolean.TRUE, Boolean.FALSE);
331:
332: if (LOG.isLoggable(Level.FINE))
333: LOG
334: .log(
335: Level.FINE,
336: "WizardPageDatabaseConnection.actionPerformed ",
337: e1);
338: JOptionPaneHelper
339: .showMessageDialog(
340: SQLQueryConfigurationPanel.this ,
341: TranslationManager
342: .getInstance()
343: .getTranslation("R",
344: "Database.CouldNotFetchData")
345: + " " + e1.getMessage(),
346: TranslationManager.getInstance()
347: .getTranslation("R",
348: "Error.Title"),
349: JOptionPaneHelper.ERROR_MESSAGE,
350: CenterPanelDialog.ModalityType.DOCUMENT_MODAL);
351: }
352:
353: }
354: });
355:
356: ArrayList<String> list = workspaceSettings
357: .getList("SQLQueryConfigurationPanel.SQLHistory");
358: oldQueries = new ArrayList<String>(list);
359:
360: sqlHistoryButton = new JButton(TranslationManager.getInstance()
361: .getTranslation("R",
362: "SQLQueryConfigurationPanel.SQLHistoryButton"));
363: bottomPanel.add(sqlHistoryButton, cc.xy(8, 4));
364: sqlHistoryButton.addActionListener(new ActionListener() {
365: public void actionPerformed(@NotNull
366: ActionEvent e) {
367: final CenterPanelDialog historyDialog = CenterPanelDialog
368: .createDialog(
369: sqlHistoryButton,
370: TranslationManager
371: .getInstance()
372: .getTranslation("R",
373: "SQLQueryConfigurationPanel.SQLHistoryDialog.Title"),
374: CenterPanelDialog.ModalityType.DOCUMENT_MODAL);
375:
376: JPanel centerPanel = new JPanel(new BorderLayout());
377: ArrayList<String> queries = new ArrayList<String>(
378: oldQueries);
379: Collections.reverse(queries);
380: final JList list = new JList(queries.toArray());
381:
382: final JTextArea queryArea = new JTextArea();
383: queryArea.setEditable(false);
384:
385: list
386: .addListSelectionListener(new ListSelectionListener() {
387: public void valueChanged(@NotNull
388: ListSelectionEvent e) {
389: if (!e.getValueIsAdjusting()) {
390: Object selectedValue = list
391: .getSelectedValue();
392: if (selectedValue != null) {
393: queryArea.setText(selectedValue
394: .toString());
395: }
396: }
397: }
398: });
399:
400: JButton okButton = new JButton(TranslationManager
401: .getInstance().getTranslation("R", "Button.ok"));
402: JButton cancelButton = new JButton(TranslationManager
403: .getInstance().getTranslation("R",
404: "Button.cancel"));
405: historyDialog.setButtons(okButton, cancelButton,
406: okButton, cancelButton);
407:
408: okButton.addActionListener(new ActionListener() {
409: public void actionPerformed(@NotNull
410: ActionEvent e) {
411: try {
412: Object selectedValue = list
413: .getSelectedValue();
414: if (selectedValue != null) {
415: if (sqlQueryTextArea.getDocument()
416: .getLength() > 0) {
417: sqlQueryTextArea
418: .getDocument()
419: .insertString(
420: sqlQueryTextArea
421: .getDocument()
422: .getLength(),
423: "\n", null);
424: }
425: sqlQueryTextArea.getDocument()
426: .insertString(
427: sqlQueryTextArea
428: .getDocument()
429: .getLength(),
430: selectedValue
431: .toString(),
432: null);
433: }
434:
435: workspaceSettings.storeDialogBounds(
436: historyDialog, "SQLHistoryDialog");
437: historyDialog.dispose();
438: } catch (BadLocationException e1) {
439: UncaughtExcpetionsModel.getInstance()
440: .addException(e1);
441: }
442: }
443: });
444:
445: cancelButton.addActionListener(new ActionListener() {
446: public void actionPerformed(@NotNull
447: ActionEvent e) {
448: workspaceSettings.storeDialogBounds(
449: historyDialog, "SQLHistoryDialog");
450: historyDialog.dispose();
451: }
452: });
453:
454: JSplitPane splitPane = new JSplitPane(
455: JSplitPane.HORIZONTAL_SPLIT, true,
456: new JScrollPane(list), new JScrollPane(
457: queryArea));
458: centerPanel.add(splitPane, BorderLayout.CENTER);
459: splitPane.setDividerLocation(150);
460: centerPanel.setPreferredSize(new Dimension(100, 100));
461:
462: historyDialog.setCenterPanel(centerPanel);
463:
464: if (!workspaceSettings.restoreDialogBounds(
465: historyDialog, "SQLHistoryDialog")) {
466: historyDialog.pack();
467: GUIUtils.ensureMinimumDialogSize(historyDialog,
468: 400, 400);
469: }
470:
471: WindowUtils.setLocationRelativeTo(historyDialog,
472: SQLQueryConfigurationPanel.this );
473: historyDialog.setVisible(true);
474: }
475: });
476:
477: DocumentListener modificationListener = new DocumentListener() {
478: public void insertUpdate(@NotNull
479: DocumentEvent e) {
480: ok = false;
481: propertyChangeSupport.firePropertyChange(OK,
482: Boolean.TRUE, Boolean.FALSE);
483: }
484:
485: public void removeUpdate(@NotNull
486: DocumentEvent e) {
487: ok = false;
488: propertyChangeSupport.firePropertyChange(OK,
489: Boolean.TRUE, Boolean.FALSE);
490: }
491:
492: public void changedUpdate(@NotNull
493: DocumentEvent e) {
494: ok = false;
495: propertyChangeSupport.firePropertyChange(OK,
496: Boolean.TRUE, Boolean.FALSE);
497: }
498: };
499:
500: sqlQueryTextArea.getDocument().addDocumentListener(
501: modificationListener);
502: maxResultsTextField.getDocument().addDocumentListener(
503: modificationListener);
504:
505: columnInfos = new ArrayList<ColumnInfo>();
506: availableColumnInfos = new ArrayList<ColumnInfo>();
507:
508: add(bottomPanel, BorderLayout.CENTER);
509: }
510:
511: @NotNull
512: public ArrayList<ColumnInfo> getAvailableColumnInfos() {
513: return availableColumnInfos;
514: }
515:
516: @NotNull
517: public ArrayList<ColumnInfo> getColumnInfos() {
518: return columnInfos;
519: }
520:
521: @NotNull
522: public String getSQLQuery() {
523: return sqlQueryTextArea.getText();
524: }
525:
526: public void setSQLQuery(@NotNull
527: String query) {
528: sqlQueryTextArea.setText(query);
529: }
530:
531: public int getMaxPreviewRows() {
532: try {
533: return Integer.parseInt(maxResultsTextField.getText());
534: } catch (NumberFormatException e) {
535: if (LOG.isLoggable(Level.FINE))
536: LOG
537: .log(
538: Level.FINE,
539: "SQLQueryConfigurationPanel.getMaxPreviewRows ",
540: e);
541: return DEFAULT_MAX_ROWS;
542: }
543: }
544:
545: public void setMaxPreviewRows(int maxPreviewRows) {
546: maxResultsTextField.setText(String.valueOf(maxPreviewRows));
547: }
548:
549: public boolean isOk() {
550: return ok;
551: }
552:
553: private void showPreviewDialog(@NotNull
554: ReportDataTableModel reportDataTableModel) {
555: final CenterPanelDialog centerPanelDialog = CenterPanelDialog
556: .createDialog(
557: parent,
558: TranslationManager
559: .getInstance()
560: .getTranslation("R",
561: "WizardPageSQLQuery.PreviewDialog.Title"),
562: CenterPanelDialog.ModalityType.DOCUMENT_MODAL);
563:
564: final JPanel centerPanel = new JPanel(new BorderLayout());
565: JTable table = new JTable(reportDataTableModel);
566: JTable rowHeaderTable = new JTable(new RowNumberTableModel(
567: reportDataTableModel.getRowCount()));
568: rowHeaderTable.setEnabled(false);
569: rowHeaderTable.getColumnModel().getColumn(0).setCellRenderer(
570: new DefaultTableCellRenderer() {
571: @NotNull
572: public Component getTableCellRendererComponent(
573: @NotNull
574: JTable table, @Nullable
575: Object value, boolean isSelected,
576: boolean hasFocus, int row, int column) {
577: JLabel tableCellRendererComponent = (JLabel) super
578: .getTableCellRendererComponent(table,
579: value, isSelected, hasFocus,
580: row, column);
581: tableCellRendererComponent
582: .setHorizontalAlignment(JLabel.TRAILING);
583: tableCellRendererComponent
584: .setBackground(centerPanel
585: .getBackground());
586: return tableCellRendererComponent;
587: }
588: });
589: rowHeaderTable.setGridColor(centerPanel.getBackground()
590: .darker());
591: rowHeaderTable.setBorder(BorderFactory.createMatteBorder(1, 0,
592: 0, 0, centerPanel.getBackground().darker()));
593:
594: JViewport viewport = new JViewport();
595: viewport.setPreferredSize(new Dimension(40, 100));
596: viewport.setView(rowHeaderTable);
597: table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
598: TableUtils.resizeAllColumns(table, 200);
599:
600: JScrollPane scrollPane = new JScrollPane(table);
601: scrollPane.setRowHeader(viewport);
602: centerPanel.add(scrollPane, BorderLayout.CENTER);
603: centerPanelDialog.setCenterPanel(centerPanel);
604: JButton closeButton = ComponentFactory.createButton("R",
605: "WizardPageSQLQuery.Close");
606: closeButton.addActionListener(new ActionListener() {
607: public void actionPerformed(@NotNull
608: ActionEvent e) {
609: workspaceSettings.storeDialogBounds(centerPanelDialog,
610: "WizardPageSQLQuery.PreviewDialog");
611: centerPanelDialog.dispose();
612: }
613: });
614: centerPanelDialog.setButtons(closeButton, closeButton,
615: CenterPanelDialog.ButtonAlignment.CENTER, closeButton);
616:
617: if (!workspaceSettings.restoreDialogBounds(centerPanelDialog,
618: "WizardPageSQLQuery.PreviewDialog")) {
619: centerPanelDialog.pack();
620: }
621:
622: if (!oldQueries.contains(sqlQueryTextArea.getText())) {
623: oldQueries.add(sqlQueryTextArea.getText());
624: while (oldQueries.size() > MAX_QUERY_HISTORY_SIZE) {
625: oldQueries.remove(0);
626: }
627: workspaceSettings
628: .put("SQLQueryConfigurationPanel.SQLHistory",
629: oldQueries);
630: }
631:
632: WindowUtils.setLocationRelativeTo(centerPanelDialog, parent);
633: centerPanelDialog.setVisible(true);
634: }
635:
636: public void setMetaDataService(@Nullable
637: final MetaDataService metaDataService) {
638: if (this .metaDataService != null) {
639: this .metaDataService.dispose();
640: }
641: this .metaDataService = metaDataService;
642: testQueryButton.setEnabled(metaDataService != null);
643:
644: if (metaDataService != null) {
645: final DatabaseSchemaTree databaseSchemaTree = new DatabaseSchemaTree(
646: metaDataService);
647:
648: databaseSchemaTree.addMouseListener(new MouseAdapter() {
649: public void mouseClicked(@NotNull
650: MouseEvent e) {
651: showPopup(e);
652: }
653:
654: public void mousePressed(@NotNull
655: MouseEvent e) {
656: showPopup(e);
657: }
658:
659: public void mouseReleased(@NotNull
660: MouseEvent e) {
661: showPopup(e);
662: }
663:
664: private void showPopup(@NotNull
665: MouseEvent e) {
666: if (e.isPopupTrigger()) {
667: TreePath[] selectionPaths = databaseSchemaTree
668: .getSelectionPaths();
669: if (selectionPaths != null
670: && selectionPaths.length == 1) {
671: if (selectionPaths[0]
672: .getLastPathComponent() instanceof DatabaseSchemaTree.TableNode) {
673: final DatabaseSchemaTree.TableNode tableNode = (DatabaseSchemaTree.TableNode) selectionPaths[0]
674: .getLastPathComponent();
675: JPopupMenu popupMenu = new JPopupMenu();
676: JMenuItem menuItem = new JMenuItem(
677: TranslationManager
678: .getInstance()
679: .getTranslation("R",
680: "WizardPageSQLQuery.InsertSelect"));
681: menuItem
682: .addActionListener(new ActionListener() {
683: public void actionPerformed(
684: @NotNull
685: ActionEvent e) {
686: if (tableNode
687: .getChildCount() == 0) {
688: StringBuilder sb = new StringBuilder(
689: 32);
690: sb
691: .append(
692: "SELECT * FROM ")
693: .append(
694: tableNode
695: .getTable());//NON-NLS
696: sqlQueryTextArea
697: .insert(
698: sb
699: .toString(),
700: sqlQueryTextArea
701: .getDocument()
702: .getLength());
703: } else {
704: StringBuilder sb = new StringBuilder(
705: 32);
706: sb
707: .append("SELECT ");//NON-NLS
708: for (int i = 0; i < tableNode
709: .getChildCount(); i++) {
710: DatabaseSchemaTree.ColumnNode columnNode = (DatabaseSchemaTree.ColumnNode) tableNode
711: .getChildAt(i);
712: sb
713: .append(columnNode
714: .getColumnInfo()
715: .getColumnName());
716: if (i < tableNode
717: .getChildCount() - 1) {
718: sb
719: .append(", ");
720: }
721: }
722: sb
723: .append(
724: "\nFROM ")
725: .append(
726: tableNode
727: .getTable());//NON-NLS
728: sqlQueryTextArea
729: .insert(
730: sb
731: .toString(),
732: sqlQueryTextArea
733: .getDocument()
734: .getLength());
735: }
736: }
737: });
738: popupMenu.add(menuItem);
739: popupMenu.show(databaseSchemaTree, e
740: .getX(), e.getY());
741: } else if (selectionPaths[0]
742: .getLastPathComponent() instanceof DatabaseSchemaTree.SchemaNode) {
743: //show query configurator
744: }
745: } else if (selectionPaths != null
746: && selectionPaths.length > 1) {
747: //get all columns from same schema
748: String firstSchema = null;
749: final ArrayList<DatabaseSchemaTree.ColumnNode> columnNodes = new ArrayList<DatabaseSchemaTree.ColumnNode>();
750: for (TreePath treePath : selectionPaths) {
751: if (treePath.getLastPathComponent() instanceof DatabaseSchemaTree.ColumnNode) {
752: DatabaseSchemaTree.ColumnNode columnNode = (DatabaseSchemaTree.ColumnNode) treePath
753: .getLastPathComponent();
754: if (firstSchema == null) {
755: firstSchema = columnNode
756: .getSchema();
757: columnNodes.add(columnNode);
758: } else if (firstSchema
759: .equals(columnNode
760: .getSchema())) {
761: columnNodes.add(columnNode);
762: }
763: }
764: }
765: if (!columnNodes.isEmpty()
766: && (metaDataService instanceof JDBCConnection)) {
767: final JDBCConnection jdbcConnection = (JDBCConnection) metaDataService;
768: JPopupMenu popupMenu = new JPopupMenu();
769: JMenuItem menuItem = new JMenuItem(
770: TranslationManager
771: .getInstance()
772: .getTranslation("R",
773: "WizardPageSQLQuery.InsertSelect"));
774: menuItem
775: .addActionListener(new ActionListener() {
776: public void actionPerformed(
777: @NotNull
778: ActionEvent e) {
779: createAutomaticQuery(
780: jdbcConnection,
781: columnNodes);
782: }
783: });
784: popupMenu.add(menuItem);
785: popupMenu.show(databaseSchemaTree, e
786: .getX(), e.getY());
787: }
788: }
789: }
790: }
791: });
792: schemaTreeScrollPane.setViewportView(databaseSchemaTree);
793:
794: CooltipManager cooltipManager = new CooltipManager();
795: cooltipManager.registerComponent(databaseSchemaTree);
796: } else {
797: schemaTreeScrollPane.setViewportView(new JPanel());
798: }
799: }
800:
801: private void createAutomaticQuery(@NotNull
802: final JDBCConnection jdbcConnection, @NotNull
803: final ArrayList<DatabaseSchemaTree.ColumnNode> columnNodes) {
804: if (graph == null) {
805: final ProgressDialog progressDialog = ProgressDialog
806: .createProgressDialog(
807: this ,
808: TranslationManager
809: .getInstance()
810: .getTranslation("R",
811: "SQLQueryConfigurationPanel.AnalyzeDatabase"),
812: "");
813: Thread analyzerThread = new Thread() {
814: public void run() {
815: try {
816: SQLQueryConfigurationPanel.this .graph = JDBCAnalyzer
817: .buildGraph(
818: jdbcConnection.getCatalog(),
819: columnNodes.get(0).getSchema(),
820: jdbcConnection.getConnection(),
821: new ProgressListener() {
822: public void taskStarted(
823: @NotNull
824: final String task) {
825: EventQueue
826: .invokeLater(new Runnable() {
827: public void run() {
828: progressDialog
829: .setTask(TranslationManager
830: .getInstance()
831: .getTranslation(
832: "R",
833: "SQLQueryConfigurationPanel.AnalyzeTable",
834: task));
835: }
836: });
837: }
838: });
839: } catch (Exception e) {
840: if (LOG.isLoggable(Level.FINE))
841: LOG.log(Level.FINE,
842: "SQLQueryConfigurationPanel.run ",
843: e);
844: UncaughtExcpetionsModel.getInstance()
845: .addException(e);//TODO show useful message
846: }
847:
848: EventQueue.invokeLater(new Runnable() {
849: public void run() {
850: progressDialog.dispose();
851: }
852: });
853: }
854: };
855:
856: analyzerThread.setDaemon(true);
857: analyzerThread.start();
858:
859: if (analyzerThread.isAlive()) {
860: progressDialog.setVisible(true);
861: } else {
862: progressDialog.dispose();
863: }
864: }
865:
866: ArrayList<QueryComposerColumn> queryComposerColumns = new ArrayList<QueryComposerColumn>();
867:
868: for (DatabaseSchemaTree.ColumnNode columnNode : columnNodes) {
869: String t = columnNode.getTable();
870: JDBCVertex table = null;
871: if (graph != null) {
872: table = graph.getVertexForTable(t);
873: }
874: if (table != null) {
875: LinkedHashMap<String, JDBCColumnInfo> infos = table
876: .getTableInfo().getColumnInfos();
877: if (infos != null) {
878: @Nullable
879: JDBCColumnInfo gueltigVon = infos.get(columnNode
880: .getColumnInfo().getColumnName());
881: if (gueltigVon != null) {
882: queryComposerColumns
883: .add(new QueryComposerColumn(
884: gueltigVon, true, null, null,
885: null, null));
886: }
887: }
888: }
889: }
890: String query = null;
891: try {
892: if (graph != null) {
893: query = QueryComposer.getQuery(graph,
894: queryComposerColumns);
895: }
896: } catch (NoAffectedTablesException e) {
897: if (LOG.isLoggable(Level.FINE))
898: LOG
899: .log(
900: Level.FINE,
901: "SQLQueryConfigurationPanel.createAutomaticQuery ",
902: e);
903: JOptionPaneHelper.showMessageDialog(this ,
904: TranslationManager.getInstance().getTranslation(
905: "R", "Database.CouldNotComposeQuery")
906: + " (" + e.getMessage() + ")",
907: TranslationManager.getInstance().getTranslation(
908: "R", "Error.Title"),
909: JOptionPaneHelper.ERROR_MESSAGE,
910: CenterPanelDialog.ModalityType.DOCUMENT_MODAL);
911: } catch (NoSuitableRootException e) {
912: if (LOG.isLoggable(Level.FINE))
913: LOG
914: .log(
915: Level.FINE,
916: "SQLQueryConfigurationPanel.createAutomaticQuery ",
917: e);
918: JOptionPaneHelper.showMessageDialog(this ,
919: TranslationManager.getInstance().getTranslation(
920: "R", "Database.CouldNotComposeQuery")
921: + " (" + e.getMessage() + ")",
922: TranslationManager.getInstance().getTranslation(
923: "R", "Error.Title"),
924: JOptionPaneHelper.ERROR_MESSAGE,
925: CenterPanelDialog.ModalityType.DOCUMENT_MODAL);
926: }
927: sqlQueryTextArea.setText(query);
928: }
929:
930: public void dispose() {
931: if (metaDataService != null) {
932: metaDataService.dispose();
933: }
934: }
935:
936: public void addPropertyChangeListener2(@NotNull
937: PropertyChangeListener listener) {
938: propertyChangeSupport.addPropertyChangeListener(listener);
939: }
940:
941: public void addPropertyChangeListener2(@NotNull
942: String propertyName, @NotNull
943: PropertyChangeListener listener) {
944: propertyChangeSupport.addPropertyChangeListener(propertyName,
945: listener);
946: }
947:
948: public void removePropertyChangeListener2(@NotNull
949: PropertyChangeListener listener) {
950: propertyChangeSupport.removePropertyChangeListener(listener);
951: }
952:
953: public void removePropertyChangeListener2(@NotNull
954: String propertyName, @NotNull
955: PropertyChangeListener listener) {
956: propertyChangeSupport.removePropertyChangeListener(
957: propertyName, listener);
958: }
959:
960: }
|