KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > it > businesslogic > ireport > data > hibernate > HQLFieldsReader


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  * HQLFieldsReader.java
28  *
29  * Created on February 22, 2006, 1:27 PM
30  *
31  */

32
33 package it.businesslogic.ireport.data.hibernate;
34
35 import bsh.Interpreter;
36 import it.businesslogic.ireport.IReportConnection;
37 import it.businesslogic.ireport.JRField;
38 import it.businesslogic.ireport.JRParameter;
39 import it.businesslogic.ireport.connection.JRHibernateConnection;
40 import it.businesslogic.ireport.data.FieldClassWrapper;
41 import it.businesslogic.ireport.gui.MainFrame;
42 import it.businesslogic.ireport.gui.ReportQueryDialog;
43 import it.businesslogic.ireport.util.Misc;
44
45 import java.util.Collection JavaDoc;
46 import java.util.Enumeration JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Iterator JavaDoc;
49 import java.util.Map JavaDoc;
50 import java.util.Vector JavaDoc;
51
52 import org.hibernate.Hibernate;
53 import org.hibernate.Query;
54 import org.hibernate.SessionFactory;
55 import org.hibernate.Transaction;
56 import org.hibernate.cfg.Configuration;
57 import org.hibernate.classic.Session;
58 import org.hibernate.type.Type;
59
60 /**
61  *
62  * @author gtoffoli
63  */

