Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fill;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.io.OutputStream;
- import java.io.PrintWriter;
- import java.io.UnsupportedEncodingException;
- import java.util.Date;
- import java.util.Properties;
- import java.util.Vector;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.activation.DataHandler;
- import javax.activation.DataSource;
- import javax.activation.FileDataSource;
- import javax.mail.Authenticator;
- import javax.mail.BodyPart;
- import javax.mail.Message;
- import javax.mail.MessagingException;
- import javax.mail.Multipart;
- import javax.mail.PasswordAuthentication;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.AddressException;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- public class Utils {
- static String[] plan1 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion.pdf"};
- static String[] plan2 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion_plus.pdf"};
- static String[] plan3 = {"plantillas\\Comprobante_de_ingresos_primas.pdf", "plantillas\\Declaracion_personal_de_salud.pdf", "plantillas\\Solicitud_de_incorporacion.pdf", "plantillas\\Costo_cero.pdf"};
- 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"};
- Vector<String> ruta_docs_firmados;
- String email = "", email_sup = "";
- archivo arc;
- public static String readFileISO85591(String in) {
- BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(new FileInputStream(in), "ISO-8859-1"));
- char[] buffer = new char[12288]; // character (not byte) buffer
- String s = "";
- while (true) {
- int charCount = br.read(buffer, 0, buffer.length);
- if (charCount == -1) {
- break;
- }
- s = String.valueOf(buffer, 0, charCount);
- }
- br.close();
- return s;
- } catch (Exception e) {
- if (br != null) {
- try {
- br.close();
- } catch (IOException ex) {
- Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- return e.toString();
- }
- }
- public static String readFileUTF8(String in) {
- BufferedReader br = null;
- try {
- br = new BufferedReader(new InputStreamReader(new FileInputStream(in), "UTF-8"));
- char[] buffer = new char[12288]; // character (not byte) buffer
- String s = "";
- while (true) {
- int charCount = br.read(buffer, 0, buffer.length);
- if (charCount == -1) {
- break;
- }
- s = String.valueOf(buffer, 0, charCount);
- }
- br.close();
- return s;
- } catch (Exception e) {
- if (br != null) {
- try {
- br.close();
- } catch (IOException ex) {
- Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
- }
- }
- return e.toString();
- }
- }
- public static boolean createLog(String nom, String val, String docname, String rut) {
- File theDir = new File("C:\\TOC\\tmp\\" + rut);
- if (!theDir.exists()) {
- try {
- theDir.mkdir();
- } catch (SecurityException se) {
- System.out.println(se.toString());
- return false;
- }
- }
- String[] nombres = nom.split("##");
- String[] valores = val.split("##");
- PrintWriter writer;
- try {
- String name = "";
- for (int i = (docname.length() - 1); i >= 0; i--) {
- if (docname.charAt(i) == '\\') {
- name = docname.substring(i + 1, docname.length() - 4);
- break;
- }
- }
- System.out.println("name: " + name);
- writer = new PrintWriter("C:\\TOC\\tmp\\" + rut + "\\" + name + ".txt", "UTF-8");
- int len;
- if (nombres.length > valores.length) {
- len = valores.length;
- } else {
- len = nombres.length;
- }
- for (int i = 0; i < len; i++) {
- writer.println(nombres[i] + "#" + valores[i] + "#");
- }
- writer.close();
- } catch (Exception ex) {
- System.out.println(ex.toString());
- return false;
- }
- return true;
- }
- public boolean moveDocs(String plan, Vector<String> ndoc, Vector<String> ruta, String rut, boolean pat, String extra) {
- Vector<String> nombreArchivo = new Vector<String>();
- Vector<String> rutaArchivo = new Vector<String>();
- ruta_docs_firmados = new Vector<String>();
- int res;
- String data[];
- System.out.println("-----------");
- for (int i = 0; i < ndoc.size(); i++) {
- System.out.println(ndoc.get(i));
- }
- System.out.println("-----------");
- if (plan.equals("Catastrófico")) {
- for (int i = 0; i < plan1.length; i++) {
- res = isThere(ndoc, plan1[i]);
- if (res == -1) {
- System.out.println("Docs plan 1 no encontrados");
- return false;
- }
- nombreArchivo.add(ndoc.get(res));
- rutaArchivo.add(ruta.get(res));
- }
- } else if (plan.equals("Catastrófico + Complementario")) {
- for (int i = 0; i < plan2.length; i++) {
- res = isThere(ndoc, plan2[i]);
- if (res == -1) {
- System.out.println(plan2[i] + " No encontrado");
- return false;
- }
- nombreArchivo.add(ndoc.get(res));
- rutaArchivo.add(ruta.get(res));
- }
- } else if (plan.equals("Catastrófico + Costo Cero")) {
- for (int i = 0; i < plan3.length; i++) {
- res = isThere(ndoc, plan3[i]);
- if (res == -1) {
- System.out.println("Docs plan 3 no encontrados");
- return false;
- }
- nombreArchivo.add(ndoc.get(res));
- rutaArchivo.add(ruta.get(res));
- }
- } else if (plan.equals("Catastrófico + Complementario + Costo Cero")) {
- for (int i = 0; i < plan4.length; i++) {
- res = isThere(ndoc, plan4[i]);
- if (res == -1) {
- System.out.println("Docs plan 4 no encontrados");
- return false;
- }
- nombreArchivo.add(ndoc.get(res));
- rutaArchivo.add(ruta.get(res));
- }
- } else {
- System.out.println("Plan: " + plan + " no existe");
- return false;
- }
- if (pat) {
- res = isThere(ndoc, "plantillas\\Mandato_PAT.pdf");
- if (res == -1) {
- System.out.println("Mandato PAT no encontrado");
- return false;
- }
- nombreArchivo.add(ndoc.get(res));
- rutaArchivo.add(ruta.get(res));
- }
- String npropuesta = "";
- try {
- DbHandler db = new DbHandler();
- npropuesta = db.getProposal(rut.replace("-", ""));
- if (npropuesta.equals("T00000000")) {
- npropuesta = db.insertProposal(rut.replace("-", ""));
- }
- System.out.println("propuestas de " + rut.replace("-", "") + " eliminadas: " + db.deleteProposal(rut.replace("-", "")));
- } catch (Exception e) {
- npropuesta = "";
- System.out.println("Error en asignacion numero de propuesta: " + e.toString());
- }
- if (!moveFiles(rutaArchivo, nombreArchivo, rut, npropuesta)) {
- System.out.println("Error al mover los archivos");
- return false;
- }
- if (!createRelatedFile(nombreArchivo, rut, plan, npropuesta, pat, extra)) {
- System.out.println("Error al crear el archivo de texto asociado");
- return false;
- }
- try {
- email = arc.email;
- String rut_ejec = arc.ejecutivo;
- System.out.println("Recuperando mail supervisor de: " + rut_ejec);
- String tmp = supvisor(rut_ejec);
- System.out.println("ans: " + tmp);
- String sep[] = tmp.split("##");
- email_sup = sep[1];
- } catch (Exception e) {
- }
- String RECIPIENT = "mariana.soto@toc.cl";
- String recipent[] = {email_sup, email, RECIPIENT};
- sendMail(rut, plan, recipent);
- return true;
- }
- public int isThere(Vector<String> names, String doc) {
- int found = -1;
- for (int i = 0; i < names.size(); i++) {
- if (names.get(i).replace("\\", "").equals(doc.replace("\\", ""))) {
- found = i;
- break;
- }
- }
- return found;
- }
- public boolean createRelatedFile(Vector<String> names, String rut, String plan, String nprop, boolean pat, String extra) {
- arc = new archivo(plan, rut);
- arc.loadValues("nprop", nprop);
- if (pat) {
- arc.loadValues("PAToPAC", "PAT");
- } else {
- arc.loadValues("PAToPAC", "PAC");
- }
- try {
- String sep[] = extra.split(",");
- for (int i = 0; i < sep.length; i += 2) {
- if (i + 1 >= sep.length) {
- break;
- }
- arc.loadValues(sep[i], sep[i + 1]);
- }
- } catch (Exception e) {
- }
- String nom, val;
- System.out.println("Analizando " + names.size() + " archivos");
- if (rut.charAt(rut.length() - 2) != '-') {
- rut = rut.substring(0, rut.length() - 1) + "-" + rut.substring(rut.length() - 1, rut.length());
- }
- for (int i = 0; i < names.size(); i++) {
- System.out.println("Agregando: " + "C:\\TOC\\tmp\\" + rut + "\\" + names.get(i).substring(10, names.get(i).length() - 3).replace("\\", "") + "txt");
- String tmp = readFileISO85591("C:\\TOC\\tmp\\" + rut + "\\" + names.get(i).substring(10, names.get(i).length() - 3).replace("\\", "") + "txt");
- String sep[] = tmp.split("#");
- nom = "";
- val = "";
- for (int j = 0; j < sep.length; j += 2) {
- if (j + 1 < sep.length) {
- //System.out.println(sep[j].trim() + " ; " + sep[j + 1].trim());
- nom += sep[j].trim() + "##";
- val += sep[j + 1].trim() + "##";
- }
- }
- arc.loadValues(nom, val);
- }
- arc.createFile(nprop);
- return true;
- }
- public boolean moveFiles(Vector<String> rutas, Vector<String> nombreArchivos, String rut, String nprop) {
- for (int i = 0; i < rutas.size(); i++) {
- System.out.println(i + ": " + rutas.get(i));
- }
- System.out.println(rut);
- System.out.println(nprop);
- rut = rut.replace("-", "");
- //createFolder("C:\\TOC\\completas\\VENDIG\\" + rut);
- createFolder("C:\\TOC\\completas\\" + rut);
- createFolder("C:\\TOC\\completas\\" + rut + "\\COBRANZA");
- createFolder("C:\\TOC\\completas\\" + rut + "\\DOCUMENTOS");
- createFolder("C:\\TOC\\completas\\" + rut + "\\LIQUIDACION");
- createFolder("C:\\TOC\\completas\\" + rut + "\\POLIZA");
- createFolder("C:\\TOC\\completas\\" + rut + "\\PROPUESTA");
- try {
- System.out.println("Moving " + rutas.size() + "Files");
- for (int i = 0; i < rutas.size(); i++) {
- File source = new File("C:\\xampp\\htdocs\\pdffirmado\\" + rutas.get(i));
- File dest = new File("C:\\TOC\\completas\\" + rut + "\\PROPUESTA\\" + nprop + "-" + rut.replace("-", "") + "-" + getName(nombreArchivos.get(i)));
- ruta_docs_firmados.add("C:\\TOC\\completas\\" + rut + "\\PROPUESTA\\" + nprop + "-" + rut.replace("-", "") + "-" + getName(nombreArchivos.get(i)));
- System.out.println("Moving: " + "C:\\xampp\\htdocs\\pdffirmado\\" + rutas.get(i) + " , to: " + "C:\\TOC\\completas\\VENDIG\\" + rut + "\\PROPUESTA\\" + nprop + "-" + rut.replace("-", "") + "-" + source.getName());
- copyFileUsingFileStreams(source, dest);
- /* File afile = new File("C:\\xampp\\htdocs\\pdffirmado\\" + rutas.get(i));
- if (afile.renameTo(new File("C:\\TOC\\completas\\" + rut + "\\" + afile.getName()))) {
- System.out.println("Moved");
- } else {
- return false;
- }*/
- }
- } catch (Exception e) {
- System.out.println("Erro: " + e.toString());
- e.printStackTrace();
- return false;
- }
- return true;
- }
- public void sendMail(String _rut, String _plan, String recipient[]) {
- final String rut = _rut, plan = _plan, toSend[] = recipient;
- Runnable r = new Runnable() {
- @Override
- public void run() {
- System.out.println("\n1st ===> Preparando el envio de mail..");
- final String asunto = "Plan firmado electronicamente cliente rut: " + rut;
- final String mensaje = "Estimado/a, <br><br>Se adjuntan documentos firmados electronicamente asociados a contratacion de plan. <br><br> Saludos.";
- final String sourceEmail = "ventas.moviles.recover@gmail.com"; // requires valid Gmail id
- final String password = "ventasrecover"; // correct password for Gmail id
- Properties props = new Properties();
- props.put("mail.smtp.host", "smtp.gmail.com");
- props.put("mail.smtp.port", "587");
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.starttls.enable", "true");
- System.out.println("\n2nd ===> Generando autentificacion..");
- Authenticator authentication = new Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(sourceEmail, password);
- }
- };
- Session session = Session.getInstance(props, authentication);
- //Llamamos a la funcion por cada destinarario
- for (int i = 0; i < toSend.length; i++) {
- generateAndSendEmail(session, toSend[0], asunto, mensaje);
- }
- }
- };
- new Thread(r).start();
- }
- private void generateAndSendEmail(Session session, String toEmail, String subject, String body) {
- try {
- long startTime = System.currentTimeMillis();
- System.out.println("\n3rd ===> Comenzando el armado del correo..");
- MimeMessage crunchifyMessage = new MimeMessage(session);
- crunchifyMessage.addHeader("Content-type", "text/HTML; charset=UTF-8");
- crunchifyMessage.addHeader("format", "flowed");
- crunchifyMessage.addHeader("Content-Transfer-Encoding", "8bit");
- crunchifyMessage.setFrom(new InternetAddress("ventas.moviles.recover@gmail.cl", "Metlife-Recover"));
- //crunchifyMessage.setReplyTo(InternetAddress.parse("noreply@toc.cl", false));
- crunchifyMessage.setSubject(subject, "UTF-8");
- crunchifyMessage.setSentDate(new Date());
- crunchifyMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));
- // Create the message body part
- BodyPart messageBodyPart = new MimeBodyPart();
- messageBodyPart.setContent(body, "text/html");
- // Create a multipart message for attachment
- Multipart multipart = new MimeMultipart();
- // Set text message part
- multipart.addBodyPart(messageBodyPart);
- messageBodyPart = new MimeBodyPart();
- // Adjunto los archivos asociados al rut y plan firmados
- for (int j = 0; j < ruta_docs_firmados.size(); j++) {
- messageBodyPart = new MimeBodyPart();
- String filename = ruta_docs_firmados.get(j);
- DataSource source = new FileDataSource(filename);
- messageBodyPart.setDataHandler(new DataHandler(source));
- messageBodyPart.setFileName(filename);
- // Trick is to add the content-id header here
- messageBodyPart.setHeader("Content-ID", "image_id");
- multipart.addBodyPart(messageBodyPart);
- }
- crunchifyMessage.setContent(multipart);
- System.out.println("\n5th ===> Enviando mensaje..");
- // Finally Send message
- Transport.send(crunchifyMessage);
- long endTime = System.currentTimeMillis();
- long duration = (endTime - startTime);
- System.out.println("\n6th ===> Email enviado, tomo " + ((endTime - startTime) / 1000) + "seg.");
- } catch (MessagingException e) {
- e.printStackTrace();
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- }
- public boolean createFolder(String path) {
- File theDir = new File(path);
- if (!theDir.exists()) {
- try {
- theDir.mkdir();
- } catch (SecurityException se) {
- System.out.println(se.toString());
- return false;
- }
- }
- return true;
- }
- private static void copyFileUsingFileStreams(File source, File dest) throws IOException {
- InputStream input = null;
- OutputStream output = null;
- try {
- input = new FileInputStream(source);
- output = new FileOutputStream(dest);
- byte[] buf = new byte[1024];
- int bytesRead;
- while ((bytesRead = input.read(buf)) > 0) {
- output.write(buf, 0, bytesRead);
- }
- } finally {
- input.close();
- output.close();
- }
- }
- private static String supvisor(java.lang.String rut) {
- localhost.webservice.WebService service = new localhost.webservice.WebService();
- localhost.webservice.WebServiceSoap port = service.getWebServiceSoap();
- return port.supvisor(rut);
- }
- public String getName(String name) {
- if (name.equals("plantillasSolicitud_de_incorporacion_plus.pdf") || name.equals("plantillasSolicitud_de_incorporacion.pdf")) {
- return "PPT";
- } else if (name.equals("plantillasDeclaracion_personal_de_salud.pdf")) {
- return "DPS";
- } else if (name.equals("plantillasCosto_cero.pdf")) {
- return "CCER";
- } else if (name.equals("plantillasComprobante_de_ingresos_primas.pdf")) {
- return "IPP";
- } else if (name.equals("plantillasMandato_PAT.pdf")) {
- return "MAN";
- } else {
- return "ERR";
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement