com.automaster.autoview.server.servlet.PdfServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.automaster.autoview.server.servlet.PdfServlet.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.automaster.autoview.server.servlet;

import com.automaster.autoview.server.DAO.ClienteDAO;
import com.automaster.autoview.server.DAO.VeiculoDAO;
import com.automaster.autoview.server.DAO.ZzzPosPlacaVeiculoDAO;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfWriter;
import java.awt.Font;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Adriano
 */
public class PdfServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private Date dataAtual;
    private String cnpjUn;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            this.dataAtual = new Date(System.currentTimeMillis());
            this.cnpjUn = null;

            String tempoDecorrido = " 0";
            int codVeiculo = Integer.parseInt(request.getParameter("cod"));
            String placa = request.getParameter("placa");
            Timestamp dataInicio = new Timestamp(Long.parseLong(request.getParameter("dataInicio")));
            Timestamp dataFim = new Timestamp(Long.parseLong(request.getParameter("dataFim")));

            TimeZone timeZonePadrao = TimeZone.getTimeZone(ZoneId.of("-3"));
            //System.out.println("Time zone : " + timeZonePadrao);

            ZzzPosPlacaVeiculoDAO zzzPosPlacaVeiculoDAO = new ZzzPosPlacaVeiculoDAO();
            VeiculoDAO veiculoDAO = new VeiculoDAO();
            TreeMap<String, String> veiculo = veiculoDAO.buscarVeiculoPorCodigo(codVeiculo);
            placa = veiculo.get("placa");
            //System.out.println("PLACA: "+veiculo.get("placa"));
            ArrayList<TreeMap<String, String>> posicoes = zzzPosPlacaVeiculoDAO
                    .buscarPosicoesPorIntervaloData(placa, dataInicio, dataFim);
            int codCliente = Integer.parseInt(veiculo.get("clienteCodCliente"));
            //System.out.println("COD CLIENTE: "+codCliente);
            ClienteDAO clienteDAO = null;
            clienteDAO = new ClienteDAO();
            TreeMap<String, String> infoClienteUnidade = clienteDAO.buscarPorCodClienteSimplificado(codCliente);
            // Get the text that will be added to the PDF
            // step 1
            Document document = new Document();
            document.addHeader("Adriano", "AutoMaster");
            document.addCreator("Adriano Vale");
            document.addAuthor("Adriano Vale");
            document.addCreationDate();
            document.setPageSize(PageSize.A4.rotate());
            // step 2
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, baos);
            TableHeader event = new TableHeader();
            writer.setPageEvent(event);
            // step 3
            document.open();
            // step 4
            //getServletContext().getRealPath("/")
            String url = getServletContext().getRealPath("/");
            //"D:\\Users\\Adriano\\Documents\\NetBeansProjects\\JRGWT\\web\\imagens\\logo.jpg"
            Image logo = Image.getInstance(url + "/imagens/logo.jpg");
            logo.setAlignment(Element.ALIGN_CENTER);

            Paragraph titulo = new Paragraph("Relatrio de Posies",
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 20, Font.BOLD));
            titulo.setAlignment(Element.ALIGN_CENTER);

            Paragraph tituloPlaca = new Paragraph("Veculo: " + placa,
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
            tituloPlaca.setAlignment(Element.ALIGN_CENTER);

            SimpleDateFormat dataFormatadaCabecalho = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            dataFormatadaCabecalho.setTimeZone(timeZonePadrao);

            Date dataHoraInicio0 = new Date(Long.parseLong(request.getParameter("dataInicio")));
            Date dataHoraFim0 = new Date(Long.parseLong(request.getParameter("dataFim")));
            Paragraph periodo = new Paragraph(
                    "Perodo: De: " + dataFormatadaCabecalho.format(dataHoraInicio0) + " at: "
                            + dataFormatadaCabecalho.format(dataHoraFim0),
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
            periodo.setSpacingAfter(10.0f);
            periodo.setAlignment(Element.ALIGN_CENTER);
            //PdfPTable tabela = new PdfPTable(new float[]{0.11f, 0.095f, 0.06f, 0.065f, 0.085f, 0.06f, 0.04f, 0.065f, 0.055f, 0.06f, 0.24f, 0.065f});
            PdfPTable tabela = new PdfPTable(new float[] { 0.07f, 0.045f, 0.045f, 0.27f });
            tabela.setWidthPercentage(98.0f);
            tabela.setHorizontalAlignment(Element.ALIGN_CENTER);
            PdfPCell tituloData = new PdfPCell(Phrase.getInstance("Data e Hora"));
            tituloData.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(tituloData);
            //tabela.addCell("Data e hora");
            PdfPCell tituloVel = new PdfPCell(Phrase.getInstance("Velocidade"));
            tituloVel.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(tituloVel);
            PdfPCell tituloIgn = new PdfPCell(Phrase.getInstance("Ignio"));
            tituloIgn.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(tituloIgn);
            //tabela.addCell("Latitude");
            //tabela.addCell("Longitude");
            //tabela.addCell("Satlite");
            //tabela.addCell("GPS");
            //tabela.addCell("Entrada");
            //tabela.addCell("Sada");
            //tabela.addCell("Evento");
            PdfPCell tituloEnd = new PdfPCell(Phrase.getInstance("Endereo"));
            tituloEnd.setHorizontalAlignment(Element.ALIGN_CENTER);
            tabela.addCell(tituloEnd);
            //tabela.addCell("Direo");
            double latAnt = 0;
            double lonAnt = 0;
            double latAtual = 0;
            double lonAtual = 0;
            double distanciaTotal = 0;
            double distancia = 0;
            event.setHeader("AutoMaster");

            for (int i = 0; i < posicoes.size(); i++) {
                //for (int col = 0; col < posicoes.get(i).size(); col++) {
                if (i == 0) {
                    distancia = 0;
                    //System.out.println("linha 00 - PDF");
                } else {
                    //System.out.println("linha 01 - PDF");
                    latAnt = Double.parseDouble(posicoes.get(i - 1).get("lat"));
                    lonAnt = Double.parseDouble(posicoes.get(i - 1).get("lon"));
                    latAtual = Double.parseDouble(posicoes.get(i).get("lat"));
                    lonAtual = Double.parseDouble(posicoes.get(i).get("lon"));
                    //System.out.println("linha 02 - PDF");
                    if (latAnt == latAtual && lonAnt == lonAtual) {
                        distancia = 0;
                    } else {
                        distancia = caculaDistanciaEntreDoisPontos(latAnt, lonAnt, latAtual, lonAtual);
                        //System.out.println("linha 03 - PDF");
                    }

                }
                distanciaTotal = distanciaTotal + distancia;
                //System.out.println("linha 04 - PDF");
                //TimeZone.setDefault(timeZoneMundial);
                Date dataHora0 = new Date(Long.parseLong(posicoes.get(i).get("dataHora")));
                //System.out.println("dataHora0 : "+dataHora0.toString());
                //TimeZone.setDefault(timeZoneCliente);
                //Date dataHora = new Date(dataHora0.getTime());
                SimpleDateFormat dataFormatada = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                dataFormatada.setTimeZone(timeZonePadrao);
                //System.out.println("dataFormatada : "+dataFormatada);
                PdfPCell celData = new PdfPCell(Phrase.getInstance(dataFormatada.format(dataHora0)));
                celData.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabela.addCell(celData);
                //tabela.addCell(dataFormatada);
                PdfPCell celVel = new PdfPCell(Phrase.getInstance(posicoes.get(i).get("vel")));
                celVel.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabela.addCell(celVel);
                PdfPCell celIgn = new PdfPCell(Phrase
                        .getInstance(posicoes.get(i).get("ign").equalsIgnoreCase("True") ? "Ligada" : "Desligada"));
                celIgn.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabela.addCell(celIgn);
                //tabela.addCell(posicoes.get(i).get("lat"));
                //tabela.addCell(posicoes.get(i).get("lon"));
                //tabela.addCell(posicoes.get(i).get("sat"));
                //tabela.addCell(posicoes.get(i).get("gps"));
                //tabela.addCell(posicoes.get(i).get("entrada"));
                //tabela.addCell(posicoes.get(i).get("saida"));
                //tabela.addCell(posicoes.get(i).get("evento"));
                PdfPCell celEnd = new PdfPCell(
                        Phrase.getInstance(posicoes.get(i).get("endereco") == null ? "Sem endereo"
                                : posicoes.get(i).get("endereco")));
                celEnd.setHorizontalAlignment(Element.ALIGN_CENTER);
                tabela.addCell(celEnd);
                //tabela.addCell(posicoes.get(i).get("direcao"));
                //}
            }
            //System.out.println("linha 05 - PDF");
            tempoDecorrido = calculaDatas(Long.parseLong(posicoes.get(0).get("dataHora")),
                    Long.parseLong(posicoes.get(posicoes.size() - 1).get("dataHora")));
            //System.out.println("linha 06 - PDF");
            int index = 0;
            String kms = "0";
            String m = "";
            double metros = 0;
            //System.out.println("linha 07 - PDF");
            if (distanciaTotal > 0) {
                //System.out.println("linha 08 - PDF");
                BigDecimal decimalFormatado = new BigDecimal(distanciaTotal).setScale(2, RoundingMode.HALF_EVEN);
                //System.out.println("linha 09 - PDF");
                index = String.valueOf(decimalFormatado).indexOf(".");
                kms = String.valueOf(decimalFormatado).substring(0, index);
                m = "0" + (String.valueOf(decimalFormatado).substring(index));
                metros = Double.parseDouble(m) * 1000;
                //System.out.println("linha 10 - PDF");
            }
            /*document.add(new Paragraph(String.format(
             "You have submitted the following text using the %s method:",
             request.getMethod())));
             document.add(new Paragraph(text));*/
            //System.out.println("linha 11 - PDF");
            Paragraph kilometragem = new Paragraph(
                    "Percorridos: " + kms + " KM e " + String.valueOf(metros) + " metros. Tempo: " + tempoDecorrido,
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 16, Font.BOLD));
            //System.out.println("linha 12 - PDF");
            periodo.setSpacingAfter(10.0f);
            periodo.setAlignment(Element.ALIGN_CENTER);
            // step 5
            document.add(logo);
            document.add(titulo);
            document.add(tituloPlaca);
            document.add(periodo);
            document.add(tabela);
            document.add(kilometragem);
            String dia = new SimpleDateFormat("dd").format(dataAtual);
            String ano = new SimpleDateFormat("yyyy").format(dataAtual);
            int mes = dataAtual.getMonth();
            String mesEscrito = null;
            switch (mes) {
            case 0:
                mesEscrito = "janeiro";
                break;
            case 1:
                mesEscrito = "fevereiro";
                break;
            case 2:
                mesEscrito = "maro";
                break;
            case 3:
                mesEscrito = "abril";
                break;
            case 4:
                mesEscrito = "maio";
                break;
            case 5:
                mesEscrito = "junho";
                break;
            case 6:
                mesEscrito = "julho";
                break;
            case 7:
                mesEscrito = "agosto";
                break;
            case 8:
                mesEscrito = "setembro";
                break;
            case 9:
                mesEscrito = "outubro";
                break;
            case 10:
                mesEscrito = "novembro";
                break;
            case 11:
                mesEscrito = "dezembro";
                break;
            }
            String textRodape = infoClienteUnidade.get("cidadeUnidade") + " , "
                    + infoClienteUnidade.get("estadoUnidade") + "    " + dia + "  de  " + mesEscrito + "  de  "
                    + ano + ".";
            Paragraph localData = new Paragraph(textRodape,
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.PLAIN));
            localData.setAlignment(Element.ALIGN_RIGHT);
            localData.setSpacingBefore(30.0f);
            localData.setSpacingAfter(10.0f);
            document.add(localData);
            Image assinatura = Image.getInstance(url + "/imagens/assinatura.png");
            assinatura.setAlignment(Element.ALIGN_CENTER);
            assinatura.scaleAbsolute(185, 91);
            document.add(assinatura);
            Paragraph infoEmpresa1 = new Paragraph("AUTO MASTER LTDA",
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
            infoEmpresa1.setAlignment(Element.ALIGN_CENTER);
            infoEmpresa1.setSpacingAfter(1f);
            document.add(infoEmpresa1);
            Paragraph infoEmpresa2 = new Paragraph("___________________________",
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
            infoEmpresa2.setAlignment(Element.ALIGN_CENTER);
            document.add(infoEmpresa2);
            String cnpjEmpresa = formataCNPJ(infoClienteUnidade.get("cnpjUnidade"));
            Paragraph infoEmpresa3 = new Paragraph(cnpjEmpresa,
                    new com.itextpdf.text.Font(com.itextpdf.text.Font.FontFamily.HELVETICA, 12, Font.BOLD));
            infoEmpresa3.setAlignment(Element.ALIGN_CENTER);
            document.add(infoEmpresa3);
            document.close();
            // setting some response headers
            response.setHeader("Expires", "0");
            response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
            response.setHeader("Pragma", "public");
            // setting the content type
            response.setContentType("application/pdf");
            response.addHeader("Content-Disposition", "attachment; filename=Historico-" + placa + ".pdf");
            // the contentlength
            response.setContentLength(baos.size());
            // write ByteArrayOutputStream to the ServletOutputStream
            OutputStream os = response.getOutputStream();
            baos.writeTo(os);
            os.flush();
            os.close();
        } catch (DocumentException e) {
            throw new IOException(e.getMessage());
        }
        //        response.setContentType("text/html;charset=UTF-8");
        //        try (PrintWriter out = response.getWriter()) {
        //            /* TODO output your page here. You may use following sample code. */
        //            out.println("<!DOCTYPE html>");
        //            out.println("<html>");
        //            out.println("<head>");
        //            out.println("<title>Servlet PdfServlet</title>");            
        //            out.println("</head>");
        //            out.println("<body>");
        //            out.println("<h1>Servlet PdfServlet at " + request.getContextPath() + "</h1>");
        //            out.println("</body>");
        //            out.println("</html>");
        //        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private static double caculaDistanciaEntreDoisPontos(double lat1, double lon1, double lat2, double lon2) {

        //Transforma cordenadas em radianos
        /*String lat1Reduzida = String.valueOf(lat1);
         int index = lat1Reduzida.indexOf(".");
         String latFinal1 = lat1Reduzida.substring(0, index+5);
            
         String lon1Reduzida = String.valueOf(lon1);
         String lonFinal1 = lon1Reduzida.substring(0, index+5);
            
         String lat2Reduzida = String.valueOf(lat2);
         String latFinal2 = lat2Reduzida.substring(0, index+5);
            
         String lon2Reduzida = String.valueOf(lon2);
         String lonFinal2 = lon2Reduzida.substring(0, index+5);*/
        double lat01 = Math.toRadians(lat1);
        double lon01 = Math.toRadians(lon1);
        double lat02 = Math.toRadians(lat2);
        double lon02 = Math.toRadians(lon2);
        //calcula a distncia em KM atravs da frmula
        double dist = (6371 * Math.acos(
                Math.cos(lat01) * Math.cos(lat02) * Math.cos(lon02 - lon01) + Math.sin(lat01) * Math.sin(lat02)));
        //formata o resultado
        if (dist > 0) {
            BigDecimal decimalFormatado = new BigDecimal(dist).setScale(2, RoundingMode.HALF_EVEN);
            return decimalFormatado.doubleValue();
        }
        return 0;
        //return dist;

    }

    private String calculaDatas(long dataFinal, long dataInicial) {

        String tempoDecorrido = "";
        try {
            //System.out.println("datas : "+ dataFinal+ " "+dataInicial);
            long diferenca = dataFinal - dataInicial;
            //System.out.println("diferenca: "  +diferenca);
            //int dia = 24*60*60*1000;
            long dia = 0;
            long hora = 0;
            long minuto = 0;
            long segundo = 0;
            //GWT.log("diferenca : "+ diferenca);
            // um dia equivale a 86400000 ms
            // uma hora equivale a 3600000 ms;
            // um minuto equivale a 60000 ms;
            // um minuto equivale a 1000 ms;
            if (diferenca > 0) {
                while (diferenca > 0) {
                    if (diferenca >= 86400000) {
                        //System.out.println("LINHA 01 calculaDatas");
                        dia = diferenca / 86400000;
                        tempoDecorrido = tempoDecorrido + " " + dia + " dia(s), ";
                        diferenca = diferenca % 86400000;
                    } else if (diferenca < 86400000 && diferenca >= 3600000) {
                        //System.out.println("LINHA 02 calculaDatas");
                        hora = diferenca / 3600000;
                        tempoDecorrido = tempoDecorrido + "" + hora + " hora(s), ";
                        diferenca = diferenca % 3600000;

                    } else if (diferenca < 3600000 && diferenca >= 60000) {
                        //System.out.println("LINHA 03 calculaDatas");
                        minuto = diferenca / 60000;
                        tempoDecorrido = tempoDecorrido + "" + minuto + " minuto(s), ";
                        diferenca = diferenca % 60000;

                    } else if (diferenca < 60000) {
                        //System.out.println("LINHA 04 calculaDatas");
                        segundo = diferenca / 1000;
                        tempoDecorrido = tempoDecorrido + "" + segundo + " segundo(s).";
                        diferenca = diferenca % 1000;

                    }
                }
            } else {
                tempoDecorrido = " 0.";
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return tempoDecorrido;
    }

    private String formataCNPJ(String cnpj) {
        String cnpjFormatado = cnpj.substring(0, 2) + "." + cnpj.substring(2, 5) + "." + cnpj.substring(5, 8) + "/"
                + cnpj.substring(8, 12) + "-" + cnpj.substring(12, 14);
        return cnpjFormatado;
    }

}