com.conecta.sat.controller.ReportsController.java Source code

Java tutorial

Introduction

Here is the source code for com.conecta.sat.controller.ReportsController.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.conecta.sat.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.JasperRunManager;
import net.sf.jasperreports.engine.export.ooxml.JRXlsxExporter;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 *
 * @author LuisOseguera
 */
@Controller
@Transactional
public class ReportsController {

    private static final Logger logger = Logger.getLogger(ReportsController.class);

    @PersistenceContext
    private EntityManager em;

    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss");

    @RequestMapping(value = "statusDeviceReport.do", method = RequestMethod.GET)
    public String statusDeviceReport(HttpServletRequest request, HttpServletResponse resp)
            throws JRException, SQLException, IOException {
        //        logger.info("Path: "+ReportsController.class.get);
        String url = request.getSession().getServletContext()
                .getRealPath("/resources/reports/EstatusDispositivos.jasper");

        logger.info("URL: " + url);
        HttpSession sessionUser = request.getSession();
        //        String fullPath = context.getRealPath("/WEB-INF/test/foo.txt"); 
        Map parameters = new HashMap();
        parameters.put("userName", sessionUser.getAttribute("userName").toString());
        parameters.put("userNumber", sessionUser.getAttribute("userId").toString());

        //        byte[] bytes = JasperRunManager.runReportToPdf("/WEB-INF/resources/reports/EstatusDispositivos.jasper", parameters);
        try {
            // String path = request.getSession().getServletContext().getRealPath("\\WEB-INF\\reports\\xxx.jrxml");
            // JasperReport jasperReport = JasperCompileManager.compileReport(url);
            Session session = em.unwrap(Session.class);
            SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
            ConnectionProvider cp = sfi.getConnectionProvider();
            Connection conn = cp.getConnection();

            //            JasperPrint jasperPrint = JasperFillManager.fillReport(url, parameters,);
            JasperPrint jasperPrint = JasperFillManager.fillReport(url, parameters, conn);
            byte[] pdfBytes = JasperExportManager.exportReportToPdf(jasperPrint);

            //uncomment this line to make browser download the file
            resp.setContentType("application/pdf");
            resp.setHeader("Content-Disposition",
                    "attachment;filename=EstatusDispositivos" + name.format(new Date()) + ".pdf");

            resp.getOutputStream().write(pdfBytes);
            resp.getOutputStream().flush();
            resp.getOutputStream().close();
            resp.flushBuffer();

        } catch (JRException ex) {
            logger.error(ex.getMessage(), ex.getCause());
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex.getCause());
        }

        //        byte[] bytes = JasperRunManager.runReportToPdf(url, parameters);
        //        resp.reset();
        //        resp.resetBuffer();
        //        resp.setContentType("application/pdf");
        //        resp.setContentLength(bytes.length);
        //        ServletOutputStream ouputStream = resp.getOutputStream();
        //        ouputStream.write(bytes, 0, bytes.length);
        //        ouputStream.flush();
        //        ouputStream.close();
        return null;
    }

    @RequestMapping(value = "statusDeviceReportXls.do", method = RequestMethod.GET)
    public String statusDeviceReportXls(HttpServletRequest request, HttpServletResponse resp)
            throws JRException, SQLException, IOException {
        String url = request.getSession().getServletContext()
                .getRealPath("/resources/reports/EstatusDispositivos.jasper");
        DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss");
        logger.info("URL: " + url);
        HttpSession sessionUser = request.getSession();
        Map parameters = new HashMap();
        parameters.put("userName", sessionUser.getAttribute("userName").toString());
        parameters.put("userNumber", sessionUser.getAttribute("userId").toString());
        Session session = em.unwrap(Session.class);
        SessionFactoryImplementor sfi = (SessionFactoryImplementor) session.getSessionFactory();
        ConnectionProvider cp = sfi.getConnectionProvider();
        Connection conn = cp.getConnection();

        //            JasperPrint jasperPrint = JasperFillManager.fillReport(url, parameters);
        JasperPrint jasperPrint = JasperFillManager.fillReport(url, parameters, conn);
        JRXlsxExporter xlsxExporter = new JRXlsxExporter();
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        xlsxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        xlsxExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
                "EstatusDispositivos" + name.format(new Date()) + ".xlsx");

        xlsxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);

        xlsxExporter.exportReport();

        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setHeader("Content-Disposition",
                "attachment; filename=EstatusDispositivos" + name.format(new Date()) + ".xlsx");

        resp.getOutputStream().write(os.toByteArray());
        resp.getOutputStream().flush();
        resp.getOutputStream().close();
        resp.flushBuffer();

        return null;
    }
}