1 19 package org.netbeans.modules.db.sql.visualeditor.querybuilder; 20 21 import org.openide.nodes.AbstractNode; 22 23 import java.awt.BorderLayout ; 24 import java.awt.Dimension ; 25 import java.awt.Color ; 26 import java.awt.Font ; 27 import java.awt.FontMetrics ; 28 import java.awt.Point ; 29 import java.awt.event.*; 30 import java.awt.Component ; 31 import java.awt.Graphics ; 32 import java.awt.Graphics2D ; 33 import java.awt.Toolkit ; 34 35 import java.awt.dnd.*; 36 import java.awt.datatransfer.*; 37 38 import java.awt.font.FontRenderContext ; 39 import java.awt.geom.Rectangle2D ; 40 41 import java.beans.PropertyVetoException ; 42 43 import java.net.URL ; 44 45 import java.util.Map ; 46 import java.util.HashMap ; 47 import java.util.Iterator ; 48 import java.util.ArrayList ; 49 import java.util.List ; 50 51 import javax.swing.AbstractAction ; 52 import javax.swing.Action ; 53 import javax.swing.ImageIcon ; 54 import javax.swing.JPopupMenu ; 55 import javax.swing.JScrollPane ; 56 import javax.swing.JLabel ; 57 import javax.swing.JInternalFrame ; 58 import javax.swing.JPanel ; 59 import javax.swing.JTextPane ; 60 import javax.swing.JDesktopPane ; 61 import javax.swing.JMenu ; 62 import javax.swing.JMenuItem ; 63 import javax.swing.JCheckBoxMenuItem ; 64 import javax.swing.JLayeredPane ; 65 import javax.swing.JViewport ; 66 import javax.swing.SwingUtilities ; 67 import javax.swing.JComboBox ; 68 import javax.swing.DefaultCellEditor ; 69 import javax.swing.UIManager ; 70 71 import javax.swing.event.TableModelEvent ; 72 import javax.swing.event.TableModelListener ; 73 import javax.swing.event.InternalFrameEvent ; 74 import javax.swing.event.InternalFrameAdapter ; 75 import javax.swing.event.InternalFrameListener ; 76 import javax.swing.table.TableModel ; 77 import javax.swing.table.DefaultTableModel ; 78 import javax.swing.table.TableColumn ; 79 import javax.swing.plaf.basic.BasicInternalFrameUI ; 80 81 import java.sql.*; 82 83 import org.openide.util.NbBundle; 84 import org.openide.ErrorManager; 85 import org.openide.nodes.Node; 86 import org.openide.NotifyDescriptor; 87 import org.openide.DialogDisplayer; 88 import org.openide.windows.WindowManager; 89 90 import com.jgraph.JGraph; 91 92 import com.jgraph.graph.GraphConstants; 93 import com.jgraph.graph.ConnectionSet; 94 import com.jgraph.graph.DefaultEdge; 95 import com.jgraph.graph.DefaultPort; 96 import com.jgraph.graph.DefaultGraphCell; 97 import com.jgraph.graph.DefaultGraphModel; 98 import com.jgraph.graph.CellView; 99 import com.jgraph.graph.AbstractCellView; 100 import com.jgraph.graph.Port; 101 import com.jgraph.graph.PortView; 102 import com.jgraph.graph.Edge; 103 104 import com.jgraph.event.GraphSelectionListener; 105 import com.jgraph.event.GraphSelectionEvent; 106 107 import org.netbeans.modules.db.sql.visualeditor.Log; 108 109 import org.netbeans.modules.db.sql.visualeditor.querymodel.JoinTable; 110 import org.netbeans.modules.db.sql.visualeditor.querymodel.Column; 111 import org.netbeans.modules.db.sql.visualeditor.querymodel.Expression; 112 import org.netbeans.modules.db.sql.visualeditor.querymodel.Value; 113 import org.netbeans.modules.db.sql.visualeditor.querymodel.Predicate; 114 import org.netbeans.modules.db.sql.visualeditor.querymodel.And; 115 import org.netbeans.modules.db.sql.visualeditor.querymodel.Or; 116 import org.netbeans.modules.db.sql.visualeditor.querymodel.Table; 117 import org.netbeans.modules.db.sql.visualeditor.querymodel.Where; 118 import org.netbeans.modules.db.sql.visualeditor.querymodel.SQLQueryFactory; 119 import org.netbeans.modules.db.sql.visualeditor.querymodel.ExpressionList; 120 121 125 public class QueryBuilderGraphFrame extends JPanel 126 implements ActionListener, TableModelListener , ItemListener, 127 KeyListener, DropTargetListener { 128 130 private static final boolean DEBUG = false; 131 132 private boolean _disableQBGF = false; 133 134 private QueryBuilder _queryBuilder; 135 136 private DropTarget _dropTarget; 137 138 private JDesktopPane _desktopPane = null; 139 private QBGFJPanel _canvas = null; 140 private QueryBuilderInputTable _queryBuilderInputTable; 141 private DefaultTableModel _inputTableModel; 142 private JTextPane _sqlTextArea; 143 private DefaultTableModel _resultTableModel; 144 private JGraph _graph = null; 145 private DefaultGraphModel _graphModel = null; 146 147 private JScrollPane _desktopScrollPane; 148 private JViewport viewport; 149 150 private FrameSelectionListener _fsl = null; 151 private FrameComponentListener _fcl = null; 152 private ComponentListener _cl = null; 153 private JPopupMenu _backgroundPopup; 154 private JPopupMenu _tableTitlePopup; 155 private AddTableDlg _addTableDlg = null; 156 157 private boolean _firstTableInserted = false; 158 private Point _location; 159 160 private static final int initX = 40; 162 private static final int initY = 40; 163 164 private static final int offsetX = 20; 165 private int offsetY = 20; 166 167 private static final int MAX_TABLES_IN_A_ROW = 5; 168 169 170 private java.util.Random randomVal = new java.util.Random (); 171 172 private JMenuItem runQueryMenuItem; 173 private JMenuItem groupByMenuItem; 174 175 180 private boolean _checkTableColumnValidity = false; 181 182 private boolean _inputTableAddCriteria = false; 183 184 java.net.URL url_primary_key = 185 getClass().getResource("/org/netbeans/modules/db/sql/visualeditor/resources/primaryKey.gif"); java.net.URL url_foreign_key = 187 getClass().getResource("/org/netbeans/modules/db/sql/visualeditor/resources/foreignKey.gif"); 189 190 192 public QueryBuilderGraphFrame(QueryBuilder queryBuilder, 196 QueryBuilderInputTable queryBuilderInputTable, 197 JTextPane sqlTextArea, 198 DefaultTableModel resultTableModel) { 199 super(new BorderLayout ()); 200 201 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QueryBuilderGraphFrame ctor"); 203 _queryBuilder = queryBuilder; 204 _queryBuilderInputTable = queryBuilderInputTable; 205 _inputTableModel = (DefaultTableModel ) _queryBuilderInputTable.getModel(); 206 _sqlTextArea = sqlTextArea; 207 _resultTableModel = resultTableModel; 208 209 _inputTableModel.addTableModelListener(this); 214 215 217 JMenu menu, subMenu; 218 JMenuItem menuItem; 219 220 _fsl = new FrameSelectionListener(); 222 _fcl = new FrameComponentListener(); 223 _cl = new CompListener(); 224 225 _graphModel = new DefaultGraphModel(); 227 _graph = new JGraph(_graphModel); 228 _graph.setEditable(false); 229 _graph.addKeyListener(this); 230 231 _canvas = new QBGFJPanel(); 233 _canvas.setBackground(Color.white); 234 _canvas.add(_graph, BorderLayout.CENTER); 235 _canvas.addKeyListener(this); 236 237 238 _desktopPane = new JDesktopPane (); 240 _desktopPane.setBackground(Color.white); 241 _desktopPane.setDragMode(JDesktopPane.LIVE_DRAG_MODE); 242 _desktopPane.addComponentListener(_cl); 243 _desktopPane.addKeyListener(this); 244 245 _desktopPane.add(_canvas,JLayeredPane.FRAME_CONTENT_LAYER); 247 248 _desktopScrollPane = new JScrollPane (); 250 viewport = new JViewport (); 251 viewport.setView(_desktopPane); 252 _desktopScrollPane.setViewportView(viewport); 253 _desktopScrollPane.setPreferredSize(new Dimension (100,100)); 255 _backgroundPopup = createBackgroundPopup(); 257 _tableTitlePopup = createTableTitlePopup(); 258 259 MouseListener backgroundPopupListener = new BackgroundPopupListener(); 262 263 _graph.addMouseListener(backgroundPopupListener); 265 _desktopPane.addMouseListener(backgroundPopupListener); 266 _desktopScrollPane.addMouseListener(backgroundPopupListener); 267 268 _graph.addGraphSelectionListener(new GraphSelListener()); 270 271 this.add(_desktopScrollPane,BorderLayout.CENTER); 273 274 setVisible(true); 276 277 _dropTarget = new DropTarget(_desktopScrollPane, 278 DnDConstants.ACTION_COPY_OR_MOVE, this); 279 280 } 281 282 void getCanvasFocus() { 283 _canvas.requestFocus(true); 284 } 285 286 void setQBGFEnabled( boolean value ) { 287 _disableQBGF = ! ( value ); 288 if ( _disableQBGF ) { 289 int frameWidth = (int) this.getSize().getWidth(); 290 int frameHeight = (int) this.getSize().getHeight(); 291 292 _canvas.setSize(new Dimension ( frameWidth, frameHeight ) ); 293 _canvas.updateUI(); 294 _desktopPane.revalidate(); 295 } 296 } 297 298 void resizeDesktop() { 299 if (DEBUG) { 300 System.out.println(" resizeDesktop() called " + "\n" ); System.out.println(" width = " + _graph.getSize().getWidth() + " Height = " + _graph.getSize().getHeight() + "\n" ); } 303 int graphWidth = (int) _graph.getSize().getWidth(); 304 int graphHeight = (int) _graph.getSize().getHeight(); 305 306 int frameWidth = (int) this.getSize().getWidth(); 307 int frameHeight = (int) this.getSize().getHeight(); 308 309 if ( graphWidth == 0 ) 311 graphWidth = frameWidth; 312 if ( graphHeight == 0 ) 313 graphHeight = frameHeight; 314 315 if (DEBUG) { 316 System.out.println(" width = " + graphWidth + " Height = " + graphHeight + "\n" ); } 318 _canvas.setSize(new Dimension ( graphWidth, graphHeight ) ); 319 _canvas.updateUI(); 320 _desktopPane.setPreferredSize(new Dimension (graphWidth, graphHeight)); 321 _desktopPane.revalidate(); 322 } 323 324 void setActivatedNode( QueryBuilderInternalFrame currentSelectedFrame ) { 325 if ( currentSelectedFrame != null ) { 326 TableNode tn = currentSelectedFrame.getNode(); 327 _queryBuilder.setActivatedNodes(new Node[] {tn}); 328 } else { 329 _queryBuilder.setActivatedNodes(new Node[0]); 330 } 331 _queryBuilder.activateActions(); 332 } 333 334 class QBGFJPanel extends JPanel { 335 protected void paintComponent(Graphics g) { 336 if (DEBUG) { 337 System.out.println(" paintComponent() called _parseErrorMessage = " + _queryBuilder.getParseErrorMessage() + "\n" ); } 339 super.paintComponent(g); 340 if ( _queryBuilder.getParseErrorMessage() != null ) { 341 Graphics2D g2d = (Graphics2D )g; 342 paintCenteredText(g2d); 343 if (DEBUG) { 344 System.out.println(" paintCenteredText() called " + "\n" ); } 346 } 347 } 348 349 350 private void paintCenteredText(Graphics2D g) { 351 final int PADDING = 5; final int LINESPACING = 3; 354 String text; 357 text = _queryBuilder.getParseErrorMessage(); 358 int textLines = 1; 359 if (DEBUG) { 360 System.out.println(" paintCenteredText() called _parseErrorMessage = " + _queryBuilder.getParseErrorMessage() + "\n" ); } 362 for (int i = 0, n = text.length(); i < n; i++) { 363 if (text.charAt(i) == '\n') { 364 textLines++; 365 } 366 } 367 368 int width = 369 _desktopScrollPane.getViewport().getWidth(); 370 int height = 371 _desktopScrollPane.getViewport().getHeight(); 372 373 this.setSize(new Dimension ( width, height ) ); 374 int center = height/2; 375 376 Font font = UIManager.getFont("Label.font"); g.setFont(font); 378 FontMetrics metrics = Toolkit.getDefaultToolkit().getFontMetrics(font); 379 FontRenderContext frc = g.getFontRenderContext(); 380 int lineHeight = metrics.getHeight()+LINESPACING; 381 382 int top = center-lineHeight*textLines/2; 383 384 int minx = width; 385 int maxx = 0; 386 int nextLine = 0; 387 for (int line = 0; line < textLines; line++) { 388 int lineEnd = text.indexOf('\n', nextLine); 389 String lineText; 390 if (lineEnd != -1) { 391 lineText = text.substring(nextLine, lineEnd); 392 nextLine = lineEnd+1; 393 } else { 394 lineText = text.substring(nextLine); 395 } 396 397 Rectangle2D bounds1 = font.getStringBounds(lineText, frc); 398 int lx = (width-((int)bounds1.getWidth()))/2; 399 if (lx < minx) { 400 minx = lx; 401 } 402 int xw = lx+(int)bounds1.getWidth(); 403 if (xw > maxx) { 404 maxx = xw; 405 } 406 } 407 408 409 Color background = null; 411 background = getBackground(); 412 g.setColor(background); 413 int miny = top; 414 int maxy = top+textLines*lineHeight; 415 g.fillRect(minx-PADDING, miny, maxx-minx+2*PADDING, maxy-miny+2*PADDING); 416 g.setColor(java.awt.Color.gray); 418 nextLine = 0; 419 int y = top+2*PADDING; y += metrics.getHeight() - metrics.getDescent(); 421 for (int line = 0; line < textLines; line++) { 422 int lineEnd = text.indexOf('\n', nextLine); 423 String lineText; 424 if (lineEnd != -1) { 425 lineText = text.substring(nextLine, lineEnd); 426 nextLine = lineEnd+1; 427 } else { 428 lineText = text.substring(nextLine); 429 } 430 431 Rectangle2D bounds1 = font.getStringBounds(lineText, frc); 432 int lx = (width-((int)bounds1.getWidth()))/2; 433 434 g.drawString(lineText, lx, y); 435 y += lineHeight; 436 } 437 } 438 } 439 440 441 public void keyTyped(KeyEvent e) { 442 _checkTableColumnValidity = true; 443 } 444 445 446 public void keyPressed(KeyEvent e) { 447 if ( DEBUG ) 448 System.out.println(" QBGF : key pressed called. " + "\n" ); _checkTableColumnValidity = true; 450 if( e.isShiftDown() ) { 451 int code = e.getKeyCode(); 452 switch(code) { 453 case KeyEvent.VK_F10: 455 _backgroundPopup.show( e.getComponent(), e.getComponent().getX(), e.getComponent().getY() ); 456 break; 457 } 458 } 459 _queryBuilder.handleKeyPress(e); 460 } 461 462 463 public void keyReleased(KeyEvent e) { 464 _checkTableColumnValidity = true; 465 } 466 467 public void setTableColumnValidity(boolean value) { 468 _checkTableColumnValidity = value; 469 } 470 471 472 public boolean checkTableColumnValidity() { 475 return ( _checkTableColumnValidity && 476 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().queryChanged() ); 477 } 478 479 481 482 public JGraph getGraph() { 483 return (_graph); 484 } 485 486 JPopupMenu createBackgroundPopup() { 489 490 JPopupMenu backgroundPopup; 491 JMenu menu, subMenu; 492 JMenuItem menuItem; 493 JMenuItem subMenuItem; 494 495 backgroundPopup = new JPopupMenu (); 497 498 runQueryMenuItem = new JMenuItem (NbBundle.getMessage(QueryBuilderGraphFrame.class, "RUN_QUERY")); runQueryMenuItem.addActionListener(this); 500 backgroundPopup.add(runQueryMenuItem); 501 502 menuItem = new JMenuItem (NbBundle.getMessage(QueryBuilderGraphFrame.class, "Add_Table")); menuItem.addActionListener(this); 504 backgroundPopup.add(menuItem); 505 506 511 512 groupByMenuItem = 513 new JCheckBoxMenuItem (NbBundle.getMessage(QueryBuilderGraphFrame.class, "GROUP_BY")); groupByMenuItem.addItemListener(this); 515 backgroundPopup.add(groupByMenuItem); 516 517 548 549 return (backgroundPopup); 550 } 551 552 554 JPopupMenu createTableTitlePopup() { 555 556 JPopupMenu tableTitlePopup; 557 JMenu menu, subMenu; 558 JMenuItem menuItem; 559 JMenuItem subMenuItem; 560 561 tableTitlePopup = new JPopupMenu (); 563 564 577 578 menuItem = new JMenuItem (NbBundle.getMessage(QueryBuilderGraphFrame.class, "REMOVE_FROM_QUERY")); menuItem.addActionListener(this); 580 tableTitlePopup.add(menuItem); 581 582 588 589 return (tableTitlePopup); 590 } 591 592 593 597 class TableTitlePopupListener extends MouseAdapter { 598 599 public void mousePressed(MouseEvent e) { 600 maybeShowPopup(e); 601 } 602 603 public void mouseReleased(MouseEvent e) { 604 maybeShowPopup(e); 605 } 606 607 private void maybeShowPopup(MouseEvent e) { 608 if (e.isPopupTrigger() && e.getComponent().isEnabled()) { 609 _tableTitlePopup.show(e.getComponent(), 610 e.getX(), e.getY()); 611 } 612 } 613 } 614 615 protected String getClassName(Object o) { 617 String classString = o.getClass().getName(); 618 int dotIndex = classString.lastIndexOf("."); return classString.substring(dotIndex+1); 620 } 621 622 630 public void tableChanged(TableModelEvent e) { 631 632 if ( _disableQBGF ) return; 634 635 if (_queryBuilder._updateModel == false) return; 637 638 Log.err.log(ErrorManager.INFORMATIONAL, 639 "Entering QBGF.tableChanged, source: " + e.getSource()); if (DEBUG) 641 System.out.println("Entering QBGF.tableChanged source = " + e.getSource()); 643 if (e.getSource() instanceof QueryBuilderTableModel) 644 tableModelChanged(e); 645 646 else if (e.getSource() instanceof QueryBuilderInputTableModel) 647 inputTableModelChanged(e); 648 } 649 650 651 653 private void tableModelChanged(TableModelEvent e) { 654 655 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.tableModelChanged"); 656 659 int row = e.getFirstRow(); int column = e.getColumn(); 663 QueryBuilderTableModel model = (QueryBuilderTableModel) e.getSource(); 664 String tableSpec = model.getTableSpec(); 665 666 String columnName = (String ) model.getValueAt(row, column+2); 668 669 Object value = model.getValueAt(row, column); 671 672 683 if (value==Boolean.TRUE) { 685 if (_queryBuilder._updateModel) { 688 _queryBuilder.getQueryModel().addColumn(tableSpec, columnName); 689 _queryBuilderInputTable.selectColumn(tableSpec, columnName, Boolean.TRUE); 690 } 691 693 697 } 698 699 else if (value==Boolean.FALSE) { 701 if (_queryBuilder._updateModel) { 704 _queryBuilder.getQueryModel().removeColumn(tableSpec, columnName); } 705 706 _queryBuilderInputTable.selectColumn(tableSpec, columnName, Boolean.FALSE); 708 709 712 } 722 723 if (_queryBuilder._updateText) { 729 _queryBuilder.generateText(); 731 } 732 } 733 734 735 737 private void inputTableModelChanged(TableModelEvent e) { 738 739 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.inputTableModelChanged"); 740 741 if (_inputTableAddCriteria) 747 return; 748 749 752 756 int column = e.getColumn(); int row = e.getFirstRow(); QueryBuilderInputTableModel model = (QueryBuilderInputTableModel) e.getSource(); 760 761 if (column!=-1) { 762 763 String columnName = (String ) model.getValueAt(row, QueryBuilderInputTable.Column_COLUMN); 764 String tableSpec = (String ) model.getValueAt(row, QueryBuilderInputTable.Table_COLUMN); 765 766 if (DEBUG) 767 System.out.println("QBGF.iTMC, row: "+row + " columnName: "+columnName + " column: "+column); 770 if (column==QueryBuilderInputTable.Alias_COLUMN) { 771 772 String result = ((String ) model.getValueAt(row, 773 QueryBuilderInputTable.Alias_COLUMN )).trim(); 774 if ( result == null || result.length() == 0 ) _queryBuilder.getQueryModel().removeDerivedColName( tableSpec, columnName ); 776 else 777 _queryBuilder.getQueryModel().setDerivedColName(tableSpec, columnName, result); 778 779 if (_queryBuilder._updateText) 781 _queryBuilder.generateText(); 782 } 783 if (column==QueryBuilderInputTable.Output_COLUMN) { 784 785 Boolean value = (Boolean ) model.getValueAt(row, column); DefaultGraphCell dgc = findNode(tableSpec); 787 QueryBuilderInternalFrame qbif = 788 (QueryBuilderInternalFrame) dgc.getUserObject(); 789 QueryBuilderTableModel qbtm = qbif.getQueryBuilderTableModel(); 790 qbtm.selectColumn(columnName, value); 791 } else if (column==QueryBuilderInputTable.Criteria_COLUMN) { 792 793 String result = ((String ) model.getValueAt(row, 794 QueryBuilderInputTable.Criteria_COLUMN )).trim(); 795 796 if ( result != null && result.length() == 0 ) { 798 _inputTableAddCriteria = true; 800 model.setValueAt("", row,QueryBuilderInputTable.CriteriaOrder_COLUMN); _inputTableAddCriteria = false; 802 _queryBuilder.getQueryModel().removeCriteria( tableSpec, columnName, 1 ); 803 } else if ( result.trim().equals(QueryBuilderInputTable.Criteria_Uneditable_String)) { 804 return; 805 } else { 806 Predicate pred = checkCriteria( tableSpec, columnName, result ) ; 807 if ( pred == null ) { 808 _queryBuilderInputTable.getModel().setValueAt("",row, column); return; 810 } 811 812 int criteriaCount= 813 _queryBuilder.getQueryModel().getCriteriaCount(); 814 String order = (String )model.getValueAt(row, 815 QueryBuilderInputTable.CriteriaOrder_COLUMN); 816 if (order != null && order.trim().length() !=0 && 817 order.trim().equals(QueryBuilderInputTable.CriteriaOrder_Uneditable_String)) { 818 return; 819 } 820 int orderNum = ((order == null) || (order.trim().length()==0)) 821 ? criteriaCount+1 822 : Integer.parseInt(order); 823 _inputTableAddCriteria = true; 824 model.setValueAt(new Integer (orderNum).toString(), row, 825 QueryBuilderInputTable.CriteriaOrder_COLUMN); 826 _inputTableAddCriteria = false; 827 if ( orderNum < criteriaCount+1 ) { 828 _queryBuilder.getQueryModel(). 829 replaceCriteria(tableSpec, columnName, pred, orderNum); 830 } else { 831 _queryBuilder.getQueryModel(). 832 addCriteria(tableSpec, columnName, pred); 833 } 834 } 835 _queryBuilderInputTable.clearSelection(); 836 _inputTableAddCriteria = true; 837 _queryBuilderInputTable.generateTableWhere(_queryBuilder.getQueryModel()); 840 _inputTableAddCriteria = false; 841 if (_queryBuilder._updateText) 843 _queryBuilder.generateText(); 844 } else if (column==QueryBuilderInputTable.CriteriaOrder_COLUMN) { 845 846 String criteria = ( (String ) model.getValueAt(row, 847 QueryBuilderInputTable.Criteria_COLUMN ) ).trim(); 848 String order = (String ) model.getValueAt(row,column ); 849 850 if (order != null && order.trim().length() !=0 && 851 order.trim().equals(QueryBuilderInputTable.CriteriaOrder_Uneditable_String )) { 852 return; 853 } 854 _queryBuilder.getQueryModel().removeCriteria( tableSpec, columnName, 1 ); 856 857 if ((order == null) || (order.trim().length()==0)) { 858 _inputTableAddCriteria = true; 859 model.setValueAt("", row,QueryBuilderInputTable.Criteria_COLUMN); _inputTableAddCriteria = false; 861 } else { 862 int orderNum = Integer.parseInt(order); 863 864 Predicate pred = checkCriteria( tableSpec, columnName, 865 criteria ) ; 866 if ( pred == null ) { 867 _queryBuilderInputTable.getModel().setValueAt("",row, column); return; 869 } 870 871 if (criteria.trim().length() != 0 ) { 872 _queryBuilder.getQueryModel().addCriteria(tableSpec, columnName, pred, orderNum); 873 } 874 } 875 876 _queryBuilderInputTable.clearSelection(); 877 _inputTableAddCriteria = true; 878 _queryBuilderInputTable.generateTableWhere(_queryBuilder.getQueryModel()); 879 _inputTableAddCriteria = false; 880 if (_queryBuilder._updateText) 881 _queryBuilder.generateText(); 882 return; 883 } 884 if (_queryBuilder._updateText) { 885 _queryBuilder.generateText(); 886 } 887 } 888 } 889 890 891 895 private Predicate checkCriteria( String tableSpec, String columnName, String result ) { 896 String op=null; 897 String val=null; 898 if ( result.startsWith(">=") ) { op = ">="; val = result.substring(2).trim(); 901 } else if ( result.startsWith("<=") ) { op = "<="; val = result.substring(2).trim(); 904 } else if ( result.startsWith("<>") ) { op = "<>"; val = result.substring(2).trim(); 907 } else if ( result.startsWith(">") ) { op = ">"; val = result.substring(1).trim(); 910 } else if ( result.startsWith("<") ) { op = "<"; val = result.substring(1).trim(); 913 } else if ( result.startsWith("=") ) { op = "="; val = result.substring(1).trim(); 916 } else if ( result.toUpperCase().startsWith("LIKE" ) ) { op = " LIKE "; val = result.substring(5).trim(); 919 } else if ( result.toUpperCase().startsWith("IN" ) ) { op = " IN "; val = result.substring(3).trim(); 922 } 923 924 if ( op == null || (op.trim().length() == 0) || val == null || (val.trim().length() == 0 ) ) { 927 String msg = NbBundle.getMessage(QueryBuilderGraphFrame.class, "CRITERIA_ERROR"); NotifyDescriptor d = 929 new NotifyDescriptor.Message(msg + "\n\n", NotifyDescriptor.ERROR_MESSAGE); DialogDisplayer.getDefault().notify(d); 931 _queryBuilderInputTable.clearSelection(); 932 return null; 933 } 934 935 Column col1 = SQLQueryFactory.createColumn(tableSpec, columnName); 936 Predicate pred = SQLQueryFactory.createPredicate(col1, val, op); 937 938 return pred; 939 } 940 941 public void setCurrentSelectedFrameTitle( String title ) { 942 if ((QueryBuilderInternalFrame)_desktopPane.getSelectedFrame() != null ) 943 ((QueryBuilderInternalFrame)_desktopPane.getSelectedFrame()).setTitle(title); 944 } 945 946 private void insertTableInteractively(String fullTableName) { 951 if (DEBUG) { 952 System.out.println( 953 "Entering QBGF.insertTableInteractively, fullTableName: " + fullTableName + " queryBuilder.queryModel : " + _queryBuilder._queryModel); } 955 Log.err.log(ErrorManager.INFORMATIONAL, 956 "Entering QBGF.insertTableInteractively, fullTableName: " + fullTableName); 958 if ( ( _queryBuilder.getQueryModel() == null ) || 963 ( _queryBuilder.getQueryModel().genText() == null ) ) { 964 String query = new String ("select * from " + fullTableName); 965 _queryBuilder.populate(query); 966 _queryBuilder.setSqlCommand(query); 967 return; 968 } 969 970 QueryBuilder.showBusyCursor( true ); 972 _queryBuilder._updateText=false; 973 try { 974 String schemaName=null, tableName, tabName; 976 String [] res = fullTableName.split("\\."); if (res.length>1) { 978 schemaName=res[0]; 979 tabName=res[1]; 980 } else 981 tabName=fullTableName; 982 983 989 tableName = new String (tabName); 990 993 994 String corrName=_queryBuilder.getQueryModel().genUniqueName(fullTableName); 996 Table tbl = (corrName==null) ? 997 SQLQueryFactory.createTable(tableName, null, schemaName) : 998 SQLQueryFactory.createTable(tableName, corrName, schemaName); 999 JoinTable joinTable=SQLQueryFactory.createJoinTable(tbl); 1000 1001 List columnNames = new ArrayList (); 1002 columnNames.add("*"); 1004 _queryBuilder.getQueryModel().insertTable(joinTable); 1006 1007 QueryBuilderInternalFrame internalFrame = insertTable(joinTable, columnNames); 1009 if ( internalFrame == null ) { 1010 QueryBuilder.showBusyCursor( false ); 1011 return; 1012 } 1013 1014 List edges = insertFKEdges(internalFrame.getGraphCell(), fullTableName); 1018 _queryBuilder.getQueryModel().addRelationships(joinTable, edges); 1020 1021 redrawFrame(internalFrame); 1025 1026 try { 1027 internalFrame.setSelected(true); 1029 _desktopPane.setSelectedFrame(internalFrame); 1033 setActivatedNode( internalFrame ) ; 1034 } catch(PropertyVetoException pve) { 1035 } 1036 1037 _firstTableInserted = true; 1038 } finally { 1039 _queryBuilder._updateText=true; 1040 QueryBuilder.showBusyCursor( false ); 1041 } 1042 } 1043 1044 1045 1048 void insertTableFromModel(JoinTable joinTable, List columnNames) { 1049 Log.err.log(ErrorManager.INFORMATIONAL, 1050 "Entering QBGF.insertTableFromModel, tablespec: " + joinTable.getTableSpec()); 1052 boolean updateText = _queryBuilder._updateText; 1054 _queryBuilder._updateText=false; 1055 try { 1056 QueryBuilderInternalFrame internalFrame = insertTable(joinTable, columnNames); 1057 if ( internalFrame == null ) return; 1058 1059 insertJoinEdges(joinTable); 1061 1062 1065 redrawFrame(internalFrame); 1066 1067 try { 1069 internalFrame.setSelected(true); 1071 _desktopPane.setSelectedFrame(internalFrame); 1075 _queryBuilder.enableDelete(); 1076 runQueryMenuItem.setEnabled(true); 1077 groupByMenuItem.setEnabled(true); 1078 } catch(PropertyVetoException pve) { 1079 } 1080 1081 _firstTableInserted = true; 1082 } finally { 1083 _queryBuilder._updateText=updateText; 1084 } 1085 } 1086 1087 1088 1090 QueryBuilderInternalFrame insertTable(JoinTable joinTable, List columnNames) { 1091 1092 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.insertTable"); 1094 1096 String joinTableName = joinTable.getFullTableName(); 1098 1099 QueryBuilderInternalFrame internalFrame = createNode(joinTable, columnNames); 1101 1102 internalFrame.setLocation(getNextLocation(internalFrame)); 1104 Log.err.log(ErrorManager.INFORMATIONAL, 1105 "Location for new cell: " + internalFrame.getLocation()); 1107 DefaultGraphCell insertCell = new DefaultGraphCell(internalFrame); 1109 internalFrame.setGraphCell(insertCell); 1110 MouseListener tableTitlePopupListener = new TableTitlePopupListener(); 1112 try { 1114 if (!System.getProperty("os.name").startsWith("Mac OS")) ((BasicInternalFrameUI )internalFrame.getUI()).getNorthPane().addMouseListener(tableTitlePopupListener); 1116 else 1117 internalFrame.addMouseListener(tableTitlePopupListener); 1118 } catch (Exception e) { 1119 e.printStackTrace(); 1120 } 1121 1122 Object insertCells[] = new Object [] {insertCell}; 1124 _graphModel.insert(insertCells,null,null,null,null); 1125 1126 1131 internalFrame.addInternalFrameListener(_fsl); 1133 internalFrame.addComponentListener(_fcl); 1134 1135 _desktopPane.add(internalFrame); 1138 1139 refresh(); 1140 1141 return internalFrame; 1142 } 1143 1144 1145 1147 QueryBuilderInternalFrame createNode(JoinTable joinTable, List selectColumnNames) { 1148 1149 String fullTableName = joinTable.getFullTableName(); 1150 String [] table = fullTableName.split("\\."); String tableName = (table.length>1) ? table[1] : table[0]; 1152 String corrName = joinTable.getCorrName(); 1153 1154 String tableSpec = ((corrName!=null) ? corrName : fullTableName); 1155 1156 Log.err.log(ErrorManager.INFORMATIONAL, 1157 "Entering QBGF.createNode, fullTableName: " + fullTableName + " corrName: " + corrName); 1159 try { String newS = _queryBuilder.checkFullTableName(fullTableName) ; 1162 if ( newS != null & ! fullTableName.equals(newS)) { 1163 fullTableName = newS ; 1164 Log.log(" fullTableName corrected to " + fullTableName ) ; 1165 } 1166 } catch (SQLException se) { 1167 Log.log( " fullTableName " + se.getMessage() ) ; 1168 } 1169 1170 final String [] columnNames = {"", "", "" }; 1174 1175 Object [][] dbData ; 1177 1178 1179 List dbColumnNames ; 1180 try { 1181 dbColumnNames = _queryBuilder.getColumnNames(fullTableName); 1182 } catch(SQLException sqle) { 1183 dbColumnNames = new ArrayList () ; 1184 } 1185 1186 dbData = new Object [dbColumnNames.size()][3]; 1189 Iterator iterator = dbColumnNames.iterator(); 1190 1191 1199 1200 List primaryKeys = null ,foreignKeyCols = null ; 1202 try { 1203 primaryKeys = _queryBuilder.getPrimaryKeys(fullTableName); 1204 foreignKeyCols = _queryBuilder.getImportedKeyColumns(fullTableName); 1205 } catch (SQLException sqle) { 1206 Log.err.log(ErrorManager.WARNING, "QueryBuilderGraphFrame: cannot get info " + sqle.getLocalizedMessage()) ; 1208 primaryKeys = new ArrayList () ; 1209 foreignKeyCols = new ArrayList () ; 1210 } 1211 1212 int i = 0; 1213 1214 while (iterator.hasNext() && i < dbColumnNames.size() ) { 1217 1218 String columnName = new String (iterator.next().toString()) ; 1219 1220 if (selectColumnNames.contains("*") || selectColumnNames.contains(columnName)) dbData[i][0] = Boolean.TRUE; 1223 else 1224 dbData[i][0] = Boolean.FALSE; 1225 1226 if (primaryKeys.contains(columnName.trim())) 1231 dbData[i][1] = new ImageIcon (url_primary_key); 1232 else if (foreignKeyCols.contains(columnName.trim())) 1233 dbData[i][1] = new ImageIcon (url_foreign_key); 1234 else 1235 dbData[i][1] = null; 1236 1237 dbData[i][2] = columnName; 1238 _queryBuilderInputTable.addRow(tableSpec, columnName); 1239 _queryBuilderInputTable.selectColumn(tableSpec, columnName, (Boolean ) dbData[i][0]); 1240 i++; 1241 } 1242 1243 QueryBuilderTableModel qbtModel = 1245 new QueryBuilderTableModel(fullTableName, corrName, columnNames, dbData); 1246 QueryBuilderInternalFrame internalFrame = new QueryBuilderInternalFrame(qbtModel, _queryBuilder); 1247 internalFrame.addKeyListener(this); 1248 qbtModel.addTableModelListener(this); 1249 1250 1263 for (i =0; i < qbtModel.getRowCount(); i++) { 1264 qbtModel.setValueAt(dbData[i][0], i, 0); 1265 } 1266 1267 1268 internalFrame.create(); 1270 String title = (corrName==null) ? tableName : corrName+": "+tableName; internalFrame.setTitle(title); 1272 1273 Log.err.log(ErrorManager.INFORMATIONAL, "TableName for new cell: " + tableName); 1275 return internalFrame; 1276 } 1277 1278 1279 1283 private List insertFKEdges(DefaultGraphCell newCell, String newFullTableName) { 1284 Log.err.log(ErrorManager.INFORMATIONAL, 1285 "Entering QBGF.insertFKEdges, newFullTableName: " + newFullTableName); 1287 List foreignKeys ; 1290 try { 1291 foreignKeys = _queryBuilder.getForeignKeys(newFullTableName); 1292 } catch (SQLException sqle) { 1293 foreignKeys = new ArrayList () ; 1294 } 1295 List foreignKeysUsed = new ArrayList (); 1296 1297 for (int i=0; i<_graphModel.getRootCount(); i++) { 1299 1300 Object root = _graphModel.getRootAt(i); 1301 1302 String [] fk; 1304 1305 if ((root instanceof DefaultGraphCell) && !(_graphModel.isEdge(root)) && (root != newCell)) { 1309 DefaultGraphCell oldCell = (DefaultGraphCell)root; 1310 String oldFullTableName=((QueryBuilderInternalFrame)oldCell.getUserObject()).getFullTableName(); 1311 if ((fk=_queryBuilder.findForeignKey(oldFullTableName,newFullTableName,foreignKeys)) != null) 1312 { 1314 String oldTableSpec=((QueryBuilderInternalFrame)oldCell.getUserObject()).getTableSpec(); 1315 String newTableSpec=((QueryBuilderInternalFrame)newCell.getUserObject()).getTableSpec(); 1316 if ( fk[0].equals(fk[2]) ) { 1322 fk[0] = oldTableSpec; 1323 fk[2] = newTableSpec; 1324 } 1325 insertEdge(oldCell, newCell, oldFullTableName, newFullTableName, oldTableSpec, 1327 newTableSpec, null, null, fk, "INNER"); 1328 foreignKeysUsed.add(fk); 1329 } 1330 } 1331 } 1332 return foreignKeysUsed; 1333 } 1334 1335 1336 void insertJoinEdges(JoinTable joinTable) { 1339 1340 Log.err.log(ErrorManager.INFORMATIONAL, "Entering insertJoinEdges"); String joinType = joinTable.getJoinType(); 1345 1346 1352 if ((joinType!=null) && (!joinType.equals("CROSS"))) { 1354 Expression cond = joinTable.getExpression(); 1355 if (cond instanceof Predicate) { 1356 Predicate pred = (Predicate) cond; 1357 insertJoinEdge(pred, joinType); 1358 } 1359 } 1364 } 1365 1366 1367 void insertJoinEdge(Predicate pred, String joinType) { 1369 1370 Log.err.log(ErrorManager.INFORMATIONAL, "QBGF.Entering insertJoinEdge"); 1372 Value val1 = pred.getVal1(); 1373 Value val2 = pred.getVal2(); 1374 1375 if ((val1 instanceof Column ) && (val2 instanceof Column )) { 1377 1378 Column col1=(Column )val1; 1379 String tableSpec1 = col1.getTableSpec(); 1380 String fullTableName1 = _queryBuilder.getQueryModel().getFullTableName(tableSpec1); 1381 DefaultGraphCell cell1 = findNode(tableSpec1); 1382 String colName1 = col1.getColumnName(); 1383 1384 Column col2=(Column )val2; 1385 String tableSpec2 = col2.getTableSpec(); 1386 String fullTableName2 = _queryBuilder.getQueryModel().getFullTableName(tableSpec2); 1387 DefaultGraphCell cell2 = findNode(tableSpec2); 1388 String colName2 = col2.getColumnName(); 1389 1390 if ((cell1==null) || (cell2==null)) 1391 Log.err.log(ErrorManager.ERROR, "Could not find node"); else { 1393 String [] fk = null; 1396 try { 1397 fk = _queryBuilder.findForeignKey(fullTableName1, colName1, fullTableName2, colName2); 1398 } catch (SQLException sqle) { 1399 Log.err.log(ErrorManager.WARNING,"QBDF: findforeignKey "+sqle.getLocalizedMessage()) ; 1400 } 1401 1402 insertEdge(cell1, cell2, fullTableName1, fullTableName2, tableSpec1, tableSpec2, 1405 colName1, colName2, fk, joinType); 1406 } 1407 } 1408 } 1409 1410 1411 1416 1423 void insertEdge(DefaultGraphCell cell1, DefaultGraphCell cell2, 1429 String fullTableName1, String fullTableName2, 1430 String tableSpec1, String tableSpec2, 1431 String colName1, String colName2, 1432 String [] fk, String joinType) { 1433 Log.err.log(ErrorManager.INFORMATIONAL, 1434 "Entering QBGF.insertEdge, fullTableName1: " + fullTableName1 + " fullTableName2: " + fullTableName2); 1437 DefaultPort cell1Port = new DefaultPort(); 1439 cell1.add(cell1Port); 1440 DefaultPort cell2Port = new DefaultPort(); 1441 cell2.add(cell2Port); 1442 1443 Map atts = GraphConstants.createMap(); 1445 1446 AbstractNode an; 1449 if (colName1==null) { 1450 1451 if (fullTableName1.equalsIgnoreCase(fk[0])) 1454 an = createPropertyNode(tableSpec1, fk[1], tableSpec2, fk[3], joinType, _queryBuilder); else 1456 an = createPropertyNode(tableSpec2, fk[1], tableSpec1, fk[3], joinType, _queryBuilder); 1458 } else { 1459 an = createPropertyNode(tableSpec1, colName1, tableSpec2, colName2, joinType, _queryBuilder); } 1462 1463 if (fk!=null) { 1465 if (fk[0].equalsIgnoreCase(fullTableName1)) { 1466 GraphConstants.setLineEnd(atts,GraphConstants.ARROW_TECHNICAL); 1467 GraphConstants.setEndFill(atts,true); 1468 } else { 1469 GraphConstants.setLineBegin(atts,GraphConstants.ARROW_TECHNICAL); 1470 GraphConstants.setBeginFill(atts,true); 1471 } 1472 } 1473 1474 GraphConstants.setLineWidth(atts,2); 1475 1477 DefaultEdge edge = new DefaultEdge(an); 1479 1480 HashMap map = new HashMap (); 1482 map.put(edge, atts); 1483 1484 ConnectionSet cs = new ConnectionSet(edge, cell1Port, cell2Port); 1486 1487 Object insertEdges[] = new Object [] {edge}; 1489 1490 _graphModel.insert(insertEdges, map, cs, null, null); 1492 1493 _queryBuilder.setActivatedNodes(new Node[] {an}); 1495 1496 QueryBuilderInternalFrame currentSelectedFrame = 1497 (QueryBuilderInternalFrame)_desktopPane.getSelectedFrame(); 1498 try { 1499 if ( currentSelectedFrame != null ) { 1500 currentSelectedFrame.setSelected( false ); 1501 } 1502 } catch ( java.beans.PropertyVetoException pve ) { 1503 } 1505 } 1509 1510 1511 AbstractNode createPropertyNode(String tableSpec1, String fk1, String tableSpec2, String fk3, 1512 String joinType, QueryBuilder _queryBuilder) { 1513 if ((joinType==null) || (joinType.equals(""))) 1514 return new CondNode(tableSpec1, fk1, tableSpec2, fk3, _queryBuilder); 1515 else 1516 return new JoinNode(tableSpec1, fk1, tableSpec2, fk3, joinType, _queryBuilder); 1517 } 1518 1519 1522 void removeTable(QueryBuilderInternalFrame currentSelectedFrame) { 1523 String tableSpec = currentSelectedFrame.getTableSpec(); 1524 1525 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.removeTable, tableSpec: " + tableSpec); if (DEBUG) { 1527 printRoots(); 1528 } 1529 1530 DefaultGraphCell graphCell = currentSelectedFrame.getGraphCell(); 1531 1532 1534 List ports = graphCell.getChildren(); 1536 1537 for (int i=ports.size()-1; i>=0; i--) { 1539 Port p = (Port)ports.get(i); 1540 1541 Iterator edges = p.edges(); 1543 while (edges.hasNext()) { 1544 1545 Edge e = (Edge)edges.next(); 1547 p.removeEdge(e); 1548 _graphModel.remove(new Object [] {e}); 1549 } 1550 1551 graphCell.remove(i); 1553 } 1554 1555 _graphModel.remove(new Object [] {graphCell}); 1557 1558 _desktopPane.remove(currentSelectedFrame); 1561 1562 _desktopPane.setSelectedFrame(null); 1563 1564 _queryBuilderInputTable.removeRows(tableSpec); 1566 1567 _queryBuilder.getQueryModel().removeTable(tableSpec); 1570 1571 _queryBuilder.generate(); 1572 1573 setGroupBy(_queryBuilder.getQueryModel().hasGroupBy() ); 1575 1576 int tableCount = 0; 1577 Component [] comps = _desktopPane.getComponents(); 1578 for(int i=0; i<comps.length; i++) { 1579 Component comp = comps[i]; 1580 if (comp instanceof QueryBuilderInternalFrame) { 1581 redrawFrameWithMove( (QueryBuilderInternalFrame) comp ); 1585 tableCount++; 1586 } 1587 } 1588 if ( tableCount == 0 ) { 1589 _firstTableInserted = false; 1590 _queryBuilder.setActivatedNodes(new Node[0]); 1591 _queryBuilder.activateActions(); 1592 } 1593 } 1594 1595 1603 void generateGraph(QueryModel query) { 1604 1605 if ( _disableQBGF ) return; 1606 1607 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QueryBuilderGraphFrame.generateGraph"); 1609 clearGraph(); 1611 1612 _queryBuilder._updateModel = false; 1613 try { 1614 1615 generateGraphFrom(query); 1616 generateGraphWhere(query); 1617 generateGraphOrderBy(query); 1618 refresh(); 1619 } catch (Exception e) { 1620 e.printStackTrace(); 1621 } finally { 1622 _queryBuilder._updateModel = true; 1623 } 1624 } 1625 1626 1627 void clearGraph() { 1632 1633 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.clearGraph"); 1635 _firstTableInserted=false; 1637 1638 _graphModel.remove((_graphModel.getDescendants(_graphModel, 1646 _graphModel.getRoots(_graphModel))).toArray()); 1647 1648 if (DEBUG) { 1649 printRoots(); 1650 } 1651 1652 _inputTableModel.setRowCount(0); 1654 1655 Component [] comps = _desktopPane.getComponents(); 1657 for(int i=0; i<comps.length; i++) { 1658 Component comp = comps[i]; 1659 if (comp instanceof QueryBuilderInternalFrame) 1660 _desktopPane.remove(comp); 1661 } 1662 1663 QueryBuilderInternalFrame.resetLocation(); 1665 } 1666 1667 1668 1672 private void generateGraphFrom(QueryModel query) { 1673 1674 Log.err.log(ErrorManager.INFORMATIONAL, 1675 "Entering QBGF.generateGraphFrom"); 1677 List tables = query.getFrom().getTableList(); 1679 1680 for (int i=0; i<tables.size(); i++) { 1682 1683 JoinTable joinTable = (JoinTable) tables.get(i); 1684 String tableSpec = joinTable.getTableSpec(); 1685 String fullTableName = joinTable.getFullTableName(); 1686 1687 List columnNames = new ArrayList (); 1693 query.getColumnNames(tableSpec, columnNames); 1694 insertTableFromModel(joinTable, columnNames); 1695 } 1696 } 1697 1698 private boolean whereHasDuplicateColumns( List whereColumns, 1703 Predicate expr ) { 1704 List columns = new ArrayList (); 1705 expr.getReferencedColumns(columns); 1706 for (int i=0; i<columns.size(); i++) { 1707 if (DEBUG) { 1708 System.out.println("expr getReferencedColumn i = " + i + 1709 " " + ((Column )columns.get(i)).genText()); 1710 } 1711 1712 Column c = (Column )columns.get(i); 1713 int found = 0; 1714 for (int j=0; j<whereColumns.size(); j++) { 1715 if (((Column )whereColumns.get(j)).equals(c)) { 1716 found++; 1717 if (DEBUG) { 1718 System.out.println( 1719 "where getReferencedColumn j = " + j + " " + 1720 " found = " + found + 1721 ((Column )whereColumns.get(j)).genText()); 1722 } 1723 } 1724 if ( found > 1 ) return true; 1726 } 1727 } 1728 return false; 1729 } 1730 1731 1734 private void generateGraphWhere(QueryModel query) { 1735 1736 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.generateGraphWhere"); if (DEBUG) 1738 System.out.println("Entering QBGF.generateGraphWhere"); 1740 _inputTableAddCriteria = true; 1742 1743 Where where = query.getWhere(); 1751 if (where != null) { 1752 1753 Expression expr = where.getExpression(); 1754 1755 List whereColumns = new ArrayList (); 1756 where.getReferencedColumns(whereColumns); 1757 1758 if ( expr == null ) { 1759 _inputTableAddCriteria = false; 1760 return; 1761 } else if ( expr instanceof Predicate ) { 1762 if ( whereHasDuplicateColumns(whereColumns, (Predicate) expr)) insertPredicate((Predicate)expr, -1); 1764 else 1765 insertPredicate((Predicate)expr, 0); 1766 } else if ( expr instanceof And ) { 1767 insertAndOr(expr, whereColumns, 0); 1768 } else if ( expr instanceof Or ) { 1769 insertAndOr(expr, whereColumns, 0); 1770 } 1771 } 1772 _inputTableAddCriteria = false; 1773 } 1774 1775 private void insertAndOr(Expression expr, List whereColumns, int order) { 1779 ExpressionList exprList = (ExpressionList)expr; 1780 for (int i=0; i<exprList.size(); i++) { 1781 expr = exprList.getExpression(i); 1782 if ( expr instanceof Predicate ) { 1783 if ( whereHasDuplicateColumns(whereColumns, (Predicate)expr)) 1784 insertPredicate((Predicate)expr, -1); 1786 else 1787 insertPredicate((Predicate)expr, order++); 1788 } else if ( expr instanceof And ) { 1789 insertAndOr(expr, whereColumns, order++ ); 1790 } else if ( expr instanceof Or ) { 1791 insertAndOr(expr, whereColumns, order++ ); 1792 } 1793 } 1794 } 1795 1796 1803 private void insertPredicate(Predicate pred, int order) { 1804 1805 Value val1 = pred.getVal1(); 1806 Value val2 = pred.getVal2(); 1807 1808 if ((val1 instanceof Column ) && (val2 instanceof Column )) { 1809 insertJoinEdge(pred, ""); 1811 } else { 1812 String marker = pred.getVal2().toString(); 1815 1816 1819 Column col = (Column )val1; 1821 String tableSpec=col.getTableSpec(); 1822 String columnName=col.getColumnName(); 1823 1824 String val = pred.getOp() + " " + marker; 1827 if ( order == -1) { 1829 _queryBuilderInputTable.addCriterion(tableSpec, columnName, 1830 QueryBuilderInputTable.Criteria_Uneditable_String, 1831 QueryBuilderInputTable.CriteriaOrder_Uneditable_String); 1832 } else { 1833 String orderString = (order == -1) ? "" : new Integer (order+1).toString(); 1834 1835 _queryBuilderInputTable.addCriterion(tableSpec, columnName, 1837 val, orderString); 1838 } 1839 } 1840 } 1841 1842 1844 private void generateGraphOrderBy(QueryModel query) { 1845 1846 _queryBuilderInputTable.generateTableOrderBy(query); 1848 } 1849 1850 1851 1854 DefaultGraphCell findNode(String tableSpec) { 1855 1856 Log.err.log(ErrorManager.INFORMATIONAL, 1857 "Entering QBGF.findNode, searching for cell: " + tableSpec); 1859 for (int i=0; i<_graphModel.getRootCount(); i++) { 1860 1861 Object root = _graphModel.getRootAt(i); 1862 1863 if ((root instanceof DefaultGraphCell) && !(_graphModel.isEdge(root)) && !(root instanceof DefaultPort)) { 1867 QueryBuilderInternalFrame internalFrame = 1868 (QueryBuilderInternalFrame) (((DefaultGraphCell) root).getUserObject()); 1869 if (internalFrame.getTableSpec().equals(tableSpec)) 1870 return (DefaultGraphCell) root; 1871 } 1872 } 1873 1874 return null; 1875 } 1876 1877 1878 public void addTable() { 1881 Log.err.log(ErrorManager.INFORMATIONAL, "Entering QBGF.addTable"); 1883 1885 QueryBuilder.showBusyCursor( true ); 1886 try { 1887 1888 List tableNames = _queryBuilder.getCachedAllTablesInDataSource(); 1889 String [] tableStrings = new String [tableNames.size()]; 1890 tableNames.toArray(tableStrings); 1891 _addTableDlg = new AddTableDlg(tableStrings, true); 1892 if (DEBUG) 1893 System.out.println("Database tablenames: " + tableNames); 1895 if (_addTableDlg.getReturnStatus() == 1) { 1899 SwingUtilities.invokeLater(new Runnable () { 1902 public void run() { 1903 Object [] selectedTables = _addTableDlg.getSelectedValues(); 1904 for ( int i=0; i < selectedTables.length; i++ ) { 1907 final String finalVal = (String ) selectedTables[i]; 1908 insertTableInteractively(finalVal); 1909 } 1910 _queryBuilder.generateText(); 1911 runQueryMenuItem.setEnabled(true); 1912 groupByMenuItem.setEnabled(true); 1913 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setRunQueryMenuEnabled(true); 1914 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setParseQueryMenuEnabled(true); 1915 } 1917 } 1918 ); 1919 } 1922 QueryBuilderInternalFrame currentSelectedFrame = 1926 (QueryBuilderInternalFrame)_desktopPane.getSelectedFrame(); 1927 if ( currentSelectedFrame != null ) { 1928 redrawFrameWithMove( currentSelectedFrame ); 1929 } 1930 } catch (SQLException sqe) { 1931 _queryBuilder.checkDatabaseAndDisable(null) ; 1932 } finally { 1933 QueryBuilder.showBusyCursor( false ); 1934 } 1935 } 1936 1937 1942 public void actionPerformed(ActionEvent e) { 1943 1944 if (DEBUG) 1945 System.out.println("Entering QBGF.actionPerformed"); 1947 JMenuItem source = (JMenuItem )(e.getSource()); 1948 1949 if (source.getText().equals(NbBundle.getMessage(QueryBuilderGraphFrame.class, "Add_Table"))) { addTable(); 1951 } 1952 1953 else if (source.getText().equals(NbBundle.getMessage(QueryBuilderGraphFrame.class, "RUN_QUERY"))) { 1955 1957 _queryBuilder.executeQuery(_sqlTextArea.getText()); 1958 } 1959 1960 else if (source.getText().equals(NbBundle.getMessage(QueryBuilderGraphFrame.class, "REMOVE_FROM_QUERY"))) { removeTable(); 1962 } 1963 } 1964 1965 public boolean isSelectionEmpty() { 1966 if ( _firstTableInserted == false ) return true; 1968 QueryBuilderInternalFrame currentSelectedFrame = 1969 (QueryBuilderInternalFrame)_desktopPane.getSelectedFrame(); 1970 return ( currentSelectedFrame == null ); 1971 } 1972 1973 public void removeNode(TableNode node) { 1976 QueryBuilder.showBusyCursor( true ); 1977 1978 1995 removeTable(); 1998 QueryBuilder.showBusyCursor( false ); 1999 } 2000 2001 public void removeNode(CondNode node) { 2004 QueryBuilder.showBusyCursor( true ); 2005 String [] rel = new String [4]; 2006 rel[0] = node.getTable1(); 2007 rel[1] = node.getColumn1(); 2008 rel[2] = node.getTable2(); 2009 rel[3] = node.getColumn2(); 2010 2011 if (DEBUG) { 2012 System.out.println(" QBGF.removeNode() table1 = " + rel[0] + " column1 = " + rel[1] + " table2 = " + rel[2] + " column2 = " + rel[3] + "\n" ); } 2014 2015 Predicate pred = SQLQueryFactory.createPredicate(rel); 2016 _queryBuilder._updateText=false; 2017 _queryBuilder.getQueryModel().removeCondition( pred ); 2018 Object cell = _graph.getSelectionCell(); 2019 if (cell instanceof DefaultEdge) { 2020 _graphModel.remove(new Object [] {cell}); 2021 } 2022 _queryBuilder._updateText=true; 2023 _queryBuilder.generateText(); 2024 _queryBuilder.activateActions(); 2025 QueryBuilder.showBusyCursor( false ); 2026 } 2027 2028 public void removeNode(JoinNode node) { 2031 QueryBuilder.showBusyCursor( true ); 2032 String [] rel = new String [4]; 2033 rel[0] = node.getTable1(); 2034 rel[1] = node.getColumn1(); 2035 rel[2] = node.getTable2(); 2036 rel[3] = node.getColumn2(); 2037 2038 if (DEBUG) { 2039 System.out.println(" QBGF.removeNode() table1 = " + rel[0] + " column1 = " + rel[1] + " table2 = " + rel[2] + " column2 = " + rel[3] + "\n" ); } 2041 2042 _queryBuilder._updateText=false; 2043 _queryBuilder.getQueryModel().removeJoinNode( rel[0], rel[1], rel[2], rel[3] ); 2044 Object cell = _graph.getSelectionCell(); 2045 if (cell instanceof DefaultEdge) { 2046 _graphModel.remove(new Object [] {cell}); 2047 } 2048 _queryBuilder._updateText=true; 2049 _queryBuilder.generateText(); 2050 _queryBuilder.activateActions(); 2051 QueryBuilder.showBusyCursor( false ); 2052 } 2053 2054 public void removeTable() { 2057 2058 QueryBuilder.showBusyCursor( true ); 2059 _queryBuilder._updateText=false; 2061 try { 2062 QueryBuilderInternalFrame currentSelectedFrame = 2063 (QueryBuilderInternalFrame)_desktopPane.getSelectedFrame(); 2064 if (currentSelectedFrame != null) 2065 removeTable(currentSelectedFrame); 2066 } finally { 2067 _queryBuilder._updateText=true; 2068 } 2069 2070 if ( _sqlTextArea.getText() == null ) { 2072 runQueryMenuItem.setEnabled(false); 2073 groupByMenuItem.setEnabled(false); 2074 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setRunQueryMenuEnabled(false); 2075 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setParseQueryMenuEnabled(false); 2076 } else if ( _sqlTextArea.getText().trim().length() == 0 ) { 2077 runQueryMenuItem.setEnabled(false); 2078 groupByMenuItem.setEnabled(false); 2079 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setRunQueryMenuEnabled(false); 2080 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setParseQueryMenuEnabled(false); 2081 } else { 2082 runQueryMenuItem.setEnabled(true); 2083 groupByMenuItem.setEnabled(true); 2084 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setRunQueryMenuEnabled(true); 2085 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setParseQueryMenuEnabled(true); 2086 } 2087 QueryBuilder.showBusyCursor( false ); 2088 } 2089 2090 2092 public void itemStateChanged(ItemEvent e) { 2093 2094 JMenuItem source = (JMenuItem )(e.getSource()); 2095 2096 if (source.getText().equals(NbBundle.getMessage(QueryBuilderGraphFrame.class, "GROUP_BY"))) { 2098 if (e.getStateChange() == ItemEvent.SELECTED) { 2100 _queryBuilder.getQueryModel().addGroupBy(); 2102 } else { 2103 _queryBuilder.getQueryModel().removeGroupBy(); 2105 } 2106 _queryBuilder.generateText(); 2107 } 2108 } 2109 2110 2111 public void setGroupBy(boolean b) { 2113 groupByMenuItem.setSelected(b); 2114 } 2115 2116 2117 void redrawFrameWithMove(QueryBuilderInternalFrame frame) { 2121 if (frame != null) 2122 { 2124 HashMap map = new HashMap (); 2125 Map atts = GraphConstants.createMap(); 2126 2127 GraphConstants.setBounds(atts,frame.getBounds()); 2128 map.put(frame.getGraphCell(),atts); 2129 _graphModel.edit(map,null,null,null); 2131 } 2132 2133 _desktopPane.setBounds(_canvas.getBounds()); 2138 _desktopPane.updateUI(); 2139 2140 resizeDesktop(); 2141 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().requestFocus(true); 2142 } 2143 2144 2145 2147 private void redrawFrame(QueryBuilderInternalFrame frame) { 2148 if (frame != null) 2149 { 2151 HashMap map = new HashMap (); 2152 Map atts = GraphConstants.createMap(); 2153 2154 GraphConstants.setBounds(atts,frame.getBounds()); 2155 map.put(frame.getGraphCell(),atts); 2156 _graphModel.edit(map,null,null,null); 2158 } 2159 } 2160 2161 2162 2165 void refresh() { 2166 _graph.graphDidChange(); 2167 _graph.revalidate(); 2168 if (DEBUG) { 2169 System.out.println(" refresh() called " + "\n" ); System.out.println(" width = " + _graph.getSize().getWidth() + " Height = " + _graph.getSize().getHeight() + "\n" ); } 2172 resizeDesktop(); 2173 } 2174 2175 2176 2180 Point getNextLocation(QueryBuilderInternalFrame internalFrame) { 2181 2182 if (!_firstTableInserted ) { 2183 _location = new Point (initX, initY); 2184 } else { 2185 Dimension size = internalFrame.getSize(); 2186 _location = new Point ((int)( 2187 _location.getX() + 2188 size.getWidth() + 2189 offsetX + 2190 randomVal.nextInt((int)size.getWidth()/2)), 2191 (int)(_location.getY() + 2192 offsetY + 2193 randomVal.nextInt((int)size.getHeight()/2))); 2194 offsetY *= -1; 2195 if ( _location.getX() > 2196 (int) size.getWidth() * MAX_TABLES_IN_A_ROW ) { 2197 _location = new Point (initX, (int)_location.getY()+(int)size.getHeight()+2*offsetY); 2198 } 2199 } 2200 return _location; 2201 } 2202 2203 2204 2206 2208 class BackgroundPopupListener extends MouseAdapter { 2209 2210 public void mousePressed(MouseEvent e) { 2211 maybeShowPopup(e); 2212 } 2213 2214 public void mouseReleased(MouseEvent e) { 2215 maybeShowPopup(e); 2216 } 2217 2218 private void maybeShowPopup(MouseEvent e) { 2219 if ( _disableQBGF ) return; 2220 if (e.isPopupTrigger() ) { 2221 Object cell = _graph.getFirstCellForLocation(e.getX(), e.getY()); 2222 if ( ( cell != null ) && ( cell instanceof DefaultEdge ) ) { 2223 return; 2226 } 2227 if (e.getComponent().isEnabled() ) 2228 _backgroundPopup.show( e.getComponent(), e.getX(), e.getY() ); 2229 } 2230 } 2231 } 2232 2233 2234 2238 private class FrameSelectionListener extends InternalFrameAdapter { 2239 2240 public void internalFrameActivated(InternalFrameEvent ife) { 2241 Object source = (Object )(ife.getSource()); 2242 2243 2247 QueryBuilderInternalFrame currentSelectedFrame = 2249 (QueryBuilderInternalFrame)_desktopPane.getSelectedFrame(); 2250 setActivatedNode( currentSelectedFrame ) ; 2251 } 2252 2253 public void internalFrameDeactivated(InternalFrameEvent ife) { 2254 } 2257 } 2258 2259 2260 2263 private class CompListener extends ComponentAdapter { 2264 2265 public void componentResized(ComponentEvent ce) { 2266 if ( _disableQBGF ) { 2267 return; 2268 } else { 2269 refresh(); 2270 } 2271 } 2272 } 2273 2274 2275 2278 private class FrameComponentListener extends ComponentAdapter { 2279 2280 public void componentResized(ComponentEvent ce) { 2282 componentMoved(ce); 2283 } 2284 2285 public void componentMoved(ComponentEvent ce) { 2286 HashMap map = new HashMap (); 2287 Map atts = GraphConstants.createMap(); 2288 QueryBuilderInternalFrame frame = (QueryBuilderInternalFrame)ce.getComponent(); 2289 refresh(); 2290 2291 GraphConstants.setBounds(atts,frame.getBounds()); 2292 map.put(frame.getGraphCell(),atts); 2293 _graphModel.edit(map,null,null,null); 2294 2295 resizeDesktop(); 2296 } 2297 } 2298 2299 2304 private class GraphSelListener implements GraphSelectionListener { 2305 2306 public void valueChanged(GraphSelectionEvent e) { 2307 2308 Log.err.log(ErrorManager.INFORMATIONAL, "Graph selection changed, event: "+e); if (_graph.getSelectionCount() > 0) { 2310 Object cell = _graph.getSelectionCell(); 2312 if ( ( cell != null ) && ( cell instanceof DefaultEdge ) ) { 2313 AbstractNode an = (AbstractNode)(((DefaultEdge) cell).getUserObject()); 2316 _queryBuilder.setActivatedNodes(new Node[] { an }); 2317 QueryBuilderInternalFrame currentSelectedFrame = 2318 (QueryBuilderInternalFrame) 2319 _desktopPane.getSelectedFrame(); 2320 try { 2321 if ( currentSelectedFrame != null ) { 2322 currentSelectedFrame.setSelected( false ); 2323 } 2324 } catch ( java.beans.PropertyVetoException pve ) { 2325 } 2327 } 2328 } 2329 } 2330 } 2331 2332 2333 2335 private void printRoots() { 2336 if (DEBUG) { 2337 System.out.println("Root Count" + _graphModel.getRootCount()); for (int i=0; i<_graphModel.getRootCount(); i++) 2339 System.out.println("Root["+i+"] class: " + _graphModel.getRootAt(i).getClass()); } 2341 } 2342 2343 2344 2346 public class PerfTimer { 2347 2348 long _time; 2349 2350 public PerfTimer() { 2351 resetTimer(); 2352 } 2353 2354 public void resetTimer(){ 2356 _time = System.currentTimeMillis(); 2358 } 2359 2360 public long elapsedTime() { 2361 return (System.currentTimeMillis() - _time); 2363 } 2364 2365 public void print(String aString) { 2366 System.out.println(aString + ": " + this.elapsedTime() + " ms"); } 2368 } 2369 2370 public void dragEnter(DropTargetDragEvent e) { 2371 e.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE); 2372 } 2373 2374 public void drop(DropTargetDropEvent e) { 2375 if ( _disableQBGF ) return; 2376 try { 2377 Transferable tr = e.getTransferable(); 2378 DataFlavor[] dataFlavors = tr.getTransferDataFlavors(); 2379 for (int i = 0; i < dataFlavors.length; i++) { 2380 Object o = tr.getTransferData( dataFlavors[i] ); 2381 if ( o instanceof Node ) { 2382 e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE); 2383 List tableNamesArrayList = 2386 _queryBuilder.getCachedAllTablesInDataSource(); 2387 String fullTableName = ( ( Node ) o ).getName(); 2388 2389 String tableName; 2391 String justTableName; 2392 for (int j=0; j < tableNamesArrayList.size(); j++){ 2393 tableName = (String ) tableNamesArrayList.get(j); 2394 justTableName = (String )tableName.split("\\.")[1]; 2395 if (justTableName.equals(fullTableName )){ 2396 fullTableName = tableName; 2397 break; 2398 } 2399 } 2400 2401 if ( tableNamesArrayList.contains( fullTableName ) ) { 2402 insertTableInteractively( fullTableName ); 2403 _queryBuilder.generateText(); 2404 runQueryMenuItem.setEnabled(true); 2405 groupByMenuItem.setEnabled(true); 2406 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setRunQueryMenuEnabled(true); 2407 _queryBuilder.getQueryBuilderPane().getQueryBuilderSqlTextArea().setParseQueryMenuEnabled(true); 2408 refresh(); 2409 _graph.getGraphLayoutCache().reload(); 2410 resizeDesktop(); 2411 QueryBuilderInternalFrame currentSelectedFrame = 2416 (QueryBuilderInternalFrame)_desktopPane.getSelectedFrame(); 2417 if ( currentSelectedFrame != null ) { 2418 redrawFrameWithMove( currentSelectedFrame ); 2419 } 2420 } else { 2421 String msg = 2422 NbBundle.getMessage(QueryBuilderGraphFrame.class, 2423 "DRAG_AND_DROP_FROM_CURRENT_DATASOURCE"); 2424 NotifyDescriptor d = new NotifyDescriptor.Message( 2425 msg + " = " + 2426 _queryBuilder. getConnectionInfo() + 2427 "\n\n", NotifyDescriptor.ERROR_MESSAGE); 2429 DialogDisplayer.getDefault().notify(d); 2430 } 2431 e.dropComplete(true); 2432 return; 2433 } 2434 } 2435 e.rejectDrop(); 2436 } catch (Exception ex) { 2437 System.out.println("Data transfer exception: " + ex); } 2439 } 2440 2441 public void dragExit(DropTargetEvent e) { 2442 2443 } 2444 2445 public void dragOver(DropTargetDragEvent e) { 2446 2447 } 2448 2449 public void dropActionChanged(DropTargetDragEvent e) { 2450 2451 } 2452 2453 public void dragOver(DragSourceDragEvent e) { 2454 2455 } 2456 2457 public void dropActionChanged(DragSourceDragEvent e) { 2458 2459 } 2460} 2461 | Popular Tags |