Advertisement
Guest User

Untitled

a guest
Nov 24th, 2015
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 19.97 KB | None | 0 0
  1. package fill;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.FileOutputStream;
  8. import java.io.FileReader;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStream;
  13. import java.io.PrintWriter;
  14. import java.io.UnsupportedEncodingException;
  15. import java.util.Date;
  16. import java.util.Properties;
  17. import java.util.Vector;
  18. import java.util.logging.Level;
  19. import java.util.logging.Logger;
  20. import javax.activation.DataHandler;
  21. import javax.activation.DataSource;
  22. import javax.activation.FileDataSource;
  23. import javax.mail.Authenticator;
  24. import javax.mail.BodyPart;
  25. import javax.mail.Message;
  26. import javax.mail.MessagingException;
  27. import javax.mail.Multipart;
  28. import javax.mail.PasswordAuthentication;
  29. import javax.mail.Session;
  30. import javax.mail.Transport;
  31. import javax.mail.internet.AddressException;
  32. import javax.mail.internet.InternetAddress;
  33. import javax.mail.internet.MimeBodyPart;
  34. import javax.mail.internet.MimeMessage;
  35. import javax.mail.internet.MimeMultipart;
  36.  
  37. public class Utils {
  38.  
  39.     static String[] plan1 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion.pdf"};
  40.     static String[] plan2 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion_plus.pdf"};
  41.     static String[] plan3 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion.pdf", "plantillas\\Costo_cero.pdf"};
  42.     static String[] plan4 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion_plus.pdf", "plantillas\\Costo_cero.pdf"};
  43.     Vector<String> ruta_docs_firmados;
  44.     String email = "", email_sup = "";
  45.     archivo arc;
  46.  
  47.     public static String readFileISO85591(String in) {
  48.         BufferedReader br = null;
  49.         try {
  50.             br = new BufferedReader(new InputStreamReader(new FileInputStream(in), "ISO-8859-1"));
  51.             char[] buffer = new char[12288]; // character (not byte) buffer
  52.             String s = "";
  53.  
  54.             while (true) {
  55.                 int charCount = br.read(buffer, 0, buffer.length);
  56.                 if (charCount == -1) {
  57.                     break;
  58.                 }
  59.                 s = String.valueOf(buffer, 0, charCount);
  60.  
  61.             }
  62.             br.close();
  63.  
  64.             return s;
  65.         } catch (Exception e) {
  66.             if (br != null) {
  67.                 try {
  68.                     br.close();
  69.                 } catch (IOException ex) {
  70.                     Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
  71.                 }
  72.             }
  73.             return e.toString();
  74.         }
  75.     }
  76.  
  77.     public static String readFileUTF8(String in) {
  78.         BufferedReader br = null;
  79.         try {
  80.             br = new BufferedReader(new InputStreamReader(new FileInputStream(in), "UTF-8"));
  81.             char[] buffer = new char[12288]; // character (not byte) buffer
  82.             String s = "";
  83.  
  84.             while (true) {
  85.                 int charCount = br.read(buffer, 0, buffer.length);
  86.                 if (charCount == -1) {
  87.                     break;
  88.                 }
  89.                 s = String.valueOf(buffer, 0, charCount);
  90.  
  91.             }
  92.             br.close();
  93.  
  94.             return s;
  95.         } catch (Exception e) {
  96.             if (br != null) {
  97.                 try {
  98.                     br.close();
  99.                 } catch (IOException ex) {
  100.                     Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
  101.                 }
  102.             }
  103.             return e.toString();
  104.         }
  105.     }
  106.  
  107.     public static boolean createLog(String nom, String val, String docname, String rut) {
  108.         File theDir = new File("C:\\TOC\\tmp\\" + rut);
  109.         if (!theDir.exists()) {
  110.             try {
  111.                 theDir.mkdir();
  112.             } catch (SecurityException se) {
  113.                 System.out.println(se.toString());
  114.                 return false;
  115.             }
  116.         }
  117.         String[] nombres = nom.split("##");
  118.         String[] valores = val.split("##");
  119.         PrintWriter writer;
  120.         try {
  121.             String name = "";
  122.             for (int i = (docname.length() - 1); i >= 0; i--) {
  123.                 if (docname.charAt(i) == '\\') {
  124.                     name = docname.substring(i + 1, docname.length() - 4);
  125.                     break;
  126.                 }
  127.             }
  128.             System.out.println("name: " + name);
  129.             writer = new PrintWriter("C:\\TOC\\tmp\\" + rut + "\\" + name + ".txt", "UTF-8");
  130.             int len;
  131.             if (nombres.length > valores.length) {
  132.                 len = valores.length;
  133.             } else {
  134.                 len = nombres.length;
  135.             }
  136.             for (int i = 0; i < len; i++) {
  137.                 writer.println(nombres[i] + "#" + valores[i] + "#");
  138.             }
  139.             writer.close();
  140.         } catch (Exception ex) {
  141.             System.out.println(ex.toString());
  142.             return false;
  143.         }
  144.  
  145.         return true;
  146.     }
  147.  
  148.     public boolean moveDocs(String plan, Vector<String> ndoc, Vector<String> ruta, String rut, boolean pat, String extra) {
  149.         Vector<String> nombreArchivo = new Vector<String>();
  150.         Vector<String> rutaArchivo = new Vector<String>();
  151.         ruta_docs_firmados = new Vector<String>();
  152.         int res;
  153.         String data[];
  154.         System.out.println("-----------");
  155.         for (int i = 0; i < ndoc.size(); i++) {
  156.             System.out.println(ndoc.get(i));
  157.         }
  158.         System.out.println("-----------");
  159.  
  160.         if (plan.equals("Catastrófico")) {
  161.             for (int i = 0; i < plan1.length; i++) {
  162.                 res = isThere(ndoc, plan1[i]);
  163.                 if (res == -1) {
  164.                     System.out.println("Docs plan 1 no encontrados");
  165.                     return false;
  166.                 }
  167.                 nombreArchivo.add(ndoc.get(res));
  168.                 rutaArchivo.add(ruta.get(res));
  169.             }
  170.         } else if (plan.equals("Catastrófico + Complementario")) {
  171.             for (int i = 0; i < plan2.length; i++) {
  172.                 res = isThere(ndoc, plan2[i]);
  173.                 if (res == -1) {
  174.                     System.out.println(plan2[i] + " No encontrado");
  175.                     return false;
  176.                 }
  177.                 nombreArchivo.add(ndoc.get(res));
  178.                 rutaArchivo.add(ruta.get(res));
  179.             }
  180.         } else if (plan.equals("Catastrófico + Costo Cero")) {
  181.             for (int i = 0; i < plan3.length; i++) {
  182.                 res = isThere(ndoc, plan3[i]);
  183.                 if (res == -1) {
  184.                     System.out.println("Docs plan 3 no encontrados");
  185.                     return false;
  186.                 }
  187.                 nombreArchivo.add(ndoc.get(res));
  188.                 rutaArchivo.add(ruta.get(res));
  189.             }
  190.         } else if (plan.equals("Catastrófico + Complementario + Costo Cero")) {
  191.             for (int i = 0; i < plan4.length; i++) {
  192.                 res = isThere(ndoc, plan4[i]);
  193.                 if (res == -1) {
  194.                     System.out.println("Docs plan 4 no encontrados");
  195.                     return false;
  196.                 }
  197.                 nombreArchivo.add(ndoc.get(res));
  198.                 rutaArchivo.add(ruta.get(res));
  199.             }
  200.         } else {
  201.             System.out.println("Plan: " + plan + " no existe");
  202.             return false;
  203.         }
  204.         if (pat) {
  205.             res = isThere(ndoc, "plantillas\\Mandato_PAT.pdf");
  206.             if (res == -1) {
  207.                 System.out.println("Mandato PAT no encontrado");
  208.                 return false;
  209.             }
  210.             nombreArchivo.add(ndoc.get(res));
  211.             rutaArchivo.add(ruta.get(res));
  212.         }
  213.         String npropuesta = "";
  214.         try {
  215.             DbHandler db = new DbHandler();
  216.             npropuesta = db.getProposal(rut.replace("-", ""));
  217.             if (npropuesta.equals("T00000000")) {
  218.                 npropuesta = db.insertProposal(rut.replace("-", ""));
  219.             }
  220.  
  221.             System.out.println("propuestas de " + rut.replace("-", "") + " eliminadas: " + db.deleteProposal(rut.replace("-", "")));
  222.         } catch (Exception e) {
  223.             npropuesta = "";
  224.             System.out.println("Error en asignacion numero de propuesta: " + e.toString());
  225.         }
  226.  
  227.         if (!moveFiles(rutaArchivo, nombreArchivo, rut, npropuesta)) {
  228.             System.out.println("Error al mover los archivos");
  229.             return false;
  230.         }
  231.         if (!createRelatedFile(nombreArchivo, rut, plan, npropuesta, pat, extra)) {
  232.             System.out.println("Error al crear el archivo de texto asociado");
  233.             return false;
  234.         }
  235.         try {
  236.             email = arc.email;
  237.             String rut_ejec = arc.ejecutivo;
  238.             System.out.println("Recuperando mail supervisor de: " + rut_ejec);
  239.             String tmp = supvisor(rut_ejec);
  240.             System.out.println("ans: " + tmp);
  241.             String sep[] = tmp.split("##");
  242.             email_sup = sep[1];
  243.         } catch (Exception e) {
  244.  
  245.         }
  246.         String RECIPIENT = "mariana.soto@toc.cl";
  247.  
  248.         String recipent[] = {email_sup, email, RECIPIENT};
  249.         sendMail(rut, plan, recipent);
  250.  
  251.         return true;
  252.     }
  253.  
  254.     public int isThere(Vector<String> names, String doc) {
  255.         int found = -1;
  256.         for (int i = 0; i < names.size(); i++) {
  257.             if (names.get(i).replace("\\", "").equals(doc.replace("\\", ""))) {
  258.                 found = i;
  259.                 break;
  260.             }
  261.         }
  262.         return found;
  263.     }
  264.  
  265.     public boolean createRelatedFile(Vector<String> names, String rut, String plan, String nprop, boolean pat, String extra) {
  266.         arc = new archivo(plan, rut);
  267.         arc.loadValues("nprop", nprop);
  268.         if (pat) {
  269.             arc.loadValues("PAToPAC", "PAT");
  270.         } else {
  271.             arc.loadValues("PAToPAC", "PAC");
  272.         }
  273.         try {
  274.             String sep[] = extra.split(",");
  275.             for (int i = 0; i < sep.length; i += 2) {
  276.                 if (i + 1 >= sep.length) {
  277.                     break;
  278.                 }
  279.                 arc.loadValues(sep[i], sep[i + 1]);
  280.             }
  281.         } catch (Exception e) {
  282.  
  283.         }
  284.         String nom, val;
  285.         System.out.println("Analizando " + names.size() + " archivos");
  286.         if (rut.charAt(rut.length() - 2) != '-') {
  287.             rut = rut.substring(0, rut.length() - 1) + "-" + rut.substring(rut.length() - 1, rut.length());
  288.         }
  289.         for (int i = 0; i < names.size(); i++) {
  290.  
  291.             System.out.println("Agregando: " + "C:\\TOC\\tmp\\" + rut + "\\" + names.get(i).substring(10, names.get(i).length() - 3).replace("\\", "") + "txt");
  292.             String tmp = readFileISO85591("C:\\TOC\\tmp\\" + rut + "\\" + names.get(i).substring(10, names.get(i).length() - 3).replace("\\", "") + "txt");
  293.             String sep[] = tmp.split("#");
  294.             nom = "";
  295.             val = "";
  296.             for (int j = 0; j < sep.length; j += 2) {
  297.                 if (j + 1 < sep.length) {
  298.                     //System.out.println(sep[j].trim() + " ; " + sep[j + 1].trim());
  299.                     nom += sep[j].trim() + "##";
  300.                     val += sep[j + 1].trim() + "##";
  301.                 }
  302.             }
  303.             arc.loadValues(nom, val);
  304.         }
  305.         arc.createFile(nprop);
  306.  
  307.         return true;
  308.     }
  309.  
  310.     public boolean moveFiles(Vector<String> rutas, Vector<String> nombreArchivos, String rut, String nprop) {
  311.         for (int i = 0; i < rutas.size(); i++) {
  312.             System.out.println(i + ": " + rutas.get(i));
  313.         }
  314.         System.out.println(rut);
  315.         System.out.println(nprop);
  316.  
  317.         rut = rut.replace("-", "");
  318.         //createFolder("C:\\TOC\\completas\\VENDIG\\" + rut);
  319.         createFolder("C:\\TOC\\completas\\" + rut);
  320.         createFolder("C:\\TOC\\completas\\" + rut + "\\COBRANZA");
  321.         createFolder("C:\\TOC\\completas\\" + rut + "\\DOCUMENTOS");
  322.         createFolder("C:\\TOC\\completas\\" + rut + "\\LIQUIDACION");
  323.         createFolder("C:\\TOC\\completas\\" + rut + "\\POLIZA");
  324.         createFolder("C:\\TOC\\completas\\" + rut + "\\PROPUESTA");
  325.         try {
  326.             System.out.println("Moving " + rutas.size() + "Files");
  327.             for (int i = 0; i < rutas.size(); i++) {
  328.                 File source = new File("C:\\xampp\\htdocs\\pdffirmado\\" + rutas.get(i));
  329.                 File dest = new File("C:\\TOC\\completas\\" + rut + "\\PROPUESTA\\" + nprop + "-" + rut.replace("-", "") + "-" + getName(nombreArchivos.get(i)));
  330.                 ruta_docs_firmados.add("C:\\TOC\\completas\\" + rut + "\\PROPUESTA\\" + nprop + "-" + rut.replace("-", "") + "-" + getName(nombreArchivos.get(i)));
  331.                 System.out.println("Moving: " + "C:\\xampp\\htdocs\\pdffirmado\\" + rutas.get(i) + " , to: " + "C:\\TOC\\completas\\VENDIG\\" + rut + "\\PROPUESTA\\" + nprop + "-" + rut.replace("-", "") + "-" + source.getName());
  332.                 copyFileUsingFileStreams(source, dest);
  333.                 /*    File afile = new File("C:\\xampp\\htdocs\\pdffirmado\\" + rutas.get(i));
  334.                  if (afile.renameTo(new File("C:\\TOC\\completas\\" + rut + "\\" + afile.getName()))) {
  335.                  System.out.println("Moved");
  336.                  } else {
  337.                  return false;
  338.                  }*/
  339.             }
  340.         } catch (Exception e) {
  341.             System.out.println("Erro: " + e.toString());
  342.             e.printStackTrace();
  343.             return false;
  344.         }
  345.         return true;
  346.     }
  347.  
  348.     public void sendMail(String _rut, String _plan, String recipient[]) {
  349.         final String rut = _rut, plan = _plan, toSend[] = recipient;
  350.         Runnable r = new Runnable() {
  351.             @Override
  352.             public void run() {
  353.  
  354.                 System.out.println("\n1st ===> Preparando el envio de mail..");
  355.  
  356.                 final String asunto = "Plan firmado electronicamente cliente rut: " + rut;
  357.                 final String mensaje = "Estimado/a, <br><br>Se adjuntan documentos firmados electronicamente asociados a contratacion de plan. <br><br> Saludos.";
  358.  
  359.                 final String sourceEmail = "ventas.moviles.recover@gmail.com"; // requires valid Gmail id
  360.                 final String password = "ventasrecover"; // correct password for Gmail id
  361.  
  362.                 Properties props = new Properties();
  363.                 props.put("mail.smtp.host", "smtp.gmail.com");
  364.                 props.put("mail.smtp.port", "587");
  365.                 props.put("mail.smtp.auth", "true");
  366.                 props.put("mail.smtp.starttls.enable", "true");
  367.  
  368.                 System.out.println("\n2nd ===> Generando autentificacion..");
  369.  
  370.                 Authenticator authentication = new Authenticator() {
  371.                     protected PasswordAuthentication getPasswordAuthentication() {
  372.                         return new PasswordAuthentication(sourceEmail, password);
  373.                     }
  374.                 };
  375.                 Session session = Session.getInstance(props, authentication);
  376.  
  377.                 //Llamamos a la funcion por cada destinarario
  378.                 for (int i = 0; i < toSend.length; i++) {
  379.                     generateAndSendEmail(session, toSend[0], asunto, mensaje);
  380.                 }
  381.             }
  382.         };
  383.  
  384.         new Thread(r).start();
  385.     }
  386.  
  387.     private void generateAndSendEmail(Session session, String toEmail, String subject, String body) {
  388.         try {
  389.  
  390.             long startTime = System.currentTimeMillis();
  391.             System.out.println("\n3rd ===> Comenzando el armado del correo..");
  392.  
  393.             MimeMessage crunchifyMessage = new MimeMessage(session);
  394.             crunchifyMessage.addHeader("Content-type", "text/HTML; charset=UTF-8");
  395.             crunchifyMessage.addHeader("format", "flowed");
  396.             crunchifyMessage.addHeader("Content-Transfer-Encoding", "8bit");
  397.  
  398.             crunchifyMessage.setFrom(new InternetAddress("ventas.moviles.recover@gmail.cl", "Metlife-Recover"));
  399.             //crunchifyMessage.setReplyTo(InternetAddress.parse("noreply@toc.cl", false));
  400.             crunchifyMessage.setSubject(subject, "UTF-8");
  401.             crunchifyMessage.setSentDate(new Date());
  402.             crunchifyMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
  403.  
  404.             // Create the message body part
  405.             BodyPart messageBodyPart = new MimeBodyPart();
  406.             messageBodyPart.setContent(body, "text/html");
  407.  
  408.             // Create a multipart message for attachment
  409.             Multipart multipart = new MimeMultipart();
  410.  
  411.             // Set text message part
  412.             multipart.addBodyPart(messageBodyPart);
  413.  
  414.             messageBodyPart = new MimeBodyPart();
  415.  
  416.             // Adjunto los archivos asociados al rut y plan firmados
  417.             for (int j = 0; j < ruta_docs_firmados.size(); j++) {
  418.                 messageBodyPart = new MimeBodyPart();
  419.                 String filename = ruta_docs_firmados.get(j);
  420.                 DataSource source = new FileDataSource(filename);
  421.                 messageBodyPart.setDataHandler(new DataHandler(source));
  422.                 messageBodyPart.setFileName(filename);
  423.                 // Trick is to add the content-id header here
  424.                 messageBodyPart.setHeader("Content-ID", "image_id");
  425.                 multipart.addBodyPart(messageBodyPart);
  426.  
  427.             }
  428.  
  429.             crunchifyMessage.setContent(multipart);
  430.  
  431.             System.out.println("\n5th ===> Enviando mensaje..");
  432.  
  433.             // Finally Send message
  434.             Transport.send(crunchifyMessage);
  435.  
  436.             long endTime = System.currentTimeMillis();
  437.             long duration = (endTime - startTime);
  438.  
  439.             System.out.println("\n6th ===> Email enviado, tomo " + ((endTime - startTime) / 1000) + "seg.");
  440.  
  441.         } catch (MessagingException e) {
  442.             e.printStackTrace();
  443.         } catch (UnsupportedEncodingException e) {
  444.             e.printStackTrace();
  445.         }
  446.     }
  447.  
  448.     public boolean createFolder(String path) {
  449.         File theDir = new File(path);
  450.         if (!theDir.exists()) {
  451.             try {
  452.                 theDir.mkdir();
  453.             } catch (SecurityException se) {
  454.                 System.out.println(se.toString());
  455.                 return false;
  456.             }
  457.         }
  458.         return true;
  459.     }
  460.  
  461.     private static void copyFileUsingFileStreams(File source, File dest) throws IOException {
  462.         InputStream input = null;
  463.         OutputStream output = null;
  464.         try {
  465.             input = new FileInputStream(source);
  466.             output = new FileOutputStream(dest);
  467.             byte[] buf = new byte[1024];
  468.             int bytesRead;
  469.             while ((bytesRead = input.read(buf)) > 0) {
  470.                 output.write(buf, 0, bytesRead);
  471.             }
  472.         } finally {
  473.             input.close();
  474.             output.close();
  475.         }
  476.     }
  477.  
  478.     private static String supvisor(java.lang.String rut) {
  479.         localhost.webservice.WebService service = new localhost.webservice.WebService();
  480.         localhost.webservice.WebServiceSoap port = service.getWebServiceSoap();
  481.         return port.supvisor(rut);
  482.     }
  483.  
  484.     public String getName(String name) {
  485.         if (name.equals("plantillasSolicitud_de_incorporacion_plus.pdf") || name.equals("plantillasSolicitud_de_incorporacion.pdf")) {
  486.             return "PPT";
  487.         } else if (name.equals("plantillasDeclaracion_personal_de_salud.pdf")) {
  488.             return "DPS";
  489.         } else if (name.equals("plantillasCosto_cero.pdf")) {
  490.             return "CCER";
  491.         } else if (name.equals("plantillasComprobante_de_ingresos_primas.pdf")) {
  492.             return "IPP";
  493.         } else if (name.equals("plantillasMandato_PAT.pdf")) {
  494.             return "MAN";
  495.         } else {
  496.             return "ERR";
  497.         }
  498.     }
  499.  
  500. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement