001: package com.calipso.reportgenerator.reportmanager;
002:
003: import com.calipso.reportgenerator.reportcalculator.IDataSource;
004: import com.calipso.reportgenerator.reportcalculator.Matrix;
005: import com.calipso.reportgenerator.common.InfoException;
006: import com.calipso.reportgenerator.common.*;
007: import com.calipso.reportgenerator.services.ISQLDataSourceResolver;
008: import com.calipso.reportgenerator.services.SQLDataSourceResolver;
009: import com.calipso.reportgenerator.services.DataSourceDefinitionConnectionString;
010:
011: import java.util.*;
012:
013: /**
014: * Resuelve la obtención de los datos ejecutando una consulta en lenguaje SQL.
015: * La consulta se genera a partir de la información sobre los campos que contiene el <code>ReportSourceDefinition</code> y el expresion del datasourcedefinition.
016: * Se encarga de generar los filtros correspondientes a partir de los <code>FilterDefinition</code> y devolver el resultado
017: * en un objeto <code>IDataSource</code>
018: */
019: public class SQLReportDataSource extends ReportDataSource {
020: private IDataSource dataSource;
021: public static final String AND_FILTER_TAG = "%and_prefilter%";
022: public static final String WHERE_FILTER_TAG = "%where_prefilter%";
023: private DataSourceDefinitionConnectionString dataSourceDefinitionConnectionString;
024:
025: public SQLReportDataSource(
026: ReportSpec reportSpec,
027: ReportDataSourceSpec dataSourceSpec,
028: ReportGeneratorConfiguration reportGeneratorConfiguration,
029: DataSourceDefinitionConnectionString dataSourceDefinitionConnectionString) {
030: super (reportSpec, dataSourceSpec);
031: setGeneratorConfiguration(reportGeneratorConfiguration);
032: this .dataSourceDefinitionConnectionString = dataSourceDefinitionConnectionString;
033: }
034:
035: /**
036: * Devuelve el DataSource
037: * @return
038: * @throws InfoException
039: */
040: public IDataSource getDataSource(Matrix matrix)
041: throws InfoException {
042: // if (dataSource == null) {
043: dataSource = getQueryDataSource(matrix);
044: //Ver si es necesario llenar los columnNames
045: //fillColumnsNames(dataSource);
046: //}
047: return dataSource;
048: }
049:
050: /**
051: * Asigna los nombres de las columnas al data source
052: * @param dataSource
053: * @throws InfoException
054: */
055: private void fillColumnsNames(IDataSource dataSource)
056: throws InfoException {
057: for (int i = 0; i < getColumnNames().size(); i++) {
058: try {
059: dataSource.setColumName(i, (String) getColumnNames()
060: .get(i));
061: } catch (Exception e) {
062: throw new InfoException(LanguageTraslator
063: .traslate("98"), e);
064: }
065: }
066: }
067:
068: /**
069: * Obtiene y construye y retorna un DataSource
070: * @return
071: */
072: private IDataSource getQueryDataSource(Matrix matrix)
073: throws InfoException {
074: ISQLDataSourceResolver resolver = getResolver();
075: resolver.setSqlText(getQueryText());
076: resolver.setReportDataSource(this );
077: return resolver.execute(matrix);
078: }
079:
080: private ISQLDataSourceResolver getResolver() throws InfoException {
081: return SQLDataSourceResolver.getResolver(
082: getReportGeneratorConfiguration(),
083: this .dataSourceDefinitionConnectionString,
084: getReportSpec());
085: }
086:
087: private void queryInfoToConsole() throws InfoException {
088: System.out.println("-----------------------------");
089: System.out.println(LanguageTraslator.traslate("498")
090: + getQueryText());
091: System.out.println("-----------------------------");
092: }
093:
094: /**
095: * Devuelve el texto de la query
096: * @return
097: */
098: private String getQueryText() throws InfoException {
099: List attributes = new ArrayList();
100: Set classes = new HashSet();
101: parseExternalData(attributes, classes);
102: StringBuffer buffer = new StringBuffer("");
103: resolveQuery(buffer);
104: return buffer.toString();
105: }
106:
107: /**
108: * Resuelve el texto de la Query
109: * @param buffer
110: */
111: private void resolveQuery(StringBuffer buffer) throws InfoException {
112: resolveCompleteFilter(buffer);
113: resolveParamTags(buffer);
114: }
115:
116: private void resolveParamTags(StringBuffer buffer)
117: throws InfoException {
118: Map filterTags = getTagsForFilters(getReportSpec()
119: .getPreFilterSpecs());
120: for (Iterator iterator = filterTags.entrySet().iterator(); iterator
121: .hasNext();) {
122: Map.Entry entry = (Map.Entry) iterator.next();
123: Collection tags = (Collection) entry.getValue();
124: for (Iterator it = tags.iterator(); it.hasNext();) {
125: String tag = ((String) it.next()).toUpperCase();
126: if (buffer.toString().toUpperCase().indexOf(tag) >= 0) {
127: replaceTag(buffer, tag, (ReportFilterSpec) entry
128: .getKey());
129: }
130: }
131: }
132: }
133:
134: private void replaceTag(StringBuffer buffer, String tag,
135: ReportFilterSpec reportFilterSpec) throws InfoException {
136: String resolvedExpression = getExpressionForTag(tag,
137: reportFilterSpec);
138: int tagSize = tag.length();
139: int pos = buffer.toString().toUpperCase().indexOf(tag);
140: for (; pos >= 0; pos = buffer.toString().toUpperCase().indexOf(
141: tag, pos + 1)) {
142: buffer.replace(pos, pos + tagSize, resolvedExpression);
143: }
144: }
145:
146: private String getExpressionForTag(String tag,
147: ReportFilterSpec reportFilterSpec) throws InfoException {
148: return getConstantValueForTag(tag.substring("%value_".length(),
149: tag.length() - 1), reportFilterSpec);
150: }
151:
152: private String getConstantValueForTag(String paramName,
153: ReportFilterSpec reportFilterSpec) throws InfoException {
154: String dimensionName = reportFilterSpec.getDimensionName();
155: int dataType;
156: if (dimensionName != null
157: && !dimensionName.equalsIgnoreCase("")) {
158: dataType = getReportSpec().getDimensionFromName(
159: dimensionName).getDataType().getType();
160: } else {
161: dataType = reportFilterSpec.getDataType().getType();
162: }
163: return ReportFilterBuilder.getExternalData(
164: getFilter().getParamValues().get(paramName),
165: getReportDataSourceSpec(), dataType).toString();
166: }
167:
168: private Map getTagsForFilters(Collection filterSpecs) {
169: Map result = new HashMap();
170: for (Iterator iterator = filterSpecs.iterator(); iterator
171: .hasNext();) {
172: ReportFilterSpec filterSpec = (ReportFilterSpec) iterator
173: .next();
174: result.put(filterSpec, getParamTags(filterSpec));
175: }
176: return result;
177: }
178:
179: private Collection getParamTags(ReportFilterSpec filterSpec) {
180: Collection result = new Vector();
181:
182: for (Iterator iterator = filterSpec.getParamNames().iterator(); iterator
183: .hasNext();) {
184: String paramName = (String) iterator.next();
185: result.add("%value_" + paramName + "%");
186: }
187: return result;
188: }
189:
190: private void resolveCompleteFilter(StringBuffer buffer) {
191: String condition = "";
192: if (getFilter() != null) {
193: condition = getFilter().toString();
194: }
195: String expression = getReportDataSourceSpec().getExpression();
196: int andTagPos = expression.indexOf(AND_FILTER_TAG);
197: int whereTagPos = expression.indexOf(WHERE_FILTER_TAG);
198: boolean findTag = ((andTagPos > 0) || (whereTagPos > 0));
199: if (findTag) {
200: while (findTag) {
201: if (andTagPos > 0) {
202: buffer.delete(0, buffer.length());
203: buffer.append(expression.substring(0, andTagPos));
204: if (!condition.equalsIgnoreCase("")) {
205: buffer.append(" and ");
206: buffer.append(condition);
207: }
208: buffer.append(expression.substring(andTagPos
209: + AND_FILTER_TAG.length(), expression
210: .length()));
211: expression = buffer.toString();
212: // expression = expression.substring(0, andTagPos)+expression.substring(andTagPos + AND_FILTER_TAG.length(), expression.length());
213: }
214: if (whereTagPos > 0) {
215: buffer.append(expression.substring(0, whereTagPos));
216: if (!condition.equalsIgnoreCase("")) {
217: buffer.append(" where ");
218: buffer.append(condition);
219: }
220: buffer.append(expression.substring(whereTagPos
221: + WHERE_FILTER_TAG.length(), expression
222: .length()));
223: expression = expression.substring(0, whereTagPos)
224: + expression.substring(whereTagPos
225: + WHERE_FILTER_TAG.length(),
226: expression.length());
227: }
228: andTagPos = expression.indexOf(AND_FILTER_TAG);
229: whereTagPos = expression.indexOf(WHERE_FILTER_TAG);
230: findTag = ((andTagPos > 0) || (whereTagPos > 0));
231: //revisar ej 61 porque no reemplaza bien el segundo y el primero le pone dos where
232: }
233: } else {
234: if (expression != null) {
235: buffer.append(expression);
236: }
237: /* if (!condition.equalsIgnoreCase("")){
238: buffer.append(" where ");
239: buffer.append(condition);
240: }*///Comentario para que no agregue el filtro where por defecto aunque no halla WHERE_FILTER_TAG
241: }
242: }
243:
244: /**
245: * Devuelve el modo de resolver el nombre de la variable
246: * @see com.calipso.reportgenerator.common.ReportFilter
247: * @return
248: */
249: public int getFilterVarMode() {
250: return ReportFilterBuilder.VARMODE_EXTERNALDATA;
251: }
252:
253: private void parseFromFieldSpecs(Collection fieldSpecs,
254: List attributes, Set classes) {
255: Iterator iterator = fieldSpecs.iterator();
256: while (iterator.hasNext()) {
257: ReportFieldSpec fieldSpec = (ReportFieldSpec) iterator
258: .next();
259: String externalData = fieldSpec.getExternalData();
260: if (!fieldSpec.getCalculated() && !externalData.equals("")) {
261: classes.add(externalData);
262: attributes.add(externalData);
263: }
264: }
265: }
266:
267: /**
268: * Llena la lista de clases y atributos a partir de los external data de las dimensiones y métricas
269: * @param attributes Lista de atributos a llenar
270: * @param classes Lista de classes a llenar
271: */
272:
273: protected void parseExternalData(List attributes, Set classes) {
274: parseFromFieldSpecs(getReportSpec().getDimensionSpecs()
275: .values(), attributes, classes);
276: parseFromFieldSpecs(getReportSpec().getMetricSpecs().values(),
277: attributes, classes);
278: }
279:
280: }
|