KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > it > businesslogic > ireport > data > BeanInspectorPanel


1 /*
2  * Copyright (C) 2005 - 2006 JasperSoft Corporation. All rights reserved.
3  * http://www.jaspersoft.com.
4  *
5  * Unless you have purchased a commercial license agreement from JasperSoft,
6  * the following license terms apply:
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License version 2 as published by
10  * the Free Software Foundation.
11  *
12  * This program is distributed WITHOUT ANY WARRANTY; and without the
13  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
14  * See the GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
18  * or write to:
19  *
20  * Free Software Foundation, Inc.,
21  * 59 Temple Place - Suite 330,
22  * Boston, MA USA 02111-1307
23  *
24  *
25  *
26  *
27  * BeanInspectorPanel.java
28  *
29  * Created on June 19, 2006, 2:57 PM
30  *
31  */

32
33 package it.businesslogic.ireport.data;
34
35 import it.businesslogic.ireport.FieldsProviderEditor;
36 import it.businesslogic.ireport.JRField;
37 import it.businesslogic.ireport.ReportClassLoader;
38 import it.businesslogic.ireport.gui.JBTreeCellRenderer;
39 import it.businesslogic.ireport.gui.MainFrame;
40 import it.businesslogic.ireport.gui.ReportQueryDialog;
41 import it.businesslogic.ireport.gui.TreeJRField;
42 import it.businesslogic.ireport.data.hibernate.HQLFieldsReader;
43 import it.businesslogic.ireport.util.Misc;
44 import java.util.ArrayList JavaDoc;
45 import java.util.List JavaDoc;
46 import java.util.Vector JavaDoc;
47 import javax.swing.JTable JavaDoc;
48 import javax.swing.SwingUtilities JavaDoc;
49 import javax.swing.table.DefaultTableModel JavaDoc;
50 import javax.swing.tree.DefaultMutableTreeNode JavaDoc;
51 import javax.swing.tree.DefaultTreeModel JavaDoc;
52 import javax.swing.tree.TreePath JavaDoc;
53 import it.businesslogic.ireport.util.I18n;
54
55 /**
56  *
57  * @author gtoffoli
58  */

