com.dominion.salud.pedicom.negocio.tools.PDFService.java Source code

Java tutorial

Introduction

Here is the source code for com.dominion.salud.pedicom.negocio.tools.PDFService.java

Source

/*
 * Copyright (C) 2016 Dominion Global
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.dominion.salud.pedicom.negocio.tools;

import com.dominion.salud.pedicom.negocio.configuration.PEDICOMConstantes;
import static com.dominion.salud.pedicom.negocio.configuration.PEDICOMConstantes._HOME;
import com.dominion.salud.pedicom.negocio.entities.Pedidos;
import com.dominion.salud.pedicom.negocio.repositories.ArtCentrosRepository;
import com.dominion.salud.pedicom.negocio.service.LtSlistService;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sf.jasperreports.engine.JRException;
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.util.JRLoader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 *
 * @author j.contreras-ext
 */
@Service("pdfService")
public class PDFService {

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

    @Autowired
    private Environment environment;

    @Autowired
    private LtSlistService ltSlistService;

    @Autowired
    private ArtCentrosRepository artCentrosRepository;

    /**
     * Genera un pdf a partir de una lista de pedidos
     *
     * @param peds Lista de pedidos.
     * @param con
     * @return Stream de datos con el pdf.
     * @throws java.sql.SQLException
     * @throws java.lang.ClassNotFoundException
     * @throws net.sf.jasperreports.engine.JRException
     */
    public ByteArrayInputStream crearPDF(List<Pedidos> peds, Connection con)
            throws SQLException, ClassNotFoundException, JRException {

        ByteArrayInputStream in = null;

        try {
            logger.debug("          Iniciando creacin del pdf");
            ArrayList<Long> numeroPedidos = new ArrayList();
            for (Pedidos pedidos : peds) {
                numeroPedidos.add(pedidos.getPedidosPK().getNumPedido());
            }
            String join = StringUtils.join(numeroPedidos, ", ");
            logger.debug("               Creando pdf con pedidos : " + join);

            Map<String, Object> parameters = new HashMap<>();
            List<Long> list = new ArrayList<>();
            Iterator<Pedidos> it = peds.iterator();

            logger.debug("                    Configurando JASPER REPORTS");
            while (it.hasNext()) {
                list.add(it.next().getPedidosPK().getNumPedido());
            }
            parameters.put("LISTA_PEDIDOS", list);
            parameters.put("CODIGO_CENTRO", peds.get(0).getPedidosPK().getCodCentro());

            logger.debug("                         Fichero seleccionado: " + "reports/"
                    + ltSlistService.findJasper(peds.get(0).getPedidosPK().getCodCentro()).getCodList()
                    + ".jasper");
            URL ruta = this.getClass().getClassLoader()
                    .getResource("reports/"
                            + ltSlistService.findJasper(peds.get(0).getPedidosPK().getCodCentro()).getCodList()
                            + ".jasper");
            logger.debug("                         Path del fichero: " + this.getClass().getClassLoader()
                    .getResource("reports/"
                            + ltSlistService.findJasper(peds.get(0).getPedidosPK().getCodCentro()).getCodList()
                            + ".jasper"));
            logger.debug("                         Lista de Pedidos [LISTA_PEDIDOS]: " + numeroPedidos);
            logger.debug("                         Codigo de Centro [CODIGO_CENTRO]: "
                    + peds.get(0).getPedidosPK().getCodCentro());

            logger.debug("                    Iniciando la creacion del fichero PDF");
            JasperReport reporte = null;
            try {
                reporte = (JasperReport) JRLoader.loadObject(ruta);
            } catch (Exception e) {
                ruta = this.getClass().getClassLoader().getResource("reports/PEDICOM_LISTADO_PEDIDOS.jasper");
                reporte = (JasperReport) JRLoader.loadObject(ruta);
            }
            JasperPrint jasperPrint = JasperFillManager.fillReport(reporte, parameters, con);
            byte[] bytes = JasperExportManager.exportReportToPdf(jasperPrint);
            in = new ByteArrayInputStream(bytes);
            logger.debug("          Pdf creado correctamente");
        } catch (Exception e) {
            logger.error("SE HAN PRODUCIDO ERRORES AL CREAR EL PDF: " + e.toString());
            throw (e);
        }

        return in;
    }

    /**
     * Demonio que realiza el borrado de pdf
     */
    @Scheduled(cron = PEDICOMConstantes._TASK_PDF_DELETE)
    public void deletePDF() {
        logger.info("Comienza el borrado automatico de pdf");
        File dir = new File(PEDICOMConstantes._HOME + File.separator + "reports" + File.separator);
        logger.debug("     Directorio de borrado en: " + dir.getPath());
        Collection<File> list = FileUtils.listFiles(dir,
                FileFilterUtils.ageFileFilter(DateUtils.addDays(new Date(), -1), true), null);
        for (File fil : list) {
            if (!StringUtils.equalsIgnoreCase(fil.getName(), "No_encontrado.pdf")) {
                FileUtils.deleteQuietly(fil);
            }
        }
        logger.info("Borrado completado");
    }

}