KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > calipso > reportgenerator > reportmanager > SQLReportDataSource


1 package com.calipso.reportgenerator.reportmanager;
2
3 import com.calipso.reportgenerator.reportcalculator.IDataSource;
4 import com.calipso.reportgenerator.reportcalculator.Matrix;
5 import com.calipso.reportgenerator.common.InfoException;
6 import com.calipso.reportgenerator.common.*;
7 import com.calipso.reportgenerator.services.ISQLDataSourceResolver;
8 import com.calipso.reportgenerator.services.SQLDataSourceResolver;
9 import com.calipso.reportgenerator.services.DataSourceDefinitionConnectionString;
10
11 import java.util.*;
12
13 /**
14  * Resuelve la obtención de los datos ejecutando una consulta en lenguaje SQL.
15  * La consulta se genera a partir de la información sobre los campos que contiene el <code>ReportSourceDefinition</code> y el expresion del datasourcedefinition.
16  * Se encarga de generar los filtros correspondientes a partir de los <code>FilterDefinition</code> y devolver el resultado
17  * en un objeto <code>IDataSource</code>
18  */

19 public class SQLReportDataSource extends ReportDataSource {
20   private IDataSource dataSource;
21   public static final String JavaDoc AND_FILTER_TAG = "%and_prefilter%";
22   public static final String JavaDoc WHERE_FILTER_TAG = "%where_prefilter%";
23   private DataSourceDefinitionConnectionString dataSourceDefinitionConnectionString;
24
25   public SQLReportDataSource(ReportSpec reportSpec, ReportDataSourceSpec dataSourceSpec, ReportGeneratorConfiguration reportGeneratorConfiguration, DataSourceDefinitionConnectionString dataSourceDefinitionConnectionString) {
26     super(reportSpec, dataSourceSpec);
27     setGeneratorConfiguration(reportGeneratorConfiguration);
28     this.dataSourceDefinitionConnectionString = dataSourceDefinitionConnectionString;
29   }
30
31   /**
32    * Devuelve el DataSource
33    * @return
34    * @throws InfoException
35    */

36   public IDataSource getDataSource(Matrix matrix) throws InfoException {
37    // if (dataSource == null) {
38
dataSource = getQueryDataSource(matrix);
39       //Ver si es necesario llenar los columnNames
40
//fillColumnsNames(dataSource);
41
//}
42
return dataSource;
43   }
44
45   /**
46    * Asigna los nombres de las columnas al data source
47    * @param dataSource
48    * @throws InfoException
49    */

50   private void fillColumnsNames(IDataSource dataSource) throws InfoException {
51     for (int i = 0; i < getColumnNames().size(); i++) {
52       try {
53         dataSource.setColumName(i, (String JavaDoc) getColumnNames().get(i));
54       } catch (Exception JavaDoc e) {
55         throw new InfoException(LanguageTraslator.traslate("98"), e);
56       }
57     }
58   }
59
60   /**
61    * Obtiene y construye y retorna un DataSource
62    * @return
63    */

64   private IDataSource getQueryDataSource(Matrix matrix) throws InfoException {
65     ISQLDataSourceResolver resolver = getResolver();
66     resolver.setSqlText(getQueryText());
67     resolver.setReportDataSource(this);
68     return resolver.execute(matrix);
69   }
70
71   private ISQLDataSourceResolver getResolver() throws InfoException {
72     return SQLDataSourceResolver.getResolver(getReportGeneratorConfiguration(), this.dataSourceDefinitionConnectionString,getReportSpec());
73   }
74
75   private void queryInfoToConsole() throws InfoException{
76     System.out.println("-----------------------------");
77     System.out.println(LanguageTraslator.traslate("498") + getQueryText());
78     System.out.println("-----------------------------");
79   }
80
81   /**
82    * Devuelve el texto de la query
83    * @return
84    */

85   private String JavaDoc getQueryText() throws InfoException {
86     List attributes = new ArrayList();
87     Set classes = new HashSet();
88     parseExternalData(attributes, classes);
89     StringBuffer JavaDoc buffer = new StringBuffer JavaDoc("");
90     resolveQuery(buffer);
91     return buffer.toString();
92   }
93
94
95   /**
96    * Resuelve el texto de la Query
97    * @param buffer
98    */

99   private void resolveQuery(StringBuffer JavaDoc buffer) throws InfoException {
100     resolveCompleteFilter(buffer);
101     resolveParamTags(buffer);
102   }
103
104   private void resolveParamTags(StringBuffer JavaDoc buffer) throws InfoException {
105     Map filterTags = getTagsForFilters(getReportSpec().getPreFilterSpecs());
106     for (Iterator iterator = filterTags.entrySet().iterator(); iterator.hasNext();) {
107       Map.Entry entry = (Map.Entry) iterator.next();
108       Collection tags = (Collection)entry.getValue();
109       for (Iterator it = tags.iterator(); it.hasNext();) {
110         String JavaDoc tag = ((String JavaDoc) it.next()).toUpperCase();
111         if(buffer.toString().toUpperCase().indexOf(tag) >= 0){
112           replaceTag(buffer, tag, (ReportFilterSpec)entry.getKey());
113         }
114       }
115     }
116   }
117
118   private void replaceTag(StringBuffer JavaDoc buffer, String JavaDoc tag, ReportFilterSpec reportFilterSpec) throws InfoException {
119     String JavaDoc resolvedExpression = getExpressionForTag(tag, reportFilterSpec);
120     int tagSize = tag.length();
121     int pos = buffer.toString().toUpperCase().indexOf(tag);
122     for(; pos >= 0 ; pos = buffer.toString().toUpperCase().indexOf(tag, pos + 1)){
123       buffer.replace(pos, pos + tagSize, resolvedExpression);
124     }
125   }
126
127   private String JavaDoc getExpressionForTag(String JavaDoc tag, ReportFilterSpec reportFilterSpec) throws InfoException{
128     return getConstantValueForTag(tag.substring("%value_".length(), tag.length()-1), reportFilterSpec);
129   }
130
131   private String JavaDoc getConstantValueForTag(String JavaDoc paramName, ReportFilterSpec reportFilterSpec) throws InfoException{
132     String JavaDoc dimensionName = reportFilterSpec.getDimensionName();
133     int dataType;
134     if(dimensionName!=null && !dimensionName.equalsIgnoreCase("")){
135       dataType = getReportSpec().getDimensionFromName(dimensionName).getDataType().getType();
136     }else{
137       dataType = reportFilterSpec.getDataType().getType();
138     }
139     return ReportFilterBuilder.getExternalData(getFilter().getParamValues().get(paramName),getReportDataSourceSpec(), dataType).toString();
140   }
141
142   private Map getTagsForFilters(Collection filterSpecs) {
143     Map result = new HashMap();
144     for (Iterator iterator = filterSpecs.iterator(); iterator.hasNext();) {
145       ReportFilterSpec filterSpec = (ReportFilterSpec) iterator.next();
146       result.put(filterSpec, getParamTags(filterSpec));
147     }
148     return result;
149   }
150
151   private Collection getParamTags(ReportFilterSpec filterSpec) {
152     Collection result = new Vector();
153
154     for (Iterator iterator = filterSpec.getParamNames().iterator(); iterator.hasNext();) {
155       String JavaDoc paramName = (String JavaDoc) iterator.next();
156       result.add("%value_" + paramName + "%");
157     }
158     return result;
159   }
160
161   private void resolveCompleteFilter(StringBuffer JavaDoc buffer) {
162     String JavaDoc condition="";
163     if (getFilter()!=null){
164       condition = getFilter().toString();
165     }
166     String JavaDoc expression = getReportDataSourceSpec().getExpression();
167     int andTagPos = expression.indexOf(AND_FILTER_TAG);
168     int whereTagPos = expression.indexOf(WHERE_FILTER_TAG);
169     boolean findTag = ((andTagPos > 0) || (whereTagPos > 0));
170     if (findTag) {
171       while (findTag) {
172         if (andTagPos > 0) {
173           buffer.delete(0,buffer.length());
174           buffer.append(expression.substring(0, andTagPos));
175           if (!condition.equalsIgnoreCase("")){
176             buffer.append(" and ");
177             buffer.append(condition);
178           }
179           buffer.append(expression.substring(andTagPos + AND_FILTER_TAG.length(), expression.length()));
180           expression = buffer.toString();
181 // expression = expression.substring(0, andTagPos)+expression.substring(andTagPos + AND_FILTER_TAG.length(), expression.length());
182
}
183         if (whereTagPos > 0) {
184           buffer.append(expression.substring(0, whereTagPos));
185           if (!condition.equalsIgnoreCase("")){
186             buffer.append(" where ");
187             buffer.append(condition);
188           }
189           buffer.append(expression.substring(whereTagPos + WHERE_FILTER_TAG.length(), expression.length()));
190           expression = expression.substring(0, whereTagPos)+expression.substring(whereTagPos + WHERE_FILTER_TAG.length(), expression.length());
191         }
192         andTagPos = expression.indexOf(AND_FILTER_TAG);
193         whereTagPos = expression.indexOf(WHERE_FILTER_TAG);
194         findTag = ((andTagPos > 0) || (whereTagPos > 0));
195         //revisar ej 61 porque no reemplaza bien el segundo y el primero le pone dos where
196
}
197     }
198     else {
199       if(expression!=null){
200         buffer.append(expression);
201       }
202 /* if (!condition.equalsIgnoreCase("")){
203         buffer.append(" where ");
204         buffer.append(condition);
205       }*/
//Comentario para que no agregue el filtro where por defecto aunque no halla WHERE_FILTER_TAG
206
}
207   }
208
209
210   /**
211    * Devuelve el modo de resolver el nombre de la variable
212    * @see com.calipso.reportgenerator.common.ReportFilter
213    * @return
214    */

215   public int getFilterVarMode() {
216     return ReportFilterBuilder.VARMODE_EXTERNALDATA;
217   }
218
219   private void parseFromFieldSpecs(Collection fieldSpecs, List attributes, Set classes){
220     Iterator iterator = fieldSpecs.iterator();
221     while (iterator.hasNext()) {
222       ReportFieldSpec fieldSpec = (ReportFieldSpec) iterator.next();
223       String JavaDoc externalData = fieldSpec.getExternalData();
224       if (!fieldSpec.getCalculated() && !externalData.equals("")) {
225         classes.add(externalData);
226         attributes.add(externalData);
227       }
228     }
229   }
230
231   /**
232    * Llena la lista de clases y atributos a partir de los external data de las dimensiones y métricas
233    * @param attributes Lista de atributos a llenar
234    * @param classes Lista de classes a llenar
235    */

236
237   protected void parseExternalData(List attributes, Set classes) {
238     parseFromFieldSpecs(getReportSpec().getDimensionSpecs().values(), attributes, classes);
239     parseFromFieldSpecs(getReportSpec().getMetricSpecs().values(), attributes, classes);
240   }
241
242 }
243
Popular Tags