64 public class HQLFieldsReader {
65     
66     private static final Map JavaDoc hibernateTypeMap;
67     
68     
69     static
70     {
71             hibernateTypeMap = new HashMap JavaDoc();
72             hibernateTypeMap.put(Boolean JavaDoc.class, Hibernate.BOOLEAN);
73             hibernateTypeMap.put(Byte JavaDoc.class, Hibernate.BYTE);
74             hibernateTypeMap.put(Double JavaDoc.class, Hibernate.DOUBLE);
75             hibernateTypeMap.put(Float JavaDoc.class, Hibernate.FLOAT);
76             hibernateTypeMap.put(Integer JavaDoc.class, Hibernate.INTEGER);
77             hibernateTypeMap.put(Long JavaDoc.class, Hibernate.LONG);
78             hibernateTypeMap.put(Short JavaDoc.class, Hibernate.SHORT);
79             hibernateTypeMap.put(java.math.BigDecimal JavaDoc.class, Hibernate.BIG_DECIMAL);
80             hibernateTypeMap.put(java.math.BigInteger JavaDoc.class, Hibernate.BIG_INTEGER);
81             hibernateTypeMap.put(Character JavaDoc.class, Hibernate.CHARACTER);
82             hibernateTypeMap.put(String JavaDoc.class, Hibernate.STRING);
83             hibernateTypeMap.put(java.util.Date JavaDoc.class, Hibernate.DATE);
84             hibernateTypeMap.put(java.sql.Timestamp JavaDoc.class, Hibernate.TIMESTAMP);
85             hibernateTypeMap.put(java.sql.Time JavaDoc.class, Hibernate.TIME);
86     }
87     
88     private Interpreter interpreter = null;
89     private Vector JavaDoc reportParameters = null;
90     private String JavaDoc queryString = "";
91     private HashMap JavaDoc queryParameters = new HashMap JavaDoc();
92     
93     private Vector JavaDoc notScalars = new Vector JavaDoc();
94         
95     /** Creates a new instance of HQLFieldsReader */
96     public HQLFieldsReader(String JavaDoc query, Vector JavaDoc reportParameters) {
97         
98         
99         this.setQueryString(query);
100         this.setReportParameters(reportParameters);
101     }
102     
103     
104     public String JavaDoc prepareQuery() throws Exception JavaDoc
105     {
106         System.out.println(getReportParameters());
107        Enumeration JavaDoc enumParams = getReportParameters().elements();
108        
109        while( enumParams.hasMoreElements() ) {
110            
111            JRParameter param = (JRParameter)enumParams.nextElement();
112            String JavaDoc parameterName = param.getName();
113            
114            if (queryString.indexOf("$P!{" + parameterName + "}") > 0)
115            {
116                 Object JavaDoc paramVal = ReportQueryDialog.recursiveInterpreter( getInterpreter(), param.getDefaultValueExpression(),getReportParameters());
117            
118                 if (paramVal == null)
119                 {
120                     paramVal = "";
121                 }
122                 
123                 queryString = Misc.string_replace(""+paramVal, "$P!{" + parameterName + "}", queryString);
124            }
125            else if (getQueryString().indexOf("$P{" + parameterName + "}") > 0)
126            {
127                Object JavaDoc paramVal = ReportQueryDialog.recursiveInterpreter( getInterpreter(), param.getDefaultValueExpression(),getReportParameters());
128                String JavaDoc parameterReplacement = "_" + getLiteral(parameterName);
129                
130                queryParameters.put(parameterReplacement, paramVal);
131                        
132                queryString = Misc.string_replace(":"+parameterReplacement, "$P{" + parameterName + "}", queryString);
133                
134                System.out.println( queryString );
135            }
136         }
137        return queryString;
138     }
139     
140     
141     public Vector JavaDoc readFields() throws Exception JavaDoc
142     {
143         prepareQuery();
144         
145         
146         SessionFactory hb_sessionFactory = null;
147         Session hb_session = null;
148         Transaction transaction = null;
149         
150         notScalars.clear();
151         
152         try {
153                 IReportConnection conn = (IReportConnection)MainFrame.getMainInstance().getProperties().get("DefaultConnection");
154                if (!(conn instanceof JRHibernateConnection))
155                {
156                    throw new Exception JavaDoc("No Hibernate connection selected.");
157                }
158                
159                hb_session = ((JRHibernateConnection)conn).createSession();
160
161                 if (hb_session == null)
162                 {
163                     throw new Exception JavaDoc("Problem creating the Session object for Hibernate");
164                 }
165
166                 transaction = hb_session.beginTransaction();
167                 Query q = hb_session.createQuery(getQueryString());
168                 
169                 Iterator JavaDoc paramIterator = queryParameters.keySet().iterator();
170                 
171                 while (paramIterator.hasNext())
172                 {
173                     String JavaDoc hqlParamName = ""+paramIterator.next();
174                     setParameter(hb_session,q, hqlParamName, queryParameters.get(hqlParamName));
175                 }
176
177                 q.setFetchSize(1);
178                 java.util.Iterator JavaDoc iterator = q.iterate();
179                 // this is a stupid thing: iterator.next();
180

181                 String JavaDoc[] aliases = q.getReturnAliases();
182                 Type[] types = q.getReturnTypes();
183
184                 
185                 Vector JavaDoc fields = new Vector JavaDoc();
186                 
187                 for (int i =0; i<types.length; ++i)
188                 {
189                     if (types[i].isComponentType() ||
190                         types[i].isEntityType())
191                     {
192                         
193                         // look for alias...
194
String JavaDoc aliasName = null;
195                         if (aliases != null && aliases.length > i && !aliases[i].equals(i+""))
196                         {
197                             aliasName = aliases[i];
198                             JRField field = new JRField(aliases[i], types[i].getReturnedClass().getName());
199                             field.setDescription(aliases[i]);
200                             fields.add(field);
201                             
202                             
203                         }
204                         
205                         // look for fields like for a javabean...
206
java.beans.PropertyDescriptor JavaDoc[] pd = org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors(types[i].getReturnedClass());
207                         
208                         if (aliasName != null)
209                         {
210                             notScalars.add( new FieldClassWrapper(aliasName, types[i].getReturnedClass().getName()));
211                         }
212                         else
213                         {
214                             notScalars.add( types[i].getReturnedClass().getName());
215                         }
216                         
217                         for (int nd =0; nd < pd.length; ++nd)
218                         {
219                                String JavaDoc fieldName = pd[nd].getName();
220                                if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null)
221                                {
222                                    if (fieldName.equals("class")) continue;
223                                    
224                                    String JavaDoc returnType = pd[nd].getPropertyType().getName();
225                                    
226                                    it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(fieldName, returnType);
227                                    if (types.length > 1 && aliasName != null)
228                                    {
229                                        fieldName = aliasName+"."+fieldName;
230                                        field.setDescription(fieldName); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
231
field.setName(fieldName);
232                                    }
233                                    fields.add(field);
234                                }
235                         }
236                         
237                         
238                     }
239                     else
240                     {
241                         String JavaDoc fieldName = types[i].getName();
242                         if (aliases != null &&
243                             aliases.length > i &&
244                             !aliases[i].equals(""+i)) fieldName = aliases[i];
245                         JRField field = new JRField(fieldName, types[i].getReturnedClass().getName());
246                         field.setDescription("");
247                         fields.add(field);
248                     }
249                 }
250                 /*
251                 else
252                 {
253                     for (int i =0; i<types.length; ++i)
254                     {
255                         if (aliases != null && aliases.length > 0 && !aliases[0].equals(""+i))
256                         {
257                             JRField field = new JRField(aliases[i], types[i].getReturnedClass().getName());
258                             field.setDescription("The whole entity/component object");
259                             fields.add(field);
260                             
261                             
262                         }
263                         
264                         
265                     // out.println(types[i].getName() + " " + types[i].getReturnedClass().getName() + "<br>");
266                     }
267                 }
268                  */

269                 
270                 return fields;
271
272            } catch (Exception JavaDoc ex)
273            {
274                ex.printStackTrace();
275                throw ex;
276             } finally {
277                
278                 if (transaction != null) try { transaction.rollback(); } catch (Exception JavaDoc ex) { }
279                if (hb_session != null) try { hb_session.close(); } catch (Exception JavaDoc ex) { }
280            }
281     }
282     
283     /**
284      * Binds a paramter value to a query paramter.
285      *
286      * @param parameter the report parameter
287      */

