KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > jasperreports > engine > fill > JRFillDataset


1 /*
2  * ============================================================================
3  * GNU Lesser General Public License
4  * ============================================================================
5  *
6  * JasperReports - Free Java report-generating library.
7  * Copyright (C) 2001-2006 JasperSoft Corporation http://www.jaspersoft.com
8  *
9  * This library is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public
11  * License as published by the Free Software Foundation; either
12  * version 2.1 of the License, or (at your option) any later version.
13  *
14  * This library is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with this library; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22  *
23  * JasperSoft Corporation
24  * 303 Second Street, Suite 450 North
25  * San Francisco, CA 94107
26  * http://www.jaspersoft.com
27  */

28 package net.sf.jasperreports.engine.fill;
29
30 import java.sql.Connection JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.HashMap JavaDoc;
33 import java.util.HashSet JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.Locale JavaDoc;
36 import java.util.Map JavaDoc;
37 import java.util.MissingResourceException JavaDoc;
38 import java.util.ResourceBundle JavaDoc;
39 import java.util.Set JavaDoc;
40 import java.util.TimeZone JavaDoc;
41
42 import net.sf.jasperreports.engine.JRAbstractScriptlet;
43 import net.sf.jasperreports.engine.JRDataSource;
44 import net.sf.jasperreports.engine.JRDataset;
45 import net.sf.jasperreports.engine.JRDefaultScriptlet;
46 import net.sf.jasperreports.engine.JRException;
47 import net.sf.jasperreports.engine.JRExpression;
48 import net.sf.jasperreports.engine.JRField;
49 import net.sf.jasperreports.engine.JRGroup;
50 import net.sf.jasperreports.engine.JRParameter;
51 import net.sf.jasperreports.engine.JRPropertiesMap;
52 import net.sf.jasperreports.engine.JRQuery;
53 import net.sf.jasperreports.engine.JRRuntimeException;
54 import net.sf.jasperreports.engine.JRSortField;
55 import net.sf.jasperreports.engine.JRVariable;
56 import net.sf.jasperreports.engine.JasperReport;
57 import net.sf.jasperreports.engine.data.JRSortableDataSource;
58 import net.sf.jasperreports.engine.design.JRDefaultCompiler;
59 import net.sf.jasperreports.engine.design.JRDesignVariable;
60 import net.sf.jasperreports.engine.query.JRQueryExecuter;
61 import net.sf.jasperreports.engine.query.JRQueryExecuterFactory;
62 import net.sf.jasperreports.engine.util.JRClassLoader;
63 import net.sf.jasperreports.engine.util.JRQueryExecuterUtils;
64
65 /**
66  * @author Lucian Chirita (lucianc@users.sourceforge.net)
67  * @version $Id: JRFillDataset.java 1474 2006-11-10 11:33:00 +0200 (Fri, 10 Nov 2006) teodord $
68  */

