Java tutorial
package com.pari.mw.api.execute.reports.template; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipInputStream; import org.apache.commons.io.FileUtils; import org.apache.log4j.Logger; import com.pari.ic.ICEntity.IC_SOURCE_TYPE; import com.pari.ic.ICManager; import com.pari.ic.ICStatisticsManager; import com.pari.mw.api.ServerIfProvider; import com.pari.nm.base.so.i18nHelper.ShadowWrapper; import com.pari.nm.gui.guiservices.PariException; import com.pari.nm.modules.session.UserDetails; import com.pari.nm.utils.backup.UnzipDir; import com.pari.pcb.zip.ZIPProcessor; import com.pari.reports.request.constants.ExportInfoConstants; import com.pari.reports.request.export.core.ExportDBHelper; import com.pari.reports.request.export.core.ExportInfo; import com.pari.reports.template.management.ReportTemplateDefManagerImpl; import com.pari.reports.template.management.ReportTemplateMetaInfo; import com.pari.reports.template.management.ReportTemplateSourceInfo; import com.pari.utils.ExportFormat; public class ReportTemplateRunner { private static final Logger logger = Logger.getLogger(ReportTemplateRunner.class); private ArrayList selectedDevices = null; private HashMap parameters = null; private ReportTemplateIndexDef templateIndexDef = null; private ReportTemplateRequestDef templateRequestDef = null; private ReportTemplateSourceInfo templateSourceInfo = null; private String zipFileName = null; private String directoryName = null; private String exportFormat = null; private static ReportTemplateRunner reportTemplateRunner = null; UserDetails userDetails = null; private ReportTemplateRunner() { } public static synchronized ReportTemplateRunner getInstance() { if (reportTemplateRunner == null) { reportTemplateRunner = new ReportTemplateRunner(); } return reportTemplateRunner; } public void setSelectedDevices(ArrayList devices) { selectedDevices = devices; } public ArrayList getSelectedDevices() { return selectedDevices; } public void setParameters(HashMap parameters) { this.parameters = parameters; } public HashMap getParameters() { return parameters; } public void executeReportTemplate(String templateId, ServerIfProvider serverIfProvider, ExportInfo exportInfo, int customerId, String customerName) throws Exception { ZipFile zipFile = null; InputStream indexStream = null; InputStream requestStream = null; try { getZipFile(templateId, serverIfProvider, exportInfo, customerId); zipFile = new ZipFile(new File(zipFileName)); // read the index xml indexStream = getInputStream(zipFile, "index.xml"); if (indexStream != null) { templateIndexDef = ReportTemplateIndexDef.loadFromXML(indexStream); } else { logger.error("Unable to find the template index file."); throw new Exception("Unable to find the template index file."); } // read the request xml if (templateIndexDef != null) { String requestFileName = templateIndexDef.getXmlRequestFileName(); if (requestFileName != null) { requestStream = getInputStream(zipFile, requestFileName); if (requestStream != null) { templateRequestDef = ReportTemplateRequestDef.loadFromXML(requestStream); } } } else { logger.error("Unable to parse/ load the template index file."); throw new Exception("Unable to parse/ load the template index file."); } if (templateRequestDef != null) { VariableListDefinition varListDef = templateRequestDef.getVariableList(); Map<String, VariableDefinition> varMap = null; if (varListDef != null) { varMap = varListDef.getVariables(); } Map<String, String> varValues = new HashMap<String, String>(); if (varMap != null) { for (String var : varMap.keySet()) { VariableDefinition def = varMap.get(var); if (def != null) { varValues.put(var, def.getDefaultValue()); } } } ExportProgressMonitor exportProgressMonitor = new ExportProgressMonitor(templateRequestDef, varValues, getDirectoryName(), ExportFormat.getEnumTypeFromExt(getExportFormat()), serverIfProvider, exportInfo, customerId, customerName, templateId); Thread t = new Thread(exportProgressMonitor); t.start(); } else { logger.error("Unable to parse/ load the template request file."); throw new Exception("Unable to parse/ load the template request file."); } } catch (Exception e) { logger.error("Report template execution failed.", e); throw new Exception("Report template execution failed"); } finally { if (indexStream != null) { try { indexStream.close(); } catch (IOException e) { logger.warn("Unable to close the InputStream " + indexStream); } } if (requestStream != null) { try { requestStream.close(); } catch (IOException e) { logger.warn("Unable to close the InputStream " + requestStream); } } if (zipFile != null) { try { zipFile.close(); } catch (IOException e) { logger.warn("Unable to close the Zip file."); } } } } private void getZipFile(String templateId, ServerIfProvider serverIfProvider, ExportInfo exportInfo, int customerId) throws Exception { templateSourceInfo = serverIfProvider.getReportTemplateManagerIf().getTemplateSourceInfo(templateId, customerId); zipFileName = templateSourceInfo.getServerFileName(); // zipFileName = ZIP_DOWNLOAD_PATH + File.separator + templateSourceInfo.getTemplateId() + ".zip"; // outStream = new FileOutputStream(zipFileName); } private File[] exportReport(ReportTemplateRequestDef templateRequestDef, Map<String, String> varValues, String directoryName, ExportFormat format, ServerIfProvider serverIfProvider, ExportInfo exportInfo, int customerIdOfTemplate, String customerNameOfTemplate, String templateId) throws PariException { // transformation resources File topLevelFolder = null; try { topLevelFolder = getTopLevelFolder(new File(zipFileName)); } catch (IOException e1) { logger.error("Unable to get top level folder of zip file " + zipFileName); } // unzip the template String outDirName = directoryName + "/" + topLevelFolder.getName(); UnzipDir.unzip(zipFileName, directoryName); File outDir = new File(outDirName); /* * if ((valueMap != null) && (valueMap.size() > 0)) { varValues.putAll(valueMap); } */ ReportTemplateMetaInfo templateMetaInfo = null; try { templateMetaInfo = ReportTemplateDefManagerImpl.getInstance().getTemplateMetaInfo(templateId, customerIdOfTemplate); if (templateMetaInfo != null && templateMetaInfo.getSourceType() == IC_SOURCE_TYPE.ICF) { // device count considered as 1 as report template wont be executed per device. ICManager.getInstance().validateLicense(customerIdOfTemplate, templateMetaInfo.getIdentifier(), 1); } } catch (Exception e) { if (templateMetaInfo != null) { logger.warn("No sufficient license to run " + templateMetaInfo.getTitle() + " - " + e.getMessage()); } else { logger.warn("No sufficient license to run.Failed to get ReportTemplateMetaInfo for " + templateId + " - " + e.getMessage()); } throw new PariException(e.getMessage()); } FileOutputStream fos = null; try { // ReportExportFactory.createDirectories(outDir.getAbsolutePath());TODO fos = new FileOutputStream(new File(outDir, templateIndexDef.getIdentifier() + ".xml")); ReportTemplateExecutor executor = new ReportTemplateExecutor(templateIndexDef, templateRequestDef); executor.setUserDetails(getUserDetails()); executor.setDevices(new HashSet<Integer>(getSelectedDevices())); executor.execute(selectedDevices, parameters, varValues, fos, serverIfProvider, customerIdOfTemplate, customerNameOfTemplate); } catch (Exception e) { logger.error("Error while exporting the report", e); throw new PariException(ShadowWrapper.getString("Error_While_Report_Export")); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { logger.warn("Error while closing the output stream"); } } } FileInputStream xml = null; FileOutputStream os = null; InputStream xsl = null; ZipFile zipFile = null; try { zipFile = new ZipFile(new File(zipFileName)); // transformation file String xslFileName = templateIndexDef.getTransformationFileMap().get(format); xsl = getInputStream(zipFile, xslFileName); // intermediate xml with data xml = new FileInputStream(new File(outDir, templateIndexDef.getIdentifier() + ".xml")); File outputFile = null; outputFile = new File(outDir.getAbsolutePath(), templateIndexDef.getIdentifier() + "." + format.getDefaultExtension()); os = new FileOutputStream(outputFile); if (format == ExportFormat.WEB_PAGE_COMPLETE) { ReportExporter.exportToHtml(xml, xsl, os, outDir); } else if (format == ExportFormat.MSWORD_DOCUMENT) { ReportExporter.exportToHtml(xml, xsl, os, outDir); } else if (format == ExportFormat.ADOBE_PDF) { ReportExporter.exportToPDF(xml, xsl, os, outDir); } // cleanup if (xml != null) { try { xml.close(); } catch (IOException ioe) { logger.warn("Could not close the InputStream" + xml, ioe); } } if (xsl != null) { try { xsl.close(); } catch (IOException ioe) { logger.warn("Could not close the InputStream" + xsl, ioe); } } if (os != null) { try { os.close(); } catch (IOException ioe) { logger.warn("Could not close the OutputStream" + os, ioe); } } if (zipFile != null) { try { zipFile.close(); } catch (Exception e) { logger.warn("Unable to close zip file."); } File file = new File(zipFileName); if (!file.delete()) { logger.warn("Unable to delete zip file."); } } // Cleanup the additional xml and png files created. File tempXmlFile = new File(outDir, templateIndexDef.getIdentifier() + ".xml"); // Delete temp file // TODO:- Not deleting. Required to write XSL. try { if (tempXmlFile.exists()) { if (!tempXmlFile.delete()) { logger.error("Could not delete the temporary xml file after" + " exporting the report: " + tempXmlFile.getAbsolutePath()); } } } catch (SecurityException se) { logger.error("Exception while deleting temporary xml file." + se); } String fileName = directoryName + "/" + topLevelFolder.getName() + "_" + exportInfo.getTaskID() + ".zip"; ZIPProcessor.zipDirectory(outDirName, fileName); updateExportInfo(new File(fileName), exportInfo); if (templateMetaInfo != null && templateMetaInfo.getSourceType() == IC_SOURCE_TYPE.ICF) { ICStatisticsManager.getInstance().populateICUsageStatisticsInfo(templateMetaInfo, 1); } return new File[] { outDir, outputFile }; } catch (Exception ex) { logger.warn(ex.getMessage()); throw new PariException(ShadowWrapper.getString("Error_While_Report_Export") + "\n" + ex.getMessage()); } finally { try { if (xml != null) { xml.close(); } } catch (IOException ex) { ex.printStackTrace(); } try { if (os != null) { os.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } private void updateExportInfo(File outputFile, ExportInfo exportInfo) { exportInfo.setFileName(outputFile.getName()); exportInfo.setFileSize(outputFile.length()); exportInfo.setState(ExportInfoConstants.STATE_GENERATED); exportInfo.setStatus(ExportInfoConstants.STATUS_SUCCESS); } private InputStream getInputStream(ZipFile zipFile, String entryFileName) throws Exception { ZipEntry topLevelFolder = null; ZipEntry specificEntry = null; InputStream ipStream = null; Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { topLevelFolder = entries.nextElement(); if (topLevelFolder.isDirectory()) { break; } } if (topLevelFolder != null) { String lookupFile = topLevelFolder + entryFileName; specificEntry = zipFile.getEntry(lookupFile); } if (specificEntry != null) { ipStream = zipFile.getInputStream(specificEntry); } return ipStream; } public static File getTopLevelFolder(File zipFile) throws IOException { ZipInputStream in = null; try { in = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry entry = null; while ((entry = in.getNextEntry()) != null) { String outFilename = entry.getName(); if (entry.isDirectory()) { return new File(outFilename); } } } finally { if (in != null) { in.close(); } } return null; } class ExportProgressMonitor implements Runnable { private ReportTemplateRequestDef templateRequestDef; private Map<String, String> varValues; private String directoryName; private ExportFormat exportFormat; private ServerIfProvider serverIfProvider; private ExportInfo exportInfo; private int customerIdOfTemplate; private String customerNameOfTemplate; private String templateId; public ExportProgressMonitor(ReportTemplateRequestDef templateRequestDef, Map<String, String> varValues, String directoryName, ExportFormat exportFormat, ServerIfProvider serverIfProvider, ExportInfo exportInfo, int customerIdOfTemplate, String customerNameOfTemplate, String templateId) { this.templateRequestDef = templateRequestDef; this.varValues = varValues; this.directoryName = directoryName; this.exportFormat = exportFormat; this.serverIfProvider = serverIfProvider; this.exportInfo = exportInfo; this.customerIdOfTemplate = customerIdOfTemplate; this.customerNameOfTemplate = customerNameOfTemplate; this.templateId = templateId; } @Override public void run() { try { File[] file = ReportTemplateRunner.this.exportReport(templateRequestDef, varValues, directoryName, exportFormat, serverIfProvider, exportInfo, customerIdOfTemplate, customerNameOfTemplate, templateId); if (file != null && file.length > 0) { try { FileUtils.deleteDirectory(file[0]); } catch (Exception e) { } } } catch (Exception ex) { logger.error("Report template execution failed.", ex); exportInfo.setError(ex.getMessage()); exportInfo.setState(ExportInfoConstants.STATE_FAILED); exportInfo.setStatus(ExportInfoConstants.STATUS_FAILED); } ExportDBHelper.updateExportInfo(exportInfo); } } public String getDirectoryName() { return directoryName; } public void setDirectoryName(String directoryName) { this.directoryName = directoryName; } public String getExportFormat() { return exportFormat; } public void setExportFormat(String exportFormat) { this.exportFormat = exportFormat; } public UserDetails getUserDetails() { return userDetails; } public void setUserDetails(UserDetails userDetails) { this.userDetails = userDetails; } }