001: /*
002: * Copyright (C) 2005 - 2008 JasperSoft Corporation. All rights reserved.
003: * http://www.jaspersoft.com.
004: *
005: * Unless you have purchased a commercial license agreement from JasperSoft,
006: * the following license terms apply:
007: *
008: * This program is free software; you can redistribute it and/or modify
009: * it under the terms of the GNU General Public License version 2 as published by
010: * the Free Software Foundation.
011: *
012: * This program is distributed WITHOUT ANY WARRANTY; and without the
013: * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
014: * See the GNU General Public License for more details.
015: *
016: * You should have received a copy of the GNU General Public License
017: * along with this program; if not, see http://www.gnu.org/licenses/gpl.txt
018: * or write to:
019: *
020: * Free Software Foundation, Inc.,
021: * 59 Temple Place - Suite 330,
022: * Boston, MA USA 02111-1307
023: *
024: *
025: *
026: *
027: * HQLFieldsReader.java
028: *
029: * Created on February 22, 2006, 1:27 PM
030: *
031: */
032:
033: package it.businesslogic.ireport.data.hibernate;
034:
035: import bsh.Interpreter;
036: import it.businesslogic.ireport.IReportConnection;
037: import it.businesslogic.ireport.JRField;
038: import it.businesslogic.ireport.JRParameter;
039: import it.businesslogic.ireport.connection.JRHibernateConnection;
040: import it.businesslogic.ireport.data.FieldClassWrapper;
041: import it.businesslogic.ireport.gui.MainFrame;
042: import it.businesslogic.ireport.gui.ReportQueryDialog;
043: import it.businesslogic.ireport.util.Misc;
044:
045: import java.util.Collection;
046: import java.util.Enumeration;
047: import java.util.HashMap;
048: import java.util.Iterator;
049: import java.util.Map;
050: import java.util.Vector;
051:
052: import org.hibernate.Hibernate;
053: import org.hibernate.Query;
054: import org.hibernate.SessionFactory;
055: import org.hibernate.Transaction;
056: import org.hibernate.cfg.Configuration;
057: import org.hibernate.classic.Session;
058: import org.hibernate.type.Type;
059:
060: /**
061: *
062: * @author gtoffoli
063: */
064: public class HQLFieldsReader {
065:
066: private static final Map hibernateTypeMap;
067:
068: static {
069: hibernateTypeMap = new HashMap();
070: hibernateTypeMap.put(Boolean.class, Hibernate.BOOLEAN);
071: hibernateTypeMap.put(Byte.class, Hibernate.BYTE);
072: hibernateTypeMap.put(Double.class, Hibernate.DOUBLE);
073: hibernateTypeMap.put(Float.class, Hibernate.FLOAT);
074: hibernateTypeMap.put(Integer.class, Hibernate.INTEGER);
075: hibernateTypeMap.put(Long.class, Hibernate.LONG);
076: hibernateTypeMap.put(Short.class, Hibernate.SHORT);
077: hibernateTypeMap.put(java.math.BigDecimal.class,
078: Hibernate.BIG_DECIMAL);
079: hibernateTypeMap.put(java.math.BigInteger.class,
080: Hibernate.BIG_INTEGER);
081: hibernateTypeMap.put(Character.class, Hibernate.CHARACTER);
082: hibernateTypeMap.put(String.class, Hibernate.STRING);
083: hibernateTypeMap.put(java.util.Date.class, Hibernate.DATE);
084: hibernateTypeMap.put(java.sql.Timestamp.class,
085: Hibernate.TIMESTAMP);
086: hibernateTypeMap.put(java.sql.Time.class, Hibernate.TIME);
087: }
088:
089: private Interpreter interpreter = null;
090: private Vector reportParameters = null;
091: private String queryString = "";
092: private HashMap queryParameters = new HashMap();
093:
094: private Vector notScalars = new Vector();
095:
096: /** Creates a new instance of HQLFieldsReader */
097: public HQLFieldsReader(String query, Vector reportParameters) {
098:
099: this .setQueryString(query);
100: this .setReportParameters(reportParameters);
101: }
102:
103: public String prepareQuery() throws Exception {
104: System.out.println(getReportParameters());
105: Enumeration enumParams = getReportParameters().elements();
106:
107: while (enumParams.hasMoreElements()) {
108:
109: JRParameter param = (JRParameter) enumParams.nextElement();
110: String parameterName = param.getName();
111:
112: if (queryString.indexOf("$P!{" + parameterName + "}") > 0) {
113: Object paramVal = ReportQueryDialog
114: .recursiveInterpreter(getInterpreter(), param
115: .getDefaultValueExpression(),
116: getReportParameters());
117:
118: if (paramVal == null) {
119: paramVal = "";
120: }
121:
122: queryString = Misc.string_replace("" + paramVal, "$P!{"
123: + parameterName + "}", queryString);
124: } else if (getQueryString().indexOf(
125: "$P{" + parameterName + "}") > 0) {
126: Object paramVal = ReportQueryDialog
127: .recursiveInterpreter(getInterpreter(), param
128: .getDefaultValueExpression(),
129: getReportParameters());
130: String parameterReplacement = "_"
131: + getLiteral(parameterName);
132:
133: queryParameters.put(parameterReplacement, paramVal);
134:
135: queryString = Misc.string_replace(":"
136: + parameterReplacement, "$P{" + parameterName
137: + "}", queryString);
138:
139: System.out.println(queryString);
140: }
141: }
142: return queryString;
143: }
144:
145: public Vector readFields() throws Exception {
146: prepareQuery();
147:
148: SessionFactory hb_sessionFactory = null;
149: Session hb_session = null;
150: Transaction transaction = null;
151:
152: notScalars.clear();
153:
154: try {
155: IReportConnection conn = (IReportConnection) MainFrame
156: .getMainInstance().getProperties().get(
157: "DefaultConnection");
158: if (!(conn instanceof JRHibernateConnection)) {
159: throw new Exception("No Hibernate connection selected.");
160: }
161:
162: hb_session = ((JRHibernateConnection) conn).createSession();
163:
164: if (hb_session == null) {
165: throw new Exception(
166: "Problem creating the Session object for Hibernate");
167: }
168:
169: transaction = hb_session.beginTransaction();
170: Query q = hb_session.createQuery(getQueryString());
171:
172: Iterator paramIterator = queryParameters.keySet()
173: .iterator();
174:
175: while (paramIterator.hasNext()) {
176: String hqlParamName = "" + paramIterator.next();
177: setParameter(hb_session, q, hqlParamName,
178: queryParameters.get(hqlParamName));
179: }
180:
181: q.setFetchSize(1);
182: java.util.Iterator iterator = q.iterate();
183: // this is a stupid thing: iterator.next();
184:
185: String[] aliases = q.getReturnAliases();
186: Type[] types = q.getReturnTypes();
187:
188: Vector fields = new Vector();
189:
190: for (int i = 0; i < types.length; ++i) {
191: if (types[i].isComponentType()
192: || types[i].isEntityType()) {
193:
194: // look for alias...
195: String aliasName = null;
196: if (aliases != null && aliases.length > i
197: && !aliases[i].equals(i + "")) {
198: aliasName = aliases[i];
199: JRField field = new JRField(aliases[i],
200: types[i].getReturnedClass().getName());
201: field.setDescription(aliases[i]);
202: fields.add(field);
203:
204: }
205:
206: // look for fields like for a javabean...
207: java.beans.PropertyDescriptor[] pd = org.apache.commons.beanutils.PropertyUtils
208: .getPropertyDescriptors(types[i]
209: .getReturnedClass());
210:
211: if (aliasName != null) {
212: notScalars.add(new FieldClassWrapper(aliasName,
213: types[i].getReturnedClass().getName()));
214: } else {
215: notScalars.add(types[i].getReturnedClass()
216: .getName());
217: }
218:
219: for (int nd = 0; nd < pd.length; ++nd) {
220: String fieldName = pd[nd].getName();
221: if (pd[nd].getPropertyType() != null
222: && pd[nd].getReadMethod() != null) {
223: if (fieldName.equals("class"))
224: continue;
225:
226: String returnType = pd[nd]
227: .getPropertyType().getName();
228:
229: it.businesslogic.ireport.JRField field = new it.businesslogic.ireport.JRField(
230: fieldName, returnType);
231: if (types.length > 1 && aliasName != null) {
232: fieldName = aliasName + "." + fieldName;
233: field.setDescription(fieldName); //Field returned by " +methods[i].getName() + " (real type: "+ returnType +")");
234: field.setName(fieldName);
235: }
236: fields.add(field);
237: }
238: }
239:
240: } else {
241: String fieldName = types[i].getName();
242: if (aliases != null && aliases.length > i
243: && !aliases[i].equals("" + i))
244: fieldName = aliases[i];
245: JRField field = new JRField(fieldName, types[i]
246: .getReturnedClass().getName());
247: field.setDescription("");
248: fields.add(field);
249: }
250: }
251: /*
252: else
253: {
254: for (int i =0; i<types.length; ++i)
255: {
256: if (aliases != null && aliases.length > 0 && !aliases[0].equals(""+i))
257: {
258: JRField field = new JRField(aliases[i], types[i].getReturnedClass().getName());
259: field.setDescription("The whole entity/component object");
260: fields.add(field);
261:
262:
263: }
264:
265:
266: // out.println(types[i].getName() + " " + types[i].getReturnedClass().getName() + "<br>");
267: }
268: }
269: */
270:
271: return fields;
272:
273: } catch (Exception ex) {
274: ex.printStackTrace();
275: throw ex;
276: } finally {
277:
278: if (transaction != null)
279: try {
280: transaction.rollback();
281: } catch (Exception ex) {
282: }
283: if (hb_session != null)
284: try {
285: hb_session.close();
286: } catch (Exception ex) {
287: }
288: }
289: }
290:
291: /**
292: * Binds a paramter value to a query paramter.
293: *
294: * @param parameter the report parameter
295: */
296: protected void setParameter(Session session, Query query,
297: String hqlParamName, Object parameterValue)
298: throws Exception {
299: //ClassLoader cl = MainFrame.getMainInstance().getReportClassLoader();
300:
301: if (parameterValue == null) {
302: System.out.println("Parameter: " + hqlParamName);
303: query.setParameter(hqlParamName, parameterValue);
304: return;
305: }
306:
307: Class clazz = parameterValue.getClass();
308: Type type = (Type) hibernateTypeMap.get(clazz);
309:
310: if (type != null) {
311: query.setParameter(hqlParamName, parameterValue, type);
312: } else if (Collection.class.isAssignableFrom(clazz)) {
313: query.setParameterList(hqlParamName,
314: (Collection) parameterValue);
315: } else {
316: if (session.getSessionFactory().getClassMetadata(clazz) != null) //param type is a hibernate mapped entity
317: {
318: query.setEntity(hqlParamName, parameterValue);
319: } else //let hibernate try to guess the type
320: {
321: query.setParameter(hqlParamName, parameterValue);
322: }
323: }
324: }
325:
326: private Interpreter prepareExpressionEvaluator()
327: throws bsh.EvalError {
328:
329: Interpreter interpreter = new Interpreter();
330: interpreter.setClassLoader(interpreter.getClass()
331: .getClassLoader());
332: return interpreter;
333: }
334:
335: /**
336: * Takes a name and returns the same if it is a Java identifier;
337: * else it substitutes the illegal characters so that it can be an identifier
338: *
339: * @param name
340: */
341: public static String getLiteral(String name) {
342: if (isValidLiteral(name)) {
343: return name;
344: }
345:
346: StringBuffer buffer = new StringBuffer(name.length() + 5);
347:
348: char[] literalChars = new char[name.length()];
349: name.getChars(0, literalChars.length, literalChars, 0);
350:
351: for (int i = 0; i < literalChars.length; i++) {
352: if (i == 0
353: && !Character
354: .isJavaIdentifierStart(literalChars[i])) {
355: buffer.append((int) literalChars[i]);
356: } else if (i != 0
357: && !Character.isJavaIdentifierPart(literalChars[i])) {
358: buffer.append((int) literalChars[i]);
359: } else {
360: buffer.append(literalChars[i]);
361: }
362: }
363:
364: return buffer.toString();
365: }
366:
367: /**
368: * Checks if the input is a valid Java literal
369: * @param literal
370: * @author Gaganis Giorgos (gaganis@users.sourceforge.net)
371: */
372: private static boolean isValidLiteral(String literal) {
373: boolean result = true;
374:
375: char[] literalChars = new char[literal.length()];
376: literal.getChars(0, literalChars.length, literalChars, 0);
377:
378: for (int i = 0; i < literalChars.length; i++) {
379: if (i == 0
380: && !Character
381: .isJavaIdentifierStart(literalChars[i])) {
382: result = false;
383: break;
384: }
385:
386: if (i != 0
387: && !Character.isJavaIdentifierPart(literalChars[i])) {
388: result = false;
389: break;
390: }
391: }
392:
393: return result;
394: }
395:
396: public Interpreter getInterpreter() {
397:
398: if (interpreter == null) {
399: try {
400: interpreter = prepareExpressionEvaluator();
401: } catch (Exception ex) {
402:
403: }
404: }
405: return interpreter;
406: }
407:
408: public void setInterpreter(Interpreter interpreter) {
409: this .interpreter = interpreter;
410: }
411:
412: public Vector getReportParameters() {
413: return reportParameters;
414: }
415:
416: public void setReportParameters(Vector reportParameters) {
417: this .reportParameters = reportParameters;
418: }
419:
420: public String getQueryString() {
421: return queryString;
422: }
423:
424: public void setQueryString(String queryString) {
425: this .queryString = queryString;
426: }
427:
428: public HashMap getQueryParameters() {
429: return queryParameters;
430: }
431:
432: public void setQueryParameters(HashMap queryParameters) {
433: this .queryParameters = queryParameters;
434: }
435:
436: public Vector getNotScalars() {
437: return notScalars;
438: }
439:
440: public void setNotScalars(Vector notScalars) {
441: this.notScalars = notScalars;
442: }
443:
444: }
|