69 public class JRFillDataset implements JRDataset
70 {
71     /**
72      * The filler that created this object.
73      */

74     private final JRBaseFiller filler;
75     
76     /**
77      * The template dataset.
78      */

79     private final JRDataset parent;
80     
81     /**
82      * Whether this is the main dataset of the report.
83      */

84     private final boolean isMain;
85     
86     /**
87      * The dataset query.
88      */

89     protected JRQuery query = null;
90     
91     private boolean useDatasourceParamValue = false;
92     private boolean useConnectionParamValue = false;
93     
94     /**
95      * The dataset parameter.
96      */

97     protected JRFillParameter[] parameters = null;
98
99     /**
100      * The dataset parameters indexed by name.
101      */

102     protected Map JavaDoc parametersMap = null;
103
104     /**
105      * The dataset fields.
106      */

107     protected JRFillField[] fields = null;
108     
109     /**
110      * The dataset fields indexed by name.
111      */

112     protected Map JavaDoc fieldsMap = null;
113     
114     /**
115      * The dataset variables.
116      */

117     protected JRFillVariable[] variables = null;
118     
119     /**
120      * The dataset variables indexed by name.
121      */

122     protected Map JavaDoc variablesMap = null;
123     
124     /**
125      * Set of {@link VariableCalculationReq VariableCalculationReq} objects.
126      */

127     protected Set JavaDoc variableCalculationReqs;
128
129     /**
130      * The element datasets.
131      */

132     protected JRFillElementDataset[] elementDatasets;
133     
134     /**
135      * Used to save the original element datasets when
136      * {@link #filterElementDatasets(JRFillElementDataset) filterElementDatasets} is called.
137      */

138     protected JRFillElementDataset[] origElementDatasets;
139
140     /**
141      * The dataset groups.
142      */

143     protected JRFillGroup[] groups = null;
144
145     /**
146      * The resource bundle base name.
147      */

148     protected String JavaDoc resourceBundleBaseName = null;
149     
150     /**
151      * The resource missing handle type.
152      */

153     protected byte whenResourceMissingType;
154     
155     /**
156      * The scriptlet class name.
157      */

158     protected String JavaDoc scriptletClassName = null;
159
160     /**
161      * The data source.
162      */

163     protected JRDataSource dataSource = null;
164     
165     /**
166      * The {@link Locale Locale} to be used by the dataset.
167      */

168     protected Locale JavaDoc locale = null;
169     
170     /**
171      * The loaded resource bundle.
172      */

173     protected ResourceBundle JavaDoc resourceBundle = null;
174
175     /**
176      * The {@link TimeZone TimeZone} to be used by the dataset.
177      */

178     protected TimeZone JavaDoc timeZone = null;
179     
180     /**
181      * The cursor used when iterating the data source.
182      */

183     protected int reportCount = 0;
184
185     /**
186      * The calculator used by the dataset.
187      */

188     protected JRCalculator calculator = null;
189
190     /**
191      * The scriptlet used by the dataset.
192      */

193     protected JRAbstractScriptlet scriptlet = null;
194
195     /**
196      * The value of the {@link JRParameter#REPORT_MAX_COUNT max count} parameter.
197      */

198     protected Integer JavaDoc reportMaxCount = null;
199
200     private JRQueryExecuter queryExecuter;
201
202     
203     /**
204      * Creates a fill dataset object.
205      * @param filler the filelr
206      * @param dataset the template dataset
207      * @param factory the fill object factory
208      */

209     protected JRFillDataset(JRBaseFiller filler, JRDataset dataset, JRFillObjectFactory factory)
210     {
211         factory.put(dataset, this);
212         
213         this.filler = filler;
214         this.parent = dataset;
215         this.isMain = dataset.isMainDataset();
216         
217         scriptletClassName = dataset.getScriptletClass();
218         resourceBundleBaseName = dataset.getResourceBundle();
219         whenResourceMissingType = dataset.getWhenResourceMissingType();
220         
221         query = dataset.getQuery();
222         
223         setParameters(dataset, factory);
224
225         setFields(dataset, factory);
226         
227         setVariables(dataset, factory);
228         
229         setGroups(dataset, factory);
230     }
231
232     
233     private void setParameters(JRDataset dataset, JRFillObjectFactory factory)
234     {
235         JRParameter[] jrParameters = dataset.getParameters();
236         if (jrParameters != null && jrParameters.length > 0)
237         {
238             parameters = new JRFillParameter[jrParameters.length];
239             parametersMap = new HashMap JavaDoc();
240             for (int i = 0; i < parameters.length; i++)
241             {
242                 parameters[i] = factory.getParameter(jrParameters[i]);
243                 parametersMap.put(parameters[i].getName(), parameters[i]);
244             }
245         }
246     }
247
248
249     private void setGroups(JRDataset dataset, JRFillObjectFactory factory)
250     {
251         JRGroup[] jrGroups = dataset.getGroups();
252         if (jrGroups != null && jrGroups.length > 0)
253         {
254             groups = new JRFillGroup[jrGroups.length];
255             for (int i = 0; i < groups.length; i++)
256             {
257                 groups[i] = factory.getGroup(jrGroups[i]);
258             }
259         }
260     }
261
262
263     private void setVariables(JRDataset dataset, JRFillObjectFactory factory)
264     {
265         JRVariable[] jrVariables = dataset.getVariables();
266         if (jrVariables != null && jrVariables.length > 0)
267         {
268             List JavaDoc variableList = new ArrayList JavaDoc(jrVariables.length * 3);
269
270             variablesMap = new HashMap JavaDoc();
271             for (int i = 0; i < jrVariables.length; i++)
272             {
273                 addVariable(jrVariables[i], variableList, factory);
274             }
275
276             setVariables(variableList);
277         }
278     }
279     
280     
281     private JRFillVariable addVariable(JRVariable parentVariable, List JavaDoc variableList, JRFillObjectFactory factory)
282     {
283         JRFillVariable variable = factory.getVariable(parentVariable);
284
285         byte calculation = variable.getCalculation();
286         switch (calculation)
287         {
288             case JRVariable.CALCULATION_AVERAGE:
289             case JRVariable.CALCULATION_VARIANCE:
290             {
291                 JRVariable countVar = createHelperVariable(parentVariable, "_COUNT", JRVariable.CALCULATION_COUNT);
292                 JRFillVariable fillCountVar = addVariable(countVar, variableList, factory);
293                 variable.setHelperVariable(fillCountVar, JRCalculable.HELPER_COUNT);
294
295                 JRVariable sumVar = createHelperVariable(parentVariable, "_SUM", JRVariable.CALCULATION_SUM);
296                 JRFillVariable fillSumVar = addVariable(sumVar, variableList, factory);
297                 variable.setHelperVariable(fillSumVar, JRCalculable.HELPER_SUM);
298
299                 break;
300             }
301             case JRVariable.CALCULATION_STANDARD_DEVIATION:
302             {
303                 JRVariable varianceVar = createHelperVariable(parentVariable, "_VARIANCE", JRVariable.CALCULATION_VARIANCE);
304                 JRFillVariable fillVarianceVar = addVariable(varianceVar, variableList, factory);
305                 variable.setHelperVariable(fillVarianceVar, JRCalculable.HELPER_VARIANCE);
306
307                 break;
308             }
309             case JRVariable.CALCULATION_DISTINCT_COUNT:
310             {
311                 JRVariable countVar = createDistinctCountHelperVariable(parentVariable);
312                 JRFillVariable fillCountVar = addVariable(countVar, variableList, factory);
313                 variable.setHelperVariable(fillCountVar, JRCalculable.HELPER_COUNT);
314
315                 break;
316             }
317         }
318
319         variableList.add(variable);
320         return variable;
321     }
322
323     private JRVariable createHelperVariable(JRVariable variable, String JavaDoc nameSuffix, byte calculation)
324     {
325         JRDesignVariable helper = new JRDesignVariable();
326         helper.setName(variable.getName() + nameSuffix);
327         helper.setValueClassName(variable.getValueClassName());
328         helper.setIncrementerFactoryClassName(variable.getIncrementerFactoryClassName());
329         helper.setResetType(variable.getResetType());
330         helper.setResetGroup(variable.getResetGroup());
331         helper.setIncrementType(variable.getIncrementType());
332         helper.setIncrementGroup(variable.getIncrementGroup());
333         helper.setCalculation(calculation);
334         helper.setSystemDefined(true);
335         helper.setExpression(variable.getExpression());
336
337         return helper;
338     }
339
340     private JRVariable createDistinctCountHelperVariable(JRVariable variable)
341     {
342         JRDesignVariable helper = new JRDesignVariable();
343         helper.setName(variable.getName() + "_DISTINCT_COUNT");
344         helper.setValueClassName(variable.getValueClassName());
345         helper.setIncrementerFactoryClassName(JRDistinctCountIncrementerFactory.class.getName());
346         helper.setResetType(JRVariable.RESET_TYPE_REPORT);
347
348         if (variable.getIncrementType() != JRVariable.RESET_TYPE_NONE)
349             helper.setResetType(variable.getIncrementType());
350             
351         helper.setResetGroup(variable.getIncrementGroup());
352         helper.setCalculation(JRVariable.CALCULATION_NOTHING);
353         helper.setSystemDefined(true);
354         helper.setExpression(variable.getExpression());
355         
356         return helper;
357     }
358
359     private void setVariables(List JavaDoc variableList)
360     {
361         variables = new JRFillVariable[variableList.size()];
362         variables = (JRFillVariable[]) variableList.toArray(variables);
363
364         for (int i = 0; i < variables.length; i++)
365         {
366             variablesMap.put(variables[i].getName(), variables[i]);
367         }
368     }
369
370
371     private void setFields(JRDataset dataset, JRFillObjectFactory factory)
372     {
373         JRField[] jrFields = dataset.getFields();
374         if (jrFields != null && jrFields.length > 0)
375         {
376             fields = new JRFillField[jrFields.length];
377             fieldsMap = new HashMap JavaDoc();
378             for (int i = 0; i < fields.length; i++)
379             {
380                 fields[i] = factory.getField(jrFields[i]);
381                 fieldsMap.put(fields[i].getName(), fields[i]);
382             }
383         }
384     }
385
386
387     /**
388      * Creates the calculator
389      * @param jasperReport the report
390      * @throws JRException
391      */

392     protected void createCalculator(JasperReport jasperReport) throws JRException
393     {
394         setCalculator(createCalculator(jasperReport, this));
395     }
396
397     protected void setCalculator(JRCalculator calculator)
398     {
399         this.calculator = calculator;
400     }
401
402     protected static JRCalculator createCalculator(JasperReport jasperReport, JRDataset dataset) throws JRException
403     {
404         JREvaluator evaluator = JRDefaultCompiler.getInstance().loadEvaluator(jasperReport, dataset);
405         return new JRCalculator(evaluator);
406     }
407
408
409     /**
410      * Initializes the calculator.
411      *
412      * @throws JRException
413      */

414     protected void initCalculator() throws JRException
415     {
416         calculator.init(this);
417     }
418
419
420     /**
421      * Inherits properties from the report.
422      */

423     protected void inheritFromMain()
424     {
425         if (resourceBundleBaseName == null && !isMain)
426         {
427             resourceBundleBaseName = filler.mainDataset.resourceBundleBaseName;
428             whenResourceMissingType = filler.mainDataset.whenResourceMissingType;
429         }
430     }
431     
432     
433     /**
434      * Creates the scriptlet.
435      *
436      * @return the scriptlet
437      * @throws JRException
438      */

439     protected JRAbstractScriptlet createScriptlet() throws JRException
440     {
441         JRAbstractScriptlet tmpScriptlet = null;
442
443         if (scriptletClassName != null)
444         {
445             try
446             {
447                 Class JavaDoc scriptletClass = JRClassLoader.loadClassForName(scriptletClassName);
448                 tmpScriptlet = (JRAbstractScriptlet) scriptletClass.newInstance();
449             }
450             catch (ClassNotFoundException JavaDoc e)
451             {
452                 throw new JRException("Error loading scriptlet class : " + scriptletClassName, e);
453             }
454             catch (Exception JavaDoc e)
455             {
456                 throw new JRException("Error creating scriptlet class instance : " + scriptletClassName, e);
457             }
458         }
459         else
460         {
461             tmpScriptlet = new JRDefaultScriptlet();
462         }
463
464         return tmpScriptlet;
465     }
466
467
468     /**
469      * Initializes the element datasets.
470      *
471      * @param factory the fill object factory used by the filler
472      */

473     protected void initElementDatasets(JRFillObjectFactory factory)
474     {
475         elementDatasets = factory.getElementDatasets(this);
476     }
477
478
479     /**
480      * Filters the element datasets, leaving only one.
481      * <p>
482      * This method is used when a dataset is instantiated by a chart or crosstab.
483      *
484      * @param elementDataset the element dataset that should remain
485      */

486     protected void filterElementDatasets(JRFillElementDataset elementDataset)
487     {
488         origElementDatasets = elementDatasets;
489         elementDatasets = new JRFillElementDataset[]{elementDataset};
490     }
491     
492     
493     /**
494      * Restores the original element datasets.
495      * <p>
496      * This method should be called after {@link #filterElementDatasets(JRFillElementDataset) filterElementDatasets}.
497      */

498     protected void restoreElementDatasets()
499     {
500         if (origElementDatasets != null)
501         {
502             elementDatasets = origElementDatasets;
503             origElementDatasets = null;
504         }
505     }
506     
507
508     /**
509      * Loads the resource bundle corresponding to the resource bundle base name and locale.
510      */

511     protected ResourceBundle JavaDoc loadResourceBundle()
512     {
513         ResourceBundle JavaDoc tmpResourceBundle = null;
514
515         if (resourceBundleBaseName != null)
516         {
517             ClassLoader JavaDoc classLoader = Thread.currentThread().getContextClassLoader();
518             if (classLoader != null)
519             {
520                 try
521                 {
522                     tmpResourceBundle = ResourceBundle.getBundle(resourceBundleBaseName, locale, classLoader);
523                 }
524                 catch (MissingResourceException JavaDoc e)
525                 {
526                     // if (log.isWarnEnabled())
527
// log.warn("Failure using
528
// Thread.currentThread().getContextClassLoader() in
529
// JRClassLoader class. Using
530
// JRClassLoader.class.getClassLoader() instead.");
531
}
532             }
533
534             if (tmpResourceBundle == null)
535             {
536                 classLoader = JRClassLoader.class.getClassLoader();
537
538                 if (classLoader == null)
539                 {
540                     tmpResourceBundle = ResourceBundle.getBundle(resourceBundleBaseName, locale);
541                 }
542                 else
543                 {
544                     tmpResourceBundle = ResourceBundle.getBundle(resourceBundleBaseName, locale, classLoader);
545                 }
546             }
547         }
548
549         return tmpResourceBundle;
550     }
551
552
553     /**
554      * Reads built-in parameter values from the value map.
555      *
556      * @param parameterValues the parameter values
557      * @throws JRException
558      */

559     protected void setParameterValues(Map JavaDoc parameterValues) throws JRException
560     {
561         parameterValues.put(JRParameter.REPORT_PARAMETERS_MAP, parameterValues);
562         
563         reportMaxCount = (Integer JavaDoc) parameterValues.get(JRParameter.REPORT_MAX_COUNT);
564
565         locale = (Locale JavaDoc) parameterValues.get(JRParameter.REPORT_LOCALE);
566         if (locale == null)
567         {
568             locale = Locale.getDefault();
569             parameterValues.put(JRParameter.REPORT_LOCALE, locale);
570         }
571         
572         resourceBundle = (ResourceBundle JavaDoc) parameterValues.get(JRParameter.REPORT_RESOURCE_BUNDLE);
573         if (resourceBundle == null)
574         {
575             resourceBundle = loadResourceBundle();
576             if (resourceBundle != null)
577             {
578                 parameterValues.put(JRParameter.REPORT_RESOURCE_BUNDLE, resourceBundle);
579             }
580         }
581         
582         timeZone = (TimeZone JavaDoc) parameterValues.get(JRParameter.REPORT_TIME_ZONE);
583         if (timeZone == null)
584         {
585             timeZone = TimeZone.getDefault();
586             parameterValues.put(JRParameter.REPORT_TIME_ZONE, timeZone);
587         }
588         
589         scriptlet = (JRAbstractScriptlet) parameterValues.get(JRParameter.REPORT_SCRIPTLET);
590         if (scriptlet == null)
591         {
592             scriptlet = createScriptlet();
593             parameterValues.put(JRParameter.REPORT_SCRIPTLET, scriptlet);
594         }
595         scriptlet.setData(parametersMap, fieldsMap, variablesMap, groups);
596         
597         setFillParameterValues(parameterValues);
598         
599         setDatasource();
600     }
601     
602     
603     private void setDatasource() throws JRException
604     {
605         queryExecuter = null;
606         
607         dataSource = (JRDataSource) getParameterValue(JRParameter.REPORT_DATA_SOURCE);
608         if (!useDatasourceParamValue && (useConnectionParamValue || dataSource == null))
609         {
610             dataSource = createQueryDatasource();
611             setParameter(JRParameter.REPORT_DATA_SOURCE, dataSource);
612         }
613         
614         JRSortField[] sortFields = getSortFields();
615         if (sortFields != null && sortFields.length > 0)
616         {
617             dataSource = new JRSortableDataSource(dataSource, fields, sortFields, locale);
618             setParameter(JRParameter.REPORT_DATA_SOURCE, dataSource);
619         }
620     }
621
622
623     /**
624      * Sets the parameter values from the values map.
625      *
626      * @param parameterValues the values map
627      * @throws JRException
628      */

629     private void setFillParameterValues(Map JavaDoc parameterValues) throws JRException
630     {
631         if (parameters != null && parameters.length > 0)
632         {
633             for (int i = 0; i < parameters.length; i++)
634             {
635                 Object JavaDoc value = null;
636                 if (parameterValues.containsKey(parameters[i].getName()))
637                 {
638                     value = parameterValues.get(parameters[i].getName());
639                 }
640                 else if (!parameters[i].isSystemDefined())
641                 {
642                     value = calculator.evaluate(parameters[i].getDefaultValueExpression(), JRExpression.EVALUATION_DEFAULT);
643                     if (value != null)
644                     {
645                         parameterValues.put(parameters[i].getName(), value);
646                     }
647                 }
648                 setParameter(parameters[i], value);
649             }
650         }
651     }
652
653     
654     /**
655      * Creates the data source from a connection.
656      *
657      * @return the data source to be used
658      * @throws JRException
659      */

660     private JRDataSource createQueryDatasource() throws JRException
661     {
662         if (query == null)
663         {
664             return null;
665         }
666
667         try
668         {
669             JRQueryExecuterFactory queryExecuterFactory = JRQueryExecuterUtils.getQueryExecuterFactory(query.getLanguage());
670             queryExecuter = queryExecuterFactory.createQueryExecuter(parent, parametersMap);
671             filler.fillContext.setRunningQueryExecuter(queryExecuter);
672             
673             return queryExecuter.createDatasource();
674         }
675         finally
676         {
677             filler.fillContext.clearRunningQueryExecuter();
678         }
679     }
680
681
682     protected void reset()
683     {
684         useDatasourceParamValue = false;
685         useConnectionParamValue = false;
686     }
687
688     
689     /**
690      * Sets the data source to be used.
691      *
692      * @param parameterValues the parameter values
693      * @param ds the data source
694      */

695     protected void setDatasourceParameterValue(Map JavaDoc parameterValues, JRDataSource ds)
696     {
697         useDatasourceParamValue = true;
698         
699         if (ds != null)
700         {
701             parameterValues.put(JRParameter.REPORT_DATA_SOURCE, ds);
702         }
703     }
704
705
706     /**
707      * Sets the JDBC connection to be used.
708      *
709      * @param parameterValues the parameter values
710      * @param conn the connection
711      */

712     protected void setConnectionParameterValue(Map JavaDoc parameterValues, Connection JavaDoc conn)
713     {
714         useConnectionParamValue = true;
715         
716         if (conn != null)
717         {
718             parameterValues.put(JRParameter.REPORT_CONNECTION, conn);
719         }
720     }
721     
722     
723     protected void closeDatasource()
724     {
725         if (queryExecuter != null)
726         {
727             queryExecuter.close();
728             queryExecuter = null;
729         }
730         
731         reset();
732     }
733
734     
735     /**
736      * Starts the iteration on the data source.
737      */

738     protected void start()
739     {
740         reportCount = 0;
741     }
742
743     
744     /**
745      * Moves to the next record in the data source.
746      *
747      * @return <code>true</code> if the data source was not exhausted
748      * @throws JRException
749      */

750     protected boolean next() throws JRException
751     {
752         boolean hasNext = false;
753
754         if (dataSource != null)
755         {
756             boolean includeRow = true;
757             JRExpression filterExpression = getFilterExpression();
758             do
759             {
760                 hasNext = advanceDataSource();
761                 if (hasNext)
762                 {
763                     setOldValues();
764
765                     calculator.estimateVariables();
766                     if (filterExpression != null)
767                     {
768                         Boolean JavaDoc filterExprResult = (Boolean JavaDoc) calculator.evaluate(filterExpression, JRExpression.EVALUATION_ESTIMATED);
769                         includeRow = filterExprResult != null && filterExprResult.booleanValue();
770                     }
771                     
772                     if (!includeRow)
773                     {
774                         revertToOldValues();
775                     }
776                 }
777             }
778             while(hasNext && !includeRow);
779             
780             if (hasNext)
781             {
782                 ++reportCount;
783             }
784         }
785
786         return hasNext;
787     }
788
789
790     protected void setOldValues() throws JRException
791     {
792         if (fields != null && fields.length > 0)
793         {
794             for (int i = 0; i < fields.length; i++)
795             {
796                 JRFillField field = fields[i];
797                 field.setPreviousOldValue(field.getOldValue());
798                 field.setOldValue(field.getValue());
799                 field.setValue(dataSource.getFieldValue(field));
800             }
801         }
802
803         if (variables != null && variables.length > 0)
804         {
805             for (int i = 0; i < variables.length; i++)
806             {
807                 JRFillVariable variable = variables[i];
808                 variable.setPreviousOldValue(variable.getOldValue());
809                 variable.setOldValue(variable.getValue());
810             }
811         }
812     }
813
814
815     protected void revertToOldValues()
816     {
817         if (fields != null && fields.length > 0)
818         {
819             for (int i = 0; i < fields.length; i++)
820             {
821                 JRFillField field = fields[i];
822                 field.setValue(field.getOldValue());
823                 field.setOldValue(field.getPreviousOldValue());
824             }
825         }
826         
827         if (variables != null && variables.length > 0)
828         {
829             for (int i = 0; i < variables.length; i++)
830             {
831                 JRFillVariable variable = variables[i];
832                 variable.setValue(variable.getOldValue());
833                 variable.setOldValue(variable.getPreviousOldValue());
834             }
835         }
836     }
837
838
839     protected boolean advanceDataSource() throws JRException
840     {
841         boolean hasNext;
842         hasNext = (reportMaxCount == null || reportMaxCount.intValue() > reportCount) && dataSource.next();
843         return hasNext;
844     }
845     
846     
847     /**
848      * Sets the value of a parameter.
849      *
850      * @param parameterName the parameter name
851      * @param value the value
852      * @throws JRException
853      */

854     protected void setParameter(String JavaDoc parameterName, Object JavaDoc value) throws JRException
855     {
856         JRFillParameter parameter = (JRFillParameter) parametersMap.get(parameterName);
857         if (parameter != null)
858         {
859             setParameter(parameter, value);
860         }
861     }
862     
863     
864     /**
865      * Sets the value of the parameter.
866      *
867      * @param parameter the parameter
868      * @param value the value
869      * @throws JRException
870      */

871     protected void setParameter(JRFillParameter parameter, Object JavaDoc value) throws JRException
872     {
873         if (value != null)
874         {
875             if (parameter.getValueClass().isInstance(value))
876             {
877                 parameter.setValue(value);
878             }
879             else
880             {
881                 throw new JRException(
882                     "Incompatible "
883                     + value.getClass().getName()
884                     + " value assigned to parameter "
885                     + parameter.getName()
886                     + " in the " + getName() + " dataset."
887                     );
888             }
889         }
890         else
891         {
892             parameter.setValue(value);
893         }
894     }
895
896     
897     /**
898      * Returns the value of a variable.
899      *
900      * @param variableName the variable name
901      * @return the variable value
902      */

903     public Object JavaDoc getVariableValue(String JavaDoc variableName)
904     {
905         JRFillVariable var = (JRFillVariable) variablesMap.get(variableName);
906         if (var == null)
907         {
908             throw new JRRuntimeException("No such variable " + variableName);
909         }
910         return var.getValue();
911     }
912
913     
914     /**
915      * Returns the value of a parameter.
916      *
917      * @param parameterName the parameter name
918      * @return the parameter value
919      */

920     public Object JavaDoc getParameterValue(String JavaDoc parameterName)
921     {
922         JRFillParameter param = (JRFillParameter) parametersMap.get(parameterName);
923         if (param == null)
924         {
925             throw new JRRuntimeException("No such parameter " + parameterName);
926         }
927         return param.getValue();
928     }
929
930     
931     /**
932      * Returns the value of a field.
933      *
934      * @param fieldName the field name
935      * @return the field value
936      */

937     public Object JavaDoc getFieldValue(String JavaDoc fieldName)
938     {
939         JRFillField var = (JRFillField) fieldsMap.get(fieldName);
940         if (var == null)
941         {
942             throw new JRRuntimeException("No such field " + fieldName);
943         }
944         return var.getValue();
945     }
946     
947     
948     /**
949      * Class used to hold expression calculation requirements.
950      */

951     protected static class VariableCalculationReq
952     {
953         String JavaDoc variableName;
954
955         byte calculation;
956
957         VariableCalculationReq(String JavaDoc variableName, byte calculation)
958         {
959             this.variableName = variableName;
960             this.calculation = calculation;
961         }
962
963         public boolean equals(Object JavaDoc o)
964         {
965             if (o == null || !(o instanceof VariableCalculationReq))
966             {
967                 return false;
968             }
969
970             VariableCalculationReq r = (VariableCalculationReq) o;
971
972             return variableName.equals(r.variableName) && calculation == r.calculation;
973         }
974
975         public int hashCode()
976         {
977             return 31 * calculation + variableName.hashCode();
978         }
979     }
980     
981     
982     /**
983      * Adds a variable calculation requirement.
984      *
985      * @param variableName the variable name
986      * @param calculation the required calculation
987      */

988     protected void addVariableCalculationReq(String JavaDoc variableName, byte calculation)
989     {
990         if (variableCalculationReqs == null)
991         {
992             variableCalculationReqs = new HashSet JavaDoc();
993         }
994
995         variableCalculationReqs.add(new VariableCalculationReq(variableName, calculation));
996     }
997
998     
999     /**
1000     * Checks if there are variable calculation requirements and creates the required variables.
1001     *
1002     * @param factory the fill object factory
1003     */

1004    protected void checkVariableCalculationReqs(JRFillObjectFactory factory)
1005    {
1006        if (variableCalculationReqs != null && !variableCalculationReqs.isEmpty())
1007        {
1008            List JavaDoc variableList = new ArrayList JavaDoc(variables.length * 2);
1009
1010            for (int i = 0; i < variables.length; i++)
1011            {
1012                JRFillVariable variable = variables[i];
1013                checkVariableCalculationReq(variable, variableList, factory);
1014            }
1015
1016            setVariables(variableList);
1017        }
1018    }
1019
1020    
1021    private void checkVariableCalculationReq(JRFillVariable variable, List JavaDoc variableList, JRFillObjectFactory factory)
1022    {
1023        if (hasVariableCalculationReq(variable, JRVariable.CALCULATION_AVERAGE) || hasVariableCalculationReq(variable, JRVariable.CALCULATION_VARIANCE))
1024        {
1025            if (variable.getHelperVariable(JRCalculable.HELPER_COUNT) == null)
1026            {
1027                JRVariable countVar = createHelperVariable(variable, "_COUNT", JRVariable.CALCULATION_COUNT);
1028                JRFillVariable fillCountVar = factory.getVariable(countVar);
1029                checkVariableCalculationReq(fillCountVar, variableList, factory);
1030                variable.setHelperVariable(fillCountVar, JRCalculable.HELPER_COUNT);
1031            }
1032
1033            if (variable.getHelperVariable(JRCalculable.HELPER_SUM) == null)
1034            {
1035                JRVariable sumVar = createHelperVariable(variable, "_SUM", JRVariable.CALCULATION_SUM);
1036                JRFillVariable fillSumVar = factory.getVariable(sumVar);
1037                checkVariableCalculationReq(fillSumVar, variableList, factory);
1038                variable.setHelperVariable(fillSumVar, JRCalculable.HELPER_SUM);
1039            }
1040        }
1041
1042        if (hasVariableCalculationReq(variable, JRVariable.CALCULATION_STANDARD_DEVIATION))
1043        {
1044            if (variable.getHelperVariable(JRCalculable.HELPER_VARIANCE) == null)
1045            {
1046                JRVariable varianceVar = createHelperVariable(variable, "_VARIANCE", JRVariable.CALCULATION_VARIANCE);
1047                JRFillVariable fillVarianceVar = factory.getVariable(varianceVar);
1048                checkVariableCalculationReq(fillVarianceVar, variableList, factory);
1049                variable.setHelperVariable(fillVarianceVar, JRCalculable.HELPER_VARIANCE);
1050            }
1051        }
1052
1053        if (hasVariableCalculationReq(variable, JRVariable.CALCULATION_DISTINCT_COUNT))
1054        {
1055            if (variable.getHelperVariable(JRCalculable.HELPER_COUNT) == null)
1056            {
1057                JRVariable countVar = createDistinctCountHelperVariable(variable);
1058                JRFillVariable fillCountVar = factory.getVariable(countVar);
1059                checkVariableCalculationReq(fillCountVar, variableList, factory);
1060                variable.setHelperVariable(fillCountVar, JRCalculable.HELPER_COUNT);
1061            }
1062        }
1063
1064        variableList.add(variable);
1065    }
1066
1067    
1068    private boolean hasVariableCalculationReq(JRVariable var, byte calculation)
1069    {
1070        return variableCalculationReqs.contains(new VariableCalculationReq(var.getName(), calculation));
1071    }
1072
1073
1074    public String JavaDoc getName()
1075    {
1076        return parent.getName();
1077    }
1078
1079    public String JavaDoc getScriptletClass()
1080    {
1081        return parent.getScriptletClass();
1082    }
1083
1084    public JRParameter[] getParameters()
1085    {
1086        return parameters;
1087    }
1088
1089    public Map JavaDoc getParametersMap()
1090    {
1091        return parametersMap;
1092    }
1093
1094    public JRQuery getQuery()
1095    {
1096        return query;
1097    }
1098
1099    public JRField[] getFields()
1100    {
1101        return fields;
1102    }
1103
1104    public JRSortField[] getSortFields()
1105    {
1106        return parent.getSortFields();
1107    }
1108
1109    public JRVariable[] getVariables()
1110    {
1111        return variables;
1112    }
1113
1114    public JRGroup[] getGroups()
1115    {
1116        return groups;
1117    }
1118
1119    public boolean isMainDataset()
1120    {
1121        return isMain;
1122    }
1123
1124    public String JavaDoc getResourceBundle()
1125    {
1126        return parent.getResourceBundle();
1127    }
1128
1129
1130    public byte getWhenResourceMissingType()
1131    {
1132        return whenResourceMissingType;
1133    }
1134
1135
1136    public void setWhenResourceMissingType(byte whenResourceMissingType)
1137    {
1138        this.whenResourceMissingType = whenResourceMissingType;
1139    }
1140
1141
1142    public JRPropertiesMap getPropertiesMap()
1143    {
1144        return parent.getPropertiesMap();
1145    }
1146
1147
1148    public JRExpression getFilterExpression()
1149    {
1150        return parent.getFilterExpression();
1151    }
1152}
1153
Popular Tags