Example usage for javax.activation DataHandler DataHandler

List of usage examples for javax.activation DataHandler DataHandler

Introduction

In this page you can find the example usage for javax.activation DataHandler DataHandler.

Prototype

public DataHandler(URL url) 

Source Link

Document

Create a DataHandler instance referencing a URL.

Usage

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Read a binary file into a byte array</p>
 * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt"
 * @return byte array with full contents of file
 * @throws FileNotFoundException// w  w w  .j a va  2  s  .  co m
 * @throws IOException
 * @throws OutOfMemoryError
 * @throws MalformedURLException
 * @throws FTPException
 */
public byte[] readfilebin(String sFilePath)
        throws MalformedURLException, FTPException, FileNotFoundException, IOException, OutOfMemoryError {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.readfilebin(" + sFilePath + ")");
        DebugFile.incIdent();
    }

    byte[] aRetVal;
    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {

        URL oUrl = new URL(sFilePath);

        if (user().equals("anonymous") || user().length() == 0) {
            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
            if (DebugFile.trace)
                DebugFile.writeln("new DataHandler(" + oUrl.toString() + ")");
            DataHandler oHndlr = new DataHandler(oUrl);
            oHndlr.writeTo(oStrm);
            aRetVal = oStrm.toByteArray();
            oStrm.close();
        } else {
            if (null == oHttpCli) {
                oHttpCli = new DefaultHttpClient();
            } // fi (oHttpCli)

            oHttpCli.getCredentialsProvider().setCredentials(
                    new AuthScope(oUrl.getHost(), AuthScope.ANY_PORT, realm()),
                    new UsernamePasswordCredentials(user(), password()));
            HttpGet oGet = null;
            try {
                oGet = new HttpGet(sFilePath);
                HttpResponse oResp = oHttpCli.execute(oGet);
                HttpEntity oEnty = oResp.getEntity();
                int nLen = (int) oEnty.getContentLength();
                if (nLen > 0) {
                    aRetVal = new byte[nLen];
                    InputStream oBody = oEnty.getContent();
                    oBody.read(aRetVal, 0, nLen);
                    oBody.close();
                } else {
                    aRetVal = null;
                } // fi         
            } finally {
                oHttpCli.getConnectionManager().shutdown();
                oHttpCli = null;
            }
        } // fi (user is anonymous)
    } else if (sLower.startsWith("ftp://")) {

        FTPClient oFTPC = null;
        boolean bFTPSession = false;

        splitURI(sFilePath);

        try {

            if (DebugFile.trace)
                DebugFile.writeln("new FTPClient(" + sHost + ")");
            oFTPC = new FTPClient(sHost);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
            oFTPC.login(sUsr, sPwd);

            bFTPSession = true;

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
            oFTPC.chdir(sPath);

            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();

            oFTPC.setType(FTPTransferType.BINARY);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
            oFTPC.get(oStrm, sFile);

            aRetVal = oStrm.toByteArray();

            oStrm.close();
        } catch (FTPException ftpe) {
            throw new FTPException(ftpe.getMessage());
        } finally {
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.quit()");
            if (bFTPSession)
                oFTPC.quit();
        }

    } else {

        File oFile = new File(sFilePath);
        int iFLen = (int) oFile.length();

        BufferedInputStream oBfStrm;
        FileInputStream oInStrm;

        if (iFLen > 0) {
            aRetVal = new byte[iFLen];
            oInStrm = new FileInputStream(oFile);
            oBfStrm = new BufferedInputStream(oInStrm, iFLen);

            int iReaded = oBfStrm.read(aRetVal, 0, iFLen);

            oBfStrm.close();
            oInStrm.close();

            oInStrm = null;
            oFile = null;

        } else
            aRetVal = null;
    }

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.readfilebin()");
    }

    return aRetVal;
}

From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java

