Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package id.co.sofcograha.gajiidapi.base.report;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.Base64;
- import java.util.Date;
- import java.util.List;
- import java.util.Map;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.http.HttpStatus;
- import org.springframework.http.ResponseEntity;
- import org.springframework.stereotype.Component;
- import org.springframework.web.context.annotation.RequestScope;
- import com.lowagie.text.pdf.PdfWriter;
- import id.co.sofcograha.gajiidapi.base.authentication.CurrentUser;
- import id.co.sofcograha.gajiidapi.base.extendables.FreeFormService;
- import id.co.sofcograha.gajiidapi.base.mst.report.entities.Report;
- import id.co.sofcograha.gajiidapi.base.mst.report.repositories.ReportRepository;
- import id.co.sofcograha.gajiidapi.base.mst.reportlog.entities.ReportLog;
- import id.co.sofcograha.gajiidapi.base.mst.reportlog.repositories.ReportLogRepository;
- import id.co.sofcograha.gajiidapi.base.mst.user.entities.User;
- import id.co.sofcograha.gajiidapi.base.mst.user.repositories.UserRepository;
- import id.co.sofcograha.gajiidapi.base.pojos.Base64StringEncodedPojo;
- import id.co.sofcograha.gajiidapi.base.utils.FileUtil;
- import id.co.sofcograha.gajiidapi.base.utils.StringUtil;
- import id.co.sofcograha.gajiidapi.base.utils.TimeUtil;
- import net.sf.jasperreports.engine.JRAbstractExporter;
- import net.sf.jasperreports.engine.JRDataSource;
- import net.sf.jasperreports.engine.JRException;
- import net.sf.jasperreports.engine.JasperCompileManager;
- import net.sf.jasperreports.engine.JasperFillManager;
- import net.sf.jasperreports.engine.JasperPrint;
- import net.sf.jasperreports.engine.JasperReport;
- import net.sf.jasperreports.engine.data.ListOfArrayDataSource;
- import net.sf.jasperreports.engine.export.JRPdfExporter;
- import net.sf.jasperreports.engine.export.JRXlsExporter;
- import net.sf.jasperreports.export.SimpleExporterInput;
- import net.sf.jasperreports.export.SimpleOutputStreamExporterOutput;
- import net.sf.jasperreports.export.SimplePdfExporterConfiguration;
- import net.sf.jasperreports.export.SimpleXlsReportConfiguration;
- @Component
- @RequestScope
- public class ReportGeneratorService extends FreeFormService {
- private Log logger = LogFactory.getLog(this.getClass());
- @Autowired
- private ReportRepository reportRepository;
- @Autowired
- private ReportLogRepository reportLogRepository;
- @Autowired
- private UserRepository userRepository;
- private final String PDF_OWNER_PASSWORD = "gaji.id";
- private final String CONTENT_TYPE_PDF = "application/pdf";
- private final String PDF_SUFIX = ".pdf";
- private final String CONTENT_TYPE_EXCEL = "application/vnd.ms-excel";
- private final String EXCEL_SUFIX = ".xls";
- public ResponseEntity<byte[]> generateJasperXlsFile(HttpServletResponse response,
- String reportId,
- String generatedFileName,
- Map<String, Object> parameters,
- List<Object[]> records,
- String[] columnNames) {
- logger.debug("START generate jasper report: " + reportId);
- Report report = getAndValidateReportEntityFromDB(reportId);
- String jrxmlFileName = report.getTemplateFile();
- validateJrxmlFile(jrxmlFileName);
- JasperPrint jasperPrint = processJasperReport(jrxmlFileName, parameters, records, columnNames);
- SimpleXlsReportConfiguration config = new SimpleXlsReportConfiguration();
- config.setDetectCellType(true);
- config.setOnePagePerSheet(true);
- JRXlsExporter exporter = new JRXlsExporter();
- exporter.setConfiguration(config);
- ByteArrayOutputStream baos = generateReport(jasperPrint, exporter);
- prepareHttpResponse(response, CONTENT_TYPE_EXCEL, generatedFileName + EXCEL_SUFIX);
- saveReportLog(report);
- logger.debug("FINISH generate jasper report: " + reportId);
- return new ResponseEntity<>(baos.toByteArray(), HttpStatus.OK);
- }
- public ResponseEntity<byte[]> generateJasperPdfFile(HttpServletResponse response,
- String reportId,
- String generatedFileName,
- Map<String, Object> parameters,
- List<Object[]> records,
- String[] columnNames) {
- return generateJasperPdfFile(response, reportId, generatedFileName, parameters, records, columnNames, null);
- }
- public ResponseEntity<byte[]> generateJasperPdfFile(HttpServletResponse response,
- String reportId,
- String generatedFileName,
- Map<String, Object> parameters,
- List<Object[]> records,
- String[] columnNames,
- String password) {
- logger.debug("START generate jasper report: " + reportId);
- Report report = getAndValidateReportEntityFromDB(reportId);
- String jrxmlFileName = report.getTemplateFile();
- validateJrxmlFile(jrxmlFileName);
- JasperPrint jasperPrint = processJasperReport(jrxmlFileName, parameters, records, columnNames);
- JRPdfExporter exporter = new JRPdfExporter();
- if (password != null && !password.isEmpty()) {
- SimplePdfExporterConfiguration config = new SimplePdfExporterConfiguration();
- config.setEncrypted(true);
- config.set128BitKey(true);
- config.setUserPassword(password);
- config.setOwnerPassword(PDF_OWNER_PASSWORD);
- config.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
- exporter.setConfiguration(config);
- }
- ByteArrayOutputStream baos = generateReport(jasperPrint, exporter);
- prepareHttpResponse(response, CONTENT_TYPE_PDF, generatedFileName + PDF_SUFIX);
- saveReportLog(report);
- logger.debug("FINISH generate jasper report: " + reportId);
- return new ResponseEntity<>(baos.toByteArray(), HttpStatus.OK);
- }
- public Base64StringEncodedPojo generateBase64PdfReportFile(String reportId,
- String generatedFileName,
- Map<String, Object> parameters,
- List<Object[]> records,
- String[] columnNames) {
- return generateBase64PdfReportFile(reportId,
- generatedFileName,
- parameters,
- records,
- columnNames,
- null);
- }
- public Base64StringEncodedPojo generateBase64PdfReportFile(String reportId,
- String generatedFileName,
- Map<String, Object> parameters,
- List<Object[]> records,
- String[] columnNames,
- String password) {
- logger.debug("START generate jasper report: " + reportId);
- Report report = getAndValidateReportEntityFromDB(reportId);
- String jrxmlFileName = report.getTemplateFile();
- validateJrxmlFile(jrxmlFileName);
- JasperPrint jasperPrint = processJasperReport(jrxmlFileName, parameters, records, columnNames);
- JRPdfExporter exporter = new JRPdfExporter();
- if (password != null && !password.isEmpty()) {
- SimplePdfExporterConfiguration config = new SimplePdfExporterConfiguration();
- config.setEncrypted(true);
- config.set128BitKey(true);
- config.setUserPassword(password);
- config.setOwnerPassword(PDF_OWNER_PASSWORD);
- config.setPermissions(PdfWriter.ALLOW_COPY | PdfWriter.ALLOW_PRINTING);
- exporter.setConfiguration(config);
- }
- ByteArrayOutputStream baos = generateReport(jasperPrint, exporter);
- saveReportLog(report);
- return new Base64StringEncodedPojo(CONTENT_TYPE_PDF, Base64.getEncoder().encodeToString(baos.toByteArray()));
- }
- @SuppressWarnings("unchecked")
- private ByteArrayOutputStream generateReport(JasperPrint jasperPrint,
- @SuppressWarnings("rawtypes") JRAbstractExporter exporter) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- try {
- exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
- exporter.setExporterOutput(new SimpleOutputStreamExporterOutput(baos));
- exporter.exportReport();
- } catch (JRException e) {
- logger.error("report.jrxml.exportReport.error", e);
- error("report.jrxml.exportReport.error");
- } finally {
- try {
- baos.close();
- } catch (IOException e) {
- logger.error("report.io.error", e);
- error("report.io.error");
- }
- }
- return baos;
- }
- private JasperPrint processJasperReport(String jrxmlFileName, Map<String, Object> parameters,
- List<Object[]> records, String[] columnNames) {
- InputStream jrxmlFile = FileUtil.getJrxmlFile(jrxmlFileName);
- JasperReport jasperReport = null;
- try {
- jasperReport = JasperCompileManager.compileReport(jrxmlFile);
- } catch (JRException e) {
- logger.error("report.jrxml.compileReport.error", e);
- error("report.jrxml.compileReport.error");
- }
- JasperPrint jasperPrint = null;
- JRDataSource dataSource = new ListOfArrayDataSource(records, columnNames);
- try {
- jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
- } catch (JRException e) {
- logger.error("report.jrxml.fillReport.error", e);
- error("report.jrxml.fillReport.error");
- }
- return jasperPrint;
- }
- private void validateJrxmlFile(String jrxmlFileName) {
- if (StringUtil.isBlank(jrxmlFileName)) {
- error("report.jrxml.fileName.required");
- }
- if (FileUtil.getJrxmlFile(jrxmlFileName) == null) {
- error("report.jrxml.file.not.found", jrxmlFileName);
- }
- }
- private void prepareHttpResponse(HttpServletResponse response, String contentType, String fileNameWithExtension) {
- response.setContentType(contentType);
- response.setHeader("Content-disposition", "attachment; filename = " + fileNameWithExtension);
- try {
- response.flushBuffer();
- } catch (IOException e) {
- logger.error("report.io.error", e);
- error("report.io.error");
- }
- }
- private Report getAndValidateReportEntityFromDB(String reportId) {
- Report result = reportRepository.findByBK(reportId).orElse(null);
- if (result == null)
- error("report.jrxml.reportId.not.found", reportId);
- if (!result.getActive())
- error("report.jrxml.reportId.not.active", reportId);
- return result;
- }
- private void saveReportLog(Report report) {
- Date systemDateTime = TimeUtil.getSystemDateTime();
- String yearMonth = TimeUtil.getFourDigitYear(systemDateTime) + TimeUtil.getTwoDigitMonth(systemDateTime);
- Integer nextSeq = getNextSeq(report, yearMonth);
- User currentUser = userRepository.getOne(CurrentUser.getUserId());
- ReportLog reportLog = new ReportLog();
- reportLog.setReport(report);
- reportLog.setYearMonth(yearMonth);
- reportLog.setNumberSeq(nextSeq);
- reportLog.setUser(currentUser);
- reportLog.setReportDate(systemDateTime);
- reportLogRepository.saveAndFlush(reportLog);
- }
- private Integer getNextSeq(Report report, String yearMonth) {
- Integer result = 0;
- ReportLog lastSeqReportLogByReportAndYearMonth = reportLogRepository
- .getLastSeqReportLogByReportAndYearMonth(report, yearMonth).orElse(null);
- if (lastSeqReportLogByReportAndYearMonth != null)
- result = lastSeqReportLogByReportAndYearMonth.getNumberSeq() + 1;
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment