KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > db > explorer > dataview > DataViewWindow


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-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.db.explorer.dataview;
21
22 import java.awt.GridBagConstraints JavaDoc;
23 import java.awt.GridBagLayout JavaDoc;
24 import java.awt.Insets JavaDoc;
25 import java.awt.datatransfer.DataFlavor JavaDoc;
26 import java.awt.datatransfer.StringSelection JavaDoc;
27 import java.awt.datatransfer.Transferable JavaDoc;
28 import java.awt.dnd.DropTarget JavaDoc;
29 import java.awt.dnd.DropTargetDragEvent JavaDoc;
30 import java.awt.dnd.DropTargetDropEvent JavaDoc;
31 import java.awt.dnd.DropTargetEvent JavaDoc;
32 import java.awt.dnd.DropTargetListener JavaDoc;
33 import java.awt.event.ActionEvent JavaDoc;
34 import java.awt.event.ActionListener JavaDoc;
35 import java.awt.event.MouseAdapter JavaDoc;
36 import java.awt.event.MouseEvent JavaDoc;
37 import java.io.ObjectStreamException JavaDoc;
38 import java.sql.Connection JavaDoc;
39 import java.sql.ResultSet JavaDoc;
40 import java.sql.ResultSetMetaData JavaDoc;
41 import java.sql.SQLException JavaDoc;
42 import java.sql.Statement JavaDoc;
43 import java.sql.Types JavaDoc;
44 import java.text.MessageFormat JavaDoc;
45 import java.util.Enumeration JavaDoc;
46 import java.util.HashMap JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.util.ResourceBundle JavaDoc;
49 import java.util.StringTokenizer JavaDoc;
50 import java.util.Vector JavaDoc;
51 import javax.swing.AbstractListModel JavaDoc;
52 import javax.swing.JButton JavaDoc;
53 import javax.swing.JComboBox JavaDoc;
54 import javax.swing.JLabel JavaDoc;
55 import javax.swing.JMenuItem JavaDoc;
56 import javax.swing.JPanel JavaDoc;
57 import javax.swing.JPopupMenu JavaDoc;
58 import javax.swing.JScrollPane JavaDoc;
59 import javax.swing.JSplitPane JavaDoc;
60 import javax.swing.JTable JavaDoc;
61 import javax.swing.JTextArea JavaDoc;
62 import javax.swing.MutableComboBoxModel JavaDoc;
63 import javax.swing.SwingUtilities JavaDoc;
64 import javax.swing.table.AbstractTableModel JavaDoc;
65 import org.netbeans.api.db.explorer.DatabaseException;
66 import org.netbeans.modules.db.explorer.infos.ColumnNodeInfo;
67 import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo;
68 import org.netbeans.modules.db.explorer.nodes.ConnectionNode;
69 import org.openide.DialogDisplayer;
70 import org.openide.NotifyDescriptor;
71 import org.openide.awt.Mnemonics;
72 import org.openide.nodes.Node;
73 import org.openide.nodes.NodeTransfer;
74 import org.openide.util.Lookup;
75 import org.openide.util.NbBundle;
76 import org.openide.util.RequestProcessor;
77 import org.openide.util.Task;
78 import org.openide.util.TaskListener;
79 import org.openide.util.datatransfer.ExClipboard;
80 import org.openide.util.datatransfer.ExTransferable;
81 import org.openide.util.datatransfer.MultiTransferObject;
82 import org.openide.windows.TopComponent;
83
84 public class DataViewWindow extends TopComponent {
85     
86     // TODO: remove this class, replace by the SQL editor
87

88     private JTextArea JavaDoc queryarea;
89     private JTable JavaDoc jtable;
90     private DataModel dbadaptor;
91     private JComboBox JavaDoc rcmdscombo;
92     private JLabel JavaDoc status;
93     private ResourceBundle JavaDoc bundle;
94     private Node node;
95     private JPopupMenu JavaDoc tablePopupMenu;
96     static final long serialVersionUID = 6855188441469780252L;
97
98     public DataViewWindow(DatabaseNodeInfo info, String JavaDoc query) throws SQLException JavaDoc {
99         node = info.getNode();
100
101         bundle = NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle"); //NOI18N
102

103         this.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewWindowA11yDesc")); //NOI18N
104

105         Node tempNode = node;
106         while(!(tempNode instanceof ConnectionNode))
107             tempNode = tempNode.getParentNode();
108
109         String JavaDoc title = tempNode.getDisplayName();
110         int idx = title.indexOf(" ["); //NOI18N
111
title = title.substring(0, idx);
112         setName(title);
113         setToolTipText(bundle.getString("CommandEditorTitle") + " " + tempNode.getDisplayName()); //NOI18N
114

115         GridBagLayout JavaDoc layout = new GridBagLayout JavaDoc();
116         GridBagConstraints JavaDoc con = new GridBagConstraints JavaDoc ();
117         setLayout (layout);
118
119         // Data model
120
dbadaptor = new DataModel(info);
121
122         // Query area and button
123
JPanel JavaDoc subpane = new JPanel JavaDoc();
124         GridBagLayout JavaDoc sublayout = new GridBagLayout JavaDoc();
125         GridBagConstraints JavaDoc subcon = new GridBagConstraints JavaDoc ();
126         subpane.setLayout(sublayout);
127
128         // query label
129
subcon.fill = GridBagConstraints.HORIZONTAL;
130         subcon.weightx = 0.0;
131         subcon.weighty = 0.0;
132         subcon.gridx = 0;
133         subcon.gridy = 0;
134         subcon.gridwidth = 3;
135         subcon.insets = new Insets JavaDoc (0, 0, 5, 0);
136         subcon.anchor = GridBagConstraints.SOUTH;
137         JLabel JavaDoc queryLabel = new JLabel JavaDoc();
138         Mnemonics.setLocalizedText(queryLabel, bundle.getString("QueryLabel"));
139         queryLabel.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewQueryLabelA11yDesc"));
140         sublayout.setConstraints(queryLabel, subcon);
141         subpane.add(queryLabel);
142
143         // query area
144
subcon.fill = GridBagConstraints.BOTH;
145         subcon.weightx = 1.0;
146         subcon.weighty = 1.0;
147         subcon.gridx = 0;
148         subcon.gridwidth = 3;
149         subcon.gridy = 1;
150         queryarea = new JTextArea JavaDoc(query, 3, 70);
151         queryarea.setLineWrap(true);
152         queryarea.setWrapStyleWord(true);
153         queryarea.setDropTarget(new DropTarget JavaDoc(queryarea, new ViewDropTarget()));
154         queryarea.getAccessibleContext().setAccessibleName(bundle.getString("ACS_DataViewTextAreaA11yName")); //NOI18N
155
queryarea.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewTextAreaA11yDesc")); //NOI18N
156
queryarea.setToolTipText(bundle.getString("ACS_DataViewTextAreaA11yDesc")); //NOI18N
157
queryLabel.setLabelFor(queryarea);
158
159         JScrollPane JavaDoc scrollpane = new JScrollPane JavaDoc(queryarea);
160         subcon.insets = new Insets JavaDoc (0, 0, 5, 0);
161         sublayout.setConstraints(scrollpane, subcon);
162         subpane.add(scrollpane);
163
164         // combo label
165
subcon.fill = GridBagConstraints.HORIZONTAL;
166         subcon.weightx = 0.0;
167         subcon.weighty = 0.0;
168         subcon.gridx = 0;
169         subcon.gridy = 2;
170         subcon.gridwidth = 1;
171         subcon.insets = new Insets JavaDoc (0, 0, 5, 5);
172         subcon.anchor = GridBagConstraints.CENTER;
173         JLabel JavaDoc comboLabel = new JLabel JavaDoc();
174         Mnemonics.setLocalizedText(comboLabel, bundle.getString("HistoryLabel")); //NOI18N
175
comboLabel.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewHistoryLabelA11yDesc")); //NOI18N
176
sublayout.setConstraints(comboLabel, subcon);
177         subpane.add(comboLabel);
178
179         // Combo recent commands
180
subcon.fill = GridBagConstraints.HORIZONTAL;
181         subcon.weightx = 1.0;
182         subcon.weighty = 0.0;
183         subcon.gridx = 1;
184         subcon.gridy = 2;
185         subcon.gridwidth = 1;
186         subcon.insets = new Insets JavaDoc (0, 0, 5, 5);
187         subcon.anchor = GridBagConstraints.SOUTH;
188         rcmdscombo = new JComboBox JavaDoc(new ComboModel());
189         rcmdscombo.getAccessibleContext().setAccessibleName(bundle.getString("ACS_DataViewComboBoxA11yName")); //NOI18N
190
rcmdscombo.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewComboBoxA11yDesc")); //NOI18N
191
rcmdscombo.setToolTipText(bundle.getString("ACS_DataViewComboBoxA11yDesc")); //NOI18N
192
comboLabel.setLabelFor(rcmdscombo);
193         sublayout.setConstraints(rcmdscombo, subcon);
194         subpane.add(rcmdscombo);
195         rcmdscombo.addActionListener(new ActionListener JavaDoc() {
196             public void actionPerformed(ActionEvent JavaDoc e) {
197                 JComboBox JavaDoc source = (JComboBox JavaDoc)e.getSource();
198                 RecentCommand cmd = (RecentCommand)source.getSelectedItem();
199                 if (cmd != null)
200                     setCommand(cmd.getCommand());
201             }
202         });
203
204         // Button Execute
205
subcon.gridx = 2;
206         subcon.gridy = 2;
207         subcon.weightx = 0.0;
208         subcon.weighty = 0.0;
209         subcon.insets = new Insets JavaDoc (0, 0, 5, 0);
210         subcon.fill = GridBagConstraints.HORIZONTAL;
211         subcon.anchor = GridBagConstraints.SOUTH;
212         final JButton JavaDoc fetchbtn = new JButton JavaDoc();
213         Mnemonics.setLocalizedText(fetchbtn, bundle.getString("ExecuteButton"));
214         fetchbtn.setToolTipText(bundle.getString("ACS_ExecuteButtonA11yDesc")); //NOI18N
215
sublayout.setConstraints(fetchbtn, subcon);
216         subpane.add(fetchbtn);
217         fetchbtn.addActionListener(new ActionListener JavaDoc() {
218             public void actionPerformed(ActionEvent JavaDoc e) {
219                 fetchbtn.setEnabled(false);
220                 Task t = RequestProcessor.getDefault().create(new Runnable JavaDoc() {
221                     public void run () {
222                         executeCommand();
223                     }
224                 });
225                 t.addTaskListener(new TaskListener() {
226                     public void taskFinished(Task task) {
227                         fetchbtn.setEnabled(true);
228                     }
229                 });
230                 RequestProcessor.getDefault().post(t, 0);
231             }
232         });
233         // status line
234
subcon.fill = GridBagConstraints.HORIZONTAL;
235         subcon.weightx = 1.0;
236         subcon.weighty = 0.0;
237         subcon.gridx = 0;
238         subcon.gridy = 3;
239         subcon.gridwidth = 3;
240         subcon.insets = new Insets JavaDoc (0, 0, 5, 0);
241         subcon.anchor = GridBagConstraints.SOUTH;
242         status = new JLabel JavaDoc(" "); //NOI18N
243
status.setBorder(new javax.swing.border.LineBorder JavaDoc(java.awt.Color.gray));
244         status.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewStatusLabelA11yDesc")); //NOI18N
245
sublayout.setConstraints(status, subcon);
246         subpane.add(status);
247
248         JPanel JavaDoc subpane2 = new JPanel JavaDoc();
249         GridBagLayout JavaDoc sublayout2 = new GridBagLayout JavaDoc();
250         GridBagConstraints JavaDoc subcon2 = new GridBagConstraints JavaDoc ();
251         subpane2.setLayout(sublayout2);
252
253         // table label
254
subcon2.fill = GridBagConstraints.HORIZONTAL;
255         subcon2.weightx = 0.0;
256         subcon2.weighty = 0.0;
257         subcon2.gridx = 0;
258         subcon2.gridy = 0;
259         subcon2.gridwidth = 1;
260         subcon2.insets = new Insets JavaDoc (5, 0, 0, 0);
261         subcon2.anchor = GridBagConstraints.SOUTH;
262         JLabel JavaDoc tableLabel = new JLabel JavaDoc();
263         Mnemonics.setLocalizedText(tableLabel, bundle.getString("ResultsLabel"));
264         tableLabel.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewResultsLabelA11yDesc")); //NOI18N
265
sublayout2.setConstraints(tableLabel, subcon2);
266         subpane2.add(tableLabel);
267
268         // content popup menu on table with results
269
tablePopupMenu = new JPopupMenu JavaDoc ();
270         JMenuItem JavaDoc miCopyValue = new JMenuItem JavaDoc (bundle.getString ("CopyCellValue")); //NOI18N
271
miCopyValue.addActionListener(new ActionListener JavaDoc () {
272             public void actionPerformed (ActionEvent JavaDoc e) {
273                 try {
274                     Object JavaDoc o = jtable.getValueAt(jtable.getSelectedRow(), jtable.getSelectedColumn());
275                     String JavaDoc output = (o != null) ? o.toString () : ""; //NOI18N
276
ExClipboard clipboard = (ExClipboard) Lookup.getDefault().lookup (ExClipboard.class);
277                     StringSelection JavaDoc strSel = new StringSelection JavaDoc (output);
278                     clipboard.setContents (strSel, strSel);
279                 } catch (ArrayIndexOutOfBoundsException JavaDoc exc) {
280                 }
281             }
282         });
283         tablePopupMenu.add (miCopyValue);
284
285         JMenuItem JavaDoc miCopyRowValues = new JMenuItem JavaDoc (bundle.getString ("CopyRowValues")); //NOI18N
286
miCopyRowValues.addActionListener(new ActionListener JavaDoc () {
287             public void actionPerformed (ActionEvent JavaDoc e) {
288                 try {
289                     int[] rows = jtable.getSelectedRows ();
290                     int[] columns;
291                     if (jtable.getRowSelectionAllowed ()) {
292                         columns = new int[jtable.getColumnCount ()];
293                         for (int a = 0; a < columns.length; a ++)
294                             columns[a] = a;
295                     } else {
296                         columns = jtable.getSelectedColumns ();
297                     }
298                     if (rows != null && columns != null) {
299                         StringBuffer JavaDoc output = new StringBuffer JavaDoc ();
300                         for (int row = 0; row < rows.length; row ++) {
301                             for (int column = 0; column < columns.length; column ++) {
302                                 if (column > 0)
303                                     output.append ('\t'); //NOI18N
304
Object JavaDoc o = jtable.getValueAt(rows[row], columns[column]);
305                                 output.append (o != null ? o.toString () : ""); //NOI18N
306
}
307                             output.append ('\n'); //NOI18N
308
}
309                         ExClipboard clipboard = (ExClipboard) Lookup.getDefault().lookup (ExClipboard.class);
310                         StringSelection JavaDoc strSel = new StringSelection JavaDoc (output.toString ());
311                         clipboard.setContents (strSel, strSel);
312                     }
313                 } catch (ArrayIndexOutOfBoundsException JavaDoc exc) {
314                 }
315             }
316         });
317         tablePopupMenu.add (miCopyRowValues);
318
319         // Table with results
320
// TableSorter sorter = new TableSorter();
321
jtable = new JTable JavaDoc(dbadaptor/*sorter*/);
322         jtable.getAccessibleContext().setAccessibleName(bundle.getString("ACS_DataViewTableA11yName")); //NOI18N
323
jtable.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewTableA11yDesc")); //NOI18N
324
jtable.setToolTipText(bundle.getString("ACS_DataViewTableA11yDesc")); //NOI18N
325
jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
326         // sorter.addMouseListenerToHeaderInTable(table);
327
jtable.addMouseListener (new MouseAdapter JavaDoc () {
328             public void mouseReleased (MouseEvent JavaDoc e) {
329                 if (e.getButton() == MouseEvent.BUTTON3) {
330                     int row = jtable.rowAtPoint (e.getPoint ());
331                     int column = jtable.columnAtPoint (e.getPoint ());
332                     boolean inSelection = false;
333                     int[] rows = jtable.getSelectedRows ();
334                     for (int a = 0; a < rows.length; a ++)
335                         if (rows[a] == row) {
336                             inSelection = true;
337                             break;
338                         }
339                     if (!jtable.getRowSelectionAllowed ()) {
340                         inSelection = false;
341                         int[] columns = jtable.getSelectedColumns ();
342                         for (int a = 0; a < columns.length; a ++)
343                             if (columns[a] == column) {
344                                 inSelection = true;
345                                 break;
346                             }
347                     }
348                     if (!inSelection)
349                         jtable.changeSelection (row, column, false, false);
350                     tablePopupMenu.show(jtable, e.getX (), e.getY ());
351                 }
352             }
353         });
354         tableLabel.setLabelFor(jtable);
355
356         scrollpane = new JScrollPane JavaDoc(jtable);
357         subcon2.fill = GridBagConstraints.BOTH;
358         subcon2.weightx = 1.0;
359         subcon2.weighty = 1.0;
360         subcon2.gridx = 0;
361         subcon2.gridy = 1;
362         subcon2.gridwidth = 1;
363         sublayout2.setConstraints(scrollpane, subcon2);
364         subpane2.add(scrollpane);
365
366         // Add it into splitview
367
con.weightx = 1.0;
368         con.weighty = 1.0;
369         con.fill = GridBagConstraints.BOTH;
370         con.gridx = 0;
371         con.gridwidth = 1;
372         con.gridy = 1;
373         con.insets = new Insets JavaDoc (12, 12, 11, 11);
374
375         JSplitPane JavaDoc split = new JSplitPane JavaDoc(JSplitPane.VERTICAL_SPLIT, subpane, subpane2);
376         layout.setConstraints(split, con);
377         add(split);
378     }
379     
380     /**Overriden to provide preferred value
381      * for unique TopComponent Id returned by getID. Returned value is used as starting
382      * value for creating unique TopComponent ID.
383      * Value should be preferably unique, but need not be.
384      * @since 4.13
385      */

386     protected String JavaDoc preferredID() {
387         return getName();
388     }
389     
390     /** Overriden to explicitely set persistence type of DataViewWindow
391      * to PERSISTENCE_NEVER */

392     public int getPersistenceType() {
393         return TopComponent.PERSISTENCE_NEVER;
394     }
395     
396     /** Returns query used by panel.
397     */

398     public String JavaDoc getCommand() {
399         return queryarea.getText();
400     }
401
402     /** Sets query used by panel.
403     */

404     public void setCommand(String JavaDoc command) {
405         queryarea.setText(command);
406     }
407
408     public boolean executeCommand() {
409         String JavaDoc command = queryarea.getText().trim();
410         boolean ret;
411
412         try {
413             dbadaptor.execute(command);
414
415             RecentCommand rcmd = new RecentCommand(command);
416             ((ComboModel)rcmdscombo.getModel()).addElement(rcmd);
417             ret = true;
418         } catch (Exception JavaDoc exc) {
419             ret = false;
420             status.setText(bundle.getString("CommandFailed")); //NOI18N
421
org.openide.DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(bundle.getString("DataViewFetchErrorPrefix") + exc.getMessage(), NotifyDescriptor.ERROR_MESSAGE)); //NOI18N
422
}
423
424         return ret;
425     }
426
427     class ColDef {
428         private String JavaDoc name;
429         private boolean writable;
430         private boolean bric;
431         int datatype;
432
433         public ColDef(String JavaDoc name, boolean flag) {
434             this.name = name;
435             writable = flag;
436         }
437
438         public String JavaDoc getName() {
439             return name;
440         }
441
442         public void setName(String JavaDoc name) {
443             this.name = name;
444         }
445
446         public int getDataType() {
447             return datatype;
448         }
449
450         public void setDataType(int type) {
451             datatype = type;
452         }
453
454         public boolean isWritable() {
455             return writable;
456         }
457
458         public void setWritable(boolean flag) {
459             writable = flag;
460         }
461
462         public boolean isBestRowIdentifierColumn() {
463             return bric;
464         }
465
466         public void setBestRowIdentifierColumn(boolean flag) {
467             bric = flag;
468         }
469     }
470
471     static int tstrg = 0;
472     static int gtcmd = 0;
473
474     class RecentCommand {
475         private String JavaDoc command;
476
477         /** The command with no new lines */
478         private String JavaDoc shortCommand;
479
480         public RecentCommand(String JavaDoc cmd) {
481             command = cmd;
482             shortCommand = getShortCommand();
483         }
484
485         public String JavaDoc toString() {
486             return shortCommand;
487         }
488
489         public String JavaDoc getCommand() {
490             return command;
491         }
492
493         public boolean equals(Object JavaDoc obj) {
494             if (obj instanceof RecentCommand)
495                 return ((RecentCommand)obj).getShortCommand().equals(shortCommand);
496
497             return super.equals(obj);
498         }
499
500         /**
501          * Gets the command String for display in the JComboBox without
502          * new lines.
503          *
504          * @return the command for display in the JComboBox
505          */

506          private String JavaDoc getShortCommand() {
507             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(command);
508             StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
509             while (tokenizer.hasMoreElements()) {
510                 buffer.append(tokenizer.nextElement());
511                 buffer.append(" ");
512             }
513             return buffer.toString();
514         }
515     }
516
517     class ComboModel extends AbstractListModel JavaDoc implements MutableComboBoxModel JavaDoc{
518         Vector JavaDoc commands;
519         Object JavaDoc selected;
520
521         static final long serialVersionUID =-5831993904798984334L;
522         public ComboModel() {
523             this(new Vector JavaDoc(1));
524         }
525
526         public ComboModel(Vector JavaDoc elems) {
527             commands = elems;
528         }
529
530         public Object JavaDoc getSelectedItem() {
531             return selected;
532         }
533
534         public void setSelectedItem(Object JavaDoc anItem) {
535             selected = anItem;
536             fireContentsChanged(this,-1,-1);
537         }
538
539         public void addElement(Object JavaDoc obj) {
540             if (!commands.contains(obj)) {
541                 commands.add(obj);
542                 fireContentsChanged(this,-1,-1);
543             }
544         }
545
546         public void removeElement(Object JavaDoc obj) {
547             commands.removeElement(obj);
548             fireContentsChanged(this,-1,-1);
549         }
550
551         public void insertElementAt(Object JavaDoc obj, int index) {
552             if (!commands.contains(obj)) {
553                 commands.insertElementAt(obj, index);
554                 fireContentsChanged(this,-1,-1);
555             }
556         }
557
558         public void removeElementAt(int index) {
559             commands.removeElementAt(index);
560             fireContentsChanged(this,-1,-1);
561         }
562
563         public int getSize() {
564             return commands.size();
565         }
566
567         public Object JavaDoc getElementAt(int index) {
568             return commands.get(index);
569         }
570     }
571
572     class ViewDropTarget implements DropTargetListener JavaDoc {
573         /** User is starting to drag over us */
574         public void dragEnter (DropTargetDragEvent JavaDoc dtde) {
575             dtde.acceptDrag(dtde.getDropAction());
576         }
577
578         /** User drags over us */
579         public void dragOver (DropTargetDragEvent JavaDoc dtde) {
580         }
581
582         public void dropActionChanged (DropTargetDragEvent JavaDoc dtde) {
583         }
584
585         /** User exits the dragging */
586         public void dragExit (DropTargetEvent JavaDoc dte) {
587         }
588
589         private ColumnNodeInfo getNodeInfo(Transferable JavaDoc t) {
590             Node n = NodeTransfer.node(t, NodeTransfer.MOVE);
591             if (n != null)
592                 return (ColumnNodeInfo)n.getCookie(ColumnNodeInfo.class);
593
594             n = NodeTransfer.node(t, NodeTransfer.COPY);
595             if (n != null)
596                 return (ColumnNodeInfo)n.getCookie(ColumnNodeInfo.class);
597
598             return null;
599         }
600
601         /** Performs the drop action */
602         public void drop (DropTargetDropEvent JavaDoc dtde) {
603             String JavaDoc query = null;
604             Transferable JavaDoc t = dtde.getTransferable();
605             StringBuffer JavaDoc buff = new StringBuffer JavaDoc();
606
607             try {
608                 DataFlavor JavaDoc multiFlavor = new DataFlavor JavaDoc (
609                     "application/x-java-openide-multinode;class=org.openide.util.datatransfer.MultiTransferObject", // NOI18N
610
NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("transferFlavorsMultiFlavorName"),
611                         MultiTransferObject.class.getClassLoader());
612
613                 if (t.isDataFlavorSupported(multiFlavor)) {
614                     MultiTransferObject mobj = (MultiTransferObject)t.getTransferData(ExTransferable.multiFlavor);
615                     int count = mobj.getCount();
616                     int tabidx = 0;
617                     HashMap JavaDoc tabidxmap = new HashMap JavaDoc();
618                     for (int i = 0; i < count; i++) {
619                         ColumnNodeInfo nfo = getNodeInfo(mobj.getTransferableAt(i));
620                         if (nfo != null) {
621                             String JavaDoc tablename = nfo.getTable();
622                             Integer JavaDoc tableidx = (Integer JavaDoc)tabidxmap.get(tablename);
623                             if (tableidx == null) tabidxmap.put(tablename, tableidx = new Integer JavaDoc(tabidx++));
624                             if (buff.length()>0) buff.append(", "); //NOI18N
625
buff.append("t"+tableidx+"."+nfo.getName()); //NOI18N
626
}
627                     }
628
629                     StringBuffer JavaDoc frombuff = new StringBuffer JavaDoc();
630                     Iterator JavaDoc iter = tabidxmap.keySet().iterator();
631                     while (iter.hasNext()) {
632                         String JavaDoc tab = (String JavaDoc)iter.next();
633                         if (frombuff.length()>0) frombuff.append(", "); //NOI18N
634
frombuff.append(tab + " t"+tabidxmap.get(tab)); //NOI18N
635
}
636
637                     query = "select "+buff.toString()+" from "+frombuff.toString(); //NOI18N
638

639                 } else {
640                     ColumnNodeInfo nfo = getNodeInfo(t);
641                     if (nfo != null) query = "select "+nfo.getName()+" from "+nfo.getTable(); //NOI18N
642
}
643
644                 if (query != null)
645                     setCommand(query);
646             } catch (Exception JavaDoc e) {
647                 e.printStackTrace();
648             }
649         }
650     }
651
652     class DataModel extends AbstractTableModel JavaDoc {
653         DatabaseNodeInfo node_info;
654         Vector JavaDoc coldef = new Vector JavaDoc();
655         Vector JavaDoc data = new Vector JavaDoc();
656         boolean editable = false;
657
658         static final long serialVersionUID =7729426847826999963L;
659
660         /** Constructor */
661         public DataModel(DatabaseNodeInfo node_info) throws SQLException JavaDoc {
662             this.node_info = node_info;
663         }
664
665         /** Executes command
666         * @param command SQL Expression
667         */

668         synchronized public void execute(String JavaDoc command) throws Exception JavaDoc {
669             if (command.length() == 0) {
670                 status.setText(" "); //NOI18N
671
return;
672             }
673
674             status.setText(bundle.getString("CommandRunning")); //NOI18N
675

676             Connection JavaDoc con;
677             Statement JavaDoc stat;
678             try {
679                 con = node_info.getConnection();
680                 stat = con.createStatement();
681             } catch ( Exception JavaDoc exc ) {
682                 String JavaDoc message = MessageFormat.format(bundle.getString("EXC_ConnectionError"), new String JavaDoc[] {exc.getMessage()}); // NOI18N
683
throw new DatabaseException(message);
684             }
685
686             ResultSet JavaDoc rs;
687
688             if (command.toLowerCase().startsWith("select")) { //NOI18N
689
rs = stat.executeQuery(command);
690
691                 ResultSetMetaData JavaDoc mdata = rs.getMetaData();
692
693                 int cols = mdata.getColumnCount();
694                 // Bug : 5083676
695
// Data is getting cleared and modified in a independent thread , while the swing
696
// thread tries to render the table. Hence this sometimes results in a
697
// ArrayIndexOutOfBoundsException
698
// Creating two 'work' vectors here and populating required changes in these
699
// Then replacing the model vectors with these.
700
Vector JavaDoc coldefWork = new Vector JavaDoc();
701                 Vector JavaDoc dataWork = new Vector JavaDoc();
702                 for(int column = 1; column <= cols; column++) {
703                     boolean writable;
704                     try {
705                         writable = mdata.isWritable(column);
706                     } catch (SQLException JavaDoc exc) {
707                         //patch for FireBirdSQL (isWritable has not been implemented yet)
708
writable = false;
709                     }
710                     ColDef cd = new ColDef(mdata.getColumnLabel(column), writable);
711                     cd.setDataType(mdata.getColumnType(column));
712                     coldefWork.add(cd);
713                 }
714
715                 // Get all rows.
716
// In future implementations should be more careful
717
int rcounter = 0;
718 // int limit = RootNode.getOption().getFetchLimit();
719
// int step = RootNode.getOption().getFetchStep();
720
int limit = 100;
721                 int step = 200;
722                 
723                 String JavaDoc cancel = bundle.getString("DataViewCancelButton"); //NOI18N
724
String JavaDoc nextset = bundle.getString("DataViewNextFetchButton"); //NOI18N
725
String JavaDoc allset = bundle.getString("DataViewAllFetchButton"); //NOI18N
726

727                 JButton JavaDoc fetchNext = new JButton JavaDoc();
728                 Mnemonics.setLocalizedText(fetchNext, nextset);
729                 fetchNext.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewNextFetchButtonA11yDesc")); //NOI18N
730

731                 JButton JavaDoc fetchAll = new JButton JavaDoc();
732                 Mnemonics.setLocalizedText(fetchAll, allset);
733                 fetchAll.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewAllFetchButtonA11yDesc")); //NOI18N
734

735                 JButton JavaDoc no = new JButton JavaDoc();
736                 Mnemonics.setLocalizedText(no, cancel);
737                 no.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_DataViewCancelButtonA11yDesc")); //NOI18N
738

739                 String JavaDoc message;
740                 NotifyDescriptor ndesc;
741                 while (rs.next()) {
742                     Vector JavaDoc row = new Vector JavaDoc(cols);
743                     for (int column = 1; column <= cols; column++)
744                         row.add(rs.getObject(column));
745                     dataWork.addElement(row);
746
747                     // Catch row count
748
if (++rcounter >= limit) {
749                         
750                         message = MessageFormat.format(bundle.getString("DataViewMessage"), new Object JavaDoc[] {
751                             new Integer JavaDoc(rcounter),
752                             new Integer JavaDoc(step)
753                         }); //NOI18N
754
ndesc = new NotifyDescriptor(message, bundle.getString("FetchDataTitle"), NotifyDescriptor.YES_NO_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE, new Object JavaDoc[] {fetchNext, fetchAll, no}, NotifyDescriptor.CANCEL_OPTION); //NOI18N
755

756                         Object JavaDoc ret = DialogDisplayer.getDefault().notify(ndesc);
757                         if (fetchAll.equals(ret)) {
758                             limit = Integer.MAX_VALUE;
759                         } else {
760                             if (fetchNext.equals(ret)) {
761                                 limit = limit + step;
762                             } else {
763                                 // window closed by close button or Esc key
764
// or the cancel button was pressed
765
break;
766                             }
767                         }
768                     }
769                 }
770                 
771                 // Replace model in the swing event thread
772
// Alternative is to lock on the instance and assign it.
773
final Vector JavaDoc assignData = dataWork;
774                 final Vector JavaDoc assignColdef = coldefWork;
775                 SwingUtilities.invokeAndWait(new Runnable JavaDoc(){
776                     public void run(){
777                         data = assignData;
778                         coldef = assignColdef;
779                         fireTableChanged(null);
780                     }
781                 });
782                 /*
783                 synchronized(coldef){
784                     coldef = assignColdef;
785                 }
786                 synchronized(data){
787                     data = assignData;
788                 }
789                  */

790                 rs.close();
791                 //fireTableChanged(null);
792
} else {
793                 if (command.toLowerCase().startsWith("delete") || command.toLowerCase().startsWith("insert") || command.toLowerCase().startsWith("update")) //NOI18N
794
stat.executeUpdate(command);
795                 else {
796                     stat.execute(command);
797
798                     //refresh DBExplorer nodes
799
while (!(node instanceof ConnectionNode))
800                         node = node.getParentNode();
801                     Enumeration JavaDoc nodes = node.getChildren().nodes();
802                     while (nodes.hasMoreElements())
803                         ((DatabaseNodeInfo)((Node)nodes.nextElement()).getCookie(DatabaseNodeInfo.class)).refreshChildren();
804                 }
805             }
806             status.setText(bundle.getString("CommandExecuted")); //NOI18N
807
stat.close();
808         }
809
810         /** Returns column name
811         * @param column Column index
812         */

813         public String JavaDoc getColumnName(int column) {
814             synchronized (coldef) {
815                 if (column < coldef.size()) {
816                     String JavaDoc cname = ((ColDef)coldef.elementAt(column)).getName();
817                     return cname;
818                 }
819
820                 return ""; //NOI18N
821
}
822         }
823
824         /** Returns column renderer/editor class
825         * @param column Column index
826         */

827         public Class JavaDoc getColumnClass(int column) {
828             synchronized (coldef) {
829                 if (column < coldef.size()) {
830                     int coltype = ((ColDef)coldef.elementAt(column)).getDataType();
831                     switch (coltype) {
832                         case Types.CHAR:
833                         case Types.VARCHAR:
834                         case Types.LONGVARCHAR: return String JavaDoc.class;
835                         case Types.BIT: return Boolean JavaDoc.class;
836                         case Types.TINYINT:
837                         case Types.SMALLINT:
838                         case Types.INTEGER: return Integer JavaDoc.class;
839                         case Types.BIGINT: return Long JavaDoc.class;
840                         case Types.FLOAT:
841                         case Types.DOUBLE: return Double JavaDoc.class;
842                         case Types.DATE: return java.sql.Date JavaDoc.class;
843                     }
844                 }
845
846                 return Object JavaDoc.class;
847             }
848         }
849
850         /** Returns true, if cell is editable
851         */

852         public boolean isCellEditable(int row, int column) {
853             synchronized (coldef) {
854                 if (!editable)
855                     return false;
856
857                 if (column < coldef.size())
858                     return ((ColDef)coldef.elementAt(column)).isWritable();
859
860                 return false;
861             }
862         }
863
864         /** Returns colun count
865         */

866         public int getColumnCount() {
867             synchronized (coldef) {
868                 return coldef.size();
869             }
870         }
871
872         /** Returns row count
873         */

874         public int getRowCount() {
875             synchronized (data) {
876                 return data.size();
877             }
878         }
879
880         /** Returns value at specified position
881         */

882         public Object JavaDoc getValueAt(int aRow, int aColumn) {
883             synchronized (data) {
884                 Vector JavaDoc row = new Vector JavaDoc();
885                 if (aRow < data.size())
886                     row = (Vector JavaDoc) data.elementAt(aRow);
887                 if (row != null && aColumn < row.size())
888                     return row.elementAt(aColumn);
889
890                 return null;
891             }
892         }
893
894         private String JavaDoc format(Object JavaDoc value, int type) {
895             if (value == null)
896                 return "null"; //NOI18N
897

898             switch(type) {
899                 case Types.INTEGER:
900                 case Types.DOUBLE:
901                 case Types.FLOAT: return value.toString();
902                 case Types.BIT: return ((Boolean JavaDoc)value).booleanValue() ? "1" : "0"; //NOI18N
903
case Types.DATE: return value.toString();
904                 default: return "\""+value.toString()+"\""; //NOI18N
905
}
906         }
907
908         public void setValueAt(Object JavaDoc value, int row, int column) {
909             synchronized (coldef) {
910                 int enucol = 0;
911                 StringBuffer JavaDoc where = new StringBuffer JavaDoc();
912                 Enumeration JavaDoc enu = coldef.elements();
913                 while (enu.hasMoreElements()) {
914                     ColDef cd = (ColDef)enu.nextElement();
915                     if (cd.isBestRowIdentifierColumn()) {
916                         String JavaDoc key = cd.getName();
917                         String JavaDoc val = format(getValueAt(row,enucol), cd.getDataType());
918                         if (where.length()>0)
919                             where.append(" and "); //NOI18N
920
where.append(key+" = "+val); //NOI18N
921
}
922                     enucol++;
923                 }
924             }
925         }
926     }
927
928     protected Object JavaDoc writeReplace() throws ObjectStreamException JavaDoc {
929         return null;
930     }
931 }
932
Popular Tags