/**
 * @see org.jlibrary.core.repository.def.ResourcesModule#createResource(org.jlibrary.core.entities.Ticket, org.jlibrary.core.properties.ResourceNodeProperties)
 *//* w  ww .  j a va2 s. co m*/
public ResourceNode createResource(Ticket ticket, ResourceNodeProperties properties)
        throws RepositoryException, SecurityException {
    try {
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("createResource");

        call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("properties", XMLType.XSD_ANY, ParameterMode.IN);

        call.setReturnType(XMLType.XSD_ANY);

        // Change the binary property for an attachment
        byte[] content = (byte[]) properties.getProperty(ResourceNodeProperties.RESOURCE_CONTENT).getValue();
        if (content != null) {
            properties.setProperty(ResourceNodeProperties.RESOURCE_CONTENT, null);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
            call.addAttachmentPart(handler);
        }
        return (ResourceNode) call.invoke(new Object[] { ticket, properties });

    } catch (Exception e) {
        // I don't know if there is a better way to do this
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("SecurityException") != -1) {
            throw new SecurityException(fault.getFaultString());
        } else {
            throw new RepositoryException(fault.getFaultString());
        }
    }
}

From source file:org.olat.core.util.mail.manager.MailManagerImpl.java

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject,
        String body, List<File> attachments, MailerResult result) {

    try {/*  ww w.jav a2  s.  c o  m*/
        //   see FXOLAT-74: send all mails as <fromemail> (in config) to have a valid reverse lookup and therefore pass spam protection.
        // following doesn't work correctly, therefore add bounce-address in message already
        Address convertedFrom = getRawEmailFromAddress(from);
        MimeMessage msg = createMessage(convertedFrom);
        Address viewableFrom = createAddressWithName(WebappHelper.getMailConfig("mailFrom"),
                WebappHelper.getMailConfig("mailFromName"));
        msg.setFrom(viewableFrom);
        msg.setSubject(subject, "utf-8");
        // reply to can only be an address without name (at least for postfix!), see FXOLAT-312
        msg.setReplyTo(new Address[] { convertedFrom });

        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }

        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }

        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }

        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }

            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    logError("Tried to send mail wit attachment that does not exist::"
                            + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        logError("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        logError("", e);
        return null;
    }
}

From source file:com.knowgate.dfs.FileSystem.java

/**
 * <p>Read a text file into a String</p>
 * @param sFilePath Full path of file to be readed. Like "file:///tmp/myfile.txt" or "ftp://myhost:21/dir/myfile.txt"
 * @param sEncoding Text Encoding for file {UTF-8, ISO-8859-1, ...}<BR>
 * if <b>null</b> then if first two bytes of file are FF FE then UTF-8 will be assumed<BR>
 * else ISO-8859-1 will be assumed.//from   ww  w  .j  a v a 2 s.  co  m
 * @return String with full contents of file
 * @throws FileNotFoundException
 * @throws IOException
 * @throws OutOfMemoryError
 * @throws MalformedURLException
 * @throws FTPException
 */
