KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.calipso.reportgenerator.reportmanager;
2
3 //import com.calipso.reportgenerator.reportcalculator.CubeFloat;
4
import com.calipso.reportgenerator.reportcalculator.CubeQuery;
5 import com.calipso.reportgenerator.reportcalculator.SharedDate;
6 import com.calipso.reportgenerator.reportcalculator.SharedFloat;
7 import com.calipso.reportgenerator.common.*;
8 import org.apache.xerces.dom.*;
9 import org.apache.xml.serialize.OutputFormat;
10 import org.apache.xml.serialize.XMLSerializer;
11 import org.w3c.dom.*;
12
13 import java.io.StringWriter JavaDoc;
14 import java.io.IOException JavaDoc;
15 import java.util.Map JavaDoc;
16 import java.text.DateFormat JavaDoc;
17 import java.text.SimpleDateFormat JavaDoc;
18 import java.text.DecimalFormat JavaDoc;
19
20 import com.calipso.reportgenerator.common.InfoException;
21
22 /**
23  * Esta clase se encarga de generar el XML de salida
24  * para un reporte de tipo Cube. Result.xml
25  */

26 public class CubeReportXmlWriter implements ReportXmlWriter {
27   private ReportData reportData;
28   private ReportDataIterator reportDataIterator;
29   private ReportSpec reportSpec;
30   private Document document;
31   private Map JavaDoc paramValues;
32   private CubeQuery cubeQuery;
33   private Element root;
34
35   public CubeReportXmlWriter(ReportData reportData, ReportSpec reportSpec, Map JavaDoc paramValues, ReportQuery query) throws InfoException {
36     this.reportData = reportData;
37     this.reportDataIterator = reportData.iterator();
38     this.reportSpec = reportSpec;
39     this.paramValues = paramValues;
40     cubeQuery = query.getCubeQuery();
41   }
42
43   /**
44    * Retorna el xml generado
45    * @return
46    */

47   public StringWriter JavaDoc getXml() throws InfoException {
48     try {
49       /*Element node;
50       startDocument();
51       if (reportDataIterator.hasNext()) {
52         reportDataIterator.advance();
53         node = createDocument();
54         root = createElement("Report");
55         node.appendChild(root);
56         iterateCube(0, root, false);
57         addParameters();
58       }*/

59       startDocument();
60       Element node = createDocument();
61       root = createElement("Report");
62       node.appendChild(root);
63       iterateRows(root);
64       return getStream();
65     } catch (Exception JavaDoc e) {
66       throw new InfoException(LanguageTraslator.traslate("76"), e);
67     }
68   }
69
70   public ReportSpec getReportSpec() {
71     return reportSpec;
72   }
73
74   public Map JavaDoc getParamValues() {
75     return paramValues;
76   }
77
78   /**
79    * Agrega los parámetros(Parameters values) al xml
80    */

81   private void addParameters() {
82     // COMPLETAR
83
}
84
85   /**
86    * Devuelve un StringWriter con el xml
87    * @return
88    * @throws IOException
89    */

90   private StringWriter JavaDoc getStream() throws IOException JavaDoc {
91     OutputFormat format = new OutputFormat(document, "ISO-8859-1", true);
92     StringWriter JavaDoc stringOut = new StringWriter JavaDoc();
93     XMLSerializer serial = new XMLSerializer(stringOut, format);
94     serial.asDOMSerializer();
95     Element elem = document.getDocumentElement();
96     if (elem != null) {
97       serial.serialize(elem);
98     }
99     return stringOut;
100   }
101
102   private void iterateRows(Element node) {
103     int i;
104     int [] rows = cubeQuery.getRows();
105     if(rows.length > 0) {
106       while(reportDataIterator.hasNext()) {
107         reportDataIterator.advance();
108         Object JavaDoc [] values = reportDataIterator.current();
109         for(i = 0 ; i < rows.length ; i++) {
110           ReportDimensionSpec dimensionSpec = reportSpec.getDimensionFromIndex(rows [i]);
111           node = getNodeFrom(dimensionSpec.getName(), getNodeValue(dimensionSpec,values [i]), node, values);
112         }
113
114         iterateColumns(node, values, i);
115         node = root;
116       }
117     }
118   }
119
120
121
122   private void iterateColumns(Element node, Object JavaDoc [] values, int i) {
123     int [] cols = cubeQuery.getColumns();
124     if(cols.length > 0) {
125       for(int j = 0 ; j < cols.length ; j++, i++) {
126         ReportDimensionSpec dimensionSpec = reportSpec.getDimensionFromIndex(cols [j]);
127         node = getNodeFrom(dimensionSpec.getName(), getNodeValue(dimensionSpec,values [i]), node, values);
128       }
129     }
130   }
131
132   /**
133    * Retorna el valor para el nodo
134    * @param dimensionSpec
135    * @param value
136    * @return
137    */

138   private String JavaDoc getNodeValue(ReportDimensionSpec dimensionSpec, Object JavaDoc value){
139     if (value instanceof SharedDate) {
140       DateFormat JavaDoc dateFormat = new SimpleDateFormat JavaDoc("yyyyMMdd");
141       return dateFormat.format(((SharedDate) value).getDateEx().getDate());
142     } else if (value instanceof SharedFloat) {
143       DecimalFormat JavaDoc df = new DecimalFormat JavaDoc();
144       return df.format(((SharedFloat) value).floatValue());
145     } else {
146       return value.toString();
147     }
148   }
149
150   private Element getNodeFrom(String JavaDoc name, String JavaDoc value, Element node, Object JavaDoc [] values) {
151     Element returnVal = null;
152
153     NodeList childs = node.getChildNodes();
154     for(int i = 0 ; i < childs.getLength() ; i++) {
155       Element child = (Element) childs.item(i);
156       Attr attr = child.getAttributeNode("Value");
157       if(attr.getValue().equalsIgnoreCase(value)) {
158         returnVal = child;
159         break;
160       }
161     }
162
163     if(returnVal == null) {
164       returnVal = document.createElement(name);
165       returnVal.setAttribute("Value", value);
166       node.appendChild(returnVal);
167     }
168
169     addMetrics(returnVal, values, cubeQuery.getRows().length + cubeQuery.getColumns().length);
170     return returnVal;
171   }
172
173   private void addMetrics(Element returnVal, Object JavaDoc [] values, int j) {
174     int [] metrics = cubeQuery.getMetrics();
175     for(int i = 0 ; i < metrics.length ; i++, j++) {
176       ReportMetricSpec metric = reportSpec.getMetricFromIndex(i);
177       if(returnVal.hasAttribute(metric.getName())) {
178         Attr attr = returnVal.getAttributeNode(metric.getName());
179         float metricValue = Float.valueOf(attr.getValue()).floatValue();
180         float result = ((SharedFloat)values [j]).floatValue() + metricValue;
181         attr.setValue(String.valueOf(result));
182       } else {
183         returnVal.setAttribute(metric.getName(), values [j].toString());
184       }
185     }
186   }
187
188   /**
189    * Recorre el iterador del cube
190    * @param dimension nivel del iterador
191    * @param ownerNode nodeo padre
192    * @param eoc fin del cube
193    */

194
195   private void iterateCube(int dimension, Element ownerNode, boolean eoc) {
196     Element elemTo;
197     Element child;
198     Object JavaDoc[] totalObj = null;
199     int dimTo;
200     int dimSize;
201     boolean lEoc = false;
202     //dimSize = reportData.getQuery().getDimensions().size();
203
//Todo: no optimo
204
dimSize = getCubeQuery().getDimensions().length;
205
206     if (!eoc) {
207       child = createNodeElement(getDimensionNameFromIndex(dimension), reportDataIterator.current()[dimension].toString());
208       ownerNode.appendChild(child);
209       if (dimension < (dimSize - 1)) {
210         iterateCube((dimension + 1), child, eoc);
211       }
212       else {
213         FillValue(child);
214         if (reportDataIterator.hasNext()) {
215           reportDataIterator.advance();
216         }
217         else {
218           lEoc = true;
219           reportDataIterator.advance();
220         }
221         elemTo = child;
222         dimTo = dimension;
223         for (int i = 0; i < (reportDataIterator.currentTotals().size()); i++) {
224           dimTo = dimTo - 1;
225           elemTo = (Element) elemTo.getParentNode();
226           if (i < (reportDataIterator.currentTotals().size())) {
227             totalObj = (Object JavaDoc[]) reportDataIterator.currentTotals().toArray()[i];
228             fillTotals(elemTo, totalObj);
229           }
230         }
231         iterateCube(dimTo, (Element) elemTo.getParentNode(), lEoc);
232       }
233     }
234   }
235
236   private CubeQuery getCubeQuery() {
237     if (cubeQuery == null) {
238       try {
239         cubeQuery = reportData.getQuery().getCubeQuery();
240       } catch (InfoException e) {
241         return null;
242       }
243     }
244     return cubeQuery;
245   }
246
247   /**
248    * Obtiene el nombre de una dimensión
249    * @param dimension indice
250    * @return
251    */

252   private String JavaDoc getDimensionNameFromIndex(int dimension) {
253     return ((QueryDimension)reportData.getQuery().getDimensions().get(dimension)).getName();
254     /*int index = reportData.getQuery().getDimensions().get[dimension];
255     return ((DataDefinition) cube.getDefinition().getDimensions()[index]).getName();*/

256   }
257
258   /**
259    * Obtienen el nombre de la métrica
260    * @param metric indice
261    * @return
262    */

263   private String JavaDoc getMetricNameFromIndex(int metric) {
264     return ((QueryMetric)reportData.getQuery().getMetrics().get(metric)).getName();
265     //return ((DataDefinition) cube.getDefinition().getMetrics()[metric]).getName();
266
}
267
268
269   /**
270    * Completa los totales para el grupo
271    * @param elem
272    * @param total lista de totales
273    */

274
275   private void fillTotals(Element elem, Object JavaDoc[] total) {
276     int index = 0;
277     int currentMetric = 0;
278     int metricsFound = 0;
279     int metricsCount = reportData.getQuery().getMetrics().size();
280
281     while (metricsFound < metricsCount) {
282       if (total[index] instanceof SharedFloat) {
283         String JavaDoc metricName = getMetricNameFromIndex(currentMetric);
284         elem.setAttribute(metricName, total[index].toString());
285         currentMetric++;
286         metricsFound++;
287       }
288       index++;
289     }
290   }
291
292   /**
293    * Completa el valor de las dimensiones
294    * @param elem nodo
295    * @param metricValues valores de las métricas
296    */

297   private void fillMetricValues(Element elem, Object JavaDoc[] metricValues) {
298     int index = 0;
299     int currentMetric = 0;
300     int metricsFound = 0;
301     int metricsCount = reportData.getQuery().getMetrics().size();
302
303     while (metricsFound < metricsCount) {
304       if (metricValues[index] instanceof SharedFloat) {
305         String JavaDoc metricName = getMetricNameFromIndex(currentMetric);
306         elem.setAttribute(metricName, metricValues[index].toString());
307         currentMetric++;
308         metricsFound++;
309       }
310       index++;
311     }
312   }
313
314   /**
315    * Completa el valor de la métrica
316    * @param elem
317    */

318   private void FillValue(Element elem) {
319     Object JavaDoc[] row;
320     row = reportDataIterator.current();
321     fillMetricValues(elem, row);
322   }
323
324   /**
325    * Crea el documento xml y el root
326    * @return
327    */

328   private Element createDocument() {
329     Element root;
330     root = createElement("Result");
331     document.appendChild(root);
332     String JavaDoc reportDefName = getReportSpec().getDescription();
333     root.setAttribute("ReportRefinition", reportDefName);
334     return root;
335   }
336
337   /**
338    * Crea un document
339    */

340   private void startDocument() {
341     document = new DocumentImpl();
342   }
343
344   /**
345    * Crea un nodo dentro del documento
346    * @param tagName Nombre del tag
347    * @param value valor del tag
348    * @return el elemento creado
349    */

350   private Element createNodeElement(String JavaDoc tagName, String JavaDoc value) {
351     Element newElem;
352     newElem = document.createElement(tagName);
353     newElem.setAttribute("Value", value);
354     return newElem;
355   }
356
357   /**
358    * Crea un element
359    * @param tagName
360    * @return
361    */

362   private Element createElement(String JavaDoc tagName) {
363     return document.createElement(tagName);
364   }
365 }
366
Popular Tags