KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > calipso > reportgenerator > userinterface > ReportFromSQL


1 package com.calipso.reportgenerator.userinterface;
2
3 import com.calipso.xmleditor.XmlEditorConnectionPane;
4 import com.calipso.xmleditor.DataTypeTableFrame;
5 import com.calipso.xmleditor.XmlEditorDefaultReports;
6 import com.calipso.xmleditor.XmlEditorException;
7 import com.calipso.reportgenerator.common.LanguageTraslator;
8 import com.calipso.reportgenerator.common.ReportGeneratorConfiguration;
9 import com.calipso.reportgenerator.common.InfoException;
10 import com.calipso.reportgenerator.reportdefinitions.ReportDefinition;
11 import com.calipso.reportgenerator.reportdefinitions.ReportSourceDefinition;
12
13 import javax.swing.*;
14 import java.util.Map JavaDoc;
15 import java.util.HashMap JavaDoc;
16 import java.util.Vector JavaDoc;
17 import java.sql.*;
18 import java.io.*;
19 import java.awt.event.ActionListener JavaDoc;
20
21 import org.apache.xalan.serialize.WriterToUTF8;
22 import org.exolab.castor.xml.Marshaller;
23
24 /**
25  * Calipso Software
26  * User: Breto
27  * Date: 03/01/2006
28  * Time: 12:12:41
29  */