public String readfilestr(String sFilePath, String sEncoding)
        throws MalformedURLException, FTPException, FileNotFoundException, IOException, OutOfMemoryError {

    if (DebugFile.trace) {
        DebugFile.writeln("Begin FileSystem.readfilestr(" + sFilePath + "," + sEncoding + ")");
        DebugFile.incIdent();
    }

    String sRetVal;
    String sLower = sFilePath.toLowerCase();

    if (sLower.startsWith("file://"))
        sFilePath = sFilePath.substring(7);

    if (sLower.startsWith("http://") || sLower.startsWith("https://")) {

        URL oUrl = new URL(sFilePath);
        if (user().equals("anonymous") || user().length() == 0) {
            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();
            DataHandler oHndlr = new DataHandler(oUrl);
            oHndlr.writeTo(oStrm);
            sRetVal = oStrm.toString(sEncoding);
            oStrm.close();
        } else {
            if (null == oHttpCli) {
                oHttpCli = new DefaultHttpClient();
            } // fi (oHttpCli)
            oHttpCli.getCredentialsProvider().setCredentials(
                    new AuthScope(oUrl.getHost(), AuthScope.ANY_PORT, realm()),
                    new UsernamePasswordCredentials(user(), password()));
            HttpGet oGet = null;
            try {

                oGet = new HttpGet(sFilePath);
                HttpResponse oResp = oHttpCli.execute(oGet);
                HttpEntity oEnty = oResp.getEntity();
                int nLen = (int) oEnty.getContentLength();
                if (nLen > 0) {
                    byte[] aRetVal = new byte[nLen];
                    InputStream oBody = oEnty.getContent();
                    oBody.read(aRetVal, 0, nLen);
                    oBody.close();
                    sRetVal = new String(aRetVal, sEncoding);
                } else {
                    sRetVal = "";
                } // fi         
            } finally {
                oHttpCli.getConnectionManager().shutdown();
                oHttpCli = null;
            }
        } // fi
    } else if (sLower.startsWith("ftp://")) {

        FTPClient oFTPC = null;
        boolean bFTPSession = false;

        splitURI(sFilePath);

        try {

            if (DebugFile.trace)
                DebugFile.writeln("new FTPClient(" + sHost + ")");
            oFTPC = new FTPClient(sHost);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.login(" + sUsr + "," + sPwd + ")");
            oFTPC.login(sUsr, sPwd);

            bFTPSession = true;

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.chdir(" + sPath + ")");
            oFTPC.chdir(sPath);

            ByteArrayOutputStream oStrm = new ByteArrayOutputStream();

            oFTPC.setType(FTPTransferType.BINARY);

            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.get(" + sPath + sFile + "," + sFile + ",false)");
            oFTPC.get(oStrm, sFile);

            sRetVal = oStrm.toString(sEncoding);

            oStrm.close();
        } catch (FTPException ftpe) {
            throw new FTPException(ftpe.getMessage());
        } finally {
            if (DebugFile.trace)
                DebugFile.writeln("FTPClient.quit()");
            try {
                if (bFTPSession)
                    oFTPC.quit();
            } catch (Exception ignore) {
            }
        }
    } else {

        File oFile = new File(sFilePath);
        int iFLen = (int) oFile.length();
        if (iFLen > 0) {
            byte byBuffer[] = new byte[3];
            char aBuffer[] = new char[iFLen];
            BufferedInputStream oBfStrm;
            FileInputStream oInStrm;
            InputStreamReader oReader;

            if (sEncoding == null) {
                oInStrm = new FileInputStream(oFile);
                oBfStrm = new BufferedInputStream(oInStrm, iFLen);

                sEncoding = new CharacterSetDetector().detect(oBfStrm, "ISO-8859-1");

                if (DebugFile.trace)
                    DebugFile.writeln("encoding is " + sEncoding);

                oBfStrm.close();
                oInStrm.close();
            } // fi

            oInStrm = new FileInputStream(oFile);
            oBfStrm = new BufferedInputStream(oInStrm, iFLen);

            oReader = new InputStreamReader(oBfStrm, sEncoding);

            int iReaded = oReader.read(aBuffer, 0, iFLen);

            // Skip FF FE character mark for Unidode files
            int iSkip = ((int) aBuffer[0] == 65279 || (int) aBuffer[0] == 65533 || (int) aBuffer[0] == 65534 ? 1
                    : 0);

            oReader.close();
            oBfStrm.close();
            oInStrm.close();

            oReader = null;
            oInStrm = null;
            oFile = null;

            sRetVal = new String(aBuffer, iSkip, iReaded - iSkip);
        } else
            sRetVal = "";
    } // fi (iFLen>0)

    if (DebugFile.trace) {
        DebugFile.decIdent();
        DebugFile.writeln("End FileSystem.readfilestr() : " + String.valueOf(sRetVal.length()));
    }

    return sRetVal;
}

From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java

