KickJava   Java API By Example, From Geeks To Geeks.

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


1 /*
2  * Copyright (C) 2006 JasperSoft http://www.jaspersoft.com
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed WITHOUT ANY WARRANTY; and without the
10  * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11  * See the GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
15  * or write to:
16  *
17  * Free Software Foundation, Inc.,
18  * 59 Temple Place - Suite 330,
19  * Boston, MA USA 02111-1307
20  *
21  *
22  * SQLFieldsProvider.java
23  *
24  * Created on December 7, 2006, 9:22 AM
25  *
26  * To change this template, choose Tools | Template Manager
27  * and open the template in the editor.
28  */

29
30 package it.businesslogic.ireport.data;
31
32 import bsh.Interpreter;
33 import it.businesslogic.ireport.FieldsProvider;
34 import it.businesslogic.ireport.FieldsProviderEditor;
35 import it.businesslogic.ireport.IReportConnection;
36 import it.businesslogic.ireport.gui.ReportQueryDialog;
37 import it.businesslogic.ireport.util.Misc;
38 import java.awt.Component JavaDoc;
39 import java.sql.Connection JavaDoc;
40 import java.sql.PreparedStatement JavaDoc;
41 import java.sql.ResultSet JavaDoc;
42 import java.sql.ResultSetMetaData JavaDoc;
43 import java.util.ArrayList JavaDoc;
44 import java.util.List JavaDoc;
45 import java.util.Map JavaDoc;
46 import javax.swing.JDialog JavaDoc;
47 import javax.swing.JOptionPane JavaDoc;
48 import net.sf.jasperreports.engine.JRDataset;
49 import net.sf.jasperreports.engine.JRException;
50 import net.sf.jasperreports.engine.JRField;
51 import net.sf.jasperreports.engine.JRParameter;
52 import net.sf.jasperreports.engine.design.JRDesignField;
53
54 /**
55  *
56  * @author gtoffoli
57  */

