KickJava   Java API By Example, From Geeks To Geeks.

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


1 package com.calipso.reportgenerator.reportmanager;
2
3 import com.calipso.reportgenerator.reportcalculator.Matrix;
4 import com.calipso.reportgenerator.common.*;
5 import com.calipso.reportgenerator.reportdefinitions.ReportSourceDefinition;
6
7 import java.util.Date JavaDoc;
8 import java.util.Calendar JavaDoc;
9 import java.util.GregorianCalendar JavaDoc;
10 import java.io.*;
11 import java.text.DateFormat JavaDoc;
12 import java.text.SimpleDateFormat JavaDoc;
13 import java.text.ParseException JavaDoc;
14 import com.calipso.reportgenerator.common.InfoException;
15 import org.apache.commons.vfs.FileObject;
16 import org.apache.commons.vfs.FileSystemException;
17
18
19 /**
20  * Repositorio de reportes cacheados
21  */

22 public class ReportSourceRepository extends Repository implements Serializable{
23   private static CacheRepository cache;
24
25   private static int MAXEXPIRATION = 849600;
26   public static final String JavaDoc NAME_FINALIZATION = "--";
27
28   public Class JavaDoc getObjectClass() {
29     return ReportSource.class;
30   }
31
32   /**
33    * Inicializa el repositorio
34    * @param directoryName
35    * @param reportGeneratorConfiguration
36    */

37   public ReportSourceRepository(String JavaDoc directoryName, ReportGeneratorConfiguration reportGeneratorConfiguration) {
38     super(directoryName, reportGeneratorConfiguration);
39     serialize = true;
40   }
41
42   protected Object JavaDoc saveFromSourceFiles(ReportGeneratorConfiguration reportGeneratorConfiguration, String JavaDoc id) throws InfoException {
43     throw new InfoException(LanguageTraslator.traslate("79"));
44   }
45
46   /**
47    * Recupera un cache vigente para un report source definition
48    * @param reportSpec
49    * @return
50    * @throws InfoException
51    */

52   public ReportSource load(ReportGeneratorConfiguration configuration, ReportSpec reportSpec, ReportSourceDefinition definition) throws InfoException {
53     String JavaDoc fileName = "";
54     if (reportSpec.getCached()) {
55       try {
56         fileName = searchFileName(reportSpec, false);
57       } catch (Exception JavaDoc e) {
58         throw new InfoException(LanguageTraslator.traslate("64"), e);
59       }
60       if (!fileName.equals("")) {
61         try {
62           if(!configuration.isCsvSerialized()){
63             return new ReportSource(reportSpec, (Matrix) super.load(fileName), getLastExecution(fileName, reportSpec.getSourceId()), reportGeneratorConfiguration);
64           }else{
65             return new ReportSource(reportSpec, this.load(configuration, fileName, definition), getLastExecution(fileName, reportSpec.getSourceId()), reportGeneratorConfiguration);
66           }
67         } catch (Exception JavaDoc e) {
68           throw new InfoException(LanguageTraslator.traslate("65"), e);
69         }
70       }
71       else {
72         return null;
73       }
74     }
75     else {
76       return null;
77     }
78   }
79
80   protected Matrix load(ReportGeneratorConfiguration configuration, String JavaDoc fileName, ReportSourceDefinition definition) throws IOException, ClassNotFoundException JavaDoc, InfoException {
81     File file = new File(getDirectoryName() + "/" + fileName.substring(0,fileName.length()-4));
82     Matrix matrix;
83     if (file.exists()){
84       try{
85          matrix = (Matrix) super.load(fileName.substring(0,fileName.length()-4));
86       }catch(Exception JavaDoc e){
87         System.out.println(LanguageTraslator.traslate("414"));
88         FileInputStream stream = new FileInputStream(getDirectoryName() + "/" + fileName);
89         matrix = MatrixCsvSerializer.deserialize(configuration, stream, definition);
90         try {
91           super.save(matrix,getDirectoryName() + "/" + fileName.substring(0,fileName.length()-4));
92         }catch(Exception JavaDoc el){
93           System.out.println(LanguageTraslator.traslate("415"));
94           el.printStackTrace();
95         }
96       }
97     } else{
98       FileInputStream stream = new FileInputStream(getDirectoryName() + "/" + fileName);
99       matrix = MatrixCsvSerializer.deserialize(configuration, stream, definition);
100       try{
101         super.save(matrix,fileName.substring(0,fileName.length()-4));
102       }catch(Exception JavaDoc el){
103         System.out.println(LanguageTraslator.traslate("415"));
104         el.printStackTrace();
105       }
106
107     }
108     return matrix;
109   }
110
111   /**
112    * Retorna la fecha de ejecución del reporte.
113    * @param fileName nombre del file origen
114    * @param reportSourceDefId Id de la definición de reporte
115    * @return
116    * @throws InfoException Si no pudo parsear la fecha
117    */

118   private Date JavaDoc getLastExecution(String JavaDoc fileName, String JavaDoc reportSourceDefId) throws InfoException {
119     DateFormat JavaDoc dateFormat;
120     Date JavaDoc lastExecution = new Date JavaDoc();
121     dateFormat = new SimpleDateFormat JavaDoc("yyyyMMdd");
122     try {
123       lastExecution = dateFormat.parse(fileName.substring(reportSourceDefId.length() + NAME_FINALIZATION.length() + 2, reportSourceDefId.length() + NAME_FINALIZATION.length() + 10));
124     } catch (Exception JavaDoc e) {
125       throw new InfoException(LanguageTraslator.traslate("66"));
126     }
127     return lastExecution;
128   }
129
130   /**
131    * Retorna el nombre del cache vigente
132    *
133    * @param reportSpec
134    * @param previusFiles Indica si se busca el nombre de los cacheados anteriores o el vigente
135    * @return
136    * @throws InfoException Si no se pudo obtener la fecha de expiración
137    */

138   private String JavaDoc searchFileName(ReportSpec reportSpec, boolean previusFiles) throws InfoException {
139     String JavaDoc fileName, returnedfileName, sourceName, sourceExpirationString;
140     Date JavaDoc sourceExpiration = new Date JavaDoc();
141     Date JavaDoc maxExpiration = new Date JavaDoc();
142     int starExpiration;
143     DateFormat JavaDoc dateFormat;
144     returnedfileName = "";
145     FileObject fileObject;
146
147     try {
148       fileObject = getFileSystemManager().resolveFile(getDirectoryName());
149     }
150     catch (FileSystemException e) {
151       throw new InfoException(LanguageTraslator.traslate("212")+":"+getDirectoryName(),e);
152     }
153     dateFormat = new SimpleDateFormat JavaDoc("yyyyMMdd");
154     try {
155       for (int i = 0; i < fileObject.getChildren().length; i++) {
156         fileName = fileObject.getChildren()[i].getName().getBaseName();
157         if (fileName.substring(fileName.length()-4,fileName.length()).equalsIgnoreCase(".TMP")){
158           int reportNameSize = reportSpec.getSourceId().length() + NAME_FINALIZATION.length();
159           if (fileName.length() > reportNameSize) {
160             sourceName = fileName.substring(0,reportNameSize).toUpperCase();
161             if (sourceName.equalsIgnoreCase(reportSpec.getSourceId().toUpperCase() + NAME_FINALIZATION)) {
162               starExpiration = sourceName.length() + 12;
163               sourceExpirationString = fileName.substring(starExpiration, starExpiration + 8);
164               if ((sourceExpirationString.compareTo("")) > 0) {
165                 try {
166                   sourceExpiration = dateFormat.parse(fileName.substring(starExpiration, starExpiration + 8));
167                   if (previusFiles) {
168                     if (sourceExpiration.before(maxExpiration) || sourceExpirationString.equals(dateFormat.format(maxExpiration))) {
169                       returnedfileName = fileName;
170                       maxExpiration = sourceExpiration;
171                     }
172                   }else{
173                     if (sourceExpiration.after(maxExpiration) || sourceExpirationString.equals(dateFormat.format(maxExpiration))) {
174                       returnedfileName = fileName;
175                       maxExpiration = sourceExpiration;
176                     } else if (sourceExpiration.before(maxExpiration)) {
177                       returnedfileName = "";
178                     }
179                   }
180
181                 } catch (ParseException JavaDoc e) {
182                   throw new InfoException(LanguageTraslator.traslate("67"), e);
183                 }
184               }
185               else {
186                 if (reportSpec.getIncrementalDimension().compareTo("") > 0) {
187                   returnedfileName = fileName;
188                   maxExpiration = sourceExpiration;
189                 }
190               }
191             }
192           }
193         }
194       }
195     }catch (Exception JavaDoc e){
196       throw new InfoException(LanguageTraslator.traslate("213")+":"+getDirectoryName(),e);
197     }
198     return returnedfileName;
199   }
200
201   /**
202    * Graba un cache nuevo asignándole la vigencia
203    * @param reportSource
204    * @throws InfoException
205    */

206   public void saveNewSource(ReportSource reportSource, boolean isCsvSerialized) throws InfoException {
207     String JavaDoc fileName;
208     if (reportSource.getReportSpec().getCached()) {
209       fileName = getNewFileName(reportSource.getReportSpec(), null);
210       try {
211         if(!isCsvSerialized){
212           super.save(reportSource.getMatrix(), fileName);
213         }else{
214           this.save(reportSource.getMatrix(), fileName);
215         }
216       } catch (Exception JavaDoc e) {
217         throw new InfoException(LanguageTraslator.traslate("68") + fileName, e);
218       }
219     }
220   }
221
222   protected void save(Matrix matrix, String JavaDoc fileName) throws InfoException, IOException {
223     ByteArrayOutputStream out = MatrixCsvSerializer.csvSerialize(matrix);
224     FileOutputStream stream = new FileOutputStream(super.getDirectoryName() + "/" + fileName);
225     stream.write(out.toByteArray());
226     stream.flush();
227     stream.close();
228   }
229
230   /**
231    * Graba un cache incremental invalidando el anterior cache vigente si existiese.
232    * @param reportSource
233    * @throws InfoException
234    */

235   public boolean saveIncrementalSource(ReportSource reportSource, boolean isCsvSerialized) throws InfoException {
236     String JavaDoc fileName,searchName;
237     if(!(searchFileName(reportSource.getReportSpec(), true).equalsIgnoreCase(""))) {
238       if (reportSource.getReportSpec().getCached()) {
239         try {
240           searchName = searchFileName(reportSource.getReportSpec(), true);
241           fileName = getNewFileName(reportSource.getReportSpec(),null);// getExecutionDateFromFileName(searchName, reportSource.getReportSpec().getSourceId()));
242
deleteReportSource(reportSource.getReportSpec());
243           if(!isCsvSerialized){
244             super.save(reportSource.getMatrix(), fileName);
245           }else{
246             this.save(reportSource.getMatrix(), fileName);
247           }
248           return true;
249         } catch (Exception JavaDoc e) {
250           throw new InfoException(LanguageTraslator.traslate("69"), e);
251         }
252       }
253     }
254     return false;
255   }
256
257
258   /**
259    * Retorna la fecha de creación del reportsource
260    * @param fileName nombre del archivo
261    * @param reportDefinitionID id de la definicion
262    * @return
263    * @throws InfoException
264    */

265   private Date JavaDoc getExecutionDateFromFileName(String JavaDoc fileName, String JavaDoc reportDefinitionID) throws InfoException {
266     DateFormat JavaDoc dateFormat;
267     int starExec;
268     String JavaDoc sourceExecutionString;
269     Date JavaDoc resultDate = new Date JavaDoc();
270
271     if (!fileName.equals("")) {
272       dateFormat = new SimpleDateFormat JavaDoc("yyyyMMdd");
273       starExec = reportDefinitionID.length() + NAME_FINALIZATION.length() + 2;
274       sourceExecutionString = fileName.substring(starExec , starExec + 8);
275       if ((sourceExecutionString.compareTo("")) > 0) {
276         try {
277           resultDate = dateFormat.parse(sourceExecutionString);
278         } catch (ParseException JavaDoc e) {
279           throw new InfoException(LanguageTraslator.traslate("70"), e);
280         }
281       }
282     }
283     return resultDate;
284   }
285
286   /**
287    * Formato de fecha por defecto
288    * @return datePattern
289    */

290   public String JavaDoc getDatePattern() {
291     return getReportGeneratorConfiguration().getDatePattern();
292   }
293
294   /**
295    * Obtiene el nombre del archivo con el cual se debe guardar en el repositorio, teniendo en cuenta las fecha de ejecución y expiración
296    * @param reportSpec
297    * @param executionDate
298    * @return nombre de archivo
299    */

300   private String JavaDoc getNewFileName(ReportSpec reportSpec, Date JavaDoc executionDate) {
301     Calendar JavaDoc expiration;
302     Calendar JavaDoc execute;
303     execute = new GregorianCalendar JavaDoc();
304
305     expiration = new GregorianCalendar JavaDoc();
306     if (executionDate != null) {
307       execute.setTime(executionDate);
308       expiration.setTime(executionDate);
309     }
310     int expirationValue = reportSpec.getExpiration().intValue();
311     if (expirationValue == 0) {
312       expirationValue = MAXEXPIRATION;
313     }
314     expiration.add(Calendar.HOUR, expirationValue);
315     return getFileName(reportSpec.getSourceId(),execute.getTime(), expiration.getTime());
316   }
317
318   /**
319    * Obtienen el nombre del archivo
320    * @param sourceID
321    * @param execution
322    * @param expiration
323    * @return nombre del archivo
324    */

325   protected String JavaDoc getFileName(String JavaDoc sourceID,Date JavaDoc execution,Date JavaDoc expiration){
326     DateFormat JavaDoc dateFormat;
327     String JavaDoc executionText = "";
328     String JavaDoc expirationText = "";
329
330     dateFormat = new SimpleDateFormat JavaDoc("yyyyMMdd");
331     executionText = "DD" + dateFormat.format(execution);
332     expirationText = "EE" + dateFormat.format(expiration);
333     return ( sourceID + NAME_FINALIZATION + executionText + expirationText + ".tmp").toUpperCase();
334
335   }
336
337   /**
338    * Borra un cache de un report source definition y todos sus anteriores
339    * @param reportSpec
340    * @return
341    * @throws InfoException Si no se pudo invalidar
342    */

343   public boolean deleteReportSource(ReportSpec reportSpec) throws InfoException {
344     String JavaDoc fileName;
345     try {
346       fileName = searchFileName(reportSpec, false);
347       if (!fileName.equals("")) {
348         super.deleteFile(fileName);
349         getCache().delete(fileName);
350       }
351       fileName = "";
352       fileName = searchFileName(reportSpec,true);
353       while (!fileName.equalsIgnoreCase("")){
354         deleteFile(fileName);
355         getCache().delete(fileName);
356         fileName = "";
357         fileName = searchFileName(reportSpec,true);
358       }
359       return true;
360     } catch (InfoException e) {
361       throw new InfoException(LanguageTraslator.traslate("278")+":"+reportSpec.getSourceId(), e);
362     }
363   }
364
365   /**
366    * Pisa la fecha de vencimiento de un cache a la actual
367    * @param reportSpec
368    * @return
369    * @throws InfoException
370    */

371   public boolean invalidateReportSource(ReportSpec reportSpec) throws InfoException {
372     try{
373       String JavaDoc fileName = searchFileName(reportSpec,false);
374       String JavaDoc newFileName = getFileName(reportSpec.getSourceId(),new Date JavaDoc(),new Date JavaDoc());
375       renameFile(fileName,newFileName);
376       return true;
377     } catch (InfoException e) {
378       throw new InfoException(LanguageTraslator.traslate("71")+":"+reportSpec.getSourceId(), e);
379     }
380   }
381
382   /**
383    * Devuelve el objeto cache del repositorio
384    * @return objeto cache del repositorio
385    */

386   public CacheRepository getCache() {
387     if (cache == null) {
388       cache = new CacheRepository("ReportSource");
389     }
390     return cache;
391   }
392
393   public void deleteAll() throws InfoException {
394     getCache().deleteAll();
395     deleteAllFiles();
396   }
397
398
399 }
Popular Tags