public ResourceNode updateResourceNode(Ticket ticket, ResourceNodeProperties properties)
        throws RepositoryException, SecurityException {

    try {//from   w  w  w  .ja va  2 s  . com
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("updateResourceNode");
        call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("properties", XMLType.XSD_ANY, ParameterMode.IN);

        call.setReturnType(XMLType.XSD_ANY);

        // Change the binary property for an attachment
        byte[] content = (byte[]) properties.getProperty(ResourceNodeProperties.RESOURCE_CONTENT).getValue();
        if (content != null) {
            properties.setProperty(ResourceNodeProperties.RESOURCE_CONTENT, null);
            DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
            call.addAttachmentPart(handler);
        }
        return (ResourceNode) call.invoke(new Object[] { ticket, properties });

    } catch (Exception e) {
        // I don't know if there is a better way to do this
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("SecurityException") != -1) {
            throw new SecurityException(fault.getFaultString());
        } else {
            throw new RepositoryException(fault.getFaultString());
        }
    }
}

From source file:org.kuali.test.utils.Utils.java

/**
 * //from   w w  w. j a  va 2  s . c o  m
 * @param configuration
 * @param overrideEmail
 * @param testSuite
 * @param testHeader
 * @param testResults
 * @param errorCount
 * @param warningCount
 * @param successCount 
 */
public static void sendMail(KualiTestConfigurationDocument.KualiTestConfiguration configuration,
        String overrideEmail, TestSuite testSuite, TestHeader testHeader, List<File> testResults,
        int errorCount, int warningCount, int successCount) {

    if (StringUtils.isNotBlank(configuration.getEmailSetup().getFromAddress())
            && StringUtils.isNotBlank(configuration.getEmailSetup().getMailHost())) {

        String[] toAddresses = getEmailToAddresses(configuration, testSuite, testHeader);

        if (toAddresses.length > 0) {
            Properties props = new Properties();
            props.put("mail.smtp.host", configuration.getEmailSetup().getMailHost());
            Session session = Session.getDefaultInstance(props, null);

            try {
                Message msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(configuration.getEmailSetup().getFromAddress()));

                if (StringUtils.isBlank(overrideEmail)) {
                    for (String recipient : toAddresses) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
                    }
                } else {
                    StringTokenizer st = new StringTokenizer(overrideEmail, ",");
                    while (st.hasMoreTokens()) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(st.nextToken()));
                    }
                }

                StringBuilder subject = new StringBuilder(configuration.getEmailSetup().getSubject());
                subject.append(" - Platform: ");
                if (testSuite != null) {
                    subject.append(testSuite.getPlatformName());
                    subject.append(", TestSuite: ");
                    subject.append(testSuite.getName());
                } else {
                    subject.append(testHeader.getPlatformName());
                    subject.append(", Test: ");
                    subject.append(testHeader.getTestName());
                }

                subject.append(" - [errors=");
                subject.append(errorCount);
                subject.append(", warnings=");
                subject.append(warningCount);
                subject.append(", successes=");
                subject.append(successCount);
                subject.append("]");

                msg.setSubject(subject.toString());

                StringBuilder msgtxt = new StringBuilder(256);
                msgtxt.append("Please see test output in the following attached files:\n");

                for (File f : testResults) {
                    msgtxt.append(f.getName());
                    msgtxt.append("\n");
                }

                // create and fill the first message part
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(msgtxt.toString());

                // create the Multipart and add its parts to it
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(mbp1);

                for (File f : testResults) {
                    if (f.exists() && f.isFile()) {
                        // create the second message part
                        MimeBodyPart mbp2 = new MimeBodyPart();

                        // attach the file to the message
                        mbp2.setDataHandler(new DataHandler(new FileDataSource(f)));
                        mbp2.setFileName(f.getName());
                        mp.addBodyPart(mbp2);
                    }
                }

                // add the Multipart to the message
                msg.setContent(mp);

                // set the Date: header
                msg.setSentDate(new Date());

                Transport.send(msg);
            } catch (MessagingException ex) {
                LOG.warn(ex.toString(), ex);
            }
        }
    }
}