59 public class BeanInspectorPanel extends javax.swing.JPanel JavaDoc implements FieldsProviderEditor {
60     
61     private boolean pathOnDescription = false;
62     private JTable JavaDoc jTableFields = null;
63     private boolean comboVisible = true;
64     private ReportQueryDialog reportQueryDialog = null;
65     
66     
67     /** Creates new form BeanInspectorPanel */
68     public BeanInspectorPanel() {
69         initComponents();
70         
71         DefaultTreeModel JavaDoc dttm = (DefaultTreeModel JavaDoc)jTree1.getModel();
72         DefaultMutableTreeNode JavaDoc root = new DefaultMutableTreeNode JavaDoc();
73         jTree1.setModel(new DefaultTreeModel JavaDoc( root ));
74         
75         jTree1.setCellRenderer( new JBTreeCellRenderer());
76         
77         applyI18n();
78     }
79     
80     
81     public void setClassNames(List JavaDoc classNames)
82     {
83         if (classNames == null) return;
84         
85         jComboBox1.removeAllItems();
86         for (int i=0; i<classNames.size(); ++i)
87         {
88             jComboBox1.addItem( classNames.get(i));
89         }
90         
91         jComboBox1ActionPerformed(null);
92     }
93     
94     /**
95      * Must be used when the combobox is not visible...
96      */

97     public void setClassName(String JavaDoc className)
98     {
99         DefaultMutableTreeNode JavaDoc root = (DefaultMutableTreeNode JavaDoc)jTree1.getModel().getRoot();
100         root.removeAllChildren();
101         jTree1.updateUI();
102         if (className != null && className.trim().length() > 0)
103         {
104             exploreBean( root,className, "");
105         }
106     }
107     
108     /** This method is called from within the constructor to
109      * initialize the form.
110      * WARNING: Do NOT modify this code. The content of this method is
111      * always regenerated by the Form Editor.
112      */

113     // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
114
private void initComponents() {
115         java.awt.GridBagConstraints JavaDoc gridBagConstraints;
116
117         jPanel1 = new javax.swing.JPanel JavaDoc();
118         jLabel1 = new javax.swing.JLabel JavaDoc();
119         jComboBox1 = new javax.swing.JComboBox JavaDoc();
120         jScrollPane1 = new javax.swing.JScrollPane JavaDoc();
121         jTree1 = new javax.swing.JTree JavaDoc();
122         jPanel2 = new javax.swing.JPanel JavaDoc();
123         jButton2 = new javax.swing.JButton JavaDoc();
124         jButton3 = new javax.swing.JButton JavaDoc();
125
126         setLayout(new java.awt.GridBagLayout JavaDoc());
127
128         jPanel1.setLayout(new java.awt.GridBagLayout JavaDoc());
129
130         jLabel1.setText("Bean");
131         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
132         gridBagConstraints.insets = new java.awt.Insets JavaDoc(4, 4, 4, 4);
133         jPanel1.add(jLabel1, gridBagConstraints);
134
135         jComboBox1.setMinimumSize(new java.awt.Dimension JavaDoc(51, 22));
136         jComboBox1.addActionListener(new java.awt.event.ActionListener JavaDoc() {
137             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
138                 jComboBox1ActionPerformed(evt);
139             }
140         });
141
142         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
143         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
144         gridBagConstraints.weightx = 1.0;
145         gridBagConstraints.insets = new java.awt.Insets JavaDoc(4, 0, 4, 0);
146         jPanel1.add(jComboBox1, gridBagConstraints);
147
148         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
149         gridBagConstraints.gridx = 0;
150         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
151         gridBagConstraints.weightx = 1.0;
152         add(jPanel1, gridBagConstraints);
153
154         jTree1.setRootVisible(false);
155         jTree1.addMouseListener(new java.awt.event.MouseAdapter JavaDoc() {
156             public void mouseClicked(java.awt.event.MouseEvent JavaDoc evt) {
157                 jTree1MouseClicked1(evt);
158             }
159         });
160
161         jScrollPane1.setViewportView(jTree1);
162
163         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
164         gridBagConstraints.gridx = 0;
165         gridBagConstraints.gridwidth = 3;
166         gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
167         gridBagConstraints.weightx = 1.0;
168         gridBagConstraints.weighty = 1.0;
169         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 4, 0, 0);
170         add(jScrollPane1, gridBagConstraints);
171
172         jPanel2.setLayout(new java.awt.GridBagLayout JavaDoc());
173
174         jButton2.setText("Add selected field(s)");
175         jButton2.addActionListener(new java.awt.event.ActionListener JavaDoc() {
176             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
177                 jButton2ActionPerformed(evt);
178             }
179         });
180
181         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
182         gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
183         gridBagConstraints.weightx = 1.0;
184         gridBagConstraints.insets = new java.awt.Insets JavaDoc(2, 0, 2, 4);
185         jPanel2.add(jButton2, gridBagConstraints);
186
187         jButton3.setText("Clear fields list");
188         jButton3.addActionListener(new java.awt.event.ActionListener JavaDoc() {
189             public void actionPerformed(java.awt.event.ActionEvent JavaDoc evt) {
190                 jButton2ActionPerformed1(evt);
191             }
192         });
193
194         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
195         gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHEAST;
196         gridBagConstraints.insets = new java.awt.Insets JavaDoc(2, 0, 2, 0);
197         jPanel2.add(jButton3, gridBagConstraints);
198
199         gridBagConstraints = new java.awt.GridBagConstraints JavaDoc();
200         gridBagConstraints.gridx = 0;
201         gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
202         gridBagConstraints.weightx = 1.0;
203         gridBagConstraints.insets = new java.awt.Insets JavaDoc(0, 4, 0, 0);
204         add(jPanel2, gridBagConstraints);
205
206     }// </editor-fold>//GEN-END:initComponents
207

208     private void jButton2ActionPerformed1(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_jButton2ActionPerformed1
209

210         DefaultTableModel JavaDoc dtm = (DefaultTableModel JavaDoc)getJTableFields().getModel();
211         dtm.setRowCount(0);
212         
213     }//GEN-LAST:event_jButton2ActionPerformed1
214

215     private void jButton2ActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_jButton2ActionPerformed
216