288     protected void setParameter(Session session, Query query, String JavaDoc hqlParamName, Object JavaDoc parameterValue) throws Exception JavaDoc
289     {
290             //ClassLoader cl = MainFrame.getMainInstance().getReportClassLoader();
291

292             if (parameterValue == null)
293             {
294                 System.out.println("Parameter: " + hqlParamName);
295                 query.setParameter(hqlParamName, parameterValue);
296                 return;
297             }
298             
299             Class JavaDoc clazz = parameterValue.getClass();
300             Type type = (Type) hibernateTypeMap.get(clazz);
301
302             if (type != null)
303             {
304                     query.setParameter(hqlParamName, parameterValue, type);
305             }
306             else if (Collection JavaDoc.class.isAssignableFrom(clazz))
307             {
308                     query.setParameterList(hqlParamName, (Collection JavaDoc) parameterValue);
309             }
310             else
311             {
312                     if (session.getSessionFactory().getClassMetadata(clazz) != null) //param type is a hibernate mapped entity
313
{
314                             query.setEntity(hqlParamName, parameterValue);
315                     }
316                     else //let hibernate try to guess the type
317
{
318                             query.setParameter(hqlParamName, parameterValue);
319                     }
320             }
321     }
322     
323     private Interpreter prepareExpressionEvaluator() throws bsh.EvalError {
324         
325         Interpreter interpreter = new Interpreter();
326         interpreter.setClassLoader(interpreter.getClass().getClassLoader());
327         return interpreter;
328     }
329     
330     
331     /**
332      * Takes a name and returns the same if it is a Java identifier;
333      * else it substitutes the illegal characters so that it can be an identifier
334      *
335      * @param name
336      */

337     public static String JavaDoc getLiteral(String JavaDoc name)
338     {
339         if (isValidLiteral(name))
340         {
341             return name;
342         }
343
344         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(name.length() + 5);
345         
346         char[] literalChars = new char[name.length()];
347         name.getChars(0, literalChars.length, literalChars, 0);
348         
349         for (int i = 0; i < literalChars.length; i++)
350         {
351             if (i == 0 && !Character.isJavaIdentifierStart(literalChars[i]))
352             {
353                 buffer.append((int)literalChars[i]);
354             }
355             else if (i != 0 && !Character.isJavaIdentifierPart(literalChars[i]))
356             {
357                 buffer.append((int)literalChars[i]);
358             }
359             else
360             {
361                 buffer.append(literalChars[i]);
362             }
363         }
364         
365         return buffer.toString();
366     }
367     
368     
369     /**
370      * Checks if the input is a valid Java literal
371      * @param literal
372      * @author Gaganis Giorgos (gaganis@users.sourceforge.net)
373      */

374     private static boolean isValidLiteral(String JavaDoc literal)
375     {
376         boolean result = true;
377         
378         char[] literalChars = new char[literal.length()];
379         literal.getChars(0, literalChars.length, literalChars, 0);
380         
381         for (int i = 0; i < literalChars.length; i++)
382         {
383             if (i == 0 && !Character.isJavaIdentifierStart(literalChars[i]))
384             {
385                 result = false;
386                 break;
387             }
388             
389             if (i != 0 && !Character.isJavaIdentifierPart(literalChars[i]))
390             {
391                 result = false;
392                 break;
393             }
394         }
395         
396         return result;
397     }
398
399     public Interpreter getInterpreter() {
400         
401         if (interpreter == null)
402         {
403             try {
404             interpreter = prepareExpressionEvaluator();
405             } catch (Exception JavaDoc ex)
406             {
407             
408             }
409         }
410         return interpreter;
411     }
412
413     public void setInterpreter(Interpreter interpreter) {
414         this.interpreter = interpreter;
415     }
416
417     public Vector JavaDoc getReportParameters() {
418         return reportParameters;
419     }
420
421     public void setReportParameters(Vector JavaDoc reportParameters) {
422         this.reportParameters = reportParameters;
423     }
424
425     public String JavaDoc getQueryString() {
426         return queryString;
427     }
428
429     public void setQueryString(String JavaDoc queryString) {
430         this.queryString = queryString;
431     }
432
433     public HashMap JavaDoc getQueryParameters() {
434         return queryParameters;
435     }
436
437     public void setQueryParameters(HashMap JavaDoc queryParameters) {
438         this.queryParameters = queryParameters;
439     }
440
441     public Vector JavaDoc getNotScalars() {
442         return notScalars;
443     }
444
445     public void setNotScalars(Vector JavaDoc notScalars) {
446         this.notScalars = notScalars;
447     }
448
449 }
450
Popular Tags