From source file:cl.cnsv.wsreporteproyeccion.service.ReporteProyeccionServiceImpl.java

@Override
public OutputObtenerCotizacionInternetVO obtenerCotizacionInternet(InputObtenerCotizacionInternetVO input) {

    //<editor-fold defaultstate="collapsed" desc="Inicio">
    LOGGER.info("Iniciando el metodo obtenerCotizacionInternet...");
    OutputObtenerCotizacionInternetVO output = new OutputObtenerCotizacionInternetVO();
    String codigo;//from  w  w w .j a va 2  s  .c  o  m
    String mensaje;
    XStream xStream = new XStream();
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Validacion de entrada">
    OutputVO outputValidacion = validator.validarObtenerCotizacionInternet(input);
    if (!Integer.valueOf(Propiedades.getFuncProperty("codigo.ok")).equals(outputValidacion.getCodigo())) {
        codigo = Integer.toString(outputValidacion.getCodigo());
        mensaje = outputValidacion.getMensaje();
        LOGGER.info(mensaje);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Ir a JasperServer">
    String numeroCotizacion = input.getNumeroCotizacion();
    InputCotizacionInternet inputCotizacionInternet = new InputCotizacionInternet();
    inputCotizacionInternet.setIdCotizacion(numeroCotizacion);
    String xmlInputCotizacionInternet = xStream.toXML(inputCotizacionInternet);
    LOGGER.info("Llamado a jasperserver: \n" + xmlInputCotizacionInternet);
    servicioJasperServer = new ServicioJasperServerJerseyImpl();
    ResultadoDocumentoVO outputJasperServer;
    try {
        outputJasperServer = servicioJasperServer.buscarArchivoByCotizacion(inputCotizacionInternet);
        String xmlOutputJasperServer = xStream.toXML(outputJasperServer);
        LOGGER.info("Respuesta de jasperserver: \n" + xmlOutputJasperServer);
        String codigoJasperServer = outputJasperServer.getCodigo();
        if (!Propiedades.getFuncProperty("jasperserver.ok.codigo").equals(codigoJasperServer)) {
            codigo = Propiedades.getFuncProperty("jasperserver.error.codigo");
            mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje");
            LOGGER.info(mensaje + ": " + outputJasperServer.getMensaje());
            output.setCodigo(codigo);
            output.setMensaje(mensaje);
            return output;
        }
    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("jasperserver.error.codigo");
        mensaje = Propiedades.getFuncProperty("jasperserver.error.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Ir a buscar datos email al servicio cotizador vida">
    ClienteServicioCotizadorVida clienteCotizadorVida;
    try {
        clienteCotizadorVida = new ClienteServicioCotizadorVida();
    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.codigo");
        mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.login.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }

    //Se busca el nombre del asegurado, glosa del plan y numero de propuesta        
    LOGGER.info("Llamado a getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlInputCotizacionInternet);
    OutputEmailCotizacionInternetVO outputEmail;
    try {
        outputEmail = clienteCotizadorVida.getDatosEmailCotizacionInternet(inputCotizacionInternet);
        String xmlOutputEmail = xStream.toXML(outputEmail);
        LOGGER.info("Respuesta de getDatosEmailCotizacionInternet - cotizadorVida: \n" + xmlOutputEmail);
        String codigoOutputEmail = outputEmail.getCodigo();
        if (!Propiedades.getFuncProperty("ws.cotizadorvida.codigo.ok").equals(codigoOutputEmail)) {
            codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo");
            mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje");
            LOGGER.info(mensaje + ": " + outputEmail.getMensaje());
            output.setCodigo(codigo);
            output.setMensaje(mensaje);
            return output;
        }

    } catch (Exception e) {
        codigo = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.codigo");
        mensaje = Propiedades.getFuncProperty("ws.cotizadorvida.error.datosemail.mensaje");
        LOGGER.error(mensaje + ": " + e.getMessage(), e);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Enviar correo con documento adjunto">
    String documento = outputJasperServer.getDocumento();
    try {
        EmailVO datosEmail = outputEmail.getDatosEmail();
        String htmlBody = Propiedades.getFuncProperty("email.html");
        String nombreAsegurable = datosEmail.getNombreAsegurable();
        if (nombreAsegurable == null) {
            nombreAsegurable = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[NOMBRE_ASEGURADO]", nombreAsegurable);
        String glosaPlan = datosEmail.getGlosaPlan();
        if (glosaPlan == null) {
            glosaPlan = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[GLOSA_PLAN]", glosaPlan);
        String numeroPropuesta = datosEmail.getNumeroPropuesta();
        if (numeroPropuesta == null) {
            numeroPropuesta = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[NRO_PROPUESTA]", numeroPropuesta);

        //Parametrizar imagenes
        String imgBulletBgVerde = Propiedades.getFuncProperty("email.images.bulletbgverde");
        if (imgBulletBgVerde == null) {
            imgBulletBgVerde = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_BULLET_BG_VERDE]", imgBulletBgVerde);

        String imgFace = Propiedades.getFuncProperty("email.images.face");
        if (imgFace == null) {
            imgFace = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FACE]", imgFace);

        String imgTwitter = Propiedades.getFuncProperty("email.images.twitter");
        if (imgTwitter == null) {
            imgTwitter = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_TWITTER]", imgTwitter);

        String imgYoutube = Propiedades.getFuncProperty("email.images.youtube");
        if (imgYoutube == null) {
            imgYoutube = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_YOUTUBE]", imgYoutube);

        String imgMail15 = Propiedades.getFuncProperty("email.images.mail00115");
        if (imgMail15 == null) {
            imgMail15 = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00115]", imgMail15);

        String imgFono = Propiedades.getFuncProperty("email.images.fono");
        if (imgFono == null) {
            imgFono = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_FONO]", imgFono);

        String imgMail16 = Propiedades.getFuncProperty("email.images.mail00116");
        if (imgMail16 == null) {
            imgMail16 = "";
        }
        htmlBody = StringUtils.replace(htmlBody, "$P[IMG_MAIL_00116]", imgMail16);

        byte[] attachmentData = Base64.decodeBase64(documento);

        final String username = Propiedades.getKeyProperty("email.username");
        final String encryptedPassword = Propiedades.getKeyProperty("email.password");
        String privateKeyFile = Propiedades.getConfProperty("KEY");
        CryptoUtil cryptoUtil = new CryptoUtil("", privateKeyFile);
        final String password = cryptoUtil.decryptData(encryptedPassword);
        final String auth = Propiedades.getFuncProperty("email.auth");
        final String starttls = Propiedades.getFuncProperty("email.starttls");
        final String host = Propiedades.getFuncProperty("email.host");
        final String port = Propiedades.getFuncProperty("email.port");

        //Log de datos de correo
        String strDatosCorreo = "username: " + username + "\n" + "auth: " + auth + "\n" + "host: " + host
                + "\n";
        LOGGER.info("Datos correo: \n".concat(strDatosCorreo));

        Properties props = new Properties();
        props.put("mail.smtp.auth", auth);
        if (!"0".equals(starttls)) {
            props.put("mail.smtp.starttls.enable", starttls);
        }
        props.put("mail.smtp.host", host);
        if (!"0".equals(port)) {
            props.put("mail.smtp.port", port);
        }
        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        String fileName = Propiedades.getFuncProperty("tmp.cotizacionInternet.file.name");
        fileName = fileName.replaceAll("%s", numeroPropuesta);
        fileName = fileName + ".pdf";

        // creates a new e-mail message
        Message msg = new MimeMessage(session);
        String from = Propiedades.getFuncProperty("email.from");
        msg.setFrom(new InternetAddress(from));
        //TODO considerar email de prueba o email del asegurado            
        String emailTo;
        if ("1".equals(Propiedades.getFuncProperty("email.to.test"))) {
            emailTo = Propiedades.getFuncProperty("email.to.mail");
        } else {
            emailTo = datosEmail.getEmail();
        }
        InternetAddress[] toAddresses = { new InternetAddress(emailTo) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        String subject = Propiedades.getFuncProperty("email.subject");
        msg.setSubject(subject);
        msg.setSentDate(new Date());

        // creates message part
        MimeBodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(htmlBody, "text/html");

        // creates multi-part
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        // adds attachments
        MimeBodyPart attachPart = new MimeBodyPart();
        DataSource dataSource = new ByteArrayDataSource(attachmentData, "application/pdf");
        attachPart.setDataHandler(new DataHandler(dataSource));
        attachPart.setFileName(fileName);
        multipart.addBodyPart(attachPart);

        // sets the multi-part as e-mail's content
        msg.setContent(multipart);

        // sends the e-mail
        Transport.send(msg);

    } catch (Exception ex) {
        codigo = Propiedades.getFuncProperty("email.error.codigo");
        mensaje = Propiedades.getFuncProperty("email.error.mensaje");
        LOGGER.error(mensaje + ": " + ex.getMessage(), ex);
        output.setCodigo(codigo);
        output.setMensaje(mensaje);
        return output;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Termino">
    codigo = Propiedades.getFuncProperty("codigo.ok");
    mensaje = Propiedades.getFuncProperty("mensaje.ok");
    output.setCodigo(codigo);
    output.setMensaje(mensaje);
    return output;
    //</editor-fold>

}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendMail(HttpServletRequest request, String providerName, int providerID, String baseUrl)
        throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtpm.csloxinfo.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from  w  ww. j  a  v a  2s. c  o m
    });

    //Create data for referral
    java.util.Date date = new java.util.Date();
    String s = providerID + (new Timestamp(date.getTime()).toString());
    MessageDigest m = null;
    try {
        m = MessageDigest.getInstance("MD5");

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(ProviderServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    m.update(s.getBytes(), 0, s.length());
    String md5 = (new BigInteger(1, m.digest()).toString(16));

    String title = "You have an invitation from your friend.";
    String receiver = request.getParameter("email");

    //        StringBuilder messageContentHtml = new StringBuilder();
    //        messageContentHtml.append(request.getParameter("message") + "<br />\n");
    //        messageContentHtml.append("You can become a provider from here:  " + baseUrl + "/Common/Provider/SignupReferral/" + md5);
    //        String messageContent = messageContentHtml.toString();
    String emailContent = "  <div style='background: url(cid:bg_Icon) no-repeat;background-color:#ebebec;text-align: center;width:610px;height:365px'>"
            + "            <p style='font-size:16px;padding-top: 45px; padding-bottom: 15px;'>Your friend <b>"
            + providerName + "</b> has invited you to complete purchase via</p>"
            + "            <a href='http://youtripper.com/Common/Provider/SignupReferral/" + md5
            + "' style='width: 160px;height: 50px;border-radius: 5px;border: 0;"
            + "                    background-color: #ff514e;font-size: 14px;font-weight: bolder;color: #fff;display: block;line-height: 50px;margin: 0 auto;text-decoration:none;' >Refferal Link</a>"
            + "            <p style='font-size:16px;margin:30px;'><b>" + providerName
            + "</b> will get 25 credit</p>"
            + "            <a href='http://youtripper.com' target='_blank'><img src='cid:gift_Icon' width='90' height='90'></a>"
            + "            <a href='http://youtripper.com' target='_blank' style='font-size:10px;color:#939598;text-decoration:none'><p>from www.youtripper.com</p></a>"
            + "            " + "            " + "        </div>";

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(emailContent, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    mp.addBodyPart(backgroundImage);
    mp.addBodyPart(giftImage);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    Transport.send(message);

    ReferralDTO referral = new ReferralDTO(providerID, receiver, String.valueOf(System.currentTimeMillis()),
            md5, 0);
    referralDAO.insertNewReferral(referral);
    return true;
}

From source file:Implement.Service.ProviderServiceImpl.java

@Override
public boolean sendEmailReferral(String data, int providerID, String baseUrl) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/*  www.j a  va  2 s.c  o m*/
    });

    String title = "You have an invitation from your friend.";

    JsonObject jsonObject = gson.fromJson(data, JsonObject.class);
    String content = jsonObject.get("content").getAsString();
    JsonArray sportsArray = jsonObject.get("emails").getAsJsonArray();
    ArrayList<String> listEmail = new ArrayList<>();
    if (sportsArray != null) {
        for (int i = 0; i < sportsArray.size(); i++) {
            listEmail.add(sportsArray.get(i).getAsString());
        }
    }

    String path = System.getProperty("catalina.base");
    MimeBodyPart backgroundImage = new MimeBodyPart();
    // attach the file to the message
    DataSource source = new FileDataSource(new File(path + "/webapps/Images/Email/backgroundImage.png"));
    backgroundImage.setDataHandler(new DataHandler(source));
    backgroundImage.setFileName("backgroundImage.png");
    backgroundImage.setDisposition(MimeBodyPart.INLINE);
    backgroundImage.setHeader("Content-ID", "<bg_Icon>"); // cid:image_cid

    MimeBodyPart giftImage = new MimeBodyPart();
    // attach the file to the message
    source = new FileDataSource(new File(path + "/webapps/Images/Email/emailGift.png"));
    giftImage.setDataHandler(new DataHandler(source));
    giftImage.setFileName("emailGift.png");
    giftImage.setDisposition(MimeBodyPart.INLINE);
    giftImage.setHeader("Content-ID", "<gift_Icon>"); // cid:image_cid

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "US-ASCII", "html");

    Multipart mp = new MimeMultipart("related");
    mp.addBodyPart(mbp1);
    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    String addresses = "";
    for (int i = 0; i < listEmail.size(); i++) {
        if (i < listEmail.size() - 1) {
            addresses = addresses + listEmail.get(i) + ",";
        } else {
            addresses = addresses + listEmail.get(i);
        }
    }

    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(addresses));

    message.setSubject(title);
    message.setContent(mp);
    message.saveChanges();
    try {
        Transport.send(message);
    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("sent");
    return true;
}

From source file:org.jlibrary.core.axis.client.AxisRepositoryDelegate.java

public Node updateContent(Ticket ticket, String docId, byte[] content)
        throws SecurityException, RepositoryException {
    try {/*from  ww  w . jav  a 2  s . co m*/
        call.removeAllParameters();

        call.setTargetEndpointAddress(new java.net.URL(endpoint));
        call.setOperationName("updateContent");
        call.addParameter("ticket", XMLType.XSD_ANY, ParameterMode.IN);
        call.addParameter("docId", XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter("content", XMLType.SOAP_BASE64BINARY, ParameterMode.IN);

        DataHandler handler = new DataHandler(new ByteArrayDataSource(content, "application/octet-stream"));
        call.addAttachmentPart(handler);

        call.setReturnType(XMLType.XSD_ANY);
        Node node = (Node) call.invoke(new Object[] { ticket, docId, content });
        return node;

    } catch (Exception e) {
        // I don't know if there is a better way to do this
        AxisFault fault = (AxisFault) e;
        if (fault.getFaultString().indexOf("SecurityException") != -1) {
            throw new SecurityException(fault.getFaultString());
        } else if (fault.getFaultString().indexOf("RepositoryAlreadyExistsException") != -1) {
            throw new RepositoryAlreadyExistsException();
        } else {
            throw new RepositoryException(fault.getFaultString());
        }
    }
}