217         
218         // Get all selected paths...
219
if (MainFrame.getMainInstance().getActiveReportFrame() == null || getJTableFields() == null){
220             return;
221         }
222         
223         DefaultTableModel JavaDoc dtm = (DefaultTableModel JavaDoc)getJTableFields().getModel();
224          
225         TreePath JavaDoc[] paths = jTree1.getSelectionPaths();
226         if (paths == null) return;
227         for (int i=0; i<paths.length; ++i)
228         {
229             boolean valid = true;
230             TreePath JavaDoc tp = paths[i];
231
232             TreeJRField tjrf = (TreeJRField)((DefaultMutableTreeNode JavaDoc)tp.getLastPathComponent()).getUserObject();
233             String JavaDoc returnType = Misc.getJRFieldType( tjrf.getObj().getName() );
234             it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(tjrf.getField().getName(), returnType);
235             field.setDescription(tjrf.getField().getDescription() );
236             Vector JavaDoc row = new Vector JavaDoc();
237             row.addElement(field);
238             row.addElement(field.getClassType());
239             row.addElement(field.getDescription());
240             
241             if (isComboVisible() && jComboBox1.getSelectedItem() instanceof FieldClassWrapper)
242             {
243                 FieldClassWrapper cw = (FieldClassWrapper)jComboBox1.getSelectedItem();
244                 field.setName( cw.getFieldName() + "." + field.getDescription() );
245                 field.setDescription( field.getName() );
246             }
247
248             // Check for duplicates fields...
249
boolean found = fieldAlreadyExists(field);
250             String JavaDoc baseName = field.getName();
251             for (int j=1; isPathOnDescription() && found; ++j)
252             {
253                     field.setName( baseName + "_" + j);
254                     found = fieldAlreadyExists(field);
255             }
256             
257             if (!found)
258             {
259                 dtm.addRow(row);
260                 getJTableFields().getSelectionModel().addSelectionInterval( getJTableFields().getRowCount()-1, getJTableFields().getRowCount()-1 );
261             }
262         }
263     }//GEN-LAST:event_jButton2ActionPerformed
264

265     private void jComboBox1ActionPerformed(java.awt.event.ActionEvent JavaDoc evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
266

267         Object JavaDoc obj = jComboBox1.getSelectedItem();
268         if (obj == null)
269         {
270             setClassName(null);
271             return;
272         }
273         if (obj instanceof String JavaDoc) setClassName( (String JavaDoc)obj );
274         if (obj instanceof FieldClassWrapper) setClassName( ((FieldClassWrapper)obj).getClassType());
275             
276     }//GEN-LAST:event_jComboBox1ActionPerformed
277

278     
279     private boolean fieldAlreadyExists(JRField field)
280     {
281         boolean found = false;
282             for (int j=0; j<getJTableFields().getRowCount(); ++j)
283             {
284                Object JavaDoc ff = getJTableFields().getValueAt(j, 0);
285                if ( ff instanceof it.businesslogic.ireport.JRField )
286                {
287                    if ( ((it.businesslogic.ireport.JRField)ff).getName().equals(field.getName()))
288                    {
289                        found = true;
290                        break;
291                    }
292                }
293             }
294         
295         return found;
296     }
297     
298     private void jTree1MouseClicked1(java.awt.event.MouseEvent JavaDoc evt) {//GEN-FIRST:event_jTree1MouseClicked1
299

300         
301          if (evt.getClickCount() == 2 && evt.getButton() == evt.BUTTON1)
302         {
303             DefaultMutableTreeNode JavaDoc tn = (DefaultMutableTreeNode JavaDoc)jTree1.getSelectionPath().getLastPathComponent();
304             
305             if (tn.getChildCount()>0) return;
306             
307                 /*if (!jTree1.isCollapsed( jTree1.getSelectionPath() ))
308             {
309                 jTree1.collapsePath( jTree1.getSelectionPath() );
310                 return;
311             }
312                  *
313                  */

314             if (tn.getUserObject() instanceof TreeJRField)
315             {
316                 TreeJRField jrf = (TreeJRField)tn.getUserObject();
317                 if (!jrf.getObj().isPrimitive() && !jrf.getObj().getName().startsWith("java.lang."))
318                 {
319                    exploreBean(tn, jrf.getObj().getName(),
320                            isPathOnDescription() ?
321                             Misc.nvl( jrf.getField().getDescription() , "") :
322                             Misc.nvl( jrf.getField().getName() , "") );
323                 }
324             }
325         }
326          
327     }//GEN-LAST:event_jTree1MouseClicked1
328

