KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > db > sql > visualeditor > querybuilder > QueryBuilderInputTable


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19 package org.netbeans.modules.db.sql.visualeditor.querybuilder;
20
21 import java.util.ArrayList JavaDoc;
22 import java.util.List JavaDoc;
23
24 import javax.swing.JTable JavaDoc;
25 import javax.swing.JComboBox JavaDoc;
26 import javax.swing.JCheckBox JavaDoc;
27 import javax.swing.DefaultCellEditor JavaDoc;
28 import javax.swing.table.TableCellEditor JavaDoc;
29 import javax.swing.table.TableCellRenderer JavaDoc;
30 import javax.swing.JPopupMenu JavaDoc;
31 import javax.swing.JMenu JavaDoc;
32 import javax.swing.JMenuItem JavaDoc;
33 import javax.swing.JTextField JavaDoc;
34 import javax.swing.table.TableColumn JavaDoc;
35 import javax.swing.table.DefaultTableModel JavaDoc;
36
37 import java.awt.*;
38
39 import java.awt.event.*;
40
41 import org.openide.ErrorManager;
42 import org.openide.util.NbBundle;
43 import org.openide.NotifyDescriptor;
44 import org.openide.DialogDisplayer;
45
46 import org.netbeans.modules.db.sql.visualeditor.Log;
47
48 import org.netbeans.modules.db.sql.visualeditor.querymodel.Column;
49 import org.netbeans.modules.db.sql.visualeditor.querymodel.Where;
50 import org.netbeans.modules.db.sql.visualeditor.querymodel.Predicate;
51 import org.netbeans.modules.db.sql.visualeditor.querymodel.Value;
52 import org.netbeans.modules.db.sql.visualeditor.querymodel.SortSpecification;
53 import org.netbeans.modules.db.sql.visualeditor.querymodel.SQLQueryFactory;
54 import org.netbeans.modules.db.sql.visualeditor.querymodel.OrderBy;
55 import org.netbeans.modules.db.sql.visualeditor.querymodel.Expression;
56 import org.netbeans.modules.db.sql.visualeditor.querymodel.And;
57 import org.netbeans.modules.db.sql.visualeditor.querymodel.ExpressionList;
58 import org.netbeans.modules.db.sql.visualeditor.querymodel.Literal;
59
60 /**
61  *
62  * @author Sanjay Dhamankar, Jim Davidson
63  */

64
65 // One of the panes of the QueryBuilder
66
// The model has columns as laid out by the constants QueryBuilderGraphFrame.
67
// There are 9 columns, of which the most important are
68
// - Column (column name)
69
// - Output (selected status)
70
// - Table (table spec).
71

