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

Java tutorial

Introduction

Here is the source code for com.conecta.sat.controller.CentroFinancieroVirtualController.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 com.conecta.sat.exceptions.Excepciones;
import com.conecta.sat.hibernate.dto.StockTokenadmin;
import com.conecta.sat.service.StockTokenAdminService;
import com.conecta.sat.service.TokenStockService;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author LuisOseguera
 */
@Controller
@Transactional
public class CentroFinancieroVirtualController {
    private final Logger logger = Logger.getLogger(CentroFinancieroVirtualController.class);

    @Autowired
    private StockTokenAdminService stockTokenAdminServiceImpl;

    @Autowired
    private TokenStockService tokenStockService;

    @PersistenceContext
    private EntityManager em;

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

    @RequestMapping(value = "virtualCenterReportPDF.do", method = RequestMethod.GET)
    public String virtualCenterReportPDF(HttpServletRequest request, HttpServletResponse resp)
            throws JRException, SQLException, IOException, Exception {
        String url = request.getSession().getServletContext()
                .getRealPath("/resources/reports/CentroFinancieroVirtual.jasper");

        logger.info("URL: " + url);
        Map parameters = new HashMap();

        StockTokenadmin soft = new StockTokenadmin();
        soft = this.stockTokenAdminServiceImpl.getStockSoft();

        parameters.put("stockUtilizado", soft.getStockUtilizado());
        parameters.put("stockTotal", soft.getStockTotal());

        try {

            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, conn);
            byte[] pdfBytes = JasperExportManager.exportReportToPdf(jasperPrint);

            DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss");

            //uncomment this line to make browser download the file
            resp.setContentType("application/pdf");
            resp.setHeader("Content-Disposition",
                    "attachment;filename=CentroFinancieroVirtual" + 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());
        }

        return null;
    }

    @RequestMapping(value = "virtualCenterReportXls.do", method = RequestMethod.GET)
    public String virtualCenterReportXls(HttpServletRequest request, HttpServletResponse resp)
            throws JRException, SQLException, IOException, Exception {
        String url = request.getSession().getServletContext()
                .getRealPath("/resources/reports/CentroFinancieroVirtual.jasper");
        DateFormat name = new SimpleDateFormat("ddMMyyyyhhmmss");

        Map parameters = new HashMap();
        StockTokenadmin soft = new StockTokenadmin();
        soft = this.stockTokenAdminServiceImpl.getStockSoft();

        parameters.put("stockUtilizado", soft.getStockUtilizado());
        parameters.put("stockTotal", soft.getStockTotal());

        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, conn);
        JRXlsxExporter xlsxExporter = new JRXlsxExporter();
        ByteArrayOutputStream os = new ByteArrayOutputStream();

        xlsxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
        xlsxExporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME,
                "CentroFinancieroVirtual" + 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=CentroFinancieroVirtual" + name.format(new Date()) + ".xlsx");

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

        return null;
    }

    @RequestMapping(value = "centroFinancieroVirtual.do", method = RequestMethod.GET)
    public ModelAndView centroFinancieroVirtual(ModelAndView model) throws Exception {
        model.setViewName("centroFinancieroVirtual");
        model.addObject("softTotal", stockTokenAdminServiceImpl.getStockSoft());
        model.addObject("softUtilizado", tokenStockService.countSoftToken());
        return model;
    }

    @RequestMapping(value = "token-admin-soft", method = RequestMethod.POST)
    public String saveSoftToken(@RequestParam(value = "licencias", required = true) Integer licencias,
            Model model) {
        try {
            if (stockTokenAdminServiceImpl.cargarLicenciasSoft(licencias)) {
                model.addAttribute("mensaje", "Se generaron " + licencias + " licencias para Soft Tokens");
                model.addAttribute("softUtilizado", tokenStockService.countSoftToken());
                model.addAttribute("softTotal", stockTokenAdminServiceImpl.getStockSoft());

                return "centroFinancieroVirtual";
            }
        } catch (Exception e) {
            logger.error(Excepciones.getStackTrace(e));
        }

        model.addAttribute("error", "Ocurri un error al generar las licencias de los Soft Tokens.");
        model.addAttribute("softTotal", stockTokenAdminServiceImpl.getStockSoft());

        return "centroFinancieroVirtual";
    }

}