001: package com.calipso.reportgenerator.reportmanager;
002:
003: import com.calipso.reportgenerator.reportcalculator.Matrix;
004: import com.calipso.reportgenerator.common.*;
005: import com.calipso.reportgenerator.reportdefinitions.ReportSourceDefinition;
006:
007: import java.util.Date;
008: import java.util.Calendar;
009: import java.util.GregorianCalendar;
010: import java.io.*;
011: import java.text.DateFormat;
012: import java.text.SimpleDateFormat;
013: import java.text.ParseException;
014: import com.calipso.reportgenerator.common.InfoException;
015: import org.apache.commons.vfs.FileObject;
016: import org.apache.commons.vfs.FileSystemException;
017:
018: /**
019: * Repositorio de reportes cacheados
020: */
021: public class ReportSourceRepository extends Repository implements
022: Serializable {
023: private static CacheRepository cache;
024:
025: private static int MAXEXPIRATION = 849600;
026: public static final String NAME_FINALIZATION = "--";
027:
028: public Class getObjectClass() {
029: return ReportSource.class;
030: }
031:
032: /**
033: * Inicializa el repositorio
034: * @param directoryName
035: * @param reportGeneratorConfiguration
036: */
037: public ReportSourceRepository(String directoryName,
038: ReportGeneratorConfiguration reportGeneratorConfiguration) {
039: super (directoryName, reportGeneratorConfiguration);
040: serialize = true;
041: }
042:
043: protected Object saveFromSourceFiles(
044: ReportGeneratorConfiguration reportGeneratorConfiguration,
045: String id) throws InfoException {
046: throw new InfoException(LanguageTraslator.traslate("79"));
047: }
048:
049: /**
050: * Recupera un cache vigente para un report source definition
051: * @param reportSpec
052: * @return
053: * @throws InfoException
054: */
055: public ReportSource load(
056: ReportGeneratorConfiguration configuration,
057: ReportSpec reportSpec, ReportSourceDefinition definition)
058: throws InfoException {
059: String fileName = "";
060: if (reportSpec.getCached()) {
061: try {
062: fileName = searchFileName(reportSpec, false);
063: } catch (Exception e) {
064: throw new InfoException(LanguageTraslator
065: .traslate("64"), e);
066: }
067: if (!fileName.equals("")) {
068: try {
069: if (!configuration.isCsvSerialized()) {
070: return new ReportSource(reportSpec,
071: (Matrix) super .load(fileName),
072: getLastExecution(fileName, reportSpec
073: .getSourceId()),
074: reportGeneratorConfiguration);
075: } else {
076: return new ReportSource(reportSpec, this .load(
077: configuration, fileName, definition),
078: getLastExecution(fileName, reportSpec
079: .getSourceId()),
080: reportGeneratorConfiguration);
081: }
082: } catch (Exception e) {
083: throw new InfoException(LanguageTraslator
084: .traslate("65"), e);
085: }
086: } else {
087: return null;
088: }
089: } else {
090: return null;
091: }
092: }
093:
094: protected Matrix load(ReportGeneratorConfiguration configuration,
095: String fileName, ReportSourceDefinition definition)
096: throws IOException, ClassNotFoundException, InfoException {
097: File file = new File(getDirectoryName() + "/"
098: + fileName.substring(0, fileName.length() - 4));
099: Matrix matrix;
100: if (file.exists()) {
101: try {
102: matrix = (Matrix) super .load(fileName.substring(0,
103: fileName.length() - 4));
104: } catch (Exception e) {
105: System.out.println(LanguageTraslator.traslate("414"));
106: FileInputStream stream = new FileInputStream(
107: getDirectoryName() + "/" + fileName);
108: matrix = MatrixCsvSerializer.deserialize(configuration,
109: stream, definition);
110: try {
111: super .save(matrix, getDirectoryName()
112: + "/"
113: + fileName.substring(0,
114: fileName.length() - 4));
115: } catch (Exception el) {
116: System.out.println(LanguageTraslator
117: .traslate("415"));
118: el.printStackTrace();
119: }
120: }
121: } else {
122: FileInputStream stream = new FileInputStream(
123: getDirectoryName() + "/" + fileName);
124: matrix = MatrixCsvSerializer.deserialize(configuration,
125: stream, definition);
126: try {
127: super .save(matrix, fileName.substring(0, fileName
128: .length() - 4));
129: } catch (Exception el) {
130: System.out.println(LanguageTraslator.traslate("415"));
131: el.printStackTrace();
132: }
133:
134: }
135: return matrix;
136: }
137:
138: /**
139: * Retorna la fecha de ejecución del reporte.
140: * @param fileName nombre del file origen
141: * @param reportSourceDefId Id de la definición de reporte
142: * @return
143: * @throws InfoException Si no pudo parsear la fecha
144: */
145: private Date getLastExecution(String fileName,
146: String reportSourceDefId) throws InfoException {
147: DateFormat dateFormat;
148: Date lastExecution = new Date();
149: dateFormat = new SimpleDateFormat("yyyyMMdd");
150: try {
151: lastExecution = dateFormat.parse(fileName.substring(
152: reportSourceDefId.length()
153: + NAME_FINALIZATION.length() + 2,
154: reportSourceDefId.length()
155: + NAME_FINALIZATION.length() + 10));
156: } catch (Exception e) {
157: throw new InfoException(LanguageTraslator.traslate("66"));
158: }
159: return lastExecution;
160: }
161:
162: /**
163: * Retorna el nombre del cache vigente
164: *
165: * @param reportSpec
166: * @param previusFiles Indica si se busca el nombre de los cacheados anteriores o el vigente
167: * @return
168: * @throws InfoException Si no se pudo obtener la fecha de expiración
169: */
170: private String searchFileName(ReportSpec reportSpec,
171: boolean previusFiles) throws InfoException {
172: String fileName, returnedfileName, sourceName, sourceExpirationString;
173: Date sourceExpiration = new Date();
174: Date maxExpiration = new Date();
175: int starExpiration;
176: DateFormat dateFormat;
177: returnedfileName = "";
178: FileObject fileObject;
179:
180: try {
181: fileObject = getFileSystemManager().resolveFile(
182: getDirectoryName());
183: } catch (FileSystemException e) {
184: throw new InfoException(LanguageTraslator.traslate("212")
185: + ":" + getDirectoryName(), e);
186: }
187: dateFormat = new SimpleDateFormat("yyyyMMdd");
188: try {
189: for (int i = 0; i < fileObject.getChildren().length; i++) {
190: fileName = fileObject.getChildren()[i].getName()
191: .getBaseName();
192: if (fileName.substring(fileName.length() - 4,
193: fileName.length()).equalsIgnoreCase(".TMP")) {
194: int reportNameSize = reportSpec.getSourceId()
195: .length()
196: + NAME_FINALIZATION.length();
197: if (fileName.length() > reportNameSize) {
198: sourceName = fileName.substring(0,
199: reportNameSize).toUpperCase();
200: if (sourceName.equalsIgnoreCase(reportSpec
201: .getSourceId().toUpperCase()
202: + NAME_FINALIZATION)) {
203: starExpiration = sourceName.length() + 12;
204: sourceExpirationString = fileName
205: .substring(starExpiration,
206: starExpiration + 8);
207: if ((sourceExpirationString.compareTo("")) > 0) {
208: try {
209: sourceExpiration = dateFormat
210: .parse(fileName.substring(
211: starExpiration,
212: starExpiration + 8));
213: if (previusFiles) {
214: if (sourceExpiration
215: .before(maxExpiration)
216: || sourceExpirationString
217: .equals(dateFormat
218: .format(maxExpiration))) {
219: returnedfileName = fileName;
220: maxExpiration = sourceExpiration;
221: }
222: } else {
223: if (sourceExpiration
224: .after(maxExpiration)
225: || sourceExpirationString
226: .equals(dateFormat
227: .format(maxExpiration))) {
228: returnedfileName = fileName;
229: maxExpiration = sourceExpiration;
230: } else if (sourceExpiration
231: .before(maxExpiration)) {
232: returnedfileName = "";
233: }
234: }
235:
236: } catch (ParseException e) {
237: throw new InfoException(
238: LanguageTraslator
239: .traslate("67"), e);
240: }
241: } else {
242: if (reportSpec
243: .getIncrementalDimension()
244: .compareTo("") > 0) {
245: returnedfileName = fileName;
246: maxExpiration = sourceExpiration;
247: }
248: }
249: }
250: }
251: }
252: }
253: } catch (Exception e) {
254: throw new InfoException(LanguageTraslator.traslate("213")
255: + ":" + getDirectoryName(), e);
256: }
257: return returnedfileName;
258: }
259:
260: /**
261: * Graba un cache nuevo asignándole la vigencia
262: * @param reportSource
263: * @throws InfoException
264: */
265: public void saveNewSource(ReportSource reportSource,
266: boolean isCsvSerialized) throws InfoException {
267: String fileName;
268: if (reportSource.getReportSpec().getCached()) {
269: fileName = getNewFileName(reportSource.getReportSpec(),
270: null);
271: try {
272: if (!isCsvSerialized) {
273: super .save(reportSource.getMatrix(), fileName);
274: } else {
275: this .save(reportSource.getMatrix(), fileName);
276: }
277: } catch (Exception e) {
278: throw new InfoException(LanguageTraslator
279: .traslate("68")
280: + fileName, e);
281: }
282: }
283: }
284:
285: protected void save(Matrix matrix, String fileName)
286: throws InfoException, IOException {
287: ByteArrayOutputStream out = MatrixCsvSerializer
288: .csvSerialize(matrix);
289: FileOutputStream stream = new FileOutputStream(super
290: .getDirectoryName()
291: + "/" + fileName);
292: stream.write(out.toByteArray());
293: stream.flush();
294: stream.close();
295: }
296:
297: /**
298: * Graba un cache incremental invalidando el anterior cache vigente si existiese.
299: * @param reportSource
300: * @throws InfoException
301: */
302: public boolean saveIncrementalSource(ReportSource reportSource,
303: boolean isCsvSerialized) throws InfoException {
304: String fileName, searchName;
305: if (!(searchFileName(reportSource.getReportSpec(), true)
306: .equalsIgnoreCase(""))) {
307: if (reportSource.getReportSpec().getCached()) {
308: try {
309: searchName = searchFileName(reportSource
310: .getReportSpec(), true);
311: fileName = getNewFileName(reportSource
312: .getReportSpec(), null);// getExecutionDateFromFileName(searchName, reportSource.getReportSpec().getSourceId()));
313: deleteReportSource(reportSource.getReportSpec());
314: if (!isCsvSerialized) {
315: super .save(reportSource.getMatrix(), fileName);
316: } else {
317: this .save(reportSource.getMatrix(), fileName);
318: }
319: return true;
320: } catch (Exception e) {
321: throw new InfoException(LanguageTraslator
322: .traslate("69"), e);
323: }
324: }
325: }
326: return false;
327: }
328:
329: /**
330: * Retorna la fecha de creación del reportsource
331: * @param fileName nombre del archivo
332: * @param reportDefinitionID id de la definicion
333: * @return
334: * @throws InfoException
335: */
336: private Date getExecutionDateFromFileName(String fileName,
337: String reportDefinitionID) throws InfoException {
338: DateFormat dateFormat;
339: int starExec;
340: String sourceExecutionString;
341: Date resultDate = new Date();
342:
343: if (!fileName.equals("")) {
344: dateFormat = new SimpleDateFormat("yyyyMMdd");
345: starExec = reportDefinitionID.length()
346: + NAME_FINALIZATION.length() + 2;
347: sourceExecutionString = fileName.substring(starExec,
348: starExec + 8);
349: if ((sourceExecutionString.compareTo("")) > 0) {
350: try {
351: resultDate = dateFormat
352: .parse(sourceExecutionString);
353: } catch (ParseException e) {
354: throw new InfoException(LanguageTraslator
355: .traslate("70"), e);
356: }
357: }
358: }
359: return resultDate;
360: }
361:
362: /**
363: * Formato de fecha por defecto
364: * @return datePattern
365: */
366: public String getDatePattern() {
367: return getReportGeneratorConfiguration().getDatePattern();
368: }
369:
370: /**
371: * 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
372: * @param reportSpec
373: * @param executionDate
374: * @return nombre de archivo
375: */
376: private String getNewFileName(ReportSpec reportSpec,
377: Date executionDate) {
378: Calendar expiration;
379: Calendar execute;
380: execute = new GregorianCalendar();
381:
382: expiration = new GregorianCalendar();
383: if (executionDate != null) {
384: execute.setTime(executionDate);
385: expiration.setTime(executionDate);
386: }
387: int expirationValue = reportSpec.getExpiration().intValue();
388: if (expirationValue == 0) {
389: expirationValue = MAXEXPIRATION;
390: }
391: expiration.add(Calendar.HOUR, expirationValue);
392: return getFileName(reportSpec.getSourceId(), execute.getTime(),
393: expiration.getTime());
394: }
395:
396: /**
397: * Obtienen el nombre del archivo
398: * @param sourceID
399: * @param execution
400: * @param expiration
401: * @return nombre del archivo
402: */
403: protected String getFileName(String sourceID, Date execution,
404: Date expiration) {
405: DateFormat dateFormat;
406: String executionText = "";
407: String expirationText = "";
408:
409: dateFormat = new SimpleDateFormat("yyyyMMdd");
410: executionText = "DD" + dateFormat.format(execution);
411: expirationText = "EE" + dateFormat.format(expiration);
412: return (sourceID + NAME_FINALIZATION + executionText
413: + expirationText + ".tmp").toUpperCase();
414:
415: }
416:
417: /**
418: * Borra un cache de un report source definition y todos sus anteriores
419: * @param reportSpec
420: * @return
421: * @throws InfoException Si no se pudo invalidar
422: */
423: public boolean deleteReportSource(ReportSpec reportSpec)
424: throws InfoException {
425: String fileName;
426: try {
427: fileName = searchFileName(reportSpec, false);
428: if (!fileName.equals("")) {
429: super .deleteFile(fileName);
430: getCache().delete(fileName);
431: }
432: fileName = "";
433: fileName = searchFileName(reportSpec, true);
434: while (!fileName.equalsIgnoreCase("")) {
435: deleteFile(fileName);
436: getCache().delete(fileName);
437: fileName = "";
438: fileName = searchFileName(reportSpec, true);
439: }
440: return true;
441: } catch (InfoException e) {
442: throw new InfoException(LanguageTraslator.traslate("278")
443: + ":" + reportSpec.getSourceId(), e);
444: }
445: }
446:
447: /**
448: * Pisa la fecha de vencimiento de un cache a la actual
449: * @param reportSpec
450: * @return
451: * @throws InfoException
452: */
453: public boolean invalidateReportSource(ReportSpec reportSpec)
454: throws InfoException {
455: try {
456: String fileName = searchFileName(reportSpec, false);
457: String newFileName = getFileName(reportSpec.getSourceId(),
458: new Date(), new Date());
459: renameFile(fileName, newFileName);
460: return true;
461: } catch (InfoException e) {
462: throw new InfoException(LanguageTraslator.traslate("71")
463: + ":" + reportSpec.getSourceId(), e);
464: }
465: }
466:
467: /**
468: * Devuelve el objeto cache del repositorio
469: * @return objeto cache del repositorio
470: */
471: public CacheRepository getCache() {
472: if (cache == null) {
473: cache = new CacheRepository("ReportSource");
474: }
475: return cache;
476: }
477:
478: public void deleteAll() throws InfoException {
479: getCache().deleteAll();
480: deleteAllFiles();
481: }
482:
483: }
|