KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > it > businesslogic > ireport > data > ejbql > EJBQLFieldsReader


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

32
33 package it.businesslogic.ireport.data.ejbql;
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.EJBQLConnection;
40 import it.businesslogic.ireport.gui.MainFrame;
41 import it.businesslogic.ireport.gui.ReportQueryDialog;
42 import it.businesslogic.ireport.util.Misc;
43
44 import java.util.Collection JavaDoc;
45 import java.util.Enumeration JavaDoc;
46 import java.util.HashMap JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.util.List JavaDoc;
49 import java.util.Map JavaDoc;
50 import java.util.Set JavaDoc;
51 import java.util.Vector JavaDoc;
52
53 import javax.persistence.EntityManager;
54 import javax.persistence.Query;
55
56
57 /**
58  *
59  * @author gtoffoli
60  */

61 public class EJBQLFieldsReader {
62     
63     private Interpreter interpreter = null;
64     private Vector JavaDoc reportParameters = null;
65     private String JavaDoc queryString = "";
66     private HashMap JavaDoc queryParameters = new HashMap JavaDoc();
67     private String JavaDoc singleClassName = null;
68         
69     /** Creates a new instance of HQLFieldsReader */
70     public EJBQLFieldsReader(String JavaDoc queryStr, Vector JavaDoc reportParameters) {
71         
72         this.setQueryString(queryStr);
73         this.setReportParameters(reportParameters);
74     }
75     
76     public String JavaDoc prepareQuery() throws Exception JavaDoc
77     {
78        Enumeration JavaDoc enumParams = getReportParameters().elements();
79        
80        while( enumParams.hasMoreElements() ) {
81            
82            JRParameter param = (JRParameter)enumParams.nextElement();
83            String JavaDoc parameterName = param.getName();
84            
85            if (queryString.indexOf("$P!{" + parameterName + "}") > 0)
86            {
87                 Object JavaDoc paramVal = ReportQueryDialog.recursiveInterpreter( getInterpreter(), param.getDefaultValueExpression(),getReportParameters());
88            
89                 if (paramVal == null)
90                 {
91                     paramVal = "";
92                 }
93                 
94                 queryString = Misc.string_replace(""+paramVal, "$P!{" + parameterName + "}", queryString);
95            }
96            else if (getQueryString().indexOf("$P{" + parameterName + "}") > 0)
97            {
98                Object JavaDoc paramVal = ReportQueryDialog.recursiveInterpreter( getInterpreter(), param.getDefaultValueExpression(),getReportParameters());
99                String JavaDoc parameterReplacement = "_" + getLiteral(parameterName);
100                
101                queryParameters.put(parameterReplacement, paramVal);
102
103            }
104         }
105        return queryString;
106     }
107     
108     
109     /**
110      * Binds a paramter value to a query paramter.
111      *
112      * @param parameter the report parameter
113      */

114     protected void setParameter(Query query, String JavaDoc hqlParamName, Object JavaDoc parameterValue) throws Exception JavaDoc
115     {
116             //ClassLoader cl = MainFrame.getMainInstance().getReportClassLoader();
117

118             if (parameterValue == null)
119             {
120                 query.setParameter( getLiteral( hqlParamName ), parameterValue);
121                 return;
122             }
123             
124             query.setParameter(hqlParamName, parameterValue);
125     }
126     
127     private Interpreter prepareExpressionEvaluator() throws bsh.EvalError {
128         
129         Interpreter interpreter = new Interpreter();
130         interpreter.setClassLoader(interpreter.getClass().getClassLoader());
131         return interpreter;
132     }
133     
134     
135     /**
136      * Takes a name and returns the same if it is a Java identifier;
137      * else it substitutes the illegal characters so that it can be an identifier
138      *
139      * @param name
140      */

141     public static String JavaDoc getLiteral(String JavaDoc name)
142     {
143         if (isValidLiteral(name))
144         {
145             return name;
146         }
147
148         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(name.length() + 5);
149         
150         char[] literalChars = new char[name.length()];
151         name.getChars(0, literalChars.length, literalChars, 0);
152         
153         for (int i = 0; i < literalChars.length; i++)
154         {
155             if (i == 0 && !Character.isJavaIdentifierStart(literalChars[i]))
156             {
157                 buffer.append((int)literalChars[i]);
158             }
159             else if (i != 0 && !Character.isJavaIdentifierPart(literalChars[i]))
160             {
161                 buffer.append((int)literalChars[i]);
162             }
163             else
164             {
165                 buffer.append(literalChars[i]);
166             }
167         }
168         
169         return buffer.toString();
170     }
171     
172     
173     /**
174      * Checks if the input is a valid Java literal
175      * @param literal
176      * @author Gaganis Giorgos (gaganis@users.sourceforge.net)
177      */

178     private static boolean isValidLiteral(String JavaDoc literal)
179     {
180         boolean result = true;
181         
182         char[] literalChars = new char[literal.length()];
183         literal.getChars(0, literalChars.length, literalChars, 0);
184         
185         for (int i = 0; i < literalChars.length; i++)
186         {
187             if (i == 0 && !Character.isJavaIdentifierStart(literalChars[i]))
188             {
189                 result = false;
190                 break;
191             }
192             
193             if (i != 0 && !Character.isJavaIdentifierPart(literalChars[i]))
194             {
195                 result = false;
196                 break;
197             }
198         }
199         
200         return result;
201     }
202
203     public Interpreter getInterpreter() {
204         
205         if (interpreter == null)
206         {
207             try {
208             interpreter = prepareExpressionEvaluator();
209             } catch (Exception JavaDoc ex)
210             {
211             
212             }
213         }
214         return interpreter;
215     }
216
217     public void setInterpreter(Interpreter interpreter) {
218         this.interpreter = interpreter;
219     }
220
221     public Vector JavaDoc getReportParameters() {
222         return reportParameters;
223     }
224
225     public void setReportParameters(Vector JavaDoc reportParameters) {
226         this.reportParameters = reportParameters;
227     }
228
229     public String JavaDoc getQueryString() {
230         return queryString;
231     }
232
233     public void setQueryString(String JavaDoc queryString) {
234         this.queryString = queryString;
235     }
236
237     public HashMap JavaDoc getQueryParameters() {
238         return queryParameters;
239     }
240
241     public void setQueryParameters(HashMap JavaDoc queryParameters) {
242         this.queryParameters = queryParameters;
243     }
244     
245
246     public Vector JavaDoc readFields() throws Exception JavaDoc
247     {
248         prepareQuery();
249         
250         Vector JavaDoc fields = new Vector JavaDoc();
251         EntityManager em = null;
252         Query query = null;
253         setSingleClassName(null);
254         try {
255             
256                IReportConnection conn = (IReportConnection)MainFrame.getMainInstance().getProperties().get("DefaultConnection");
257                if (!(conn instanceof EJBQLConnection))
258                {
259                    throw new Exception JavaDoc("No EJBQL connection selected.");
260                }
261                
262                em = ((EJBQLConnection)conn).getEntityManager();
263                
264                query = em.createQuery(queryString);
265                
266                for (Iterator JavaDoc iter = queryParameters.keySet().iterator(); iter.hasNext();) {
267                       String JavaDoc parameterName = (String JavaDoc)iter.next();
268                       query.setParameter( parameterName, queryParameters.get(parameterName ));
269                 }
270                 
271                query.setMaxResults(1);
272            List JavaDoc list = query.getResultList();
273                         
274                
275                if (list.size() > 0)
276                {
277                    Object JavaDoc obj = list.get(0);
278                    
279                    if (obj != null &&
280                        obj.getClass().isArray())
281                    {
282                        // Fields array...
283
Object JavaDoc[] fiels_obj = (Object JavaDoc[])obj;
284                        for (int i=0; i<fiels_obj.length; ++i)
285                        {
286                           fields.add( createField( fiels_obj[i], i));
287                        }
288                    }
289                    else
290                    {
291                        setSingleClassName(obj.getClass().getName());
292                         fields = getFields(obj);
293                    }
294                }
295                 
296                 return fields;
297
298            } catch (Exception JavaDoc ex)
299            {
300                ex.printStackTrace();
301                throw ex;
302             } finally {
303                
304               
305            }
306     }
307     
308     public Vector JavaDoc getFields(Object JavaDoc obj)
309     {
310         
311         Vector JavaDoc fields = new Vector JavaDoc();
312         java.beans.PropertyDescriptor JavaDoc[] pd = org.apache.commons.beanutils.PropertyUtils.getPropertyDescriptors(obj.getClass());
313         for (int nd =0; nd < pd.length; ++nd)
314         {
315                    String JavaDoc fieldName = pd[nd].getName();
316                    if (pd[nd].getPropertyType() != null && pd[nd].getReadMethod() != null)
317                    {
318                        String JavaDoc returnType = pd[nd].getPropertyType().getName();
319                        it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(fieldName, Misc.getJRFieldType(returnType));
320                        field.setDescription(""); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
321
fields.addElement(field);
322                    }
323         }
324         
325         return fields;
326         
327         
328     }
329     
330     public JRField createField(Object JavaDoc obj, int pos)
331     {
332         String JavaDoc fieldName = "COLUMN_" + (pos+1);
333         if (pos < 0)
334         {
335             fieldName = obj.getClass().getName();
336             if (fieldName.indexOf(".") > 0)
337             {
338                 fieldName = fieldName.substring(fieldName.indexOf(".")+1);
339             }
340             if (fieldName.length() == 0) fieldName = "COLUMN_1";
341         }
342         JRField field = new JRField(fieldName, obj.getClass().getName());
343         field.setDescription("");
344         
345         return field;
346     }
347
348     public String JavaDoc getSingleClassName() {
349         return singleClassName;
350     }
351
352     public void setSingleClassName(String JavaDoc singleClassName) {
353         this.singleClassName = singleClassName;
354     }
355
356 }
357
Popular Tags