KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > calipso > reportgenerator > common > MatrixCsvSerializer


1 package com.calipso.reportgenerator.common;
2
3 import com.calipso.reportgenerator.reportcalculator.*;
4 import com.calipso.reportgenerator.reportdefinitions.ReportSourceDefinition;
5 import com.calipso.reportgenerator.reportdefinitions.DimensionSourceDefinition;
6 import com.calipso.reportgenerator.reportdefinitions.types.ReportDataType;
7 import com.calipso.common.DateEx;
8
9 import java.io.*;
10 import java.util.Iterator JavaDoc;
11 import java.util.Date JavaDoc;
12 import java.util.StringTokenizer JavaDoc;
13 import java.text.SimpleDateFormat JavaDoc;
14
15 /**
16  *
17  * User: jbassino
18  * Date: 08-ago-2005
19  * Time: 14:04:07
20  * Calipso Software
21  */

22 public class MatrixCsvSerializer {
23
24   public static ByteArrayOutputStream csvSerialize(Matrix matrix) throws IOException, InfoException {
25     ByteArrayOutputStream stream = new ByteArrayOutputStream();
26     Iterator JavaDoc it = matrix.iterator();
27     while (it.hasNext()) {
28       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
29       Object JavaDoc[] objects = (Object JavaDoc[]) it.next();
30       for (int i = 0; i < objects.length; i++) {
31         Object JavaDoc object = objects[i];
32         //Verifica si el objeto es date. Caso contrario retornara null
33
String JavaDoc date = serializeDate(object);
34         if(object==null){
35             buffer.append(";");
36         }else{
37           if(date != null){
38             buffer.append(date + ";");
39           }else{
40             if(object.toString().indexOf(";")>-1 || object.toString().indexOf("\"")>-1 ||
41                 object.toString().indexOf("\n") > -1 || object.toString().indexOf("\r") > -1
42             || object.toString().indexOf("\t") > -1){
43               String JavaDoc s = object.toString().replaceAll("\"", "\"\"");
44               buffer.append("\"" + s + "\"" + ";");
45             }else{
46               buffer.append(object.toString() + ";");
47             }
48           }
49         }
50       }
51       buffer.replace(buffer.length()-1, buffer.length(), "\n"); //reemplaza el ultimo ; de mas por un fin de linea
52
stream.write(buffer.toString().getBytes());
53     }
54     System.gc();
55     return stream;
56   }
57
58   private static String JavaDoc serializeDate(Object JavaDoc object) {
59     Date JavaDoc date = null;
60     if(object instanceof SharedDate){
61       date = ((SharedDate)object).getDateEx().getDate();
62     }else if(object instanceof DateEx){
63       date = ((DateEx)object).getDate();
64     }else if(object instanceof Date JavaDoc){
65       date = (Date JavaDoc)object;
66     }else{
67       return null;
68     }
69     SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc("yyyyMMdd");
70     return format.format(date);
71   }
72
73   public static Matrix deserialize(ReportGeneratorConfiguration configuration,InputStream stream, ReportSourceDefinition definition) throws IOException, InfoException {
74     Matrix result = DataSourceBuilder.buildMatrix(configuration, definition);
75     String JavaDoc line;
76     int lineCount = 0;
77     while(!(line = readLine(stream)).equalsIgnoreCase("")){
78         lineCount++;
79         result.add(getObjectArray(line, definition));
80     }
81     return result;
82   }
83
84   private static String JavaDoc readLine(InputStream stream) throws IOException {
85     byte[] bytes = new byte[1024];
86     String JavaDoc result = "";
87     int pos = 0;
88     int c;
89     boolean open = false;
90     while((c = stream.read()) > -1){
91       if(pos==1024){
92         result += new String JavaDoc(bytes, 0 ,pos);
93         pos = 0;
94       }
95       if(c=='\"'){
96         //Define si se abrieron o cerraron comillas
97
open = !open;
98       }
99       if(c=='\n' && !open){
100         //bytes[pos] = (byte)c;
101
//pos++;
102
result += new String JavaDoc(bytes, 0 ,pos);
103         return result;
104       }
105       bytes[pos] = (byte)c;
106       pos++;
107     }
108     result += new String JavaDoc(bytes, 0, pos);
109     return result;
110   }
111
112   private static Object JavaDoc[] getObjectArray(String JavaDoc line, ReportSourceDefinition definition) {
113     //TODO optimizar pasando dimCount y arrayLen como parametros para calcularlo una sola vez
114
int dimCount = definition.getDimensionSourceDefinitions().getDimensionSourceDefinitionCount();
115     int arrayLen = definition.getMetricSourceDefinitions().getMetricSourceDefinitionCount() + dimCount;
116     Object JavaDoc[] result = new Object JavaDoc[arrayLen];
117     int pos = 0;
118     //Cuando hay dos ;; significa que hay un valor NULL para la dimension.
119
//Al inicio, si empieza con ; el primer valor es null
120
boolean nullToken = true;
121     StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(line, ";", true);
122     while(tokenizer.hasMoreTokens()){
123       String JavaDoc token = tokenizer.nextToken();
124       if(token.equals(";")){
125         if(nullToken){
126           //Realiza el mismo comportamiento que el DefaultSQLDataSource.
127
result[pos] = null;
128           pos++;
129         }else{
130           nullToken = true;
131         }
132         continue;
133       }
134       nullToken = false;
135       token = token.trim();
136       if(((token.startsWith("\"") && !token.startsWith("\"\""))|| token.startsWith("\"\"\"")) && tokenizer.hasMoreTokens()){
137         token = token.substring(1, token.length());
138         if((token.endsWith("\"") && (!token.endsWith("\"\"")))|| token.endsWith("\"\"\"")){
139           token = token.substring(0, token.length()-1);
140         }else{
141           while(tokenizer.hasMoreTokens()){
142             String JavaDoc aux = tokenizer.nextToken();
143             token += aux;
144             if((aux.endsWith("\"") && (!aux.endsWith("\"\"")))|| aux.endsWith("\"\"\"")){
145               token = token.substring(0, token.length() - 1);
146               break;
147             }
148           }
149         }
150       }
151       token = cleanQuotes(token);
152       if(pos < dimCount){
153         DimensionSourceDefinition dimensionDef = definition.getDimensionSourceDefinitions().getDimensionSourceDefinition(pos);
154         result[pos] = getObjectFrom(token, dimensionDef.getDataType());
155       }else{
156         //Este es el caso de las metricas. Siempre son float
157
result[pos] = SharedFloat.newFrom(Float.valueOf(token));
158       }
159       pos++;
160     }
161     return result;
162   }
163
164   private static String JavaDoc cleanQuotes(String JavaDoc token) {
165     int first = token.indexOf("\"\"");
166     if(first > -1){
167       return token.replaceAll("\"\"", "\"");
168     }else{
169       return token;
170     }
171   }
172
173   private static Object JavaDoc getObjectFrom(String JavaDoc token, ReportDataType dataType) {
174     switch(dataType.getType()){
175       case ReportDataType.DATE_TYPE:
176       case ReportDataType.DATETIME_TYPE:
177         SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc("yyyyMMdd");
178         Date JavaDoc date = null;
179         try{
180           date = format.parse(token);
181         }catch (Exception JavaDoc e){
182           //No debería fallar la levantada de un Date, porque la misma aplicación la escribio con este formato
183
//Si falla, el objeto quedará null
184
e.printStackTrace();
185         }
186         return SharedDate.newFrom(new DateEx(date));
187       case ReportDataType.STRING_TYPE:
188         return SharedString.newFrom(token);
189       case ReportDataType.BOOLEAN_TYPE:
190         return new Boolean JavaDoc(token);
191       case ReportDataType.INTEGER_TYPE:
192         return SharedInteger.newFrom(Integer.valueOf(token));
193       case ReportDataType.FLOAT_TYPE:
194         return SharedFloat.newFrom(Float.valueOf(token));
195     }
196     return null;
197   }
198 }
199
Popular Tags