329     
330     public void exploreBean(DefaultMutableTreeNode JavaDoc root, String JavaDoc classname, String JavaDoc parentPath)
331     {
332         try {
333             
334             root.removeAllChildren();
335             if (parentPath.length() > 0) parentPath += ".";
336             
337             MainFrame.reportClassLoader.rescanLibDirectory();
338             Class JavaDoc clazz = Class.forName(classname,true,MainFrame.reportClassLoader);
339             
340             java.beans.PropertyDescriptor JavaDoc[] pd = org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors(clazz);
341             for (int nd =0; nd < pd.length; ++nd)
342             {
343                    String JavaDoc fieldName = pd[nd].getName();
344                    if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null)
345                    {
346                        String JavaDoc returnType = pd[nd].getPropertyType().getName();
347                        it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField( Misc.getJRFieldType( fieldName ), returnType);
348                        if (isPathOnDescription())
349                        {
350                             field.setDescription(parentPath + fieldName);
351                        }
352                        else
353                        {
354                            field.setName(parentPath + fieldName);
355                        }
356                        
357                        TreeJRField jtf = new TreeJRField();
358                    
359                        jtf.setField( field );
360                        jtf.setObj( pd[nd].getPropertyType() );
361                    
362                        boolean bChildrens = true;
363                        if (pd[nd].getPropertyType().isPrimitive() || pd[nd].getPropertyType().getName().startsWith("java.lang."))
364                        {
365                            bChildrens = false;
366                        }
367                        root.add(new DefaultMutableTreeNode JavaDoc(jtf, bChildrens));
368                    }
369             }
370             
371             jTree1.expandPath( new TreePath JavaDoc(root.getPath()) );
372             jTree1.updateUI();
373             
374         } catch (ClassNotFoundException JavaDoc cnf)
375         {
376             javax.swing.JOptionPane.showMessageDialog(this,
377                     I18n.getFormattedString("messages.BeanInspectorPanel.classNotFoundError",
378                                 "Class not found error!!\nCheck your classpath and retry!\n{0}", new Object JavaDoc[]{cnf.getMessage()}),
379                     I18n.getString("message.title.error","Error"),javax.swing.JOptionPane.ERROR_MESSAGE);
380             return;
381         } catch (Exception JavaDoc ex)
382         {
383             javax.swing.JOptionPane.showMessageDialog(this, ex.getMessage() ,I18n.getString("message.title.error","Error"),javax.swing.JOptionPane.ERROR_MESSAGE);
384             return;
385         }
386     }
387
388     public JTable JavaDoc getJTableFields() {
389         return jTableFields;
390     }
391
392     public void setJTableFields(JTable JavaDoc jTableFields) {
393         this.jTableFields = jTableFields;
394     }
395
396     public boolean isComboVisible() {
397         return comboVisible;
398     }
399
400     public void setComboVisible(boolean comboVisible) {
401         this.comboVisible = comboVisible;
402         jPanel1.setVisible( comboVisible );
403     }
404
405     public boolean isPathOnDescription() {
406         return pathOnDescription;
407     }
408
409     public void setPathOnDescription(boolean pathOnDescription) {
410         this.pathOnDescription = pathOnDescription;
411     }
412     
413     // Variables declaration - do not modify//GEN-BEGIN:variables
414
private javax.swing.JButton JavaDoc jButton2;
415     private javax.swing.JButton JavaDoc jButton3;
416     private javax.swing.JComboBox JavaDoc jComboBox1;
417     private javax.swing.JLabel JavaDoc jLabel1;
418     private javax.swing.JPanel JavaDoc jPanel1;
419     private javax.swing.JPanel JavaDoc jPanel2;
420     private javax.swing.JScrollPane JavaDoc jScrollPane1;
421     private javax.swing.JTree JavaDoc jTree1;
422     // End of variables declaration//GEN-END:variables
423

424     
425     
426     
427     public void applyI18n(){
428                 // Start autogenerated code ----------------------
429
jButton2.setText(I18n.getString("beanInspectorPanel.button2","Add selected field(s)"));
430                 jButton3.setText(I18n.getString("beanInspectorPanel.button3","Clear fields list"));
431                 jLabel1.setText(I18n.getString("beanInspectorPanel.label1","Bean"));
432                 // End autogenerated code ----------------------
433
}
434
435     int lastExecution = 0;
436     
437     public void queryChanged(String JavaDoc newQuery) {
438     
439         lastExecution++;
440         int thisExecution = lastExecution;
441         // Execute a thread to perform the query change...
442

443         String JavaDoc error_msg = "";
444         lastExecution++;
445             
446         int in = lastExecution;
447         
448         if (getReportQueryDialog() == null) return;
449             
450         getReportQueryDialog().getJLabelStatusSQL().setText("Executing HQL query....");
451         /////////////////////////////
452

453         try {
454         Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader());
455         } catch (Exception JavaDoc ex)
456         {
457             ex.printStackTrace();
458         }
459             
460         if (in < lastExecution) return; //Abort, new execution requested
461