72 public class QueryBuilderInputTable extends JTable JavaDoc
73     implements ActionListener, ItemListener, KeyListener
74     // , MouseListener
75
{
76     // Constants for offsets into the inputTableModel
77
// These aren't used much; they should probably be defined on the QBInputTableModel class
78

79     public static final int Column_COLUMN = 0;
80     public static final int Alias_COLUMN = 1;
81     public static final int Table_COLUMN = 2;
82     public static final int Output_COLUMN = 3;
83     public static final int SortType_COLUMN = 4;
84     public static final int SortOrder_COLUMN = 5;
85     public static final int Criteria_COLUMN = 6;
86     public static final int CriteriaOrder_COLUMN = 7;
87
88
89     public static final int Column_COLUMN_WIDTH = 140;
90     public static final int Alias_COLUMN_WIDTH = 70;
91     public static final int Table_COLUMN_WIDTH = 180;
92     // this is checkbox, no need to set the width
93
// public static final int Output_COLUMN_WIDTH = 80;
94
public static final int SortType_COLUMN_WIDTH = 80;
95     public static final int SortOrder_COLUMN_WIDTH = 80;
96     public static final int Criteria_COLUMN_WIDTH = 100;
97     public static final int CriteriaOrder_COLUMN_WIDTH = 40;
98
99     public static final String JavaDoc Criteria_Uneditable_String = "*****";
100     public static final String JavaDoc CriteriaOrder_Uneditable_String = "*";
101     // Private variables
102

103     private static final boolean DEBUG = false;
104     private QueryBuilder _queryBuilder;
105     private JPopupMenu JavaDoc _inputTablePopup;
106     private int _inputTablePopupRow;
107     private int _inputTablePopupColumn;
108     private JComboBox JavaDoc _sortOrderComboBox; // this instancevar, not localvar
109
private JComboBox JavaDoc _criteriaOrderComboBox;
110
111     AddQueryParameterDlg _addQueryParameterDlg = null;
112
113
114     // Constructor
115

116     public QueryBuilderInputTable(QueryBuilder queryBuilder) {
117
118         super();
119
120         Log.err.log(ErrorManager.INFORMATIONAL, "Entering QueryBuilderInputTable ctor"); // NOI18N
121

122         _queryBuilder = queryBuilder;
123
124         QueryBuilderInputTableModel queryBuilderInputTableModel = new QueryBuilderInputTableModel();
125
126         super.setModel( queryBuilderInputTableModel );
127
128         TableColumn JavaDoc column = this.getColumnModel().getColumn(Column_COLUMN);
129         column.setPreferredWidth(Column_COLUMN_WIDTH);
130
131         column = this.getColumnModel().getColumn(Alias_COLUMN);
132         column.setPreferredWidth(Alias_COLUMN_WIDTH);
133         column.setCellEditor(new FocusCellEditor(new JTextField JavaDoc()));
134
135         column = this.getColumnModel().getColumn(Table_COLUMN);
136         column.setPreferredWidth(Table_COLUMN_WIDTH);
137
138         column = this.getColumnModel().getColumn(SortType_COLUMN);
139         column.setPreferredWidth(SortType_COLUMN_WIDTH);
140
141         column = this.getColumnModel().getColumn(SortOrder_COLUMN);
142         column.setPreferredWidth(SortOrder_COLUMN_WIDTH);
143
144         column = this.getColumnModel().getColumn(Criteria_COLUMN);
145         column.setPreferredWidth(Criteria_COLUMN_WIDTH);
146         column.setCellEditor(new FocusCellEditor(new JTextField JavaDoc()));
147
148         column = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
149         column.setPreferredWidth(CriteriaOrder_COLUMN_WIDTH);
150
151         this.getColumnModel().getColumn(0).setCellEditor(
152             new FocusCellEditor(new JTextField JavaDoc()));
153
154         final Object JavaDoc[] sortTypeItems = {
155             "",
156             NbBundle.getMessage(QueryBuilderInputTable.class, "ASCENDING"), // NOI18N
157
NbBundle.getMessage(QueryBuilderInputTable.class, "DESCENDING") // NOI18N
158
};
159         TableColumn JavaDoc sortTypeColumn = this.getColumnModel().getColumn(SortType_COLUMN);
160         JComboBox JavaDoc sortTypeComboBox = new JComboBox JavaDoc(sortTypeItems);
161         sortTypeColumn.setCellEditor(new DefaultCellEditor JavaDoc(sortTypeComboBox));
162         sortTypeComboBox.addItemListener(this);
163
164         final Object JavaDoc[] sortOrderItems = {""}; // NOI18N
165
TableColumn JavaDoc sortOrderColumn = this.getColumnModel().getColumn(SortOrder_COLUMN);
166         _sortOrderComboBox = new JComboBox JavaDoc(sortOrderItems);
167         sortOrderColumn.setCellEditor(new DefaultCellEditor JavaDoc(_sortOrderComboBox));
168         _sortOrderComboBox.addItemListener(this);
169
170         final Object JavaDoc[] criteriaOrderItems = {""}; // NOI18N
171
TableColumn JavaDoc criteriaOrderColumn = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
172         _criteriaOrderComboBox = new JComboBox JavaDoc(criteriaOrderItems);
173         criteriaOrderColumn.setCellEditor(new DefaultCellEditor JavaDoc(_criteriaOrderComboBox));
174 // _criteriaOrderComboBox.addItemListener(this);
175

176         this.setAutoResizeMode (JTable.AUTO_RESIZE_OFF);
177         _inputTablePopup = createInputTablePopup();
178         MouseListener inputTablePopupListener = new InputTablePopupListener();
179         super.addMouseListener(inputTablePopupListener);
180         this.setMinimumSize(new Dimension (200, 200) );
181         this.setBackground(Color.white);
182         this.getTableHeader().setReorderingAllowed (false);
183
184         addKeyListener(this);
185
186 // this.getModel().addTableModelListener(this);
187

188 // Listen for checkbox selections in output column; handled by tableChange event instead
189
// TableColumn outputColumn = this.getColumnModel().getColumn(Output_COLUMN);
190
// JCheckBox outputCheckBox = new JCheckBox();
191
// outputColumn.setCellEditor(new DefaultCellEditor(outputCheckBox));
192
// outputCheckBox.addItemListener(this);
193
}
194
195     // cell editor to handle focus lost events on particular
196
// cells.
197
private class FocusCellEditor extends DefaultCellEditor JavaDoc {
198         Component c;
199         public FocusCellEditor(JTextField JavaDoc jtf) {
200             super(jtf);
201             addFocusListener(jtf);
202         }
203         private void addFocusListener(Component C) {
204             super.getComponent().addFocusListener(new java.awt.event.FocusAdapter JavaDoc() {
205             public void focusLost(java.awt.event.FocusEvent JavaDoc fe) { lostFocus(); }
206         });
207         }
208         public void lostFocus() {
209             stopCellEditing();
210         }
211     }
212
213
214     /** ignore */
215     public void keyTyped(KeyEvent e) {
216     }
217
218     /** ignore */
219     public void keyReleased(KeyEvent e) {
220     }
221
222     /** Handle the key pressed event and change the focus if a particular
223      * key combination is pressed. */

224     public void keyPressed(KeyEvent e) {
225         if( e.isShiftDown() ) {
226              int code = e.getKeyCode();
227              switch(code) {
228                  // diagram pane
229
case KeyEvent.VK_F10:
230                     JTable JavaDoc source = (JTable JavaDoc)(e.getSource());
231
232                     if (DEBUG)
233                         System.out.println( "QBIT : keyPressed called Shift+F10 Down source.isEnabled() returns : " + source.isEnabled() + "\n" );
234
235                     if ( ! source.isEnabled () ) return;
236
237                     // _inputTablePopupRow = source.getEditingRow();
238
_inputTablePopupRow = source.getSelectedRow();
239                     _inputTablePopupColumn = source.getEditingColumn();
240                     if (_inputTablePopupColumn == (Criteria_COLUMN-1)) {
241                         source.setEditingColumn(Column_COLUMN);
242                     }
243         if (DEBUG)
244             System.out.println( "QBIT : keyPressed called\n"
245                     + " inputTablePopupRow = " + _inputTablePopupRow // NOI18N
246
+ " inputTablePopupColumn == Criteria_COLUMN " + (_inputTablePopupRow == Criteria_COLUMN ) // NOI18N
247
+ " inputTablePopupColumn = " + _inputTablePopupColumn ); // NOI18N
248
// Make sure the row where click occurred is selected.
249
if (_inputTablePopupRow != -1) {
250                         source.setRowSelectionInterval (_inputTablePopupRow,
251                                                         _inputTablePopupRow);
252                     }
253                     _inputTablePopup.show ( source, source.getWidth() / 2,
254                                                     source.getHeight() / 2 );
255                     break;
256              }
257         }
258         _queryBuilder.handleKeyPress(e);
259     }
260
261     JComboBox JavaDoc getSortOrderComboBox () {
262         return _sortOrderComboBox; // this instancevar, not localvar
263
}
264
265     JComboBox JavaDoc getCriteriaOrderComboBox () {
266         return _criteriaOrderComboBox;
267     }
268
269     JPopupMenu JavaDoc createInputTablePopup()
270     {
271         JPopupMenu JavaDoc inputTablePopup;
272         JMenu JavaDoc menu, subMenu;
273         JMenuItem JavaDoc menuItem;
274         JMenuItem JavaDoc subMenuItem;
275
276         //Create the popup menu.
277
inputTablePopup = new JPopupMenu JavaDoc();
278
279         // remove for time being to avoid confusion.
280
/*
281           menuItem = new JMenuItem("Run Query");
282           menuItem.addActionListener(this);
283           inputTablePopup.add(menuItem);
284         */

285
286         menuItem = new JMenuItem JavaDoc(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_QUERY_CRITERIA")); // NOI18N
287
menuItem.addActionListener(this);
288         inputTablePopup.add(menuItem);
289
290 /*
291         menuItem = new JMenuItem(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_AND_QUERY_CRITERIA")); // NOI18N
292         menuItem.addActionListener(this);
293         inputTablePopup.add(menuItem);
294
295         menuItem = new JMenuItem(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_OR_QUERY_CRITERIA")); // NOI18N
296         menuItem.addActionListener(this);
297         inputTablePopup.add(menuItem);
298 */

299
300 // menuItem = new JMenuItem(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_SORT_SPECIFICATION"));
301
// menuItem.addActionListener(this);
302
// inputTablePopup.add(menuItem);
303

304         /*
305         menuItem = new JMenuItem(
306             NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_CUT") );
307         menuItem.addActionListener(this);
308         inputTablePopup.add(menuItem);
309
310         menuItem = new JMenuItem ( NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_COPY") );
311         menuItem.addActionListener(this);
312         inputTablePopup.add(menuItem);
313
314         menuItem = new JMenuItem ( NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_PASTE") );
315         menuItem.addActionListener(this);
316         inputTablePopup.add(menuItem);
317
318         menuItem = new JMenuItem ( NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_DELETE") );
319         menuItem.addActionListener(this);
320         inputTablePopup.add(menuItem);
321
322         menuItem = new JMenuItem ( NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_GROUP_BY") );
323         menuItem.addActionListener(this);
324         inputTablePopup.add(menuItem);
325
326         menuItem = new JMenuItem ( NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_CHANGE_TYPE") );
327         menuItem.addActionListener(this);
328         inputTablePopup.add(menuItem);
329
330         menuItem = new JMenuItem ( NbBundle.getMessage(QueryBuilderInputTable.class, "INPUT_TABLE_COLLAPSE_PANE") );
331         menuItem.addActionListener(this);
332         inputTablePopup.add(menuItem);
333 */

334 // menuItem = new JMenuItem("Properties");
335
// menuItem.addActionListener(this);
336
// inputTablePopup.add(menuItem);
337

338         return ( inputTablePopup );
339     }
340
341
342     // Inner classes for handling events
343

344
345     // Mouse listener -- bring up background menu
346
class InputTablePopupListener extends MouseAdapter {
347         public void mousePressed(MouseEvent e) {
348             JTable JavaDoc source = (JTable JavaDoc)(e.getSource());
349
350             maybeShowPopup(e);
351         }
352
353         public void mouseReleased(MouseEvent e) {
354             mousePressed(e);
355         }
356
357         private void maybeShowPopup(MouseEvent e) {
358             if (e.isPopupTrigger()) {
359                 JTable JavaDoc source = (JTable JavaDoc)(e.getSource());
360
361                 if ( ! source.isEnabled () ) return;
362
363                 _inputTablePopupRow =
364                         source.rowAtPoint(new Point (e.getX(), e.getY()));
365                 _inputTablePopupColumn =
366                         source.columnAtPoint(new Point (e.getX(), e.getY()));
367                 // Make sure the row where click occurred is selected.
368
if (_inputTablePopupRow != -1) {
369                     source.setRowSelectionInterval (_inputTablePopupRow,
370                                                     _inputTablePopupRow);
371                 }
372 // if ( _inputTablePopupColumn != Criteria_COLUMN )
373
// {
374
// // return without showing popup
375
// return;
376
// }
377

378                 _inputTablePopup.show(e.getComponent(), e.getX(), e.getY());
379             }
380         }
381     }
382
383
384     // Specified by ActionListener.
385
// Respond to menu selections. The only menu item currently supported is "Add Criteria".
386

387     public void actionPerformed(ActionEvent e) {
388
389         JMenuItem JavaDoc source = (JMenuItem JavaDoc)(e.getSource());
390
391         if (source.getText().equals(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_QUERY_CRITERIA"))) // NOI18N
392
{
393             // Bring up a dialog for adding a query parameter, and update the table with the result
394
_addQueryParameterDlg =
395                 new AddQueryParameterDlg(true, (String JavaDoc)(this.getValueAt(getSelectedRow(), Column_COLUMN)));
396
397         if (DEBUG)
398             System.out.println( "QBIT : actionPerformed called\n_addQueryParameterDlg returns : " + (_addQueryParameterDlg.getReturnStatus() == AddQueryParameterDlg.RET_OK) ); // NOI18N
399

400             if ( _addQueryParameterDlg.getReturnStatus() == AddQueryParameterDlg.RET_OK )
401             {
402                 // Suppress bogus text regeneration
403
_queryBuilder._updateText=false;
404                 try {
405                 
406                     // Split the string on " "
407
String JavaDoc result = (String JavaDoc)(_addQueryParameterDlg.getCriteria());
408         if (DEBUG)
409             System.out.println( "QBIT : actionPerformed called\nresult " + result + " length : " + (result.trim().length() ) + " inputTablePopupRow = " + _inputTablePopupRow + " inputTablePopupColumn = " + _inputTablePopupColumn ); // NOI18N); // NOI18N
410

411                     if ( result.trim().length() == 0 )
412                         return;
413
414                     this.getCellEditor ( _inputTablePopupRow, Criteria_COLUMN ).stopCellEditing();
415
416                     // this.setValueAt ( result, _inputTablePopupRow, _inputTablePopupColumn );
417
this.setValueAt ( result, _inputTablePopupRow, Criteria_COLUMN );
418                 }
419                 finally {
420                     _queryBuilder._updateText=true;
421                 }
422
423                 // Now regenerate the text query
424
_queryBuilder.generateText();
425             }
426         }
427         else if (source.getText().equals(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_AND_QUERY_CRITERIA"))) // NOI18N
428
{
429             int row=getSelectedRow();
430             String JavaDoc tableSpec=(String JavaDoc)this.getValueAt(row,Table_COLUMN);
431             String JavaDoc columnName=(String JavaDoc)this.getValueAt(row,Column_COLUMN);
432             String JavaDoc result0 = (String JavaDoc) this.getValueAt ( _inputTablePopupRow, _inputTablePopupColumn );
433             if ( _queryBuilder._queryModel.getWhere() == null ) {
434                 String JavaDoc msg = NbBundle.getMessage(QueryBuilderInputTable.class, "EMPTY_QUERY_CRITERIA");
435                 NotifyDescriptor d =
436                     new NotifyDescriptor.Message(msg + "\n\n", NotifyDescriptor.ERROR_MESSAGE); // NOI18N
437
DialogDisplayer.getDefault().notify(d);
438                 return;
439             }
440
441             Column JavaDoc col = _queryBuilder._queryModel.findSelectColumn(tableSpec, columnName);
442             String JavaDoc derColName = col.getDerivedColName();
443
444             // add a row identical to the current row
445
Object JavaDoc[] rowData = {
446                 (columnName.equals("* { All Columns }")) ? "*" : columnName, // * or column name // NOI18N
447
(derColName==null) ? "" : derColName, // derived col name (not corrName) // NOI18N
448
tableSpec, // tableSpec
449
Boolean.TRUE, // output: true = selected
450
"", // sort type // NOI18N
451
"", // sort order // NOI18N
452
"", // criteria // NOI18N
453
"", // criteria order // NOI18N
454
/* "", "", "" */ }; // or... // NOI18N
455

456
457             _addQueryParameterDlg =
458                 new AddQueryParameterDlg(true, (String JavaDoc)(this.getValueAt(getSelectedRow(), Column_COLUMN)));
459
460             if ( _addQueryParameterDlg.getReturnStatus() == AddQueryParameterDlg.RET_OK )
461             {
462                 ((DefaultTableModel JavaDoc)this.getModel()).insertRow ( row+1, rowData );
463                 // Bring up a dialog for adding a query parameter, and update the table with the result
464
this.setRowSelectionInterval (row+1, row+1);
465                 // Split the string on " "
466
String JavaDoc result = (String JavaDoc)(_addQueryParameterDlg.getCriteria());
467
468                 if ( result.trim().length() == 0 ) return;
469
470                 if (DEBUG)
471                 System.out.println(
472                         " Table Row = " + row +
473                         " Table = " + tableSpec +
474                         " Column = " + columnName +
475                         " Result = " + result
476                         + "\n" ); // NOI18N
477
// Also need to update the Query Model with the new condition
478

479                 this.setValueAt ( result, getSelectedRow(), Criteria_COLUMN );
480
481                 int i = result.indexOf(" "); // NOI18N
482
String JavaDoc op = result.substring(0, i);
483                 String JavaDoc val = result.substring(i+1);
484                 
485                 // Also need to update the Query Model with the new condition
486

487                 Column JavaDoc col1 = SQLQueryFactory.createColumn(tableSpec, columnName);
488                 Literal lit2 = new Literal(val);
489                 Predicate pred = SQLQueryFactory.createPredicate(col1, lit2, op);
490
491                 _queryBuilder._queryModel.addOrCreateAndExpression(pred);
492
493                 // And regenerate the text query
494
_queryBuilder.generateText();
495             }
496         }
497         else if (source.getText().equals(NbBundle.getMessage(QueryBuilderInputTable.class, "ADD_OR_QUERY_CRITERIA"))) // NOI18N
498
{
499             int row=getSelectedRow();
500             String JavaDoc tableSpec=(String JavaDoc)this.getValueAt(row,Table_COLUMN);
501             String JavaDoc columnName=(String JavaDoc)this.getValueAt(row,Column_COLUMN);
502             String JavaDoc result0 = (String JavaDoc) this.getValueAt ( _inputTablePopupRow, _inputTablePopupColumn );
503             if ( _queryBuilder._queryModel.getWhere() == null ) {
504                 String JavaDoc msg = NbBundle.getMessage(QueryBuilderInputTable.class, "EMPTY_QUERY_CRITERIA");
505                 NotifyDescriptor d =
506                     new NotifyDescriptor.Message(msg + "\n\n", NotifyDescriptor.ERROR_MESSAGE); // NOI18N
507
DialogDisplayer.getDefault().notify(d);
508                 return;
509             }
510
511             Column JavaDoc col = _queryBuilder._queryModel.findSelectColumn(tableSpec, columnName);
512             String JavaDoc derColName = col.getDerivedColName();
513
514             // add a row identical to the current row
515
Object JavaDoc[] rowData = {
516                 (columnName.equals("* { All Columns }")) ? "*" : columnName, // * or column name // NOI18N
517
(derColName==null) ? "" : derColName, // derived col name (not corrName) // NOI18N
518
tableSpec, // tableSpec
519
Boolean.TRUE, // output: true = selected
520
"", // sort type // NOI18N
521
"", // sort order // NOI18N
522
"", // criteria // NOI18N
523
"" // criteria order // NOI18N
524
/* "", "", "" */ }; // or... // NOI18N
525

526
527             _addQueryParameterDlg =
528                 new AddQueryParameterDlg(true, (String JavaDoc)(this.getValueAt(getSelectedRow(), Column_COLUMN)));
529
530             if ( _addQueryParameterDlg.getReturnStatus() == AddQueryParameterDlg.RET_OK )
531             {
532                 ((DefaultTableModel JavaDoc)this.getModel()).addColumn ("Or..." );
533                 int orColumn = ((DefaultTableModel JavaDoc)this.getModel()).getColumnCount ();
534                 ((DefaultTableModel JavaDoc)this.getModel()).addColumn ("Order" );
535                 // Bring up a dialog for adding a query parameter, and update the table with the result
536
// Split the string on " "
537
String JavaDoc result = (String JavaDoc)(_addQueryParameterDlg.getCriteria());
538
539                 if ( result.trim().length() == 0 ) return;
540
541                 if (DEBUG)
542                 System.out.println(
543                         " OR called \n " +
544                         " Table Row = " + row +
545                         " Table = " + tableSpec +
546                         " Column = " + columnName +
547                         " orColumn = " + orColumn +
548                         " Result = " + result
549                         + "\n" ); // NOI18N
550
// Also need to update the Query Model with the new condition
551

552                 ((DefaultTableModel JavaDoc)this.getModel()).setValueAt ( result, row, orColumn-1);
553
554                 int i = result.indexOf(" "); // NOI18N
555
String JavaDoc op = result.substring(0, i);
556                 String JavaDoc val = result.substring(i+1);
557
558                 // Also need to update the Query Model with the new condition
559

560                 Column JavaDoc col1 = SQLQueryFactory.createColumn(tableSpec, columnName);
561                 Literal lit2 = new Literal(val);
562                 Predicate pred = SQLQueryFactory.createPredicate(col1, lit2, op);
563
564                 _queryBuilder._queryModel.addOrCreateOrExpression(pred);
565
566                 // And regenerate the text query
567
_queryBuilder.generateText();
568             }
569         }
570     }
571
572
573     // Specified by ItemListener
574
// Detects menu selections for the sort menus
575
// Also detects changes to checkbox for output status
576

577     public void itemStateChanged (ItemEvent e) {
578
579         int row=getSelectedRow();
580
581         if (DEBUG)
582             System.out.println( "QBIT : itemStateChanged called\nTable Row: " + row + // NOI18N
583
" Item: " + e.getItem() + " Item Selectable: " + e.getItemSelectable()); // NOI18N
584

585         if (_queryBuilder._updateModel &&
586              (row!=-1) &&
587              (e.getStateChange() == ItemEvent.SELECTED))
588         {
589             // Save the value of _updateText
590
boolean updateText = _queryBuilder._updateText;
591             _queryBuilder._updateText=false;
592             try {
593                 String JavaDoc item= (String JavaDoc)e.getItem();
594                 String JavaDoc tableSpec= (String JavaDoc)(getValueAt(row, Table_COLUMN));
595                 String JavaDoc columnName= (String JavaDoc)(getValueAt(row, Column_COLUMN));
596                 int sortCount= _queryBuilder._queryModel.getSortCount();
597
598                 if (item.equals("")) { // NOI18N
599
// This could come from either SortOrder or SortType
600
// Action is the same in either case -- remove sort spec
601
setValueAt("", row, SortType_COLUMN); // NOI18N
602
setValueAt("", row, SortOrder_COLUMN); // NOI18N
603
_queryBuilder._queryModel.
604                         removeSortSpecification(tableSpec, columnName);
605                 }
606
607                 else if ( item.equals("ASC") || // NOI18N
608
item.equals ( NbBundle.getMessage(QueryBuilderInputTable.class, "ASCENDING") ) ) // NOI18N
609
{
610                     // Sort Type specification
611
String JavaDoc order = (String JavaDoc)getValueAt(row, SortOrder_COLUMN);
612                     int orderNum = order.equals("") ? sortCount+1 : Integer.parseInt(order); // NOI18N
613
_queryBuilder._queryModel.
614                         addSortSpecification(tableSpec, columnName, "ASC", orderNum);
615                 }
616                 else if ( item.equals("DESC") || // NOI18N
617
item.equals ( NbBundle.getMessage(QueryBuilderInputTable.class, "DESCENDING") ) ) // NOI18N
618
{
619                     // Sort Type specification
620
String JavaDoc order = (String JavaDoc)getValueAt(row, SortOrder_COLUMN);
621                     int orderNum = order.equals("") ? sortCount+1 : Integer.parseInt(order); // NOI18N
622
_queryBuilder._queryModel.
623                         addSortSpecification(tableSpec, columnName, "DESC", orderNum);
624                 } else {
625                     // Must be a Sort Order specification
626
String JavaDoc type=(String JavaDoc)getValueAt(row, SortType_COLUMN);
627                     int orderNum = Integer.parseInt(item);
628                     if (!type.equals("")) { // NOI18N
629
// this implies that the type is either Ascending or
630
// Descending ( I18N ) string.
631
String JavaDoc sortType = new String JavaDoc ("ASC");
632                         if (type.equals ( NbBundle.getMessage(QueryBuilderInputTable.class, "DESCENDING") ) ) { // NOI18N
633
sortType = new String JavaDoc ("DESC");
634                         }
635                         // When the user clicks in the Sort Order column for
636
// a query column that's already sorted, he should
637
// not be allowed to select the N+1 case.
638
// add sort specifcation only if the selected value is
639
// less than sort count.
640
if ( orderNum <= sortCount ) {
641                             _queryBuilder._queryModel.
642                                 addSortSpecification(tableSpec, columnName, sortType, orderNum);
643                         }
644                     }
645                     // 5064209 Order By is difficult to use - can't enter
646
// "sort order" without "
647
else {
648                         _queryBuilder._queryModel.
649                             addSortSpecification(tableSpec, columnName, "ASC", orderNum); // NOI18N
650
}
651                 }
652
653                 // Important. Without this, we generate bogus events on active row
654
clearSelection();
655                 
656                 // Update the InputTable from scratch, in any case
657
// This will also update the sortOrder dropdown
658
generateTableOrderBy(_queryBuilder._queryModel);
659             }
660             finally {
661                 // Restore the value of updateText
662
_queryBuilder._updateText=updateText;
663             }
664                     
665             // And regenerate the text query if we're not driven by someone else
666
if (_queryBuilder._updateText)
667                 _queryBuilder.generateText();
668         }
669     }
670
671
672     void selectColumn(String JavaDoc tableSpec, String JavaDoc columnName, Boolean JavaDoc select) {
673         int row = findRow(tableSpec, columnName);
674         if (row == -1)
675             return;
676         if ((select==Boolean.TRUE) &&
677                               (getValueAt(row,Output_COLUMN)!=Boolean.TRUE))
678                 setValueAt(Boolean.TRUE,row,Output_COLUMN);
679         else if ((select==Boolean.FALSE) &&
680                               (getValueAt(row,Output_COLUMN)!=Boolean.FALSE))
681                 setValueAt(Boolean.FALSE,row,Output_COLUMN);
682     }
683
684     // Add a row to the InputTable, or mark an existing row for output
685

686     void addRow(String JavaDoc tableSpec, String JavaDoc columnName) {
687         
688         if (DEBUG)
689             System.out.println("QBIT.addRow, tableSpec: "+tableSpec + " columnName: "+columnName); //NOI18N
690

691     // We used to have an existence check here, which may have been intended to break
692
// event loops between the two tables; we may need to reinstate that.
693

694         // Check whether this column is already represented by a row in the table
695
int i = findRow(tableSpec, columnName);
696         if (i!=-1) {
697
698             // Found an existing row; mark for output
699
if (this.getValueAt(i, Output_COLUMN)!=Boolean.TRUE)
700                 this.setValueAt(Boolean.TRUE, i, Output_COLUMN);
701
702         } else {
703         
704             // Temporary hack -- find the select column in the model, and see if there's a derived name
705
// This will go away once we start updating the table independent of the graph
706
Column JavaDoc col = _queryBuilder._queryModel.findSelectColumn(tableSpec, columnName);
707             String JavaDoc derColName = null;
708             if ( col != null )
709                 derColName = col.getDerivedColName();
710
711             // Note that all the operations below will cause new events to be fired
712
// by the inputTableModel. So, we get the rowData set up the way we want it,
713
// and do the entire insertion as a single event
714
Object JavaDoc[] rowData = {
715                 (columnName.equals("* { All Columns }")) ? "*" : columnName, // * or column name // NOI18N
716
(derColName==null) ? "" : derColName, // derived col name (not corrName) // NOI18N
717
tableSpec, // tableSpec
718
Boolean.TRUE, // output: true = selected
719
"", // sort type // NOI18N
720
"", // sort order // NOI18N
721
"", // criteria // NOI18N
722
"" // criteria order // NOI18N
723
/* "", "", "" */ }; // or... // NOI18N
724

725             // Add the new row to the table
726
((DefaultTableModel JavaDoc)dataModel).addRow(rowData);
727
728         }
729     }
730
731
732     // Remove the row that matches this tableSpec and columnName, if any
733
// There should be only one
734
// Only remove the row if none of the other columns are non-empty
735
void removeRow(String JavaDoc tableSpec, String JavaDoc columnName) {
736
737         // Iterate through the current columns
738
// ToDo: see if we should iterate back to front for stability
739
for (int i=0; i < this.getRowCount(); i++) {
740
741             // First check for match on tablename
742
if (this.getValueAt(i, Table_COLUMN).equals(tableSpec)) {
743
744                 // Now check for match on column
745
if (this.getValueAt(i, Column_COLUMN).equals(columnName))
746                 {
747                     // We have found the row to update.
748

749                     // This handles the corner case where it appears in a sort specification
750
// (requires some cleanup afterwards)
751
boolean sortOrderRow =
752                         ! (((String JavaDoc)this.getValueAt(i,SortType_COLUMN)).trim().equals("") && // NOI18N
753
((String JavaDoc)this.getValueAt(i,SortOrder_COLUMN)).trim().equals("")); // NOI18N
754

755                     // If this row also has a sort spec, clear the two cells; not a common corner
756
if (sortOrderRow) {
757                         setValueAt("", i, SortType_COLUMN); // NOI18N
758
setValueAt("", i, SortOrder_COLUMN);
759                     }// NOI18N
760

761                     // If all of the other important columns are empty, we can remove the row
762
if (((String JavaDoc)this.getValueAt(i,CriteriaOrder_COLUMN)).trim().equals("") && // NOI18N
763
((String JavaDoc)this.getValueAt(i,Criteria_COLUMN)).trim().equals("")) // NOI18N
764
{
765                         ((DefaultTableModel JavaDoc)this.getModel()).removeRow(i);
766                     }
767                     else {
768                         // If it's still in use, just mark it as non-selected
769
if (this.getValueAt(i, Output_COLUMN)!=Boolean.FALSE)
770                             this.setValueAt(Boolean.FALSE, i, Output_COLUMN);
771                     }
772                     
773                     // If we changed the overall sort ordering, clean up
774
if (sortOrderRow)
775                         generateTableOrderBy(_queryBuilder._queryModel);
776                 }
777                 /*
778                 if ((this.getValueAt(i, Column_COLUMN).equals(columnName)) ||
779                     ((columnName.equals("* { All Columns }")) &&
780                      (this.getValueAt(i, Column_COLUMN).equals("*"))))
781                 {
782                     // Check that none of the other columns are non-empty
783                     if (this.getValueAt(i,SortType_COLUMN).equals("") &&
784                         this.getValueAt(i,SortOrder_COLUMN).equals("") &&
785                         this.getValueAt(i,Criteria_COLUMN).equals(""))
786                     {
787                         // Remove the row
788                         ((DefaultTableModel)this.getModel()).removeRow(i);
789                     }
790                     else {
791                         // Just mark it as non-selected
792                         if (this.getValueAt(i, Output_COLUMN)!=Boolean.FALSE)
793                             this.setValueAt(Boolean.FALSE, i, Output_COLUMN);
794                     }
795                 }
796                 */

797             }
798         }
799     }
800
801
802     // Remove the rows that refer to this tableSpec
803

804     void removeRows(String JavaDoc tableSpec) {
805
806         Log.err.log(ErrorManager.INFORMATIONAL, "Entering removeRows, tableSpec: " + tableSpec); // NOI18N
807

808         for (int i=this.getRowCount()-1; i>=0; i--) {
809             if (this.getValueAt(i, Table_COLUMN).equals(tableSpec)) {
810                 ((DefaultTableModel JavaDoc)this.getModel()).removeRow(i);
811             }
812         }
813     }
814
815
816     // Add a criterion or parameter to the table. Does not update the Model.
817

818     void addCriterion(String JavaDoc tableSpec, String JavaDoc columnName, String JavaDoc val, String JavaDoc order) {
819         
820         if (DEBUG) {
821             System.out.println(
822                     "Entering QueryBuilderInputTable.addCriterion, tableSpec: " + tableSpec // NOI18N
823
+ " columnName: "+columnName + " val: "+val + "Order: " + order + "\n"); // NOI18N
824
}
825         Log.err.log(ErrorManager.INFORMATIONAL,
826                     "Entering QueryBuilderInputTable.addCriterion, tableSpec: " + tableSpec // NOI18N
827
+ " columnName: " + columnName + " val: " + val); // NOI18N
828

829         // Get the Table object representing this table
830
// ITable tbl = _queryBuilder._queryModel.findTable(tableSpec);
831
// String tableName = tbl.getTableName();
832
// String corrName = tbl.getCorrName();
833

834         // search for the column (row) in the table
835
boolean foundIt=false;
836         int row = 0;
837         for (int i=0; i<this.getRowCount(); i++) {
838             if (((String JavaDoc)this.getValueAt(i, Table_COLUMN)).equals(tableSpec) &&
839                 ((String JavaDoc)this.getValueAt(i, Column_COLUMN)).equals(columnName))
840 // && ((corrName==null) || ((String)this.getValueAt(i, Alias_COLUMN)).equals(corrName)))
841
{
842                 // Found it -- modify the row
843
foundIt=true;
844                 row = i;
845                 if ( ! this.getValueAt( i, Criteria_COLUMN ).equals (
846                          Criteria_Uneditable_String ) ) {
847                     this.setValueAt(val, i, Criteria_COLUMN );
848                     this.setValueAt(order, i, CriteriaOrder_COLUMN );
849                     break;
850                 }
851             }
852             /*
853             else {
854                 this.setValueAt("", i, Criteria_COLUMN ); // NOI18N
855                 this.setValueAt("", i, CriteriaOrder_COLUMN ); // NOI18N
856             }
857             */

858         }
859                         
860         Object JavaDoc[] rowData = { columnName,
861                              "", // derived col name
862
tableSpec,
863                              Boolean.FALSE, "", "", // NOI18N
864
val, // the new criterion/parameter
865
order
866                              /* "", "", "" */ }; // NOI18N
867

868         if (!foundIt) {
869             // Not there -- add a new row
870
((DefaultTableModel JavaDoc)this.getModel()).addRow(rowData);
871         }
872         /*
873         else {
874             ((DefaultTableModel)this.getModel()).insertRow(row+1,rowData);
875
876         }
877          */

878     }
879
880
881     // Generate InputTable entries from criteria information in the WHERE clause
882
// Does not update the model
883

884     void generateTableWhere (QueryModel query) {
885
886         if (DEBUG)
887             System.out.println(
888                 "Entering QueryBuilderInputTable.generateTableWhere"); // NOI18N
889

890         boolean needsCriteriaOrder = false;
891         int criteriaCount=0;
892         String JavaDoc[] criteriaOrderItems = null;
893         Where where=query.getWhere();
894         if (where!=null) {
895
896             // Iterate through the where condition list
897
// For each one
898
// - get the tableSpec.columnName
899
// - find it in the list, and update the criteria column
900
// - if not found, insert a row (shouldn't happen)
901
Expression expr = where.getExpression();
902             if (expr != null) {
903                 criteriaCount = 1; // there is something, if it's not an AND it's a 1 expression item in terms of criteria count
904
if (expr instanceof Predicate) {
905                     needsCriteriaOrder = true;
906                     generatePredicateInTableWhere((Predicate)expr, 0, needsCriteriaOrder);
907                 }
908                 else if (expr instanceof And) {
909                     needsCriteriaOrder = true;
910                     ExpressionList andExpr = (ExpressionList)expr;
911                     criteriaCount=andExpr.size();
912                     for (int i=0; i<criteriaCount; i++) {
913                         expr = andExpr.getExpression(i);
914                         if (expr instanceof Predicate) {
915                             Predicate pred = (Predicate)expr;
916                             generatePredicateInTableWhere(pred, i, needsCriteriaOrder);
917                         }
918                     }
919                 }
920             }
921         }
922
923         // Update the Criteria Order combobox if necessary
924
//if (_criteriaOrderComboBox.getItemCount() != criteriaCount+1) {
925
criteriaOrderItems = new String JavaDoc[criteriaCount+1];
926             criteriaOrderItems[0]=""; // NOI18N
927
TableColumn JavaDoc criteriaOrderColumn = this.getColumnModel().getColumn(CriteriaOrder_COLUMN);
928             if (needsCriteriaOrder) {
929                 for (int i=0; i<criteriaCount; i++)
930                     criteriaOrderItems[i+1]=String.valueOf(i+1);
931             }
932             _criteriaOrderComboBox = new JComboBox JavaDoc(criteriaOrderItems);
933             criteriaOrderColumn.setCellEditor(new DefaultCellEditor JavaDoc(_criteriaOrderComboBox));
934             // _criteriaOrderComboBox.addItemListener(this);
935
//}
936
}
937
938     private void generatePredicateInTableWhere (Predicate pred, int order, boolean needsCriteriaOrder) {
939         Value val1 = pred.getVal1();
940         Value val2 = pred.getVal2();
941
942         // Assume that the right hand side is a literal value
943
// This will result in an entry into the InputTable
944
String JavaDoc marker = pred.getVal2().toString();
945
946         // Treat this like any other literal value now
947
// if (marker.equals("?")) {}
948

949         // We can only count on the tableSpec; tableName might
950
// contain corrName
951
if ( (val1 instanceof Column JavaDoc) && !(val2 instanceof Column JavaDoc) ) {
952             Column JavaDoc col = (Column JavaDoc)val1;
953             String JavaDoc tableSpec=col.getTableSpec();
954             String JavaDoc columnName=col.getColumnName();
955             // Create the value that we're going to put into the table
956
String JavaDoc val = pred.getOp() + " " + marker; // NOI18N
957

958             int row = findRow(tableSpec, columnName);
959             if (row!=-1) {
960                 setValueAt(val, row, Criteria_COLUMN);
961                 if (needsCriteriaOrder)
962                     setValueAt(String.valueOf(order+1), row, CriteriaOrder_COLUMN);
963             }
964         }
965     }
966
967     // Generate any table entries that are specified in the Orderby clause -- sort specifications
968

969     void generateTableOrderBy (QueryModel query) {
970
971         OrderBy orderBy=query.getOrderBy();
972         if (orderBy!=null) {
973
974             // Iterate through the sortSpecificationList
975
// For each one
976
// - get the tableSpec.columnName
977
// - find it in the list, and update the sort column
978
// - if not found, insert a row (shouldn't happen)
979
int size=orderBy.getSortSpecificationCount();
980             for (int i=0; i<size; i++) {
981                 SortSpecification sortSpec = orderBy.getSortSpecification(i);
982                 int row = findRow(sortSpec.getColumn().getTableSpec(), sortSpec.getColumn().getColumnName());
983                 if (row!=-1) {
984                     // Fix for 5081347
985
// I18N - setting sort type in another row causes existing
986
// sort type's change
987
if ( sortSpec.getDirection().equals("ASC") ) {
988                         setValueAt (
989                             ( NbBundle.getMessage(QueryBuilderInputTable.class,
990                                                 "ASCENDING") ) , // NOI18N
991
row, SortType_COLUMN );
992                     }
993                     else if ( sortSpec.getDirection().equals("DESC") ) {
994                         setValueAt (
995                             ( NbBundle.getMessage(QueryBuilderInputTable.class,
996                                                 "DESCENDING") ) , // NOI18N
997
row, SortType_COLUMN );
998
999                     }
1000                    setValueAt(String.valueOf(i+1), row, SortOrder_COLUMN);
1001                }
1002            }
1003        }
1004
1005        // Update the Sort Order combobox if necessary
1006
// Changed to fix
1007
// 5064209 Order By is difficult to use - can't enter "sort order"
1008
// without "
1009
int sortCount=_queryBuilder._queryModel.getSortCount();
1010        if ( sortCount < this.getRowCount() ) {
1011                sortCount += 1;
1012        }
1013        if (_sortOrderComboBox.getItemCount() != sortCount+1) {
1014            final String JavaDoc[] sortOrderItems = new String JavaDoc[sortCount+1];
1015            sortOrderItems[0]=""; // NOI18N
1016
for (int i=1; i<sortCount+1; i++)
1017                sortOrderItems[i]=String.valueOf(i);
1018            TableColumn JavaDoc sortOrderColumn = this.getColumnModel().getColumn(SortOrder_COLUMN);
1019            _sortOrderComboBox = new JComboBox JavaDoc(sortOrderItems);
1020            sortOrderColumn.setCellEditor(new DefaultCellEditor JavaDoc(_sortOrderComboBox));
1021            _sortOrderComboBox.addItemListener(this);
1022        }
1023    }
1024
1025
1026    // Find the row that describes this column
1027
private int findRow(String JavaDoc tableSpec, String JavaDoc columnName)
1028    {
1029        for (int i=0; i<this.getRowCount(); i++) {
1030            if ((this.getValueAt(i, Table_COLUMN).equals(tableSpec)) &&
1031                (this.getValueAt(i, Column_COLUMN).equals(columnName)))
1032                return i;
1033        }
1034        return -1;
1035    }
1036        
1037        
1038    // Returns just the class name -- no package info.
1039

1040    protected String JavaDoc getClassName(Object JavaDoc o) {
1041        String JavaDoc classString = o.getClass().getName();
1042        int dotIndex = classString.lastIndexOf("."); // NOI18N
1043
return classString.substring(dotIndex+1);
1044    }
1045
1046
1047    /**
1048     * Clears the model
1049     */

1050    void clearModel() {
1051        ((DefaultTableModel JavaDoc)this.getModel()).setRowCount(0);
1052    }
1053
1054}
1055
Popular Tags