58 public class SQLFieldsProvider implements FieldsProvider {
59     
60     public static boolean useVisualDesigner = true;
61     
62     static {
63         
64         java.util.Properties JavaDoc p = new java.util.Properties JavaDoc();
65         try {
66             java.io.InputStream JavaDoc is = SQLFieldsProvider.class.getClass().getResourceAsStream("/it/businesslogic/ireport/data/fieldsprovider.properties");
67             
68             p.load( is );
69
70             if (p.getProperty("sql").equals("0"))
71             {
72                 useVisualDesigner = false;
73             }
74         } catch (Exception JavaDoc ex)
75         {
76             ex.printStackTrace();
77         }
78         
79     }
80     
81     
82     /** Creates a new instance of SQLFieldsProvider */
83     public SQLFieldsProvider() {
84         
85         
86     }
87     
88     /**
89      * Returns true if the provider supports the {@link #getFields(IReportConnection,JRDataset,Map) getFields}
90      * operation. By returning true in this method the data source provider indicates
91      * that it is able to introspect the data source and discover the available fields.
92      *
93      * @return true if the getFields() operation is supported.
94      */

95     public boolean supportsGetFieldsOperation() {
96         return true;
97     }
98
99     public JRField[] getFields(IReportConnection irConn, JRDataset reportDataset, Map JavaDoc parameters) throws JRException, UnsupportedOperationException JavaDoc {
100         
101         if (irConn == null || !irConn.isJDBCConnection()) {
102              throw new JRException("The active connection is not of type JDBC. Activate a JDBC connection first.");
103         }
104         
105         String JavaDoc query = reportDataset.getQuery().getText();
106         String JavaDoc error_msg = "";
107         Connection con = null;
108         PreparedStatement JavaDoc ps = null;
109         
110         try {
111                 // look for parameters in the query and replace them with default values.
112
// parameters look something like
113
// $P{QuoteGroupID}
114
// or
115
// $P!{OrderByClause}
116
java.util.List JavaDoc queryParams = new ArrayList JavaDoc();
117                 JRParameter[] jrParams = reportDataset.getParameters();
118                 for (int k=0; k<jrParams.length; ++k)
119                 {
120                     JRParameter parameter = jrParams[k];
121
122                     String JavaDoc p1 = "$P{" + parameter.getName() + "}";
123                     String JavaDoc p2 = "$P!{" + parameter.getName() + "}";
124
125                     Object JavaDoc defValue = parameters.get(parameter.getName());
126                     
127                     int ip1 = query.indexOf(p1);
128                     while( ip1!=-1 ) {
129                         // add a query parameter
130
if( defValue==null ) {
131                             throw new IllegalArgumentException JavaDoc("Please set a " +
132                             "default value for the parameter '" +
133                             parameter.getName() + "'" );
134                         }
135
136                         String JavaDoc before = query.substring(0, ip1);
137                         String JavaDoc after = query.substring(ip1+p1.length());
138                         query = before + " ? " + after;
139                         queryParams.add( defValue );
140                         ip1 = query.indexOf(p1);
141                     }
142
143                     int ip2 = query.indexOf(p2);
144                     while( ip2!=-1 ) {
145                         // String replacement, Altering the SQL statement.
146
if( defValue==null ) {
147                             throw new IllegalArgumentException JavaDoc("Please set a " +
148                                 "default value for the parameter '"
149                                 + parameter.getName() + "'" );
150                         }
151
152                         String JavaDoc before = query.substring(0, ip2);
153                         String JavaDoc after = query.substring(ip2+p2.length());
154                         query = before + "" + defValue.toString() + "" + after;
155                         ip2 = query.indexOf(p2);
156                     }
157                 }
158                 
159                 con = irConn.getConnection();
160                 
161                 //if (in < num) return;
162
ps = con.prepareStatement( query );
163                 for(int pc=0; pc<queryParams.size(); pc++ ) {
164                     ps.setObject(pc+1, queryParams.get(pc) );
165                 }
166                 
167                 // Some JDBC drivers don't supports this method...
168
try { ps.setFetchSize(0); } catch(Exception JavaDoc e ) {}
169                 
170                 
171                 ResultSet JavaDoc rs = ps.executeQuery();
172                 
173                 //if (in < num) return;
174

175                 ResultSetMetaData JavaDoc rsmd = rs.getMetaData();
176
177                 //if (in < num) return;
178

179                 List JavaDoc columns = new ArrayList JavaDoc();
180                 for (int i=1; i <=rsmd.getColumnCount(); ++i) {
181                     JRDesignField field = new JRDesignField();
182                     field.setName( rsmd.getColumnLabel(i) );
183                     field.setValueClassName( Misc.getJdbcTypeClass(rsmd, i) );
184                     field.setDescription("");
185                     columns.add( field );
186                 }
187
188                 JRField[] final_fields = new JRField[columns.size()];
189                 for (int i=0; i<final_fields.length; ++i)
190                 {
191                     final_fields[i] = (JRField)columns.get(i);
192                 }
193                 
194                 return final_fields;
195                 
196             } catch( IllegalArgumentException JavaDoc ie ) {
197                 throw new JRException( ie.getMessage() );
198             } catch (NoClassDefFoundError JavaDoc ex) {
199                 ex.printStackTrace();
200                 error_msg = "NoClassDefFoundError!!\nCheck your classpath!";
201                 throw new JRException( error_msg );
202             } catch (java.sql.SQLException JavaDoc ex) {
203                 error_msg = "SQL problems:\n"+ex.getMessage();
204                 throw new JRException( error_msg );
205             } catch (Exception JavaDoc ex) {
206                 ex.printStackTrace();
207                 error_msg = "General problem:\n"+ex.getMessage()+
208                     "\n\nCheck username and password; is the DBMS active ?!";
209                 throw new JRException( error_msg );
210             } catch (Throwable JavaDoc t)
211             {
212               throw new JRException( t.getMessage() );
213             } finally {
214                 if(ps!=null) try { ps.close(); } catch(Exception JavaDoc e ) {}
215                 if(con !=null) try { con.close(); } catch(Exception JavaDoc e ) {}
216             }
217     }
218
219     public boolean supportsAutomaticQueryExecution() {
220         return true;
221     }
222
223     public boolean hasQueryDesigner() {
224         return useVisualDesigner;
225     }
226
227     public boolean hasEditorComponent() {
228         return false;
229     }
230
231     public String JavaDoc designQuery(IReportConnection con, String JavaDoc query, ReportQueryDialog reportQueryDialog) throws JRException, UnsupportedOperationException JavaDoc {
232         // Start FREE QUERY BUILDER....
233
QueryBuilderDialog qbd = new QueryBuilderDialog( (reportQueryDialog != null) ? reportQueryDialog : new JDialog JavaDoc(), true);
234         
235         if (con.isJDBCConnection())
236         {
237             qbd.setConnection( con.getConnection() );
238         }
239         try {
240             
241             if (query != null && query.length() > 0)
242             {
243                 qbd.setQuery(query);
244             }
245         } catch (Exception JavaDoc ex)
246         {
247             if (reportQueryDialog != null)
248             {
249                 reportQueryDialog.getJLabelStatusSQL().setText("I'm sorry, I'm unable to parse the query...");
250                 ex.printStackTrace();
251             }
252             return null;
253         }
254         qbd.setVisible(true);
255         
256         if (qbd.getDialogResult() == JOptionPane.OK_OPTION)
257         {
258             return qbd.getQuery();
259         }
260         return null;
261     }
262
263     public FieldsProviderEditor getEditorComponent(ReportQueryDialog reportQueryDialog) {
264         return null;
265     }
266     
267 }
268
Popular Tags