462         HQLFieldsReader hqlFR = new HQLFieldsReader(newQuery, getReportQueryDialog().getSubDataset().getParameters());
463             
464         if (in < lastExecution) return; //Abort, new execution requested
465

466         try {
467             Vector JavaDoc fields = hqlFR.readFields();
468
469             List JavaDoc columns = new ArrayList JavaDoc();
470             for (int i=0; i<fields.size(); ++i)
471             {
472                 JRField field = (JRField)fields.elementAt(i);
473                 columns.add( new Object JavaDoc[]{field, field.getClassType(), field.getDescription()} );
474             }
475
476             Vector JavaDoc v = hqlFR.getNotScalars();
477
478             if (v.size() == 0) v = null;
479             
480             if (in < lastExecution) return; //Abort, new execution requested
481
setBeanExplorerFromWorker(v,true,true);
482
483             if (in < lastExecution) return; //Abort, new execution requested
484
setColumnsFromWorker(columns);
485
486         } catch (Exception JavaDoc ex)
487         {
488             ex.printStackTrace();
489             setBeanExplorerFromWorker(null,true,true);
490             setColumnErrorFromWork( "Error: " + ex.getMessage() );
491         }
492         
493         getReportQueryDialog().getJLabelStatusSQL().setText("Ready");
494     }
495     
496     /**
497      * Set the columns error message in the ReportQueryDialog....
498      * This is called from a none swing thread, hence all the invoke and
499      * wait magic.
500      * The message is only set if the query string matches the one the
501      * error message is for.
502      *
503      * @param columns The list of columns to set.
504      */

505     protected void setColumnErrorFromWork( final String JavaDoc error_msg) {
506         try {
507
508             Runnable JavaDoc r = new Runnable JavaDoc() {
509                 public void run() {
510                     getReportQueryDialog().setColumnsError( error_msg );
511                     getReportQueryDialog().getSQLExpressionArea().requestFocusInWindow();
512                 }
513             };
514
515             if (SwingUtilities.isEventDispatchThread()) { r.run(); }
516             else { SwingUtilities.invokeAndWait( r ); }
517         
518         } catch(Exception JavaDoc e) {
519             // oh well we got interrupted.
520
}
521     }
522     
523     /**
524      * Set the columns in the ReportQueryDialog....
525      * This is called from a none swing thread, hence all the invoke and
526      * wait magic.
527      * The message is only set if the query string matches the one the
528      * error message is for.
529      *
530      * @param columns The list of columns to set.
531      */

532     protected void setColumnsFromWorker( final List JavaDoc columns) {
533         try {
534
535             Runnable JavaDoc r = new Runnable JavaDoc() {
536                 public void run() {
537                     getReportQueryDialog().setColumns( columns );
538                     getReportQueryDialog().getSQLExpressionArea().requestFocusInWindow();
539                 }
540             };
541
542             if (SwingUtilities.isEventDispatchThread()) { r.run(); }
543             else { SwingUtilities.invokeAndWait( r ); }
544         
545         } catch(Exception JavaDoc e) {
546             // oh well we got interrupted.
547
}
548     }
549     
550     /**
551      * Set the bean explorer
552      *
553      * @param columns The list of columns to set.
554      */

555     protected void setBeanExplorerFromWorker( final Vector JavaDoc v,final boolean pathOnDescription, final boolean useCombo){
556         try {
557             SwingUtilities.invokeAndWait( new Runnable JavaDoc() {
558                 public void run() {
559                     Vector JavaDoc v1 = v;
560                     if (v1 == null) v1 = new Vector JavaDoc();
561                     
562                     setComboVisible(useCombo);
563                     setPathOnDescription(pathOnDescription);
564                     setClassNames(v1);
565             
566                     getReportQueryDialog().getSQLExpressionArea().requestFocusInWindow();
567                     getReportQueryDialog().getSQLExpressionArea().requestFocus();
568                 }
569             } );
570         } catch(Exception JavaDoc e) {
571             // oh well we got interrupted.
572
e.printStackTrace();
573         }
574     }
575
576     public ReportQueryDialog getReportQueryDialog() {
577         return reportQueryDialog;
578     }
579
580     public void setReportQueryDialog(ReportQueryDialog reportQueryDialog) {
581         this.reportQueryDialog = reportQueryDialog;
582     }
583     
584     
585 }
586
Popular Tags