KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > db > explorer > dlg > CreateTableDialog


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.dlg;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.io.InputStream JavaDoc;
25 import java.util.*;
26 import java.text.MessageFormat JavaDoc;
27 import javax.swing.*;
28 import javax.swing.border.*;
29 import javax.swing.table.*;
30 import org.openide.DialogDescriptor;
31 import org.openide.DialogDisplayer;
32 import org.openide.NotifyDescriptor;
33 import org.openide.util.NbBundle;
34 import org.openide.util.RequestProcessor;
35 import org.netbeans.lib.ddl.impl.Specification;
36 import org.netbeans.lib.ddl.impl.CreateTable;
37 import org.netbeans.lib.ddl.util.CommandBuffer;
38 import org.netbeans.lib.ddl.impl.CreateIndex;
39 import org.netbeans.lib.ddl.util.PListReader;
40 import org.netbeans.modules.db.explorer.infos.DatabaseNodeInfo;
41 import org.netbeans.modules.db.util.TextFieldValidator;
42 import org.netbeans.modules.db.util.ValidableTextField;
43 import org.openide.awt.Mnemonics;
44 import org.openide.util.Utilities;
45
46 public class CreateTableDialog {
47     boolean result = false;
48     Dialog dialog = null;
49     JTextField dbnamefield, dbownerfield;
50     JTable table;
51     JComboBox ownercombo;
52     JButton addbtn, delbtn;
53     Specification spec;
54     private Vector ttab;
55
56     private static Map dlgtab = null;
57     private static final String JavaDoc filename = "org/netbeans/modules/db/resources/CreateTableDialog.plist"; // NOI18N
58
private ResourceBundle bundle = NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle"); // NOI18N
59

60     public static final Map getProperties() {
61         if (dlgtab == null) try {
62             ClassLoader JavaDoc cl = CreateTableDialog.class.getClassLoader();
63             InputStream JavaDoc stream = cl.getResourceAsStream(filename);
64             if (stream == null) {
65                 String JavaDoc message = MessageFormat.format(NbBundle.getBundle("org.netbeans.modules.db.resources.Bundle").getString("EXC_UnableToOpenStream"), new String JavaDoc[] {filename}); // NOI18N
66
throw new Exception JavaDoc(message);
67             }
68             PListReader reader = new PListReader(stream);
69             dlgtab = reader.getData();
70             stream.close();
71         } catch (Exception JavaDoc e) {
72             e.printStackTrace();
73             dlgtab = null;
74         }
75
76         return dlgtab;
77     }
78
79     public CreateTableDialog(final Specification spe, DatabaseNodeInfo nfo) throws java.sql.SQLException JavaDoc {
80         spec = spe;
81         try {
82             JLabel label;
83             JPanel pane = new JPanel();
84             pane.setBorder(new EmptyBorder(new Insets(5,5,5,5)));
85             GridBagLayout layout = new GridBagLayout();
86             GridBagConstraints constr = new GridBagConstraints();
87             pane.setLayout(layout);
88             pane.setMinimumSize(new Dimension(200,100));
89      
90             // Table name field
91

92             label = new JLabel();
93             Mnemonics.setLocalizedText(label, bundle.getString("CreateTableName")); // NOI18N
94
label.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_CreateTableNameA11yDesc"));
95             constr.anchor = GridBagConstraints.WEST;
96             constr.weightx = 0.0;
97             constr.weighty = 0.0;
98             constr.fill = GridBagConstraints.NONE;
99             constr.insets = new java.awt.Insets JavaDoc (2, 2, 2, 2);
100             constr.gridx = 0;
101             constr.gridy = 0;
102             layout.setConstraints(label, constr);
103             pane.add(label);
104
105             constr.fill = GridBagConstraints.HORIZONTAL;
106             constr.weightx = 1.0;
107             constr.weighty = 0.0;
108             constr.gridx = 1;
109             constr.gridy = 0;
110             constr.insets = new java.awt.Insets JavaDoc (2, 2, 2, 2);
111             dbnamefield = new JTextField(bundle.getString("CreateTableUntitledName"), 10); // NOI18N
112
dbnamefield.setToolTipText(bundle.getString("ACS_CreateTableNameTextFieldA11yDesc"));
113             dbnamefield.getAccessibleContext().setAccessibleName(bundle.getString("ACS_CreateTableNameTextFieldA11yName"));
114             label.setLabelFor(dbnamefield);
115             layout.setConstraints(dbnamefield, constr);
116             pane.add(dbnamefield);
117
118             // Table owner combo
119

120             label = new JLabel();
121             Mnemonics.setLocalizedText(label, bundle.getString("CreateTableOwner")); // NOI18N
122
label.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_CreateTableOwnerA11yDesc"));
123             constr.anchor = GridBagConstraints.WEST;
124             constr.weightx = 0.0;
125             constr.weighty = 0.0;
126             constr.fill = GridBagConstraints.NONE;
127             constr.insets = new java.awt.Insets JavaDoc (2, 10, 2, 2);
128             constr.gridx = 2;
129             constr.gridy = 0;
130             layout.setConstraints(label, constr);
131             pane.add(label);
132
133             Vector users = new Vector();
134             String JavaDoc schema = nfo.getDriverSpecification().getSchema();
135             if (schema != null && schema.length() > 0)
136                 users.add(schema);
137             else
138                 users.add(" "); //NOI18N
139

140             constr.fill = GridBagConstraints.HORIZONTAL;
141             constr.weightx = 0.0;
142             constr.weighty = 0.0;
143             constr.gridx = 3;
144             constr.gridy = 0;
145             constr.insets = new java.awt.Insets JavaDoc (2, 2, 2, 2);
146             ownercombo = new JComboBox(users);
147             ownercombo.setSelectedIndex(0);
148             ownercombo.setRenderer(new ListCellRendererImpl());
149             ownercombo.setToolTipText(bundle.getString("ACS_CreateTableOwnerComboBoxA11yDesc"));
150             ownercombo.getAccessibleContext().setAccessibleName(bundle.getString("ACS_CreateTableOwnerComboBoxA11yName"));
151             label.setLabelFor(ownercombo);
152             layout.setConstraints(ownercombo, constr);
153             pane.add(ownercombo);
154
155             // Table columns in scrollpane
156

157             constr.fill = GridBagConstraints.BOTH;
158             constr.weightx = 1.0;
159             constr.weighty = 1.0;
160             constr.gridx = 0;
161             constr.gridy = 1;
162             constr.gridwidth = 4;
163             constr.gridheight = 3;
164             constr.insets = new java.awt.Insets JavaDoc (2, 2, 2, 2);
165             table = new DataTable(new DataModel());
166             table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
167             table.setToolTipText(bundle.getString("ACS_CreateTableColumnTableA11yDesc"));
168             table.getAccessibleContext().setAccessibleName(bundle.getString("ACS_CreateTableColumnTableA11yName"));
169             table.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_CreateTableColumnTableA11yDesc"));
170             JScrollPane scrollpane = new JScrollPane(table);
171             scrollpane.setBorder(new BevelBorder(BevelBorder.LOWERED));
172             layout.setConstraints(scrollpane, constr);
173             pane.add(scrollpane);
174
175             // Setup cell editors for table
176

177             Map tmap = spec.getTypeMap();
178             ttab = new Vector(tmap.size());
179             Iterator iter = tmap.keySet().iterator();
180             while (iter.hasNext()) {
181                 String JavaDoc iterkey = (String JavaDoc)iter.next();
182                 String JavaDoc iterval = (String JavaDoc)tmap.get(iterkey);
183                 ttab.add(new TypeElement(iterkey, iterval));
184             }
185
186             final JComboBox combo = new JComboBox(ttab);
187             combo.setSelectedIndex(0);
188             table.setDefaultEditor(String JavaDoc.class, new DataCellEditor(new JTextField()));
189             table.getColumn("type").setCellEditor(new ComboBoxEditor(combo)); // NOI18N
190
table.getColumn("size").setCellEditor(new DataCellEditor(new ValidableTextField(new TextFieldValidator.integer()))); // NOI18N
191
table.getColumn("scale").setCellEditor(new DataCellEditor(new ValidableTextField(new TextFieldValidator.integer()))); // NOI18N
192
table.setRowHeight(combo.getPreferredSize().height);
193
194             // Button pane
195

196             constr.fill = GridBagConstraints.HORIZONTAL;
197             constr.anchor = GridBagConstraints.NORTH;
198             constr.weightx = 0.0;
199             constr.weighty = 0.0;
200             constr.gridx = 4;
201             constr.gridy = 1;
202             constr.insets = new java.awt.Insets JavaDoc (2, 8, 2, 2);
203             JPanel btnpane = new JPanel();
204             GridLayout btnlay = new GridLayout(2,1,0,5);
205             btnpane.setLayout(btnlay);
206             layout.setConstraints(btnpane, constr);
207             pane.add(btnpane);
208
209             // Button add column
210

211             addbtn = new JButton();
212             Mnemonics.setLocalizedText(addbtn, bundle.getString("CreateTableAddButtonTitle")); // NOI18N
213
addbtn.setToolTipText(bundle.getString("ACS_CreateTableAddButtonTitleA11yDesc"));
214             btnpane.add(addbtn);
215             addbtn.addActionListener(new ActionListener() {
216                 public void actionPerformed(ActionEvent event) {
217                     if (table.getCellEditor() != null) {
218                         table.getCellEditor().stopCellEditing();
219                     }
220                     DataModel model = (DataModel)table.getModel();
221                     ColumnItem item = new ColumnItem();
222                     item.setProperty(ColumnItem.TYPE, ttab.elementAt(0));
223                     model.addRow(item);
224                 }
225             });
226
227             // Button delete column
228

229             delbtn = new JButton();
230             Mnemonics.setLocalizedText(delbtn, bundle.getString("CreateTableRemoveButtonTitle")); // NOI18N
231
delbtn.setToolTipText(bundle.getString("ACS_CreateTableRemoveButtonTitleA11yDesc"));
232             btnpane.add(delbtn);
233             delbtn.addActionListener(new ActionListener() {
234                 public void actionPerformed(ActionEvent event) {
235                     if (table.getCellEditor() != null) {
236                         table.getCellEditor().stopCellEditing();
237                     }
238                     int idx = table.getSelectedRow();
239                     if (idx != -1)
240                         ((DataModel)table.getModel()).removeRow(idx);
241                 }
242             });
243
244             ActionListener listener = new ActionListener() {
245                 public void actionPerformed(ActionEvent event) {
246                     final ActionEvent evt = event;
247                     if (table.getCellEditor() != null) {
248                         table.getCellEditor().stopCellEditing();
249                     }
250                     RequestProcessor.getDefault().post(new Runnable JavaDoc() {
251                         public void run () {
252                           if (evt.getSource() == DialogDescriptor.OK_OPTION) {
253                               result = validate();
254
255                               CommandBuffer cbuff = new CommandBuffer();
256                               Vector idxCommands = new Vector();
257
258                               if (result) {
259                                   try {
260                                       String JavaDoc tablename = getTableName();
261                                       DataModel dataModel = (DataModel)table.getModel();
262                                       Vector data = dataModel.getData();
263                                       CreateTable cmd = spec.createCommandCreateTable(tablename);
264
265                                       cmd.setObjectOwner(((String JavaDoc)ownercombo.getSelectedItem()).trim());
266
267                                       /* this variables and operation provide support for
268                                        * creating indexes for primary or unique keys,
269                                        * most of database are creating indexes by myself,
270                                        * support was removed */

271                                       org.netbeans.lib.ddl.impl.TableColumn cmdcol = null;
272                                       CreateIndex xcmd = null;
273                                       Enumeration enu = data.elements();
274                                       while (enu.hasMoreElements()) {
275                                           ColumnItem enuele = (ColumnItem)enu.nextElement();
276                                           String JavaDoc name = enuele.getName();
277                                           if (enuele.isPrimaryKey()&&!dataModel.isTablePrimaryKey())
278                                               cmdcol = cmd.createPrimaryKeyColumn(name);
279                                           else if (enuele.isUnique()&&!enuele.isPrimaryKey())
280                                               cmdcol = cmd.createUniqueColumn(name);
281                                           else cmdcol = cmd.createColumn(name);
282
283                                           //bugfix for #31064
284
combo.setSelectedItem(combo.getSelectedItem());
285
286                                           cmdcol.setColumnType(Specification.getType(enuele.getType().getType()));
287                                           cmdcol.setColumnSize(enuele.getSize());
288                                           cmdcol.setDecimalSize(enuele.getScale());
289                                           cmdcol.setNullAllowed(enuele.allowsNull());
290                                           String JavaDoc defval = enuele.getDefaultValue();
291                                           if (defval != null && defval.length() > 0)
292                                               cmdcol.setDefaultValue(defval);
293                                           if (enuele.hasCheckConstraint())
294                                               // add the TABLE check constraint
295
cmd.createCheckConstraint(name, enuele.getCheckConstraint());
296                                           if (enuele.isIndexed()&&!enuele.isPrimaryKey()&&!enuele.isUnique()) {
297                                               xcmd = spec.createCommandCreateIndex(tablename);
298                                               xcmd.setIndexName(tablename+ "_" + name + "_idx"); // NOI18N
299
xcmd.setIndexType(new String JavaDoc());
300                                               xcmd.setObjectOwner((String JavaDoc)ownercombo.getSelectedItem());
301                                               xcmd.specifyColumn(name);
302                                               idxCommands.add(xcmd);
303                                           }
304                                       }
305                                       if(dataModel.isTablePrimaryKey()) {
306                                           cmdcol = cmd.createPrimaryKeyConstraint(tablename);
307                                           cmdcol.setTableConstraintColumns(dataModel.getTablePrimaryKeys());
308                                           cmdcol.setColumnType(0);
309                                           cmdcol.setColumnSize(0);
310                                           cmdcol.setDecimalSize(0);
311                                           cmdcol.setNullAllowed(true);
312
313                                       }
314                                       cbuff.add(cmd);
315                                       for(int i=0;i<idxCommands.size();i++)
316                                           cbuff.add((CreateIndex)idxCommands.elementAt(i));
317                                       // index support removed!
318
//if (icmd.getColumns().size()>0) cbuff.add(icmd);
319

320                                       //execute DDL command
321
cbuff.execute();
322
323                                       // was execution of commands with or without exception?
324
if(!cbuff.wasException()) {
325                                           // dialog is closed after successfully create table
326
dialog.setVisible(false);
327                                           dialog.dispose();
328                                       }
329                                       //dialog is not closed after unsuccessfully create table
330

331                                   } catch (Exception JavaDoc e) {
332                                       e.printStackTrace();
333
334                                   }
335                               } else {
336                                   String JavaDoc msg = bundle.getString("EXC_InsufficientCreateTableInfo");
337                                   DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE));
338                               }
339                           }
340                         }
341                     }, 0);
342                }
343             };
344
345             pane.getAccessibleContext().setAccessibleDescription(bundle.getString("ACS_CreateTableDialogA11yDesc"));
346
347             addbtn.doClick();
348             DialogDescriptor descriptor = new DialogDescriptor(pane, bundle.getString("CreateTableDialogTitle"), true, listener); // NOI18N
349
// inbuilt close of the dialog is only after CANCEL button click
350
// after OK button is dialog closed by hand
351
Object JavaDoc [] closingOptions = {DialogDescriptor.CANCEL_OPTION};
352             descriptor.setClosingOptions(closingOptions);
353             dialog = DialogDisplayer.getDefault().createDialog(descriptor);
354             dialog.setResizable(true);
355         } catch (MissingResourceException ex) {
356             ex.printStackTrace();
357         }
358     }
359
360     public boolean run() {
361         if (dialog != null) dialog.setVisible(true);
362         return result;
363     }
364
365     public String JavaDoc getTableName() {
366         return dbnamefield.getText();
367     }
368
369     private boolean validate() {
370         String JavaDoc tname = getTableName();
371         if (tname == null || tname.length()<1)
372             return false;
373
374         Vector cols = ((DataModel)table.getModel()).getData();
375         Enumeration colse = cols.elements();
376         while(colse.hasMoreElements())
377             if (!((ColumnItem)colse.nextElement()).validate())
378                 return false;
379
380         return true;
381     }
382
383     class DataTable extends JTable {
384         static final long serialVersionUID =1222037401669064863L;
385         public DataTable(TableModel model) {
386             super(model);
387             setSurrendersFocusOnKeystroke(true);
388             TableColumnModel cmodel = getColumnModel();
389             int i;
390             int ccount = model.getColumnCount();
391             int columnWidth;
392             int preferredWidth;
393             String JavaDoc columnName;
394             int width = 0;
395             for (i = 0; i < ccount; i++) {
396                 TableColumn col = cmodel.getColumn(i);
397                 Map cmap = ColumnItem.getColumnProperty(i);
398                 col.setIdentifier(cmap.get("name")); //NOI18N
399
columnName = bundle.getString("CreateTable_" + i); //NOI18N
400
columnWidth = (new Double JavaDoc(getFontMetrics(getFont()).getStringBounds(columnName, getGraphics()).getWidth())).intValue() + 20;
401                 if (cmap.containsKey("width")) { // NOI18N
402
if (((Integer JavaDoc)cmap.get("width")).intValue() < columnWidth)
403                         col.setPreferredWidth(columnWidth);
404                     else
405                         col.setPreferredWidth(((Integer JavaDoc)cmap.get("width")).intValue()); // NOI18N
406
preferredWidth = col.getPreferredWidth();
407                 }
408                 if (cmap.containsKey("minwidth")) // NOI18N
409
if (((Integer JavaDoc)cmap.get("minwidth")).intValue() < columnWidth)
410                         col.setMinWidth(columnWidth);
411                     else
412                         col.setMinWidth(((Integer JavaDoc)cmap.get("minwidth")).intValue()); // NOI18N
413
// if (cmap.containsKey("alignment")) {}
414
// if (cmap.containsKey("tip")) ((JComponent)col.getCellRenderer()).setToolTipText((String)cmap.get("tip"));
415
if (i < 7) { // the first 7 columns should be visible
416
width += col.getPreferredWidth();
417                 }
418             }
419             width = Math.min(Math.max(width, 380), Toolkit.getDefaultToolkit().getScreenSize().width - 100);
420             setPreferredScrollableViewportSize(new Dimension(width, 150));
421         }
422     }
423
424     class FocusInvoker implements Runnable JavaDoc {
425         private JTextField xxx;
426         public FocusInvoker(JTextField fld) {
427             xxx=fld;
428         }
429
430         public void run() {
431             xxx.selectAll();
432         }
433     }
434
435     class DataCellEditor extends DefaultCellEditor {
436         static final long serialVersionUID =3855371868128838794L;
437
438         public DataCellEditor(final JTextField x) {
439             super(x);
440             setClickCountToStart(1);
441         }
442     }
443     
444     class PopupInvoker implements Runnable JavaDoc {
445         private JComboBox jComboBox;
446
447         public PopupInvoker(JComboBox aJComboBox) {
448             jComboBox = aJComboBox;
449         }
450
451         public void run() {
452             try {
453                 jComboBox.showPopup();
454             } catch (IllegalComponentStateException icse) {
455                 // This is a valid exception that occurs
456
// if the jComboBox is somehow hide. Do nothing.
457
}
458         }
459
460     }
461
462     class ComboBoxEditor extends DefaultCellEditor {
463         public ComboBoxEditor(final JComboBox jComboBox) {
464             super(jComboBox);
465             jComboBox.addFocusListener(new FocusListener() {
466                 public void focusGained(FocusEvent e) {
467                     SwingUtilities.invokeLater(new PopupInvoker(jComboBox));
468                 }
469
470                 public void focusLost(FocusEvent e) {}
471             });
472         }
473     }
474
475     private static final class ListCellRendererImpl extends DefaultListCellRenderer {
476         
477         public Dimension getPreferredSize() {
478             Dimension size = super.getPreferredSize();
479             // hack to fix issue 65759
480
if (Utilities.isWindows()) {
481                 size.width += 4;
482             }
483             return size;
484         }
485     }
486 }
487
Popular Tags