30 public class ReportFromSQL {
31   private XmlEditorConnectionPane connectionPane;
32   private Map JavaDoc typeColumn = new HashMap JavaDoc();
33   private JFrame frame;
34   private ReportGeneratorConfiguration reportGeneratorConfiguration;
35
36   public ReportFromSQL(JFrame owner,ReportGeneratorConfiguration generatorConfiguration) {
37     frame = owner;
38     reportGeneratorConfiguration = generatorConfiguration;
39   }
40
41
42   public void createReportFrame() throws InfoException {
43     XmlEditorConnectionPane connectionPane = getConnectionPane();
44     connectionPane.pack();
45     connectionPane.setVisible(true);
46     if((!connectionPane.isCancelled())){
47       if (createReportDefinitionsFromSql( connectionPane.getReportName(), connectionPane.getClassName(), connectionPane.getLocalUrl(),
48               connectionPane.getUser(), String.valueOf(connectionPane.getPassword()), connectionPane.getSqlText())){
49         JOptionPane.showMessageDialog(frame, LanguageTraslator.traslate("559"));
50         JOptionPane.showMessageDialog(frame, LanguageTraslator.traslate("556"));
51       }
52     }
53   }
54
55   public boolean createReportDefinitionsFromSql(String JavaDoc reportName, String JavaDoc className, String JavaDoc localUrl, String JavaDoc user,
56                                                 String JavaDoc password, String JavaDoc sql) throws InfoException {
57     Map JavaDoc currentColumnsDimensions;
58     Map JavaDoc currentColumnsMetrics;
59
60     try{
61       connectionPane.setVisible(false);
62       DataTypeTableFrame dataTypeTableFrame;
63       Class.forName(className);
64       System.out.print(LanguageTraslator.traslate("519"));
65       Connection con = DriverManager.getConnection(localUrl, user, password);
66       Statement stmt = con.createStatement();
67       //stmt.setMaxRows();
68
//stmt.setFetchSize();
69
ResultSet rs=null;
70       try {
71         rs = stmt.executeQuery(prepareSQL(sql));
72       }catch (Exception JavaDoc ee){
73         throw new InfoException(LanguageTraslator.traslate("551"),ee);
74       }
75       ResultSetMetaData meta = rs.getMetaData();
76
77       System.out.println(LanguageTraslator.traslate("520"));
78       currentColumnsDimensions = getColumnsDimensionsMap(meta);
79       currentColumnsMetrics = getColumnsMetricsMap(meta);
80       dataTypeTableFrame = new DataTypeTableFrame(frame,typeColumn);
81       dataTypeTableFrame.setVisible(true);
82        if(!dataTypeTableFrame.isCancelled()) {
83             Map JavaDoc map2 = dataTypeTableFrame.getRowsLatestVersion();
84             dataTypeTableFrame.setVisible(false);
85             currentColumnsDimensions = getColumnsDimensionsMap(map2);
86             currentColumnsMetrics = getColumnsMetricsMap(map2);
87        }
88
89       if ((currentColumnsDimensions.size()!=0)||(currentColumnsMetrics.size()!=0)){
90        writeReports(reportName, currentColumnsDimensions, currentColumnsMetrics, prepareSQL(sql), className, localUrl, user, password);
91        File xmlFile = new File(reportGeneratorConfiguration.getSourceReportDefinitionsPath() + "/" + XmlEditorDefaultReports.getReportId(reportName) + ".xml");
92        return true;
93       }
94     }catch (Exception JavaDoc e){
95       throw new InfoException(LanguageTraslator.traslate("565"), e);
96     }
97     return false;
98   }
99
100   private String JavaDoc prepareSQL(String JavaDoc sql) {
101     return sql.replaceAll("\n"," ");
102   }
103
104   private XmlEditorConnectionPane getConnectionPane() {
105     if(connectionPane==null){
106       connectionPane = new XmlEditorConnectionPane(frame, true, reportGeneratorConfiguration.getValues());
107     }
108     return connectionPane;
109   }
110
111   private Map JavaDoc getColumnsDimensionsMap(ResultSetMetaData meta) throws InfoException {
112      Map JavaDoc result = new HashMap JavaDoc();
113      int cantidad = 0;
114
115      try{
116          cantidad = meta.getColumnCount();
117           for (int i=0; i < cantidad; i++) {
118             if (!(isMetric(meta.getColumnType(i+1)))){
119             System.out.println(LanguageTraslator.traslate("280") + meta.getColumnName(i+1));
120             result.put(meta.getColumnName(i+1),new Integer JavaDoc(meta.getColumnType(i+1)));
121             Vector JavaDoc data = new Vector JavaDoc(3);
122             data.add(meta.getColumnName(i+1));
123             data.add("Dimension");
124             data.add(new Integer JavaDoc (meta.getColumnType(i+1)));; // ver si es necesario q devuelva int ...
125
typeColumn.put(new Integer JavaDoc(i+1),data);
126             }
127           }
128         }catch (Exception JavaDoc e){
129             throw new InfoException(LanguageTraslator.traslate("566"), e);
130           }
131       return result;
132         }
133
134   private Map JavaDoc getColumnsMetricsMap(ResultSetMetaData meta) throws InfoException {
135      Map JavaDoc result = new HashMap JavaDoc();
136      int cantidad = 0;
137      try{
138         cantidad = meta.getColumnCount();
139         for (int i=0; i < cantidad; i++) {
140           if (isMetric(meta.getColumnType(i+1))){
141             System.out.println(LanguageTraslator.traslate("529") + meta.getColumnName(i+1));
142             result.put(meta.getColumnName(i+1),new Integer JavaDoc(meta.getColumnType(i+1)));
143             Vector JavaDoc data = new Vector JavaDoc(3);
144             data.add(meta.getColumnName(i+1));
145             data.add("Metric");
146             data.add(new Integer JavaDoc (meta.getColumnType(i+1))); // ver si es necesario q devuelva int ...
147
typeColumn.put(new Integer JavaDoc(i+1),data);
148           }
149         }
150       }catch (Exception JavaDoc e){
151         throw new InfoException(LanguageTraslator.traslate("567"), e);
152       }
153       return result;
154     }
155
156   /**
157    * Verifica que el tipo de dato de la columna sea acumulable(metrica)
158    * @param typeColumn
159    * @return
160    */

161
162   private boolean isMetric(int typeColumn){
163
164     switch(typeColumn) {
165        case Types.TINYINT:
166        case Types.SMALLINT:
167        case Types.INTEGER:
168        case Types.BIGINT:
169        case Types.FLOAT:
170        case Types.DOUBLE:
171        case Types.REAL:
172        case Types.DECIMAL:
173        case Types.NUMERIC:
174          return true;
175       default:
176          return false;
177       }
178   }
179
180   private Map JavaDoc getColumnsDimensionsMap(Map JavaDoc map){
181    Map JavaDoc mapAux = new HashMap JavaDoc();
182     for (int i = 0; i < (this.typeColumn.keySet().size()); i++) {
183       Vector JavaDoc vector =(Vector JavaDoc) map.get(new Integer JavaDoc(1+i));
184          if (vector != null){
185            String JavaDoc columnName;
186            Vector JavaDoc vec = new Vector JavaDoc(2);
187            Integer JavaDoc columnType;
188            String JavaDoc extData;
189            if (vector.get(1).equals("Dimension") ) {
190              columnName = (String JavaDoc) vector.get(0);
191              columnType = getIdType((String JavaDoc)vector.get(2));
192         extData = (String JavaDoc)vector.get(3);
193              vec.add(columnType);
194        vec.add(extData);
195              mapAux.put(columnName,vec);
196            }
197          }
198     }
199  return mapAux;
200   }
201
202
203   private Integer JavaDoc getIdType(String JavaDoc s){
204    if(s.equalsIgnoreCase("DECIMAL")){
205      return new Integer JavaDoc(3);
206    }
207    if(s.equalsIgnoreCase("INTEGER")){
208      return new Integer JavaDoc(4);
209    }
210    if(s.equalsIgnoreCase("FLOAT")){
211      return new Integer JavaDoc(6);
212    }
213    if(s.equalsIgnoreCase("BOOLEAN")){
214      return new Integer JavaDoc(16);
215    }
216    if(s.equalsIgnoreCase("DATETIME")){
217      return new Integer JavaDoc(91);
218    }else{
219      return new Integer JavaDoc(12);
220    }
221   }
222
223   private Map JavaDoc getColumnsMetricsMap(Map JavaDoc map){
224   Map JavaDoc mapAux = new HashMap JavaDoc();
225    for (int i = 0; i < (this.typeColumn.keySet().size()); i++) {
226      Vector JavaDoc vector =(Vector JavaDoc) map.get(new Integer JavaDoc(1+i));
227         if (vector != null){
228           String JavaDoc columnName;
229           Vector JavaDoc vec = new Vector JavaDoc(2);
230           Integer JavaDoc columnType;
231           String JavaDoc extData;
232           if (vector.get(1).equals("Metric") ) {
233             columnName = (String JavaDoc) vector.get(0);
234             columnType = getIdType((String JavaDoc)vector.get(2));
235            extData = (String JavaDoc)vector.get(3);
236             vec.add(columnType);
237              vec.add(extData);
238             mapAux.put(columnName,vec);
239           }
240         }
241    }
242     return mapAux;
243   }
244
245   /**
246    * Con los datos obtenidos de la query genera los archivos XML que seran la especificacion del reporte.
247    * @param reportName
248    * @param dimensionMap
249    * @param metricMap
250    * @param query
251    * @param className
252    * @param localUrl
253    * @param user
254    * @param password
255    */

256   private void writeReports(String JavaDoc reportName, Map JavaDoc dimensionMap, Map JavaDoc metricMap, String JavaDoc query, String JavaDoc className, String JavaDoc localUrl, String JavaDoc user, String JavaDoc password) throws InfoException {
257     System.out.println(LanguageTraslator.traslate("521"));
258     String JavaDoc reportPath = writeReportDefinition(reportName, dimensionMap, metricMap);
259     System.out.println("reportName:"+reportName+"dimensionMap: "+dimensionMap.size()+ "tostring:"+dimensionMap.toString()+"metricMap:"+metricMap.toString());
260     System.out.println(LanguageTraslator.traslate("522"));
261     reportPath = writeReportSourceDefinition(reportName, dimensionMap, metricMap, query, className, localUrl, user, password);
262   }
263
264
265   /**
266    * Genera en base a los datos obtenidos una ReportDefinition estandar.
267    * @param reportName
268    * @param dimensionMap
269    * @param metricMap
270    * @return
271    */

272   private String JavaDoc writeReportDefinition(String JavaDoc reportName, Map JavaDoc dimensionMap, Map JavaDoc metricMap) throws InfoException {
273     ReportDefinition report = XmlEditorDefaultReports.getReportDefinition(reportGeneratorConfiguration, reportName, dimensionMap, metricMap);
274     System.out.println("report.toString():"+report.toString());
275     System.out.println("report.toString():"+report.getDimensionDefinitions().getDimensionDefinition().length+":"+ report.getDimensionDefinitions().enumerateDimensionDefinition().toString());
276     String JavaDoc fullPath = reportGeneratorConfiguration.getSourceReportDefinitionsPath() + "/" + XmlEditorDefaultReports.getReportId(reportName) + ".xml";
277     try{
278       System.out.println(LanguageTraslator.traslate("525"));
279       Writer wr = new FileWriter(fullPath);
280       report.marshal(wr);
281       wr.flush();
282       wr.close();
283     }catch (Exception JavaDoc e){
284       e.printStackTrace();
285       throw new InfoException(LanguageTraslator.traslate("568"), e);
286     }
287     return fullPath;
288   }
289
290   private String JavaDoc writeReportSourceDefinition(String JavaDoc reportName, Map JavaDoc dimensionMap, Map JavaDoc metricMap, String JavaDoc query, String JavaDoc className, String JavaDoc localUrl, String JavaDoc user, String JavaDoc password) throws InfoException {
291     ReportSourceDefinition report = XmlEditorDefaultReports.getReportSourceDefinition(reportName, dimensionMap, metricMap, query, className, localUrl, user, password);
292     String JavaDoc fullPath = reportGeneratorConfiguration.getSourceReportSourceDefinitionsPath() + "/" + XmlEditorDefaultReports.getSourceId(reportName) + ".xml";
293     try{
294       System.out.println(LanguageTraslator.traslate("524"));
295       Writer wr = new FileWriter(fullPath);
296       report.marshal(wr);
297       wr.flush();
298       wr.close();
299     }catch (Exception JavaDoc e){
300       throw new InfoException(LanguageTraslator.traslate("569"), e);
301     }
302     return fullPath;
303   }
304
305
306
307 }
308
Popular Tags