Java Examples for javax.mail.util.ByteArrayDataSource

The following java examples will help you to understand the usage of javax.mail.util.ByteArrayDataSource. These source code samples are taken from different open source projects.

Example 1
Project: elmis-master  File: ReportingRateNotificationController.java View source code
@RequestMapping(value = "/send/report", method = POST, headers = BaseController.ACCEPT_JSON)
public ResponseEntity<OpenLmisResponse> sendWithReportAttachment(@RequestBody MessageCollection messageParams, HttpServletRequest request) {
    Integer userId = loggedInUserId(request).intValue();
    /** extract message inputs from the payload **/
    String reportKey = messageParams.getReportKey();
    List<MessageDto> messages = messageParams.getMessages();
    String subject = messageParams.getSubject();
    String outputOption = messageParams.getOutputOption();
    Map<String, String[]> reportFilterParams = messageParams.getReportParams();
    /** Export report and process email attachment **/
    ByteArrayOutputStream byteArrayOutputStream = reportManager.exportReportBytesStream(userId, reportKey, reportFilterParams, outputOption);
    byte[] bytes = byteArrayOutputStream.toByteArray();
    DataSource attachmentDataSource;
    String fileName;
    switch(outputOption.toUpperCase()) {
        case XLS:
            attachmentDataSource = new ByteArrayDataSource(bytes, APPLICATION_VND_MS_EXCEL);
            fileName = REPORT_XLS;
            break;
        case HTML:
            attachmentDataSource = new ByteArrayDataSource(bytes, APPLICATION_HTML);
            fileName = REPORT_HTML;
            break;
        default:
            attachmentDataSource = new ByteArrayDataSource(bytes, APPLICATION_PDF);
            fileName = REPORT_PDF;
            break;
    }
    for (MessageDto dto : messages) {
        emailService.sendMimeMessage(dto.getContact(), subject, dto.getMessage(), fileName, attachmentDataSource);
    }
    return OpenLmisResponse.success("Success");
}
Example 2
Project: ishacrmserver-master  File: GAEEmail.java View source code
public static void send(EmailProp emailProp) throws UnsupportedEncodingException, MessagingException {
    // Client.ensureValidClient(client);
    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    Message message = new MimeMessage(session);
    String fromEmail = ConfigCRMDNA.get().toProp().fromEmail;
    if (fromEmail == null)
        fromEmail = User.SUPER_USER;
    Utils.ensureValidEmail(fromEmail);
    String fromNickName = fromEmail;
    InternetAddress from = new InternetAddress(fromEmail, fromNickName);
    message.setFrom(from);
    for (String email : emailProp.toEmailAddresses) {
        Utils.ensureValidEmail(email);
        InternetAddress to = new InternetAddress(email, email);
        message.addRecipient(Message.RecipientType.TO, to);
    }
    String applicationId = ApiProxy.getCurrentEnvironment().getAppId();
    if (applicationId != null)
        emailProp.subject = applicationId + ": " + emailProp.subject;
    message.setSubject(emailProp.subject);
    Multipart mp = new MimeMultipart();
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(emailProp.bodyHtml, "text/html");
    mp.addBodyPart(htmlPart);
    if (emailProp.csvAttachmentData != null) {
        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setFileName(emailProp.attachmentName);
        attachment.setDataHandler(new DataHandler(new ByteArrayDataSource(emailProp.csvAttachmentData.getBytes(), "text/csv")));
        mp.addBodyPart(attachment);
    }
    message.setContent(mp);
    Logger logger = Logger.getLogger(GAEEmail.class.getName());
    //handle quota exceeded exception
    try {
        Transport.send(message);
    } catch (OverQuotaException e) {
        logger.severe(Utils.stackTraceToString(e));
    }
}
Example 3
Project: ogham-master  File: StreamResourceHandler.java View source code
@Override
public void setData(BodyPart part, NamedResource resource, Attachment attachment) throws AttachmentResourceHandlerException {
    ByteResource streamResource = (ByteResource) resource;
    try (InputStream stream = streamResource.getInputStream()) {
        InputStream s = stream;
        // stream that is able to do it
        if (!stream.markSupported()) {
            s = new ByteArrayInputStream(IOUtils.toByteArray(stream));
        }
        // mark to reset at the start of the stream
        s.mark(Integer.MAX_VALUE);
        // detect the mimetype
        String mimetype = mimetypeProvider.detect(s).toString();
        // reset the stream
        s.reset();
        // set the content
        part.setDataHandler(new DataHandler(new ByteArrayDataSource(s, mimetype)));
    } catch (MimeTypeDetectionException e) {
        throw new AttachmentResourceHandlerException("Failed to attach " + resource.getName() + ". Mime type can't be detected", attachment, e);
    } catch (MessagingException e) {
        throw new AttachmentResourceHandlerException("Failed to attach " + resource.getName(), attachment, e);
    } catch (IOException e) {
        throw new AttachmentResourceHandlerException("Failed to attach " + resource.getName() + ". Stream can't be read", attachment, e);
    }
}
Example 4
Project: Resteasy-master  File: MimeMultipartProviderTest.java View source code
/**
     * @tpTestDetails Custom jaxb object in put request with @XopWithMultipartRelated
     * @tpSince RESTEasy 3.0.16
     */
@Test
public void testXop() throws Exception {
    MimeMultipartProviderClient proxy = ProxyBuilder.builder(MimeMultipartProviderClient.class, client.target(generateURL(""))).build();
    MimeMultipartProviderResource.Xop xop = new MimeMultipartProviderResource.Xop(new MimeMultipartProviderCustomer("billé"), new MimeMultipartProviderCustomer("monica"), "Hello Xop World!".getBytes(StandardCharsets.UTF_8), new DataHandler(new ByteArrayDataSource("Hello Xop World!".getBytes(StandardCharsets.UTF_8), MediaType.APPLICATION_OCTET_STREAM)));
    proxy.putXop(xop);
}
Example 5
Project: simple-java-mail-master  File: EmailBuilder.java View source code
/**
	 * Adds an attachment to the email message and generates the necessary {@link DataSource} with the given byte data. Then delegates to {@link
	 * #addAttachment(String, DataSource)}. At this point the datasource is actually a {@link ByteArrayDataSource}.
	 *
	 * @param name     The name of the extension (eg. filename including extension).
	 * @param data     The byte data of the attachment.
	 * @param mimetype The content type of the given data (eg. "plain/text", "image/gif" or "application/pdf").
	 * @see ByteArrayDataSource
	 * @see #addAttachment(String, DataSource)
	 */
public EmailBuilder addAttachment(@Nullable final String name, @Nonnull final byte[] data, @Nonnull final String mimetype) {
    checkNonEmptyArgument(data, "data");
    checkNonEmptyArgument(mimetype, "mimetype");
    final ByteArrayDataSource dataSource = new ByteArrayDataSource(data, mimetype);
    dataSource.setName(MiscUtil.encodeText(name));
    addAttachment(MiscUtil.encodeText(name), dataSource);
    return this;
}
Example 6
Project: axis2-java-master  File: BeanUtilTest.java View source code
/**
     * Test that for a {@link DataHandler} object, {@link BeanUtil} creates sequence of
     * events that allows Axiom to recognize the optimized binary.
     */
public void testGetOMElementWithDataHandlerArg() {
    DataHandler dh = new DataHandler(new ByteArrayDataSource(new byte[4096], "application/octet-stream"));
    OMElement element = BeanUtil.getOMElement(new QName("urn:ns1", "myop"), new Object[] { dh }, new QName("urn:ns1", "part"), true, new TypeTable());
    OMText text = (OMText) element.getFirstElement().getFirstOMChild();
    assertTrue(text.isOptimized());
    assertSame(dh, text.getDataHandler());
}
Example 7
Project: Broadleaf-eCommerce-master  File: MessageCreator.java View source code
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
    EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
    EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
    boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
    message.setTo(emailUser.getEmailAddress());
    message.setFrom(info.getFromAddress());
    message.setSubject(info.getSubject());
    if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
        message.setBcc(emailUser.getBCCAddresses());
    }
    if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
        message.setCc(emailUser.getCCAddresses());
    }
    String messageBody = info.getMessageBody();
    if (messageBody == null) {
        messageBody = buildMessageBody(info, props);
    }
    message.setText(messageBody, true);
    for (Attachment attachment : info.getAttachments()) {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
        message.addAttachment(attachment.getFilename(), dataSource);
    }
}
Example 8
Project: BroadleafCommerce-master  File: MessageCreator.java View source code
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
    EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
    EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
    boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
    message.setTo(emailUser.getEmailAddress());
    message.setFrom(info.getFromAddress());
    message.setSubject(info.getSubject());
    if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
        message.setBcc(emailUser.getBCCAddresses());
    }
    if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
        message.setCc(emailUser.getCCAddresses());
    }
    String messageBody = info.getMessageBody();
    if (messageBody == null) {
        messageBody = buildMessageBody(info, props);
    }
    message.setText(messageBody, true);
    for (Attachment attachment : info.getAttachments()) {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
        message.addAttachment(attachment.getFilename(), dataSource);
    }
}
Example 9
Project: commerce-master  File: MessageCreator.java View source code
@Override
public void prepare(MimeMessage mimeMessage) throws Exception {
    EmailTarget emailUser = (EmailTarget) props.get(EmailPropertyType.USER.getType());
    EmailInfo info = (EmailInfo) props.get(EmailPropertyType.INFO.getType());
    boolean isMultipart = CollectionUtils.isNotEmpty(info.getAttachments());
    MimeMessageHelper message = new MimeMessageHelper(mimeMessage, isMultipart, info.getEncoding());
    message.setTo(emailUser.getEmailAddress());
    message.setFrom(info.getFromAddress());
    message.setSubject(info.getSubject());
    if (emailUser.getBCCAddresses() != null && emailUser.getBCCAddresses().length > 0) {
        message.setBcc(emailUser.getBCCAddresses());
    }
    if (emailUser.getCCAddresses() != null && emailUser.getCCAddresses().length > 0) {
        message.setCc(emailUser.getCCAddresses());
    }
    String messageBody = info.getMessageBody();
    if (messageBody == null) {
        messageBody = buildMessageBody(info, props);
    }
    message.setText(messageBody, true);
    for (Attachment attachment : info.getAttachments()) {
        ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment.getData(), attachment.getMimeType());
        message.addAttachment(attachment.getFilename(), dataSource);
    }
}
Example 10
Project: cxf-master  File: JAXRSMultipartTest.java View source code
@Test
public void testXopWebClient() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore/xop";
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);
    bean.setProperties(Collections.singletonMap(org.apache.cxf.message.Message.MTOM_ENABLED, (Object) "true"));
    WebClient client = bean.createWebClient();
    WebClient.getConfig(client).getInInterceptors().add(new LoggingInInterceptor());
    WebClient.getConfig(client).getOutInterceptors().add(new LoggingOutInterceptor());
    WebClient.getConfig(client).getRequestContext().put("support.type.as.multipart", "true");
    client.type("multipart/related").accept("multipart/related");
    XopType xop = new XopType();
    xop.setName("xopName");
    InputStream is = getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd");
    byte[] data = IOUtils.readBytesFromStream(is);
    xop.setAttachinfo(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    xop.setAttachInfoRef(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    String bookXsd = IOUtils.readStringFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    xop.setAttachinfo2(bookXsd.getBytes());
    xop.setImage(getImage("/org/apache/cxf/systest/jaxrs/resources/java.jpg"));
    XopType xop2 = client.post(xop, XopType.class);
    String bookXsdOriginal = IOUtils.readStringFromStream(getClass().getResourceAsStream("/org/apache/cxf/systest/jaxrs/resources/book.xsd"));
    String bookXsd2 = IOUtils.readStringFromStream(xop2.getAttachinfo().getInputStream());
    assertEquals(bookXsdOriginal, bookXsd2);
    String bookXsdRef = IOUtils.readStringFromStream(xop2.getAttachInfoRef().getInputStream());
    assertEquals(bookXsdOriginal, bookXsdRef);
    String ctString = client.getResponse().getMetadata().getFirst("Content-Type").toString();
    MediaType mt = MediaType.valueOf(ctString);
    Map<String, String> params = mt.getParameters();
    assertEquals(4, params.size());
    assertNotNull(params.get("boundary"));
    assertNotNull(params.get("type"));
    assertNotNull(params.get("start"));
    assertNotNull(params.get("start-info"));
}
Example 11
Project: PacketCaptureTool-master  File: EMailUtil.java View source code
/**
     * 邮件��程�
     * 
     * @param host
     *            邮件�务器 如:smtp.qq.com
     * @param address
     *            ��邮件的地� 如:545099227@qq.com
     * @param from
     *            �自: wsx2miao@qq.com
     * @param password
     *            您的邮箱密�
     * @param to
     *            接收人
     * @param port
     *            端�(QQ:25)
     * @param subject
     *            邮件主题
     * @param content
     *            邮件内容
     * @throws Exception
     */
public static void SendEmail(String host, String address, String from, String password, String to, String port, String subject, String content) throws Exception {
    Multipart multiPart;
    String finalString = "";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", host);
    props.put("mail.smtp.user", address);
    props.put("mail.smtp.password", password);
    props.put("mail.smtp.port", port);
    props.put("mail.smtp.auth", "true");
    Log.i("Check", "done pops");
    Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");
    multiPart = new MimeMultipart();
    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(content);
    Log.i("check", "transport");
    Transport transport = session.getTransport("smtp");
    Log.i("check", "connecting");
    transport.connect(host, address, password);
    Log.i("check", "wana send");
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
    Log.i("check", "sent");
}
Example 12
Project: theone4ever_git-master  File: AttachmentTest.java View source code
//END SNIPPET: setup    
/**
     * Create a webservice client using wsdl url
     *
     * @throws Exception
     */
//START SNIPPET: webservice
public void testAttachmentViaWsInterface() throws Exception {
    Service service = Service.create(new URL("http://127.0.0.1:4204/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService"));
    assertNotNull(service);
    AttachmentWs ws = service.getPort(AttachmentWs.class);
    // retrieve the SOAPBinding
    SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();
    binding.setMTOMEnabled(true);
    String request = "tsztelak@gmail.com";
    // Byte array
    String response = ws.stringFromBytes(request.getBytes());
    assertEquals(request, response);
    // Data Source
    DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8");
    // not yet supported !
    //        response = ws.stringFromDataSource(source);
    //        assertEquals(request, response);
    // Data Handler
    response = ws.stringFromDataHandler(new DataHandler(source));
    assertEquals(request, response);
}
Example 13
Project: activityinfo-master  File: SmtpMailSender.java View source code
@Override
@LogException
public void send(Message message) {
    try {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject(message.getSubject(), Charsets.UTF_8.name());
        mimeMessage.addRecipients(RecipientType.TO, toArray(message.getTo()));
        mimeMessage.addRecipients(RecipientType.BCC, toArray(message.getBcc()));
        mimeMessage.setFrom(new InternetAddress(configuration.getProperty("smtp.from", "activityinfo@configure-me.com"), configuration.getProperty("smtp.from.name", "ActivityInfo")));
        if (message.getReplyTo() != null) {
            mimeMessage.setReplyTo(new Address[] { message.getReplyTo() });
        }
        String body;
        if (message.hasHtmlBody()) {
            body = message.getHtmlBody();
            mimeMessage.setDataHandler(new DataHandler(new HTMLDataSource(body)));
        } else {
            body = message.getTextBody();
            mimeMessage.setText(body, Charsets.UTF_8.name());
        }
        LOGGER.finest("message to " + message.getTo() + ":\n" + body);
        if (!message.getAttachments().isEmpty()) {
            Multipart multipart = new MimeMultipart();
            for (MessageAttachment attachment : message.getAttachments()) {
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(attachment.getFilename());
                DataSource src = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
                part.setDataHandler(new DataHandler(src));
                multipart.addBodyPart(part);
            }
            mimeMessage.setContent(multipart);
        }
        mimeMessage.saveChanges();
        Transport.send(mimeMessage);
    } catch (MessagingExceptionUnsupportedEncodingException |  e) {
        throw new RuntimeException(e);
    }
}
Example 14
Project: blynk-server-master  File: SparkPostMailClient.java View source code
@Override
public void sendHtmlWithAttachment(String to, String subj, String body, QrHolder[] attachments) throws Exception {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
    message.setSubject(subj, "UTF-8");
    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodyMessagePart = new MimeBodyPart();
    bodyMessagePart.setContent(body, "text/html; charset=UTF-8");
    multipart.addBodyPart(bodyMessagePart);
    for (QrHolder qrHolder : attachments) {
        MimeBodyPart attachmentsPart = new MimeBodyPart();
        attachmentsPart.setDataHandler(new DataHandler(new ByteArrayDataSource(qrHolder.data, "image/jpeg")));
        attachmentsPart.setFileName(qrHolder.makeQRFilename());
        multipart.addBodyPart(attachmentsPart);
    }
    message.setContent(multipart);
    Transport transport = session.getTransport();
    try {
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
    } finally {
        transport.close();
    }
    log.trace("Mail to {} was sent. Subj : {}, body : {}", to, subj, body);
}
Example 15
Project: camel-master  File: MailBinding.java View source code
protected String populateContentOnMimeMessage(MimeMessage part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException {
    String contentType = determineContentType(configuration, exchange);
    LOG.trace("Using Content-Type {} for MimeMessage: {}", contentType, part);
    String body = exchange.getIn().getBody(String.class);
    if (body == null) {
        body = "";
    }
    // always store content in a byte array data store to avoid various content type and charset issues
    DataSource ds = new ByteArrayDataSource(body, contentType);
    part.setDataHandler(new DataHandler(ds));
    // set the content type header afterwards
    part.setHeader("Content-Type", contentType);
    return contentType;
}
Example 16
Project: dsql-master  File: SendEmailAction.java View source code
@Override
protected void replace(String tag, String mimeType, String ext, byte[] bytes, Writer writer) throws IOException {
    try {
        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setFileName(tag + "." + ext);
        DataSource src = new ByteArrayDataSource(bytes, mimeType);
        attachment.setDataHandler(new DataHandler(src));
        String cid = tag + "." + ext;
        attachment.setHeader("Content-ID", "<" + cid + ">");
        multiPart.addBodyPart(attachment);
        if (mimeType.startsWith("image")) {
            writer.write("<div><br></div><div><img src=\"cid:" + cid + "\"><br></div>");
        } else {
            writer.write("<div><br></div><div><a href=\"cid:" + cid + "\"><br></div>");
        }
    } catch (MessagingException ex) {
        throw new IOException(ex);
    }
}
Example 17
Project: eGov-master  File: EmailService.java View source code
public boolean sendMailWithAttachment(final String toEmail, final String subject, final String mailBody, final String fileType, final String fileName, final Object attachment) {
    boolean isSent = false;
    if (applicationProperties.emailEnabled()) {
        MimeMessage message = mailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(message, true);
            mimeMessageHelper.setTo(toEmail);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(mailBody);
            ByteArrayDataSource source = new ByteArrayDataSource((byte[]) attachment, fileType);
            mimeMessageHelper.addAttachment(fileName, source);
        } catch (MessagingException e) {
            throw new MailParseException(e);
        } catch (IllegalArgumentException e) {
            throw new MailParseException(e);
        }
        mailSender.send(message);
    }
    return isSent;
}
Example 18
Project: Elasticsearch2Excel-plugin-master  File: MailAPI.java View source code
public void attachWB(XSSFWorkbook wb, String fileName) {
    messageBodyPart = new MimeBodyPart();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataSource ds = null;
    try {
        wb.write(baos);
        byte[] bytes = baos.toByteArray();
        ds = new ByteArrayDataSource(bytes, "application/excel");
        DataHandler dh = new DataHandler(ds);
        messageBodyPart.setDataHandler(dh);
        messageBodyPart.setFileName(fileName + ".xlsx");
        multipart.addBodyPart(messageBodyPart);
        message.setContent(multipart);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    }
}
Example 19
Project: everrest-master  File: DataSourceEntityProvider.java View source code
/**
     * Create DataSource instance dependent entity size. If entity has size less
     * then <tt>MAX_BUFFER_SIZE</tt> then {@link ByteArrayDataSource} will be
     * created otherwise {@link MimeFileDataSource} will be created.
     *
     * @param entityStream
     *         the {@link InputStream} of the HTTP entity
     * @param mimeType
     *         media type of data, HTTP header 'Content-type'
     * @return See {@link DataSource}
     * @throws IOException
     *         if any i/o errors occurs
     */
private DataSource createDataSource(InputStream entityStream, String mimeType) throws IOException {
    boolean overflow = false;
    byte[] buffer = new byte[8192];
    ApplicationContext context = ApplicationContext.getCurrent();
    int bufferSize = context.getEverrestConfiguration().getMaxBufferSize();
    ByteArrayOutputStream bos = new ByteArrayOutputStream(bufferSize);
    int bytesNum;
    while (!overflow && ((bytesNum = entityStream.read(buffer)) != -1)) {
        bos.write(buffer, 0, bytesNum);
        if (bos.size() > bufferSize) {
            overflow = true;
        }
    }
    if (overflow) {
        File file = FileCollector.getInstance().createFile();
        try (OutputStream fos = new FileOutputStream(file)) {
            bos.writeTo(fos);
            while ((bytesNum = entityStream.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesNum);
            }
        }
        return new MimeFileDataSource(file, mimeType);
    }
    return new ByteArrayDataSource(bos.toByteArray(), mimeType);
}
Example 20
Project: Funambol-Citadel-Connector-master  File: CitadelToRFC822.java View source code
public static String convertToRFC822(CitadelMailObject cmo, int cropTextAt, boolean allowAttachments) throws Exception {
    if (!cmo.hasData()) {
        throw new IllegalArgumentException("Submitted mail object has no data part");
    }
    MimeMessage mmessage = new MimeMessage((javax.mail.Session) null);
    InternetAddress fromAddr = new InternetAddress();
    fromAddr.setPersonal(cmo.getFrom());
    String rfca = (String) cmo.getProperties().get("rfca");
    if (rfca == null) {
        // try from + node instead
        String node = (String) cmo.getProperties().get("node");
        String from = cmo.getFrom() + "@" + node;
        from = from.replace(" ", "_");
        fromAddr.setAddress(from);
    } else {
        fromAddr.setAddress((String) cmo.getProperties().get("rfca"));
    }
    String data = cmo.getData();
    if (cropTextAt > 0 && data.length() > cropTextAt) {
        data = data.substring(0, cropTextAt);
    }
    if (cmo.getSubject() != null) {
        mmessage.setSubject(cmo.getSubject());
    }
    mmessage.setFrom(fromAddr);
    mmessage.setSentDate(cmo.getTime());
    if (allowAttachments) {
        MimeMultipart mpart = new MimeMultipart();
        MimeBodyPart contentPart = new MimeBodyPart();
        // todo: allow other type
        contentPart.setContent(data, "text/plain");
        mpart.addBodyPart(contentPart);
        Iterator<CitadelPart> partIterator = cmo.getAttachedParts().iterator();
        while (partIterator.hasNext()) {
            CitadelPart part = partIterator.next();
            MimeBodyPart attachment = new MimeBodyPart();
            ByteArrayDataSource ds = new ByteArrayDataSource(part.getPartData(), part.getPartType());
            attachment.setDataHandler(new DataHandler(ds));
            attachment.setFileName(part.getPartName());
            attachment.setDisposition("attachment");
            mpart.addBodyPart(attachment);
        }
        mmessage.setContent(mpart);
    } else {
        mmessage.setContent(data, "text/plain");
    }
    ByteArrayOutputStream rfcStream = new ByteArrayOutputStream();
    mmessage.writeTo(rfcStream);
    return rfcStream.toString();
}
Example 21
Project: jstore-struts2-mybatis3-master  File: Utils.java View source code
private static void collect(String text, Message msg) throws MessagingException, IOException {
    String subject = msg.getSubject();
    StringBuffer sb = new StringBuffer();
    sb.append("<HTML>\n");
    sb.append("<HEAD>\n");
    sb.append("<TITLE>\n");
    sb.append(subject + "\n");
    sb.append("</TITLE>\n");
    sb.append("</HEAD>\n");
    sb.append("<BODY>\n");
    sb.append("<H2>" + subject + "</H2>" + "\n");
    sb.append(text);
    sb.append("</BODY>\n");
    sb.append("</HTML>\n");
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(sb.toString(), "text/html")));
}
Example 22
Project: kfs-master  File: AttachmentMailerImpl.java View source code
/**
     * Construct and a send mime email message from an Attachment Mail Message.
     *
     * @param message the Attachement Mail Message
     * @throws MessagingException
     */
@Override
public void sendEmail(AttachmentMailMessage message) throws MessagingException {
    // Construct a mime message from the Attachment Mail Message
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeBodyPart body = new MimeBodyPart();
    body.setText(message.getMessage());
    MimeBodyPart attachment = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(body);
    ByteArrayDataSource ds = new ByteArrayDataSource(message.getContent(), message.getType());
    attachment.setDataHandler(new DataHandler(ds));
    attachment.setFileName(message.getFileName());
    multipart.addBodyPart(attachment);
    mimeMessage.setContent(multipart);
    MimeMailMessage mmm = new MimeMailMessage(mimeMessage);
    mmm.setTo((String[]) message.getToAddresses().toArray(new String[message.getToAddresses().size()]));
    mmm.setBcc((String[]) message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]));
    mmm.setCc((String[]) message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]));
    mmm.setSubject(message.getSubject());
    mmm.setFrom(message.getFromAddress());
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("sendEmail() - Sending message: " + mmm.toString());
        }
        mailSender.send(mmm.getMimeMessage());
    } catch (Exception e) {
        LOG.error("sendEmail() - Error sending email.", e);
        throw new RuntimeException(e);
    }
}
Example 23
Project: openxds-master  File: XdsTest.java View source code
protected OMElement addOneDocument(OMElement request, String document, String documentId) throws IOException {
    OMFactory fac = OMAbstractFactory.getOMFactory();
    OMNamespace ns = fac.createOMNamespace("urn:ihe:iti:xds-b:2007", null);
    OMElement docElem = fac.createOMElement("Document", ns);
    docElem.addAttribute("id", documentId, null);
    // A string, turn it into an StreamSource
    DataSource ds = new ByteArrayDataSource(document, "text/xml");
    DataHandler handler = new DataHandler(ds);
    OMText binaryData = fac.createOMText(handler, true);
    docElem.addChild(binaryData);
    Iterator iter = request.getChildrenWithLocalName("SubmitObjectsRequest");
    OMElement submitObjectsRequest = null;
    for (; iter.hasNext(); ) {
        submitObjectsRequest = (OMElement) iter.next();
        if (submitObjectsRequest != null)
            break;
    }
    submitObjectsRequest.insertSiblingAfter(docElem);
    return request;
}
Example 24
Project: pentaho-reporting-master  File: MailProcessor.java View source code
public static MimeMessage createReport(final MailDefinition mailDefinition, final Session session, final DataRow parameters) throws ReportProcessingException, ContentIOException, MessagingException {
    final MasterReport bodyReport = mailDefinition.getBodyReport();
    final String[] paramNames = parameters.getColumnNames();
    final ReportParameterValues parameterValues = bodyReport.getParameterValues();
    for (int i = 0; i < paramNames.length; i++) {
        final String paramName = paramNames[i];
        if (isParameterDefined(bodyReport, paramName)) {
            parameterValues.put(paramName, parameters.get(paramName));
        }
    }
    final ReportProcessTaskRegistry registry = ReportProcessTaskRegistry.getInstance();
    final String bodyType = mailDefinition.getBodyType();
    final ReportProcessTask processTask = registry.createProcessTask(bodyType);
    final ByteArrayOutputStream bout = new ByteArrayOutputStream();
    ReportProcessTaskUtil.configureBodyStream(processTask, bout, "report", null);
    processTask.setReport(bodyReport);
    if (processTask instanceof MultiStreamReportProcessTask) {
        final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) processTask;
        mtask.setBulkLocation(mtask.getBodyContentLocation());
        mtask.setBulkNameGenerator(new DefaultNameGenerator(mtask.getBodyContentLocation(), "data"));
        mtask.setUrlRewriter(new MailURLRewriter());
    }
    processTask.run();
    if (processTask.isTaskSuccessful() == false) {
        if (processTask.isTaskAborted()) {
            logger.info("EMail Task received interrupt.");
            return null;
        } else {
            logger.info("EMail Task failed:", processTask.getError());
            throw new ReportProcessingException("EMail Task failed", processTask.getError());
        }
    }
    final EmailRepository repository = new EmailRepository(session);
    final MimeBodyPart messageBodyPart = repository.getBodypart();
    final ByteArrayDataSource dataSource = new ByteArrayDataSource(bout.toByteArray(), processTask.getReportMimeType());
    messageBodyPart.setDataHandler(new DataHandler(dataSource));
    final int attachmentsSize = mailDefinition.getAttachmentCount();
    for (int i = 0; i < attachmentsSize; i++) {
        final MasterReport report = mailDefinition.getAttachmentReport(i);
        final String type = mailDefinition.getAttachmentType(i);
        final ContentLocation location = repository.getRoot();
        final ContentLocation bulkLocation = location.createLocation("attachment-" + i);
        final ReportProcessTask attachmentProcessTask = registry.createProcessTask(type);
        attachmentProcessTask.setBodyContentLocation(bulkLocation);
        attachmentProcessTask.setBodyNameGenerator(new DefaultNameGenerator(bulkLocation, "report"));
        attachmentProcessTask.setReport(report);
        if (attachmentProcessTask instanceof MultiStreamReportProcessTask) {
            final MultiStreamReportProcessTask mtask = (MultiStreamReportProcessTask) attachmentProcessTask;
            mtask.setBulkLocation(bulkLocation);
            mtask.setBulkNameGenerator(new DefaultNameGenerator(bulkLocation, "data"));
            mtask.setUrlRewriter(new MailURLRewriter());
        }
        attachmentProcessTask.run();
        if (attachmentProcessTask.isTaskSuccessful() == false) {
            if (attachmentProcessTask.isTaskAborted()) {
                logger.info("EMail Task received interrupt.");
            } else {
                logger.info("EMail Task failed:", attachmentProcessTask.getError());
                throw new ReportProcessingException("EMail Task failed", attachmentProcessTask.getError());
            }
        }
    }
    return repository.getEmail();
}
Example 25
Project: tomee-master  File: AttachmentTest.java View source code
//END SNIPPET: setup    
/**
     * Create a webservice client using wsdl url
     *
     * @throws Exception
     */
//START SNIPPET: webservice
public void testAttachmentViaWsInterface() throws Exception {
    Service service = Service.create(new URL("http://localhost:" + port + "/webservice-attachments/AttachmentImpl?wsdl"), new QName("http://superbiz.org/wsdl", "AttachmentWsService"));
    assertNotNull(service);
    AttachmentWs ws = service.getPort(AttachmentWs.class);
    // retrieve the SOAPBinding
    SOAPBinding binding = (SOAPBinding) ((BindingProvider) ws).getBinding();
    binding.setMTOMEnabled(true);
    String request = "tsztelak@gmail.com";
    // Byte array
    String response = ws.stringFromBytes(request.getBytes());
    assertEquals(request, response);
    // Data Source
    DataSource source = new ByteArrayDataSource(request.getBytes(), "text/plain; charset=UTF-8");
    // not yet supported !
    //        response = ws.stringFromDataSource(source);
    //        assertEquals(request, response);
    // Data Handler
    response = ws.stringFromDataHandler(new DataHandler(source));
    assertEquals(request, response);
}
Example 26
Project: wildfly-master  File: JaxrsMultipartProviderTestCase.java View source code
@Test
public void testJaxRsWithNoApplication() throws Exception {
    String result = performCall("myjaxrs/form");
    DataSource mimeData = new ByteArrayDataSource(result.getBytes(), "multipart/related");
    MimeMultipart mime = new MimeMultipart(mimeData);
    String string = (String) mime.getBodyPart(0).getContent();
    Assert.assertEquals("Hello", string);
    string = (String) mime.getBodyPart(1).getContent();
    Assert.assertEquals("World", string);
}
Example 27
Project: wonder-master  File: ERMailDataAttachment.java View source code
@Override
protected BodyPart getBodyPart() throws MessagingException {
    MimeBodyPart bp = new MimeBodyPart();
    if (getDataHandler() == null) {
        DataSource ds = new ByteArrayDataSource((byte[]) content(), _mimeType);
        bp.setDataHandler(new DataHandler(ds));
    } else {
        bp.setDataHandler(getDataHandler());
        if (_mimeType != null) {
            bp.setHeader("Content-type", _mimeType);
        }
    }
    if (contentID() != null) {
        bp.setHeader("Content-ID", contentID());
    }
    bp.setFileName(fileName());
    return bp;
}
Example 28
Project: wso2-axis2-transports-master  File: MailClient.java View source code
protected String sendMessage(ContentType contentType, byte[] message) throws Exception {
    String msgId = UUIDGenerator.getUUID();
    MimeMessage msg = new MimeMessage(session);
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(channel.getRecipient().getAddress()));
    msg.setFrom(new InternetAddress(channel.getSender().getAddress()));
    msg.setSentDate(new Date());
    msg.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgId);
    msg.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgId);
    DataHandler dh = new DataHandler(new ByteArrayDataSource(message, contentType.toString()));
    layout.setupMessage(msg, dh);
    Transport.send(msg);
    return msgId;
}
Example 29
Project: BlackboardVCPortlet-master  File: PresentationWSDaoImplTestBase.java View source code
private BlackboardPresentationResponse createRepoPresentation() throws Exception {
    InputStream is = new ByteArrayInputStream("fdsdfsfsdadsfasfda".getBytes());
    ByteArrayDataSource rawData = new ByteArrayDataSource(is, "video/mpeg");
    DataHandler dataHandler = new DataHandler(rawData);
    BlackboardPresentationResponse presenetation = dao.uploadPresentation(user.getUniqueId(), "test.elp", "aliens", dataHandler);
    presentations.put(presenetation.getPresentationId(), presenetation);
    return presenetation;
}
Example 30
Project: capedwarf-blue-master  File: MessageConverter.java View source code
private MimeBodyPart createAttachmentBodyPart(MailService.Attachment attachment) throws MessagingException {
    if (hasInvalidAttachmentFileType(attachment.getFileName())) {
        throw new IllegalArgumentException(String.format("Invalid attachment file type: %s", attachment));
    }
    DataSource source = new ByteArrayDataSource(attachment.getData(), "application/octet-stream");
    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(source));
    bodyPart.setFileName(attachment.getFileName());
    return bodyPart;
}
Example 31
Project: cleverbus-master  File: EmailServiceCamelSmtpImpl.java View source code
@Override
public void process(final Exchange exchange) throws Exception {
    Message in = exchange.getIn();
    in.setHeader("To", StringUtils.join(email.getRecipients(), ","));
    in.setHeader("From", StringUtils.isBlank(email.getFrom()) ? from : email.getFrom());
    in.setHeader("Subject", email.getSubject());
    in.setHeader("contentType", email.getContentType().getContentType());
    in.setBody(email.getBody());
    if (email.getAllAtachments() != null && !email.getAllAtachments().isEmpty()) {
        for (EmailAttachment attachment : email.getAllAtachments()) {
            in.addAttachment(attachment.getFileName(), new DataHandler(new ByteArrayDataSource(attachment.getContent(), "*/*")));
        }
    }
}
Example 32
Project: constellio-master  File: EmailServices.java View source code
public Message createMessage(String from, String subject, String body, List<MessageAttachment> attachments) throws MessagingException, IOException {
    Message message = new MimeMessage(Session.getInstance(System.getProperties()));
    if (StringUtils.isNotBlank(from)) {
        message.setFrom(new InternetAddress(from));
    }
    if (subject != null) {
        message.setSubject(subject);
    }
    MimeBodyPart content = new MimeBodyPart();
    if (body != null) {
        content.setText(body);
    } else {
        content.setText("");
    }
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(content);
    // add attachments
    if (attachments != null && !attachments.isEmpty()) {
        for (MessageAttachment messageAttachment : attachments) {
            MimeBodyPart attachment = new MimeBodyPart();
            DataSource source = new ByteArrayDataSource(messageAttachment.getInputStream(), messageAttachment.getMimeType());
            attachment.setDataHandler(new DataHandler(source));
            attachment.setFileName(messageAttachment.getAttachmentName());
            multipart.addBodyPart(attachment);
        }
    }
    message.setContent(multipart);
    return message;
}
Example 33
Project: droolsjbpm-master  File: SendIcal.java View source code
public void sendIcal(long taskId, String name, String summary, String description, int priority, Date startDate, User owner, User creator, Date createdOn, UserInfo userInfo, String type) throws Exception {
    MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
    mimetypes.addMimeTypes("text/calendar ics ICS");
    MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
    mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    System.out.println(connection);
    Session session = Session.getInstance(connection, null);
    // Define message
    MimeMessage message = new MimeMessage(session);
    message.setHeader("Content-Class", "urn:content-classes:calendarmessage");
    message.setHeader("Content-ID", "calendar_message");
    String creatorEmail = userInfo.getEmailForEntity(creator);
    message.setFrom(new InternetAddress(creatorEmail));
    message.setReplyTo(new InternetAddress[] { new InternetAddress(creatorEmail) });
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(userInfo.getEmailForEntity(owner)));
    message.setSubject("Task Assignment " + type + " Event: " + name);
    message.setSentDate(new Date());
    // Create a Multipart
    Multipart multipart = new MimeMultipart("alternative");
    // Add text message
    BodyPart messageBodyPart = new MimeBodyPart();
    String text = "Summary\n-------\n\n" + summary + "\n\nDescription\n-----------\n\n" + description;
    messageBodyPart.setText(text);
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(text, "text/plain; charset=UTF8;")));
    multipart.addBodyPart(messageBodyPart);
    // Add ical
    messageBodyPart = new MimeBodyPart();
    String filename = "ical-" + type + "-" + taskId + ".ics";
    messageBodyPart.setFileName(filename);
    messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
    messageBodyPart.setHeader("Content-ID", "calendar_message");
    String icalStr = getIcal(summary, description, startDate, priority, userInfo.getDisplayName(creator), creatorEmail, type);
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(icalStr, "text/calendar; charset=UTF8; ")));
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    message.saveChanges();
    Transport.send(message);
}
Example 34
Project: esxx-master  File: XMTPParser.java View source code
protected void convertBody(XMLStreamReader xr, Part part) throws XMLStreamException, MessagingException {
    ContentType content_type = new ContentType(part.getContentType());
    String base_type = content_type.getBaseType().toLowerCase();
    String prim_type = content_type.getPrimaryType().toLowerCase();
    String encoding[] = part.getHeader("Content-Transfer-Encoding");
    if (encoding != null && encoding.length >= 1 && // Xcerion workaround for old mails with
    encoding[0].equalsIgnoreCase("base64") && // stale Content-Transfer-Encoding header
    !encoding[0].isEmpty()) {
        // Encoded content; dump to disk and add a DataHandler for it
        EncodedDataSource ds = new EncodedDataSource(xr, part.getFileName(), part.getContentType(), encoding[0]);
        part.setDataHandler(new DataHandler(ds));
    } else if (prim_type.equals("multipart")) {
        part.setContent(convertMultiPartBody(xr, content_type), part.getContentType());
    } else if (base_type.equals("message/rfc822")) {
        part.setContent(convertMessage(xr), part.getContentType());
    } else if (base_type.endsWith("/xml") || base_type.endsWith("+xml")) {
        // By serializing to a byte array, we can control the XML
        // charset, and we select ASCII, which is 7-bit
        // clean. Otherwise, JavaMail might decide to base64-encode
        // the XML document, which is somewhat ugly-looking.
        ByteArrayOutputStream bo = new ByteArrayOutputStream(4096);
        DOMResult dr = null;
        XMLEventWriter ew;
        XMLEventReader er = XMLInputFactory.newInstance().createXMLEventReader(xr);
        javax.xml.stream.events.XMLEvent peek = er.peek();
        if (peek.isStartElement() && peek.asStartElement().getName().equals(new javax.xml.namespace.QName(MIMEParser.MIME_NAMESPACE, "Body"))) {
            er.nextEvent();
        }
        if (base_type.equals("text/x-html+xml")) {
            try {
                // Convert XHTML to HTML -- copy content into a DOM node first
                Document doc = DOMImplementationRegistry.newInstance().getDOMImplementation("XML 3.0").createDocument("", "root", null);
                dr = new DOMResult(doc.getDocumentElement());
                ew = XMLOutputFactory.newInstance().createXMLEventWriter(dr);
            } catch (Exception ex) {
                throw new XMLStreamException("Unable to transfrom 'text/x-html+xml' into 'text/xml': " + ex.getMessage(), ex);
            }
        } else {
            // Copy XML as-is
            ew = XMLOutputFactory.newInstance().createXMLEventWriter(bo, "ASCII");
        }
        for (int level = 0; ; ) {
            javax.xml.stream.events.XMLEvent ev = er.nextEvent();
            if (ev.isStartElement()) {
                ++level;
            } else if (ev.isEndElement()) {
                --level;
            }
            if (level >= 0) {
                ew.add(ev);
            } else {
                break;
            }
        }
        er.close();
        ew.flush();
        if (base_type.equals("text/x-html+xml")) {
            try {
                // Convert XHTML to HTML -- transform DOM node using HTML rules
                TransformerFactory tf = TransformerFactory.newInstance();
                tf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
                Transformer tr = tf.newTransformer();
                tr.setOutputProperty(OutputKeys.METHOD, "html");
                tr.setOutputProperty(OutputKeys.VERSION, "4.0");
                tr.setOutputProperty(OutputKeys.ENCODING, "us-ascii");
                tr.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                tr.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/html");
                Node node = dr.getNode().getFirstChild();
                while (node.getNodeType() != Node.ELEMENT_NODE) {
                    node = node.getNextSibling();
                    if (node == null) {
                        throw new XMLStreamException("Unable to transform 'text/x-html+xml' into 'text/xml': " + "Missing HTML node.");
                    }
                }
                tr.transform(new DOMSource(node), new StreamResult(bo));
            } catch (TransformerException ex) {
                throw new XMLStreamException("Unable to transform 'text/x-html+xml' into 'text/xml': " + ex.getMessage(), ex);
            }
            part.setDataHandler(new DataHandler(new ByteArrayDataSource(bo.toByteArray(), "text/html")));
        } else {
            part.setDataHandler(new DataHandler(new ByteArrayDataSource(bo.toByteArray(), part.getContentType())));
        }
    } else if (base_type.startsWith("text/")) {
        try {
            part.setDataHandler(new DataHandler(new ByteArrayDataSource(convertTextBody(xr), part.getContentType())));
        } catch (IOException ex) {
            throw new XMLStreamException("Unable to convert text Body: " + ex.getMessage(), ex);
        }
    } else {
        throw new XMLStreamException("Unsupported Content-Type/Content-Transfer-Encoding " + "combination");
    }
}
Example 35
Project: etk-component-master  File: DataSourceEntityProvider.java View source code
/**
   * Create DataSource instance dependent entity size. If entity has size less
   * then <tt>MAX_BUFFER_SIZE</tt> then {@link ByteArrayDataSource} will be
   * created otherwise {@link MimeFileDataSource} will be created.
   * 
   * @param entityStream the {@link InputStream} of the HTTP entity
   * @param mimeType media type of data, HTTP header 'Content-type'
   * @return See {@link DataSource}
   * @throws IOException if any i/o errors occurs
   */
private static DataSource createDataSource(InputStream entityStream, String mimeType) throws IOException {
    boolean overflow = false;
    byte[] buffer = new byte[8192];
    ApplicationContext context = ApplicationContextImpl.getCurrent();
    int bufferSize = (Integer) context.getAttributes().get(RequestHandler.WS_RS_BUFFER_SIZE);
    ByteArrayOutputStream bout = new ByteArrayOutputStream(bufferSize);
    int bytes = -1;
    while ((bytes = entityStream.read(buffer)) != -1) {
        bout.write(buffer, 0, bytes);
        if (bout.size() > bufferSize) {
            overflow = true;
            break;
        }
    }
    if (!overflow)
        // small data , use bytes
        return new ByteArrayDataSource(bout.toByteArray(), mimeType);
    // large data, use file
    final File file = File.createTempFile("datasource", "tmp");
    OutputStream fout = new FileOutputStream(file);
    // copy data from byte array in file
    bout.writeTo(fout);
    while ((bytes = entityStream.read(buffer)) != -1) fout.write(buffer, 0, bytes);
    fout.close();
    return new MimeFileDataSource(file, mimeType);
}
Example 36
Project: fcrepo-master  File: FedoraAPIMMTOMImpl.java View source code
/*
     * (non-Javadoc)
     * @see org.fcrepo.server.management.FedoraAPIMMTOM#getObjectXML(String pid
     * )*
     */
@Override
public DataHandler getObjectXML(String pid) {
    assertInitialized();
    try {
        MessageContext ctx = context.getMessageContext();
        InputStream in = m_management.getObjectXML(ReadOnlyContext.getSoapContext(ctx), pid, "UTF-8");
        ByteArrayOutputStream out = new ByteArrayOutputStream(2048);
        pipeStream(in, out);
        return new DataHandler(new ByteArrayDataSource(out.toByteArray(), "text/xml"));
    } catch (Throwable th) {
        LOG.error("Error getting object XML", th);
        throw CXFUtility.getFault(th);
    }
}
Example 37
Project: gyrex-jaxrs-application-master  File: MimeMultipartProvider.java View source code
public MimeMultipart readFrom(Class<MimeMultipart> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
    if (mediaType == null)
        mediaType = new MediaType("multipart", "form-data");
    ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
    try {
        return new MimeMultipart(ds);
    } catch (ParseException ex) {
        throw new WebApplicationException(ex, Status.BAD_REQUEST);
    } catch (MessagingException ex) {
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
Example 38
Project: javamail4android-master  File: MimeUtilityTest.java View source code
/**
     * Test that getEncoding returns a valid value even if the content
     * type is bad.  The return value should be a valid
     * Content-Transfer-Encoding, but mostly we care that it doesn't
     * throw NullPointerException.
     */
@Test
public void getEncodingBadContent() throws Exception {
    String content = "bad-content-type";
    ContentType type = null;
    try {
        type = new ContentType(content);
        fail(type.toString());
    } catch (ParseException expect) {
        if (type != null) {
            throw expect;
        }
    }
    ByteArrayDataSource bads = new ByteArrayDataSource("", content);
    bads.setName(null);
    assertTrue(encodings.contains(MimeUtility.getEncoding(bads)));
    assertTrue(encodings.contains(MimeUtility.getEncoding(new DataHandler(bads))));
    bads.setName("");
    assertTrue(encodings.contains(MimeUtility.getEncoding(bads)));
    assertTrue(encodings.contains(MimeUtility.getEncoding(new DataHandler(bads))));
    bads.setName(getClass().getName());
    assertTrue(encodings.contains(MimeUtility.getEncoding(bads)));
    assertTrue(encodings.contains(MimeUtility.getEncoding(new DataHandler(bads))));
}
Example 39
Project: jboss-seam-2.3.0.Final-Hibernate.3-master  File: UIAttachment.java View source code
@Override
public void encodeEnd(FacesContext context) throws IOException {
    DataSource ds = null;
    try {
        if (getValue() instanceof URL) {
            URL url = (URL) getValue();
            ds = new URLDataSource(url);
        } else if (getValue() instanceof File) {
            File file = (File) getValue();
            ds = new FileDataSource(file);
        } else if (getValue() instanceof String) {
            String string = (String) getValue();
            ds = new URLDataSource(FacesResources.getResource(string, context.getExternalContext()));
        } else if (getValue() instanceof InputStream) {
            InputStream is = (InputStream) getValue();
            ds = new ByteArrayDataSource(is, getContentType());
        } else if (getValue() != null && Reflections.isInstanceOf(getValue().getClass(), "org.jboss.seam.document.DocumentData")) {
            Method dataGetter = Reflections.getGetterMethod(getValue().getClass(), "data");
            Method docTypeGetter = Reflections.getGetterMethod(getValue().getClass(), "documentType");
            Object docType = Reflections.invokeAndWrap(docTypeGetter, getValue());
            Method mimeTypeGetter = Reflections.getGetterMethod(docType.getClass(), "mimeType");
            ds = new ByteArrayDataSource((byte[]) Reflections.invokeAndWrap(dataGetter, getValue()), (String) Reflections.invokeAndWrap(mimeTypeGetter, docType));
        } else if (getValue() != null && getValue().getClass().isArray()) {
            if (getValue().getClass().getComponentType().isAssignableFrom(Byte.TYPE)) {
                byte[] b = (byte[]) getValue();
                ds = new ByteArrayDataSource(b, getContentType());
            }
        }
        if (ds != null) {
            // Check the DataSource is available
            try {
                ds.getInputStream();
            } catch (Exception e) {
                if (value != null) {
                    throw new NullPointerException("Error accessing " + value);
                } else {
                    throw new NullPointerException("Error accessing " + getValueExpression("value").getExpressionString());
                }
            }
            MimeBodyPart attachment = new MimeBodyPart();
            // Need to manually set the contentid
            String contentId = RandomStringUtils.randomAlphabetic(20).toLowerCase();
            if (disposition.equals("inline")) {
                attachment.setContentID(new Header("<" + contentId + ">").getSanitizedValue());
            }
            attachment.setDataHandler(new DataHandler(ds));
            attachment.setFileName(new Header(getName(ds.getName())).getSanitizedValue());
            attachment.setDisposition(new Header(getDisposition()).getSanitizedValue());
            findMessage().getAttachments().add(attachment);
            if (getStatus() != null) {
                AttachmentStatus attachmentStatus = new AttachmentStatus();
                if (disposition.equals("inline")) {
                    attachmentStatus.setContentId(contentId);
                }
                Contexts.getEventContext().set(getStatus(), attachmentStatus);
            }
        }
    } catch (MessagingException e) {
        throw new FacesException(e.getMessage(), e);
    }
}
Example 40
Project: jersey-1.x-old-master  File: MimeMultipartProvider.java View source code
public MimeMultipart readFrom(Class<MimeMultipart> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
    if (mediaType == null)
        mediaType = new MediaType("multipart", "form-data");
    ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
    try {
        return new MimeMultipart(ds);
    } catch (ParseException ex) {
        throw new WebApplicationException(ex, Status.BAD_REQUEST);
    } catch (MessagingException ex) {
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
Example 41
Project: jersey-old-master  File: MimeMultipartProvider.java View source code
public MimeMultipart readFrom(Class<MimeMultipart> type, Type genericType, Annotation annotations[], MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
    if (mediaType == null)
        mediaType = new MediaType("multipart", "form-data");
    ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
    try {
        return new MimeMultipart(ds);
    } catch (ParseException ex) {
        throw new WebApplicationException(ex, Status.BAD_REQUEST);
    } catch (MessagingException ex) {
        throw new WebApplicationException(ex, Status.INTERNAL_SERVER_ERROR);
    }
}
Example 42
Project: Labos3eSup-master  File: Smtp.java View source code
public void addPartFichier(byte[] file, String name) {
    if (messageMultipart == null) {
        messageMultipart = new MimeMultipart();
        multipart = true;
    }
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    DataSource dataSource = new ByteArrayDataSource(file, "application/octet-stream");
    try {
        mimeBodyPart.setDataHandler(new DataHandler(dataSource));
        mimeBodyPart.setFileName(name);
        messageMultipart.addBodyPart(mimeBodyPart);
    } catch (MessagingException ex) {
        Logger.getLogger(Smtp.class.getName()).log(Level.SEVERE, null, ex);
        correct = false;
    }
}
Example 43
Project: Official-Library-Android-master  File: BVMoMmsClient.java View source code
/**
	 * Gets the content of a message with a 'messageId' sent to the 'registrationId'
	 * 
	 * @param registrationId the registration id (short number) that receives the messages
	 * @param messageId the message id (obtained in getAllMessages function)
	 * @return the MmsMessage  the complete MmsMessage (including attachments)
	 * @throws BlueviaException
	 * @throws IOException 
	 */
public MmsMessage getMessage(String registrationId, String messageId) throws BlueviaException, IOException {
    // Check params
    checkRegistrationId(registrationId);
    if (Utils.isEmpty(messageId))
        throw new BlueviaException("Bad request: Message identifier is either null or empty", BlueviaException.BAD_REQUEST_EXCEPTION);
    // Build feed uri for the request
    String feedUri = "/" + registrationId + RECEIVED_MESSAGES + "/" + messageId;
    HashMap<String, String> parameters = new HashMap<String, String>();
    parameters.put(XmlConstants.PARAM_VERSION_KEY, XmlConstants.VERSION_1);
    MmsMessage res = null;
    InputStream is = null;
    try {
        String uri = mBaseUri + feedUri;
        GenericResponse response = mConnector.retrieve(uri, parameters);
        is = response.getAdditionalData().getBody();
        HashMap<String, String> responseHeaders = response.getAdditionalData().getHeaders();
        String contentType = responseHeaders.get("Content-Type");
        ByteArrayDataSource ds = new ByteArrayDataSource(is, contentType);
        MimeMultipart multipart = new MimeMultipart(ds);
        res = mMultipartParser.parseMultipart(multipart);
    } catch (ConnectorException e) {
        if (e.getAdditionalData().getBody() == null)
            throw e;
        else {
            is = e.getAdditionalData().getBody();
            String error = parseError(is);
            String completeError = e.getMessage();
            if (error != null)
                completeError += ": " + error;
            throw new ConnectorException(completeError, e.getCode());
        }
    } catch (MessagingException e) {
        throw new ParseException("Unable to parse multpart", e);
    } finally {
        closeStream(is);
    }
    return res;
}
Example 44
Project: Official-Library-Java-master  File: BVMoMmsClient.java View source code
@Override
protected Entity retrieve(String feedUri, HashMap<String, String> parameters) throws IOException, BlueviaException {
    if (feedUri.endsWith(RECEIVED_MESSAGES)) {
        return super.retrieve(feedUri, parameters);
    } else {
        String uri = mBaseUri + feedUri;
        GenericResponse response = mConnector.retrieve(uri, parameters);
        InputStream is = response.getAdditionalData().getBody();
        HashMap<String, String> responseHeaders = response.getAdditionalData().getHeaders();
        try {
            String contentType = responseHeaders.get("Content-Type");
            String contentDisp = responseHeaders.get("Content-Disposition");
            MultipartMmsParser parser = new MultipartMmsParser(mParser);
            if (feedUri.contains(ATTACHMENTS_FEED_PATH)) {
                if (contentType.contains("xml") || contentType.contains("smil") || contentType.contains("text"))
                    return (Entity) parser.buildMimeContent(contentType, contentDisp, Utils.convertStreamToString(is), true);
                else
                    return (Entity) parser.buildMimeContent(contentType, contentDisp, is, true);
            } else {
                ByteArrayDataSource ds = new ByteArrayDataSource(is, contentType);
                MimeMultipart multipart = new MimeMultipart(ds);
                return (Entity) parser.parseMultipart(multipart);
            }
        } catch (MessagingException e) {
            throw new ParseException("Error parsing multipart: " + e.getLocalizedMessage(), e);
        } finally {
            if (is != null)
                is.close();
        }
    }
}
Example 45
Project: resin-master  File: MailService.java View source code
/**
   * Sends to a mailbox
   */
public void sendWithAttachment(String subject, String textBody, String attachmentType, String attachmentName, InputStream is) {
    try {
        MimeMessage msg = new MimeMessage(getSession());
        if (_from.length > 0)
            msg.addFrom(_from);
        msg.addRecipients(RecipientType.TO, _to);
        if (subject != null)
            msg.setSubject(subject);
        // msg.setContent(textBody, "multipart/mime");
        MimeMultipart multipart = new MimeMultipart();
        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(textBody);
        multipart.addBodyPart(textBodyPart);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        TempBuffer tb = TempBuffer.allocate();
        byte[] buffer = tb.getBuffer();
        int len;
        while ((len = is.read(buffer, 0, buffer.length)) >= 0) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        byte[] content = bos.toByteArray();
        TempBuffer.free(tb);
        DataSource dataSource = new ByteArrayDataSource(content, attachmentType);
        MimeBodyPart pdfBodyPart = new MimeBodyPart();
        pdfBodyPart.setDataHandler(new DataHandler(dataSource));
        pdfBodyPart.setFileName(attachmentName);
        multipart.addBodyPart(pdfBodyPart);
        msg.setContent(multipart);
        send(msg);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 46
Project: restlet-framework-java-master  File: MultipartProvider.java View source code
/**
     * @see MessageBodyReader#readFrom(Class, Type, Annotation[], MediaType,
     *      MultivaluedMap, InputStream)
     */
public Multipart readFrom(Class<Multipart> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpResponseHeaders, InputStream entityStream) throws IOException {
    final String contentType = "multipart/form-data";
    final DataSource ds = new ByteArrayDataSource(entityStream, contentType);
    try {
        return new MimeMultipart(ds);
    } catch (MessagingException e) {
        if (e.getCause() instanceof IOException) {
            throw (IOException) e.getCause();
        }
        final IOException ioExc = new IOException("Could not deserialize the data to a Multipart");
        ioExc.initCause(e);
        throw ioExc;
    }
}
Example 47
Project: seam-2.2-master  File: UIAttachment.java View source code
@Override
public void encodeEnd(FacesContext context) throws IOException {
    DataSource ds = null;
    try {
        if (getValue() instanceof URL) {
            URL url = (URL) getValue();
            ds = new URLDataSource(url);
        } else if (getValue() instanceof File) {
            File file = (File) getValue();
            ds = new FileDataSource(file);
        } else if (getValue() instanceof String) {
            String string = (String) getValue();
            ds = new URLDataSource(FacesResources.getResource(string, context.getExternalContext()));
        } else if (getValue() instanceof InputStream) {
            InputStream is = (InputStream) getValue();
            ds = new ByteArrayDataSource(is, getContentType());
        } else if (getValue() != null && Reflections.isInstanceOf(getValue().getClass(), "org.jboss.seam.document.DocumentData")) {
            Method dataGetter = Reflections.getGetterMethod(getValue().getClass(), "data");
            Method docTypeGetter = Reflections.getGetterMethod(getValue().getClass(), "documentType");
            Object docType = Reflections.invokeAndWrap(docTypeGetter, getValue());
            Method mimeTypeGetter = Reflections.getGetterMethod(docType.getClass(), "mimeType");
            ds = new ByteArrayDataSource((byte[]) Reflections.invokeAndWrap(dataGetter, getValue()), (String) Reflections.invokeAndWrap(mimeTypeGetter, docType));
        } else if (getValue() != null && getValue().getClass().isArray()) {
            if (getValue().getClass().getComponentType().isAssignableFrom(Byte.TYPE)) {
                byte[] b = (byte[]) getValue();
                ds = new ByteArrayDataSource(b, getContentType());
            }
        }
        if (ds != null) {
            // Check the DataSource is available
            try {
                ds.getInputStream();
            } catch (Exception e) {
                if (value != null) {
                    throw new NullPointerException("Error accessing " + value);
                } else {
                    throw new NullPointerException("Error accessing " + getValueExpression("value").getExpressionString());
                }
            }
            MimeBodyPart attachment = new MimeBodyPart();
            // Need to manually set the contentid
            String contentId = RandomStringUtils.randomAlphabetic(20).toLowerCase();
            if (disposition.equals("inline")) {
                attachment.setContentID(new Header("<" + contentId + ">").getSanitizedValue());
            }
            attachment.setDataHandler(new DataHandler(ds));
            attachment.setFileName(new Header(getName(ds.getName())).getSanitizedValue());
            attachment.setDisposition(new Header(getDisposition()).getSanitizedValue());
            findMessage().getAttachments().add(attachment);
            if (getStatus() != null) {
                AttachmentStatus attachmentStatus = new AttachmentStatus();
                if (disposition.equals("inline")) {
                    attachmentStatus.setContentId(contentId);
                }
                Contexts.getEventContext().set(getStatus(), attachmentStatus);
            }
        }
    } catch (MessagingException e) {
        throw new FacesException(e.getMessage(), e);
    }
}
Example 48
Project: seam-revisited-master  File: UIAttachment.java View source code
@Override
public void encodeEnd(FacesContext context) throws IOException {
    DataSource ds = null;
    try {
        if (getValue() instanceof URL) {
            URL url = (URL) getValue();
            ds = new URLDataSource(url);
        } else if (getValue() instanceof File) {
            File file = (File) getValue();
            ds = new FileDataSource(file);
        } else if (getValue() instanceof String) {
            String string = (String) getValue();
            ds = new URLDataSource(FacesResources.getResource(string, context.getExternalContext()));
        } else if (getValue() instanceof InputStream) {
            InputStream is = (InputStream) getValue();
            ds = new ByteArrayDataSource(is, getContentType());
        } else if (getValue() != null && Reflections.isInstanceOf(getValue().getClass(), "org.jboss.seam.document.DocumentData")) {
            Method dataGetter = Reflections.getGetterMethod(getValue().getClass(), "data");
            Method docTypeGetter = Reflections.getGetterMethod(getValue().getClass(), "documentType");
            Object docType = Reflections.invokeAndWrap(docTypeGetter, getValue());
            Method mimeTypeGetter = Reflections.getGetterMethod(docType.getClass(), "mimeType");
            ds = new ByteArrayDataSource((byte[]) Reflections.invokeAndWrap(dataGetter, getValue()), (String) Reflections.invokeAndWrap(mimeTypeGetter, docType));
        } else if (getValue() != null && getValue().getClass().isArray()) {
            if (getValue().getClass().getComponentType().isAssignableFrom(Byte.TYPE)) {
                byte[] b = (byte[]) getValue();
                ds = new ByteArrayDataSource(b, getContentType());
            }
        }
        if (ds != null) {
            // Check the DataSource is available
            try {
                ds.getInputStream();
            } catch (Exception e) {
                if (value != null) {
                    throw new NullPointerException("Error accessing " + value);
                } else {
                    throw new NullPointerException("Error accessing " + getValueExpression("value").getExpressionString());
                }
            }
            MimeBodyPart attachment = new MimeBodyPart();
            // Need to manually set the contentid
            String contentId = RandomStringUtils.randomAlphabetic(20).toLowerCase();
            if (disposition.equals("inline")) {
                attachment.setContentID(new Header("<" + contentId + ">").getSanitizedValue());
            }
            attachment.setDataHandler(new DataHandler(ds));
            attachment.setFileName(new Header(getName(ds.getName())).getSanitizedValue());
            attachment.setDisposition(new Header(getDisposition()).getSanitizedValue());
            findMessage().getAttachments().add(attachment);
            if (getStatus() != null) {
                AttachmentStatus attachmentStatus = new AttachmentStatus();
                if (disposition.equals("inline")) {
                    attachmentStatus.setContentId(contentId);
                }
                Contexts.getEventContext().set(getStatus(), attachmentStatus);
            }
        }
    } catch (MessagingException e) {
        throw new FacesException(e.getMessage(), e);
    }
}
Example 49
Project: seam2jsf2-master  File: UIAttachment.java View source code
@Override
public void encodeEnd(FacesContext context) throws IOException {
    DataSource ds = null;
    try {
        if (getValue() instanceof URL) {
            URL url = (URL) getValue();
            ds = new URLDataSource(url);
        } else if (getValue() instanceof File) {
            File file = (File) getValue();
            ds = new FileDataSource(file);
        } else if (getValue() instanceof String) {
            String string = (String) getValue();
            ds = new URLDataSource(FacesResources.getResource(string, context.getExternalContext()));
        } else if (getValue() instanceof InputStream) {
            InputStream is = (InputStream) getValue();
            ds = new ByteArrayDataSource(is, getContentType());
        } else if (getValue() != null && Reflections.isInstanceOf(getValue().getClass(), "org.jboss.seam.document.DocumentData")) {
            Method dataGetter = Reflections.getGetterMethod(getValue().getClass(), "data");
            Method docTypeGetter = Reflections.getGetterMethod(getValue().getClass(), "documentType");
            Object docType = Reflections.invokeAndWrap(docTypeGetter, getValue());
            Method mimeTypeGetter = Reflections.getGetterMethod(docType.getClass(), "mimeType");
            ds = new ByteArrayDataSource((byte[]) Reflections.invokeAndWrap(dataGetter, getValue()), (String) Reflections.invokeAndWrap(mimeTypeGetter, docType));
        } else if (getValue() != null && getValue().getClass().isArray()) {
            if (getValue().getClass().getComponentType().isAssignableFrom(Byte.TYPE)) {
                byte[] b = (byte[]) getValue();
                ds = new ByteArrayDataSource(b, getContentType());
            }
        }
        if (ds != null) {
            // Check the DataSource is available
            try {
                ds.getInputStream();
            } catch (Exception e) {
                if (value != null) {
                    throw new NullPointerException("Error accessing " + value);
                } else {
                    throw new NullPointerException("Error accessing " + getValueExpression("value").getExpressionString());
                }
            }
            MimeBodyPart attachment = new MimeBodyPart();
            // Need to manually set the contentid
            String contentId = RandomStringUtils.randomAlphabetic(20).toLowerCase();
            if (disposition.equals("inline")) {
                attachment.setContentID(new Header("<" + contentId + ">").getSanitizedValue());
            }
            attachment.setDataHandler(new DataHandler(ds));
            attachment.setFileName(new Header(getName(ds.getName())).getSanitizedValue());
            attachment.setDisposition(new Header(getDisposition()).getSanitizedValue());
            findMessage().getAttachments().add(attachment);
            if (getStatus() != null) {
                AttachmentStatus attachmentStatus = new AttachmentStatus();
                if (disposition.equals("inline")) {
                    attachmentStatus.setContentId(contentId);
                }
                Contexts.getEventContext().set(getStatus(), attachmentStatus);
            }
        }
    } catch (MessagingException e) {
        throw new FacesException(e.getMessage(), e);
    }
}
Example 50
Project: subetha-master  File: DetacherBean.java View source code
/*
	 * (non-Javadoc)
	 * @see org.subethamail.core.injector.Detacher#attach(javax.mail.internet.MimePart)
	 */
@SuppressWarnings("deprecation")
public void attach(MimePart part) throws MessagingException, IOException {
    log.log(Level.FINE, "Attempting reattachment for {0} of type {1}", new Object[] { part, part.getContentType() });
    String contentType = part.getContentType().toLowerCase();
    if (contentType.startsWith("multipart/")) {
        log.log(Level.FINE, "Content is multipart");
        Multipart multi = (Multipart) part.getContent();
        // This is necessary because of the mysterious JavaMail bug 4404733
        part.setContent(multi);
        for (int i = 0; i < multi.getCount(); i++) this.attach((MimePart) multi.getBodyPart(i));
    } else if (contentType.startsWith(SubEthaMessage.DETACHMENT_MIME_TYPE)) {
        Long attachmentId = (Long) part.getContent();
        log.log(Level.FINE, "Reattaching attachment {0} for type {1}", new Object[] { attachmentId, contentType });
        try {
            Attachment att = this.em.get(Attachment.class, attachmentId);
            if (INPUTSTREAM_RESET_NOT_NEEDED_OR_ISSUE_44) {
                String ct = att.getContentType();
                ByteArrayDataSource bads = new ByteArrayDataSource(att.getContentStream(), ct);
                //this was lazy, now it always runs. What is the performance impact (~6 string searches/operations)?
                if (ct != null)
                    bads.setName(MailUtils.getNameFromContentType(ct));
                DataHandler dh = new DataHandler(bads);
                part.setDataHandler(dh);
            } else {
                part.setDataHandler(new DataHandler(new TrivialDataSource(att.getContentStream(), att.getContentType())));
            }
            part.removeHeader(SubEthaMessage.HDR_ORIGINAL_CONTENT_TYPE);
        } catch (NotFoundException ex) {
            log.log(Level.SEVERE, "Missing referenced attachment {0}", attachmentId);
        }
    } else {
        Object content = part.getContent();
        if (content instanceof MimePart) {
            log.log(Level.FINE, "Content {0} is part, probably a message", contentType);
            this.attach((MimePart) content);
        } else {
            log.log(Level.FINE, "Ignoring part of type {0}", contentType);
        }
    }
}
Example 51
Project: taylor-seam-jsf2-master  File: UIAttachment.java View source code
@Override
public void encodeEnd(FacesContext context) throws IOException {
    DataSource ds = null;
    try {
        if (getValue() instanceof URL) {
            URL url = (URL) getValue();
            ds = new URLDataSource(url);
        } else if (getValue() instanceof File) {
            File file = (File) getValue();
            ds = new FileDataSource(file);
        } else if (getValue() instanceof String) {
            String string = (String) getValue();
            ds = new URLDataSource(FacesResources.getResource(string, context.getExternalContext()));
        } else if (getValue() instanceof InputStream) {
            InputStream is = (InputStream) getValue();
            ds = new ByteArrayDataSource(is, getContentType());
        } else if (getValue() != null && Reflections.isInstanceOf(getValue().getClass(), "org.jboss.seam.document.DocumentData")) {
            Method dataGetter = Reflections.getGetterMethod(getValue().getClass(), "data");
            Method docTypeGetter = Reflections.getGetterMethod(getValue().getClass(), "documentType");
            Object docType = Reflections.invokeAndWrap(docTypeGetter, getValue());
            Method mimeTypeGetter = Reflections.getGetterMethod(docType.getClass(), "mimeType");
            ds = new ByteArrayDataSource((byte[]) Reflections.invokeAndWrap(dataGetter, getValue()), (String) Reflections.invokeAndWrap(mimeTypeGetter, docType));
        } else if (getValue() != null && getValue().getClass().isArray()) {
            if (getValue().getClass().getComponentType().isAssignableFrom(Byte.TYPE)) {
                byte[] b = (byte[]) getValue();
                ds = new ByteArrayDataSource(b, getContentType());
            }
        }
        if (ds != null) {
            // Check the DataSource is available
            try {
                ds.getInputStream();
            } catch (Exception e) {
                if (value != null) {
                    throw new NullPointerException("Error accessing " + value);
                } else {
                    throw new NullPointerException("Error accessing " + getValueExpression("value").getExpressionString());
                }
            }
            MimeBodyPart attachment = new MimeBodyPart();
            // Need to manually set the contentid
            String contentId = RandomStringUtils.randomAlphabetic(20).toLowerCase();
            if (disposition.equals("inline")) {
                attachment.setContentID(new Header("<" + contentId + ">").getSanitizedValue());
            }
            attachment.setDataHandler(new DataHandler(ds));
            attachment.setFileName(new Header(getName(ds.getName())).getSanitizedValue());
            attachment.setDisposition(new Header(getDisposition()).getSanitizedValue());
            findMessage().getAttachments().add(attachment);
            if (getStatus() != null) {
                AttachmentStatus attachmentStatus = new AttachmentStatus();
                if (disposition.equals("inline")) {
                    attachmentStatus.setContentId(contentId);
                }
                Contexts.getEventContext().set(getStatus(), attachmentStatus);
            }
        }
    } catch (MessagingException e) {
        throw new FacesException(e.getMessage(), e);
    }
}
Example 52
Project: Tempo-master  File: TaskAttachmentTest.java View source code
private void addAttachment(String pathToFile) throws Exception {
    // get file, file metadata and file content
    File f = new File(pathToFile);
    String fileName = f.getName();
    String mimetype = new MimetypesFileTypeMap().getContentType(f);
    byte[] bytes = getBytesFromFile(f);
    // start creating the request
    TasStub tas = new TasStub();
    AddRequest req = new AddRequest();
    // add the content of the file
    AddRequestChoice_type0 choice = new AddRequestChoice_type0();
    DataHandler h = new DataHandler(new ByteArrayDataSource(bytes, "base64"));
    choice.setPayload(h);
    req.setAddRequestChoice_type0(choice);
    // add the TAS metadata
    AttachmentMetadata meta = new AttachmentMetadata();
    meta.setFilename(fileName);
    meta.setMimeType(mimetype);
    req.setAttachmentMetadata(meta);
    // add TAS credentials
    AuthCredentials cred = new AuthCredentials();
    AuthorizedRoles_type0 roles = new AuthorizedRoles_type0();
    roles.setRole(ROLES);
    cred.setAuthorizedRoles(roles);
    cred.setParticipantToken(TOKEN);
    req.setAuthCredentials(cred);
    // test resulting url
    // this will throw an exception if the URL is not valid
    URL url = new URL(tas.add(req).getUrl().toString());
    Assert.assertNotNull(url);
}
Example 53
Project: converge-1.x-master  File: DailyMailDecoderTest.java View source code
/**
     * This test performs the following steps:
     *
     * <ol>
     *    <li>Mail sent to (in-memory) mail server containing a Daily Mail package</li>
     *    <li>Decoder picks the mail and decodes the attachment</li>
     * </ol>
     *
     * @throws Exception
     */
@Test
@Ignore
public void testDecodeOld() throws Exception {
    int EXPECTED_NEWSWIRE_ITEMS = 116;
    PluginContext mockCtx = createMock(PluginContext.class);
    expect(mockCtx.getWorkingDirectory()).andReturn("target/newswiretestdata");
    expect(mockCtx.createNewswireItem(new NewswireItem())).andReturn(new NewswireItem()).times(EXPECTED_NEWSWIRE_ITEMS);
    replay(mockCtx);
    NewswireService service = new NewswireService();
    service.setDecoderClass(DailyMailDecoder.class.getName());
    service.setSource("Daily Mail");
    // By including mock-javamail in the test classpath, the connection will be done to a dummy mail in-memory mail server
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT, DailyMailDecoder.TRANSPORT_IMAP));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_SERVER, "i2m.dk"));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_PORT, "143"));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_USERNAME, "converge-ecms"));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_PASSWORD, "C0nvergeEcm$"));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_FOLDER_NEWSWIRE, "INBOX"));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_FOLDER_PROCESSED, "processed"));
    service.getProperties().add(new NewswireServiceProperty(service, DailyMailDecoder.TRANSPORT_IMAP_DELETE_PROCESSED, "false"));
    Properties props = new Properties();
    Session mailSession = Session.getDefaultInstance(props, null);
    mailSession.setDebug(true);
    // Drop mails in the in-memory mailbox (mock-javamail)
    MimeMessage msg = new MimeMessage(mailSession);
    msg.setRecipients(RecipientType.TO, "converge-ecms@i2m.dk");
    msg.setSubject("Daily Mail newswire");
    msg.setFrom(new InternetAddress("allan@i2m.dk"));
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText("Hi");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(getClass().getResourceAsStream("/dk/i2m/converge/plugins/decoders/dailymail/DM 07-11-08.zip"), "application/zip");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName("DM 07-11-08.zip");
    multipart.addBodyPart(messageBodyPart);
    msg.setContent(multipart);
    Transport.send(msg);
//List<NewswireItem> results = service.getDecoder().decode(mockCtx, service);
//assertNotNull(results);
//assertEquals("Incorrect results returned", EXPECTED_NEWSWIRE_ITEMS, results.size());
}
Example 54
Project: fenix-ist-master  File: ExportCarParkUsers.java View source code
private void sendParkingInfoToRemoteCarPark(String filename, byte[] byteArray) throws AddressException, MessagingException {
    final Properties properties = new Properties();
    properties.put("mail.smtp.host", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpHost());
    properties.put("mail.smtp.name", FenixEduAcademicConfiguration.getConfiguration().getMailSmtpName());
    properties.put("mailSender.max.recipients", FenixEduAcademicConfiguration.getConfiguration().getMailSenderMaxRecipients());
    properties.put("mail.debug", "false");
    final Session session = Session.getDefaultInstance(properties, null);
    final Sender sender = Bennu.getInstance().getSystemSender();
    final Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender.getFromAddress()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(EMAIL_ADDRESSES_TO_SEND_DATA));
    message.setSubject("Utentes IST - Atualização");
    message.setText("Listagem atualizada de utentes do IST: " + new DateTime().toString("yyyy-MM-dd HH:mm"));
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    messageBodyPart = new MimeBodyPart();
    DataSource source = new ByteArrayDataSource(byteArray, "text/plain");
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    Transport.send(message);
}
Example 55
Project: geronimo-specs-master  File: MimeUtilityTest.java View source code
public void testGetEncoding() throws Exception {
    ByteArrayDataSource source = new ByteArrayDataSource(new byte[] { 'a', 'b', 'c' }, "text/plain");
    assertEquals("7bit", MimeUtility.getEncoding(source));
    source = new ByteArrayDataSource(new byte[] { 'a', 'b', (byte) 0x81 }, "text/plain");
    assertEquals("quoted-printable", MimeUtility.getEncoding(source));
    source = new ByteArrayDataSource(new byte[] { 'a', (byte) 0x82, (byte) 0x81 }, "text/plain");
    assertEquals("base64", MimeUtility.getEncoding(source));
    source = new ByteArrayDataSource(new byte[] { 'a', 'b', 'c' }, "application/binary");
    assertEquals("7bit", MimeUtility.getEncoding(source));
    source = new ByteArrayDataSource(new byte[] { 'a', 'b', (byte) 0x81 }, "application/binary");
    assertEquals("base64", MimeUtility.getEncoding(source));
    source = new ByteArrayDataSource(new byte[] { 'a', (byte) 0x82, (byte) 0x81 }, "application/binary");
    assertEquals("base64", MimeUtility.getEncoding(source));
}
Example 56
Project: jbpm-master  File: SendHtml.java View source code
private static Message fillMessage(Email email, Session session) {
    org.jbpm.process.workitem.email.Message message = email.getMessage();
    String subject = message.getSubject();
    String from = message.getFrom();
    String replyTo = message.getReplyTo();
    String mailer = "sendhtml";
    if (from == null) {
        throw new RuntimeException("Email must have 'from' address");
    }
    if (replyTo == null) {
        replyTo = from;
    }
    // Construct and fill the Message
    Message msg = null;
    try {
        msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));
        msg.setReplyTo(new InternetAddress[] { new InternetAddress(replyTo) });
        for (Recipient recipient : message.getRecipients().getRecipients()) {
            RecipientType type = null;
            if ("To".equals(recipient.getType())) {
                type = Message.RecipientType.TO;
            } else if ("Cc".equals(recipient.getType())) {
                type = Message.RecipientType.CC;
            } else if ("Bcc".equals(recipient.getType())) {
                type = Message.RecipientType.BCC;
            } else {
                throw new RuntimeException("Unable to determine recipient type");
            }
            msg.addRecipients(type, InternetAddress.parse(recipient.getEmail(), false));
        }
        if (message.hasAttachment()) {
            Multipart multipart = new MimeMultipart();
            // prepare body as first mime body part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(message.getBody(), "text/html")));
            multipart.addBodyPart(messageBodyPart);
            List<String> attachments = message.getAttachments();
            for (String attachment : attachments) {
                MimeBodyPart attachementBodyPart = new MimeBodyPart();
                URL attachmentUrl = getAttachemntURL(attachment);
                String contentType = MimetypesFileTypeMap.getDefaultFileTypeMap().getContentType(attachmentUrl.getFile());
                attachementBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(attachmentUrl.openStream(), contentType)));
                String fileName = new File(attachmentUrl.getFile()).getName();
                attachementBodyPart.setFileName(fileName);
                attachementBodyPart.setContentID("<" + fileName + ">");
                multipart.addBodyPart(attachementBodyPart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message.getBody(), "text/html")));
        }
        msg.setSubject(subject);
        msg.setHeader("X-Mailer", mailer);
        msg.setSentDate(new Date());
    } catch (Exception e) {
        throw new RuntimeException("Unable to send email", e);
    }
    return msg;
}
Example 57
Project: kaleido-repository-master  File: SynchronousMailDispatcher.java View source code
public static void send(MailMessage message, Session session) throws InvalidMailAddressException, MailDispatcherException {
    final MimeMessage mimeMessage = new MimeMessage(session);
    MimeBodyPart messageBodyPart = new MimeBodyPart();
    final Multipart multipart = new MimeMultipart();
    Iterator<String> iterator = null;
    boolean hasAdress = false;
    List<String> incorrectAddresses = new ArrayList<String>();
    try {
        // From
        if (StringHelper.isEmpty(message.getFromAddress())) {
            // skip the send
            throw InvalidMailAddressException.emptyFromMailAddressException();
        }
        try {
            mimeMessage.setFrom(new InternetAddress(message.getFromAddress(), true));
        } catch (final AddressException ade) {
            throw InvalidMailAddressException.invalidMailAddressException(message.getFromAddress());
        }
        mimeMessage.setSubject(message.getSubject(), message.getBodyCharSet());
        // mime type and charset
        messageBodyPart.setContent(message.getBody(), message.getBodyContentType() + "; charset=" + message.getBodyCharSet());
        // priority
        mimeMessage.addHeaderLine("X-Priority: " + String.valueOf(message.getPriority()));
        // first part of the message as multipart
        multipart.addBodyPart(messageBodyPart);
        // To Addresses
        if (message.getToAddresses() != null) {
            for (iterator = message.getToAddresses().iterator(); iterator.hasNext(); ) {
                String mail = iterator.next();
                try {
                    mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(mail, true));
                    hasAdress = true;
                } catch (final Throwable ae) {
                    incorrectAddresses.add(mail);
                }
            }
        }
        // CC Addresses
        if (message.getCcAddresses() != null) {
            for (iterator = message.getCcAddresses().iterator(); iterator.hasNext(); ) {
                String mail = iterator.next();
                try {
                    mimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(mail, true));
                    hasAdress = true;
                } catch (final Throwable ae) {
                    incorrectAddresses.add(mail);
                }
            }
        }
        // BCC Addresses
        if (message.getBccAddresses() != null) {
            for (iterator = message.getBccAddresses().iterator(); iterator.hasNext(); ) {
                String mail = iterator.next();
                try {
                    mimeMessage.addRecipient(Message.RecipientType.BCC, new InternetAddress(mail, true));
                    hasAdress = true;
                } catch (final Throwable ae) {
                    incorrectAddresses.add(mail);
                }
            }
        }
        // Attachments
        if (hasAdress && message.getAttachmentNames() != null) {
            for (final String attachName : message.getAttachmentNames()) {
                try {
                    final MailAttachment mailAttach = message.getAttachment(attachName);
                    StringBuilder contentType = new StringBuilder();
                    if (mailAttach.getContentType() != null) {
                        contentType.append(mailAttach.getContentType());
                    }
                    if (mailAttach.getContentCharset() != null) {
                        if (contentType.length() > 0) {
                            contentType.append("; ");
                        }
                        contentType.append("charset=").append(mailAttach.getContentCharset());
                    }
                    messageBodyPart = new MimeBodyPart();
                    messageBodyPart.setFileName(attachName);
                    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(mailAttach.getInputStream(), contentType.length() > 0 ? contentType.toString() : null)));
                    multipart.addBodyPart(messageBodyPart);
                } catch (IOException ioe) {
                    throw MailDispatcherException.ioReadMailAttachmentException(attachName, ioe);
                }
            }
        }
        // add content to the envelope
        mimeMessage.setContent(multipart);
    } catch (MessagingException me) {
        throw new MailDispatcherException("mail.service.message.build.error", me);
    }
    // send the message
    if (hasAdress == true) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            LOGGER.debug("mail sending starting at {}", new Date().toString());
            Transport.send(mimeMessage);
            LOGGER.debug("mail sending ended in an elapsed time of {} ms", System.currentTimeMillis() - currentTimeMillis);
        } catch (MessagingException me) {
            throw new MailDispatcherException("mail.service.message.send.error", me);
        }
    }
    // no valid address & no incorrect address
    if (!hasAdress && incorrectAddresses.isEmpty()) {
        throw InvalidMailAddressException.emptyToMailAddressException();
    } else // valid address & incorrect address
    if (!incorrectAddresses.isEmpty()) {
        throw InvalidMailAddressException.invalidMailAddressException(incorrectAddresses.toArray(new String[incorrectAddresses.size()]));
    }
}
Example 58
Project: kernel-master  File: MailServiceImpl.java View source code
/**
    * {@inheritDoc}
    */
public void sendMessage(Message message) throws Exception {
    MimeMessage mimeMessage = new MimeMessage(getMailSession());
    String FROM = message.getFrom();
    String TO = message.getTo();
    String CC = message.getCC();
    String BCC = message.getBCC();
    String subject = message.getSubject();
    String mimeType = message.getMimeType();
    String body = message.getBody();
    List<Attachment> attachment = message.getAttachment();
    // set From to the message
    if (FROM != null && !FROM.equals("")) {
        InternetAddress sentFrom = new InternetAddress(FROM);
        mimeMessage.setFrom(sentFrom);
    }
    // set To to the message
    InternetAddress[] sendTo = new InternetAddress[getArrs(TO).length];
    for (int i = 0; i < getArrs(TO).length; i++) {
        sendTo[i] = new InternetAddress(getArrs(TO)[i]);
    }
    mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, sendTo);
    // set CC to the message
    if ((getArrs(CC) != null) && (getArrs(CC).length > 0)) {
        InternetAddress[] copyTo = new InternetAddress[getArrs(CC).length];
        for (int i = 0; i < getArrs(CC).length; i++) {
            copyTo[i] = new InternetAddress(getArrs(CC)[i]);
        }
        mimeMessage.setRecipients(javax.mail.Message.RecipientType.CC, copyTo);
    }
    // set BCC to the message
    if ((getArrs(BCC) != null) && (getArrs(BCC).length > 0)) {
        InternetAddress[] bccTo = new InternetAddress[getArrs(BCC).length];
        for (int i = 0; i < getArrs(BCC).length; i++) {
            bccTo[i] = new InternetAddress(getArrs(BCC)[i]);
        }
        mimeMessage.setRecipients(javax.mail.Message.RecipientType.BCC, bccTo);
    }
    // set Subject to the message
    mimeMessage.setSubject(subject);
    mimeMessage.setSubject(message.getSubject(), "UTF-8");
    mimeMessage.setSentDate(new Date());
    MimeMultipart multipPartRoot = new MimeMultipart("mixed");
    MimeMultipart multipPartContent = new MimeMultipart("alternative");
    if (attachment != null && attachment.size() != 0) {
        MimeBodyPart contentPartRoot = new MimeBodyPart();
        if (mimeType != null && mimeType.indexOf("text/plain") > -1)
            contentPartRoot.setContent(body, "text/plain; charset=utf-8");
        else
            contentPartRoot.setContent(body, "text/html; charset=utf-8");
        MimeBodyPart mimeBodyPart1 = new MimeBodyPart();
        mimeBodyPart1.setContent(body, mimeType);
        multipPartContent.addBodyPart(mimeBodyPart1);
        multipPartRoot.addBodyPart(contentPartRoot);
        for (Attachment att : attachment) {
            InputStream is = att.getInputStream();
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(is, att.getMimeType());
            mimeBodyPart.setDataHandler(new DataHandler(byteArrayDataSource));
            mimeBodyPart.setDisposition(Part.ATTACHMENT);
            if (att.getName() != null)
                mimeBodyPart.setFileName(MimeUtility.encodeText(att.getName(), "utf-8", null));
            multipPartRoot.addBodyPart(mimeBodyPart);
        }
        mimeMessage.setContent(multipPartRoot);
    } else {
        if (mimeType != null && mimeType.indexOf("text/plain") > -1)
            mimeMessage.setContent(body, "text/plain; charset=utf-8");
        else
            mimeMessage.setContent(body, "text/html; charset=utf-8");
    }
    sendMessage(mimeMessage);
}
Example 59
Project: linshare-core-master  File: MailNotifierServiceImpl.java View source code
@Override
public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String textContent, String inReplyTo, String references) throws SendFailedException {
    if (smtpServer.equals("")) {
        logger.warn("Mail notifications are disabled.");
        return;
    }
    // get the mail session
    Session session = getMailSession();
    // Define message
    MimeMessage messageMim = new MimeMessage(session);
    try {
        messageMim.setFrom(new InternetAddress(smtpSender));
        if (replyTo != null) {
            InternetAddress reply[] = new InternetAddress[1];
            reply[0] = new InternetAddress(replyTo);
            messageMim.setReplyTo(reply);
        }
        messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
        if (inReplyTo != null && inReplyTo != "") {
            // This field should contain only ASCCI character (RFC 822)
            if (isPureAscii(inReplyTo)) {
                messageMim.setHeader("In-Reply-To", inReplyTo);
            }
        }
        if (references != null && references != "") {
            // This field should contain only ASCCI character (RFC 822)  
            if (isPureAscii(references)) {
                messageMim.setHeader("References", references);
            }
        }
        messageMim.setSubject(subject, charset);
        // Create a "related" Multipart message
        // content type is multipart/alternative
        // it will contain two part BodyPart 1 and 2
        Multipart mp = new MimeMultipart("alternative");
        // BodyPart 2
        // content type is multipart/related
        // A multipart/related is used to indicate that message parts should
        // not be considered individually but rather
        // as parts of an aggregate whole. The message consists of a root
        // part (by default, the first) which reference other parts inline,
        // which may in turn reference other parts.
        Multipart html_mp = new MimeMultipart("related");
        // Include an HTML message with images.
        // BodyParts: the HTML file and an image
        // Get the HTML file
        BodyPart rel_bph = new MimeBodyPart();
        rel_bph.setDataHandler(new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset)));
        html_mp.addBodyPart(rel_bph);
        // inline image ?
        if (displayLogo || displayLicenceLogo) {
            String cid = "image.part.1@linshare.org";
            MimeBodyPart rel_bpi = new MimeBodyPart();
            // Initialize and add the image file to the html body part
            rel_bpi.setFileName("mail_logo.png");
            rel_bpi.setText("linshare");
            URL resource = null;
            if (displayLicenceLogo) {
                resource = getClass().getResource("/org/linagora/linshare/core/service/mail_logo_licence.png");
            } else {
                if (externalLogo != null && !"".equals(externalLogo)) {
                    File file = new File(externalLogo);
                    if (file.canRead()) {
                        resource = file.toURI().toURL();
                    } else {
                        logger.error("Can not read your personal logo.");
                    }
                }
                if (resource == null) {
                    resource = getClass().getResource("/org/linagora/linshare/core/service/mail_logo.png");
                }
            }
            if (resource == null) {
                logger.error("Embedded logo was not found.");
                throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification : embedded logo was not found.");
            }
            rel_bpi.setDataHandler(new DataHandler(resource));
            rel_bpi.setHeader("Content-ID", "<" + cid + ">");
            rel_bpi.setDisposition("inline");
            html_mp.addBodyPart(rel_bpi);
        }
        // Create the second BodyPart of the multipart/alternative,
        // set its content to the html multipart, and add the
        // second bodypart to the main multipart.
        BodyPart alt_bp2 = new MimeBodyPart();
        alt_bp2.setContent(html_mp);
        mp.addBodyPart(alt_bp2);
        messageMim.setContent(mp);
        // RFC 822 "Date" header field
        // Indicates that the message is complete and ready for delivery
        messageMim.setSentDate(new GregorianCalendar().getTime());
        // Since we used html tags, the content must be marker as text/html
        // messageMim.setContent(content,"text/html; charset="+charset);
        Transport tr = session.getTransport("smtp");
        // Connect to smtp server, if needed
        if (needsAuth) {
            tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword);
            messageMim.saveChanges();
            tr.sendMessage(messageMim, messageMim.getAllRecipients());
            tr.close();
        } else {
            // Send message
            Transport.send(messageMim);
        }
    } catch (SendFailedException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e);
        throw e;
    } catch (MessagingException e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    } catch (Exception e) {
        logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e);
        throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e);
    }
}
Example 60
Project: MailsterSMTP-master  File: SMTPClientTest.java View source code
/** */
public void testBinaryEightBitMessage() throws Exception {
    byte[] body = new byte[64];
    rnd.nextBytes(body);
    MimeMessage message = new MimeMessage(this.session);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("anyone@anywhere.com"));
    message.setFrom(new InternetAddress("someone@somewhereelse.com"));
    message.setSubject("hello");
    message.setHeader("Content-Transfer-Encoding", "8bit");
    message.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "application/octet-stream")));
    Transport.send(message);
    InputStream in = this.wiser.getMessages().get(0).getMimeMessage().getInputStream();
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    byte[] buf = new byte[64];
    int n;
    while ((n = in.read(buf)) != -1) {
        tmp.write(buf, 0, n);
    }
    in.close();
    assertTrue(Arrays.equals(body, tmp.toByteArray()));
}
Example 61
Project: MyPublicRepo-master  File: Test1ServiceImpl.java View source code
private void echoAttachment(MyMessage msg) {
    DataHandler inDataHandler = msg.getBinaryData();
    ByteArrayOutputStream inData = new ByteArrayOutputStream();
    try {
        inDataHandler.writeTo(inData);
    } catch (IOException e) {
    }
    //		System.out.println("Incoming attachment data: " + inData.toString());
    //TODO: uncomment me when mail.jar issue resolved.
    DataSource outDataSource = new ByteArrayDataSource(inData.toByteArray(), inDataHandler.getContentType());
    DataHandler outDataHandler = new DataHandler(outDataSource);
    msg.setBinaryData(outDataHandler);
//		msg.setBinaryData(null);
}
Example 62
Project: Openfire-master  File: EmailSenderUtility.java View source code
public void sendEmail() {
    ByteArrayOutputStream outputStream = null;
    try {
        String host = JiveGlobals.getProperty("mail.smtp.host", "localhost");
        String port = JiveGlobals.getProperty("mail.smtp.port", "25");
        String username = JiveGlobals.getProperty("mail.smtp.username");
        String password = JiveGlobals.getProperty("mail.smtp.password");
        String debugEnabled = JiveGlobals.getProperty("mail.debug");
        boolean sslEnabled = JiveGlobals.getBooleanProperty("mail.smtp.ssl", true);
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", port);
        props.setProperty("mail.smtp.sendpartial", "true");
        props.setProperty("mail.debug", debugEnabled);
        if (sslEnabled) {
            // Register with security provider.
            Security.setProperty("ssl.SocketFactory.provider", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "true");
        }
        if (username != null) {
            props.put("mail.smtp.auth", "true");
        }
        Session session = Session.getInstance(props);
        outputStream = new ByteArrayOutputStream();
        createPdfAttachment(outputStream);
        byte[] bytes = outputStream.toByteArray();
        ByteArrayDataSource dataSource = new ByteArrayDataSource(bytes, "application/pdf");
        MimeBodyPart pdfBodyPart = new MimeBodyPart();
        pdfBodyPart.setDataHandler(new DataHandler(dataSource));
        pdfBodyPart.setFileName("ResultSummary.pdf");
        MimeMultipart multipart = new MimeMultipart();
        multipart.addBodyPart(pdfBodyPart);
        MimeMessage msg = new MimeMessage(session);
        DefaultAdminProvider defaultAdminProvider = new DefaultAdminProvider();
        java.util.List<JID> adminList = defaultAdminProvider.getAdmins();
        java.util.List<String> adminListEmails = new ArrayList<String>();
        UserManager manager = UserManager.getInstance();
        Log.info("Number of Admins " + adminList.size());
        for (int i = 0; i < adminList.size(); i++) {
            User user;
            try {
                user = manager.getUser(adminList.get(i).getNode().toString());
                Log.info("Admin Emails: " + user.getEmail());
                adminListEmails.add(user.getEmail());
            } catch (Exception ex) {
                continue;
            }
        }
        // java.util.List<String> recipientsList=Arrays.asList("", "", "");
        InternetAddress[] recipients = new InternetAddress[adminListEmails.size()];
        for (int i = 0; i < adminListEmails.size(); i++) {
            recipients[i] = new InternetAddress(adminListEmails.get(i).toString());
        }
        msg.setFrom(new InternetAddress("no-reply@openfire.org", "Openfire Admin"));
        msg.setRecipients(javax.mail.Message.RecipientType.TO, recipients);
        msg.setSubject("MONITORING REPORT - " + new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));
        msg.setContent(multipart);
        if (username != null) {
            URLName url = new URLName("smtp", host, Integer.parseInt(port), "", username, password);
            Transport transport = new com.sun.mail.smtp.SMTPTransport(session, url);
            transport.connect(host, Integer.parseInt(port), username, password);
            transport.sendMessage(msg, msg.getRecipients(MimeMessage.RecipientType.TO));
        } else
            Transport.send(msg);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Could not send email");
    }
}
Example 63
Project: oxalis-master  File: As2MessageSender.java View source code
protected TransmissionResponse handleResponse(CloseableHttpResponse closeableHttpResponse) throws OxalisTransmissionException {
    Span span = tracer.newChild(root.context()).name("response").start();
    try (CloseableHttpResponse response = closeableHttpResponse) {
        span.tag("code", String.valueOf(response.getStatusLine().getStatusCode()));
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            LOGGER.error("AS2 HTTP POST expected HTTP OK, but got : {} from {}", response.getStatusLine().getStatusCode(), transmissionRequest.getEndpoint().getAddress());
            // Throws exception
            handleFailedRequest(response);
        }
        // handle normal HTTP OK response
        LOGGER.debug("AS2 transmission to {} returned HTTP OK, verify MDN response", transmissionRequest.getEndpoint().getAddress());
        Header contentTypeHeader = response.getFirstHeader("Content-Type");
        if (contentTypeHeader == null)
            throw new OxalisTransmissionException("No Content-Type header in response, probably a server error.");
        // Read MIME Message
        MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(response.getEntity().getContent(), contentTypeHeader.getValue());
        // Add headers to MIME Message
        for (Header header : response.getAllHeaders()) mimeMessage.addHeader(header.getName(), header.getValue());
        SMimeReader sMimeReader = new SMimeReader(mimeMessage);
        // Timestamp of reception of MDN
        Timestamp t3 = timestampProvider.generate(sMimeReader.getSignature(), Direction.OUT);
        // Extract signed digest and digest algorithm
        SMimeDigestMethod digestMethod = sMimeReader.getDigestMethod();
        // Preparing calculation of digest
        MessageDigest messageDigest = BCHelper.getMessageDigest(digestMethod.getIdentifier());
        InputStream digestInputStream = new DigestInputStream(sMimeReader.getBodyInputStream(), messageDigest);
        // Reading report
        MimeMultipart mimeMultipart = new MimeMultipart(new ByteArrayDataSource(digestInputStream, mimeMessage.getContentType()));
        // Create digest object
        Digest digest = Digest.of(digestMethod.getDigestMethod(), messageDigest.digest());
        // Verify signature
        /*
            X509Certificate certificate = SMimeBC.verifySignature(
                    ImmutableMap.of(digestMethod.getOid(), digest.getValue()),
                    sMimeReader.getSignature()
            );
            */
        // verify the signature of the MDN, we warn about dodgy signatures
        SignedMimeMessage signedMimeMessage = new SignedMimeMessage(mimeMessage);
        X509Certificate certificate = signedMimeMessage.getSignersX509Certificate();
        // the response message does not match its certificate published by the SMP
        if (!transmissionRequest.getEndpoint().getCertificate().equals(certificate))
            throw new OxalisTransmissionException(String.format("Certificate in MDN ('%s') does not match certificate from SMP ('%s').", certificate.getSubjectX500Principal().getName(), transmissionRequest.getEndpoint().getCertificate().getSubjectX500Principal().getName()));
        LOGGER.debug("MDN signature was verified for : " + certificate.getSubjectDN().toString());
        // Verifies the actual MDN
        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();
        if (!mdnMimeMessageInspector.isOkOrWarning(new Mic(outboundMic))) {
            LOGGER.error("AS2 transmission failed with some error message '{}'.", msg);
            throw new OxalisTransmissionException(String.format("AS2 transmission failed : %s", msg));
        }
        // Read structured content
        MimeBodyPart mimeBodyPart = (MimeBodyPart) mdnMimeMessageInspector.getMessageDispositionNotificationPart();
        InternetHeaders internetHeaders = new InternetHeaders((InputStream) mimeBodyPart.getContent());
        // Fetch timestamp if set
        Date date = t3.getDate();
        if (internetHeaders.getHeader(MdnHeader.DATE) != null)
            date = As2DateUtil.RFC822.parse(internetHeaders.getHeader(MdnHeader.DATE)[0]);
        // Return TransmissionResponse
        return new As2TransmissionResponse(transmissionIdentifier, transmissionRequest, outboundMic, MimeMessageHelper.toBytes(mimeMessage), t3, date);
    } catch (TimestampExceptionIOException |  e) {
        throw new OxalisTransmissionException(e.getMessage(), e);
    } catch (NoSuchAlgorithmExceptionMessagingException |  e) {
        throw new OxalisTransmissionException("Unable to parse received content.", e);
    } finally {
        span.finish();
    }
}
Example 64
Project: RSB-master  File: SoapMtomJobHandlerTestCase.java View source code
@Test
public void processXmlFunctionCall() {
    final JobType job = Util.SOAP_OBJECT_FACTORY.createJobType();
    job.setApplicationName(TEST_APP_NAME);
    final PayloadType xmlFunctionCallPayload = Util.SOAP_OBJECT_FACTORY.createPayloadType();
    xmlFunctionCallPayload.setContentType(Constants.XML_CONTENT_TYPE);
    xmlFunctionCallPayload.setData(new DataHandler(new ByteArrayDataSource("<fake_job/>".getBytes(), xmlFunctionCallPayload.getContentType())));
    job.getPayload().add(xmlFunctionCallPayload);
    final XmlFunctionCallResult result = mock(XmlFunctionCallResult.class);
    when(result.getMimeType()).thenReturn(Constants.XML_MIME_TYPE);
    when(result.getPayload()).thenReturn("<fake_result/>");
    when(result.getJobId()).thenReturn(UUID.randomUUID());
    when(messageDispatcher.process(any(XmlFunctionCallJob.class))).thenAnswer(new Answer<AbstractResult<?>>() {

        public AbstractResult<?> answer(final InvocationOnMock invocation) throws Throwable {
            return result;
        }
    });
    final ResultType processResult = soapMtomJobHandler.process(job);
    assertThat(processResult.getPayload().size(), is(1));
}
Example 65
Project: smartly-master  File: RunnablePostman.java View source code
private MimeBodyPart[] getAttachments() throws MessagingException {
    final List<MimeBodyPart> result = new ArrayList<MimeBodyPart>();
    // file attachments
    for (final File file : _fileAttachments) {
        final DataHandler dh = new DataHandler(new FileDataSource(file));
        final MimeBodyPart part = new MimeBodyPart();
        part.setDataHandler(dh);
        part.setFileName(file.getName());
        result.add(part);
    }
    // stream attachments
    final Set<Entry<String, InputStream>> entries = _streamAttachments.entrySet();
    for (final Entry<String, InputStream> entry : entries) {
        try {
            final String name = entry.getKey();
            final InputStream stream = entry.getValue();
            final DataHandler dh = new DataHandler(new ByteArrayDataSource(stream, name));
            final MimeBodyPart body = new MimeBodyPart();
            body.setDataHandler(dh);
            result.add(body);
        } catch (Throwable t) {
        }
    }
    return result.toArray(new MimeBodyPart[result.size()]);
}
Example 66
Project: subethasmtp-master  File: MessageContentTest.java View source code
/** */
public void testBinaryEightBitMessage() throws Exception {
    byte[] body = new byte[64];
    new Random().nextBytes(body);
    MimeMessage message = new MimeMessage(this.session);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("anyone@anywhere.com"));
    message.setFrom(new InternetAddress("someone@somewhereelse.com"));
    message.setSubject("hello");
    message.setHeader("Content-Transfer-Encoding", "8bit");
    message.setDataHandler(new DataHandler(new ByteArrayDataSource(body, "application/octet-stream")));
    Transport.send(message);
    InputStream in = this.wiser.getMessages().get(0).getMimeMessage().getInputStream();
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    byte[] buf = new byte[64];
    int n;
    while ((n = in.read(buf)) != -1) {
        tmp.write(buf, 0, n);
    }
    in.close();
    assertTrue(Arrays.equals(body, tmp.toByteArray()));
}
Example 67
Project: sventon-master  File: MailNotifier.java View source code
/**
   * @param logEntry       Log entry
   * @param repositoryName Name
   * @param mailTemplate   Template
   * @return Message
   * @throws MessagingException If a message exception occurs.
   * @throws IOException        if a IO exception occurs while creating the data source.
   */
private Message createMessage(final LogEntry logEntry, RepositoryName repositoryName, String mailTemplate) throws MessagingException, IOException {
    final Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(from));
    msg.setRecipients(Message.RecipientType.BCC, receivers.toArray(new InternetAddress[receivers.size()]));
    msg.setSubject(formatSubject(subject, logEntry.getRevision(), repositoryName));
    msg.setDataHandler(new DataHandler(new ByteArrayDataSource(HTMLCreator.createRevisionDetailBody(mailTemplate, logEntry, baseURL, repositoryName, dateFormat, null), "text/html")));
    msg.setHeader("X-Mailer", "sventon");
    msg.setSentDate(new Date());
    return msg;
}
Example 68
Project: TNTConcept-master  File: DefaultMailService.java View source code
public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments) throws MessagingException {
    Transport t = null;
    try {
        MimeMessage message = new MimeMessage(session);
        t = session.getTransport("smtp");
        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    //NOSONAR
                    messageBodyPart.setFileName(attachments.get(attachment));
                    //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                    multipart.addBodyPart(messageBodyPart);
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }
        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }
}
Example 69
Project: turmeric-runtime-master  File: Test1ServiceImpl.java View source code
private void echoAttachment(MyMessage msg) {
    DataHandler inDataHandler = msg.getBinaryData();
    ByteArrayOutputStream inData = new ByteArrayOutputStream();
    try {
        inDataHandler.writeTo(inData);
    } catch (IOException e) {
    }
    //		System.out.println("Incoming attachment data: " + inData.toString());
    //TODO: uncomment me when mail.jar issue resolved.
    DataSource outDataSource = new ByteArrayDataSource(inData.toByteArray(), inDataHandler.getContentType());
    DataHandler outDataHandler = new DataHandler(outDataSource);
    msg.setBinaryData(outDataHandler);
//		msg.setBinaryData(null);
}
Example 70
Project: Ulysse-master  File: JabutiServiceBean.java View source code
@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public String createProject(String IdUserName, String projectName, byte[] projectFile) throws JabutiServiceException {
    logger.debug("createProject(...) called");
    init();
    // MyDataHandler not really necessary...
    MyDataHandler projectFileHandler = new MyDataHandler(new ByteArrayDataSource(projectFile, "application/java-archive"));
    //save the attached file in a temporary directory 
    //		File f = saveTempFile(projectFileHandler);
    File f = VerifingData.saveTempFile(projectFileHandler);
    FileValidation fv = new FileValidation();
    if (fv.validateFile(f)) {
        try {
            WsProject control = new WsProject(props);
            String ret[] = control.create(projectName, f);
            return ret[0];
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            throw new JabutiServiceException(e);
        }
    } else {
        InvalidFileFault e = new InvalidFileFault(fv.getMessage());
        logger.error(e);
        e.printStackTrace();
        throw new JabutiServiceException(e);
    }
}
Example 71
Project: as2-master  File: BCCryptoHelper.java View source code
/**Returns the digest OID algorithm from a signature that signes the passed message part
     *The return value for sha1 is e.g. "1.3.14.3.2.26".
     */
public String getDigestAlgOIDFromSignature(Part part) throws Exception {
    if (part == null) {
        throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Part is null");
    }
    if (part.isMimeType("multipart/signed")) {
        MimeMultipart signedMultiPart = null;
        if (part.getContent() instanceof MimeMultipart) {
            signedMultiPart = (MimeMultipart) part.getContent();
        } else {
            //assuming it is an inputstream now
            signedMultiPart = new MimeMultipart(new ByteArrayDataSource((InputStream) part.getContent(), part.getContentType()));
        }
        SMIMESigned signed = new SMIMESigned(signedMultiPart);
        SignerInformationStore signerStore = signed.getSignerInfos();
        Iterator iterator = signerStore.getSigners().iterator();
        while (iterator.hasNext()) {
            SignerInformation signerInfo = (SignerInformation) iterator.next();
            return (signerInfo.getDigestAlgOID());
        }
        throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Unable to identify signature algorithm.");
    }
    throw new GeneralSecurityException("Content-Type indicates data isn't signed");
}
Example 72
Project: elasticsearch-imap-master  File: AttachmentMapperTest.java View source code
@Test
public void testAttachments() throws Exception {
    Map<String, Object> settings = settings("/river-imap-attachments.json");
    final Properties props = new Properties();
    final String user = XContentMapValues.nodeStringValue(settings.get("user"), null);
    final String password = XContentMapValues.nodeStringValue(settings.get("password"), null);
    for (final Map.Entry<String, Object> entry : settings.entrySet()) {
        if (entry != null && entry.getKey().startsWith("mail.")) {
            props.setProperty(entry.getKey(), String.valueOf(entry.getValue()));
        }
    }
    registerRiver("imap_river", "river-imap-attachments.json");
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);
    checkStoreForTestConnection(store);
    final Folder inbox = store.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(EMAIL_TO));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
    message.setSubject(EMAIL_SUBJECT + "::attachment test");
    message.setSentDate(new Date());
    BodyPart bp = new MimeBodyPart();
    bp.setText("Text");
    Multipart mp = new MimeMultipart();
    mp.addBodyPart(bp);
    bp = new MimeBodyPart();
    DataSource ds = new ByteArrayDataSource(this.getClass().getResourceAsStream("/httpclient-tutorial.pdf"), AttachmentMapperTest.APPLICATION_PDF);
    bp.setDataHandler(new DataHandler(ds));
    bp.setFileName("httpclient-tutorial.pdf");
    mp.addBodyPart(bp);
    message.setContent(mp);
    inbox.appendMessages(new Message[] { message });
    IMAPUtils.close(inbox);
    IMAPUtils.close(store);
    //let the river index
    Thread.sleep(20 * 1000);
    esSetup.client().admin().indices().refresh(new RefreshRequest()).actionGet();
    SearchResponse searchResponse = esSetup.client().prepareSearch("imapriverdata").setTypes("mail").execute().actionGet();
    Assert.assertEquals(1, searchResponse.getHits().totalHits());
    //BASE64 content httpclient-tutorial.pdf
    Assert.assertTrue(searchResponse.getHits().hits()[0].getSourceAsString().contains(AttachmentMapperTest.PDF_BASE64_DETECTION));
    searchResponse = esSetup.client().prepareSearch("imapriverdata").addFields("*").setTypes("mail").setQuery(QueryBuilders.matchPhraseQuery("attachments.content.content", PDF_CONTENT_TO_SEARCH)).execute().actionGet();
    Assert.assertEquals(1, searchResponse.getHits().totalHits());
    Assert.assertEquals(1, searchResponse.getHits().hits()[0].field("attachments.content.content").getValues().size());
    Assert.assertEquals("HttpClient Tutorial", searchResponse.getHits().hits()[0].field("attachments.content.title").getValue().toString());
    Assert.assertEquals("application/pdf", searchResponse.getHits().hits()[0].field("attachments.content.content_type").getValue().toString());
    Assert.assertTrue(searchResponse.getHits().hits()[0].field("attachments.content.content").getValue().toString().contains(PDF_CONTENT_TO_SEARCH));
}
Example 73
Project: imixs-marty-master  File: MailPlugin.java View source code
/**
	 * This method adds all files of a given BlobWOrkitem to the current
	 * MailMessage
	 * 
	 * 
	 * @param blobWorkitem
	 * @throws MessagingException
	 */
private void attachFiles(ItemCollection blobWorkitem) throws MessagingException {
    String sFilePattern = null;
    while ((sFilePattern = getAttachmentName()) != null) {
        logger.fine("MailPlugin attach file pattern: \"" + sFilePattern + "\"");
        // get all fileNames....
        List<String> fileNames = blobWorkitem.getFileNames();
        // iterate over all files ....
        for (String aFileName : fileNames) {
            // test if aFilename matches the pattern
            if (sFilePattern.isEmpty() || Pattern.matches(sFilePattern, aFileName)) {
                // fetch the file content
                FileInfo fileInfo = getFileFromWorkItem(aFileName, blobWorkitem);
                logger.fine("MailPlugin - attach : " + aFileName);
                // get Mulitpart Message
                Multipart multipart = super.getMultipart();
                // now attache the file
                MimeBodyPart attachmentPart = new MimeBodyPart();
                // construct the body part from the byte array
                DataSource dataSource = new ByteArrayDataSource(fileInfo.content, fileInfo.contentType);
                attachmentPart.setDataHandler(new DataHandler(dataSource));
                attachmentPart.setFileName(aFileName);
                attachmentPart.setDescription("");
                multipart.addBodyPart(attachmentPart);
            }
        }
    }
}
Example 74
Project: jboss-as7-jbpm-module-master  File: SendIcal.java View source code
public void sendIcal(long taskId, String name, String summary, String description, int priority, Date startDate, User owner, User creator, Date createdOn, UserInfo userInfo, String type) throws Exception {
    MimetypesFileTypeMap mimetypes = (MimetypesFileTypeMap) MimetypesFileTypeMap.getDefaultFileTypeMap();
    mimetypes.addMimeTypes("text/calendar ics ICS");
    MailcapCommandMap mailcap = (MailcapCommandMap) MailcapCommandMap.getDefaultCommandMap();
    mailcap.addMailcap("text/calendar;; x-java-content-handler=com.sun.mail.handlers.text_plain");
    System.out.println(connection);
    Session session = Session.getInstance(connection, null);
    // Define message
    MimeMessage message = new MimeMessage(session);
    message.setHeader("Content-Class", "urn:content-classes:calendarmessage");
    message.setHeader("Content-ID", "calendar_message");
    String creatorEmail = userInfo.getEmailForEntity(creator);
    message.setFrom(new InternetAddress(creatorEmail));
    message.setReplyTo(new InternetAddress[] { new InternetAddress(creatorEmail) });
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(userInfo.getEmailForEntity(owner)));
    message.setSubject("Task Assignment " + type + " Event: " + name);
    message.setSentDate(new Date());
    // Create a Multipart
    Multipart multipart = new MimeMultipart("alternative");
    // Add text message
    BodyPart messageBodyPart = new MimeBodyPart();
    String text = "Summary\n-------\n\n" + summary + "\n\nDescription\n-----------\n\n" + description;
    messageBodyPart.setText(text);
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(text, "text/plain; charset=UTF8;")));
    multipart.addBodyPart(messageBodyPart);
    // Add ical
    messageBodyPart = new MimeBodyPart();
    String filename = "ical-" + type + "-" + taskId + ".ics";
    messageBodyPart.setFileName(filename);
    messageBodyPart.setHeader("Content-Class", "urn:content-classes:calendarmessage");
    messageBodyPart.setHeader("Content-ID", "calendar_message");
    String icalStr = getIcal(summary, description, startDate, priority, userInfo.getDisplayName(creator), creatorEmail, type);
    messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(icalStr, "text/calendar; charset=UTF8; ")));
    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);
    message.saveChanges();
    Transport.send(message);
}
Example 75
Project: KolabDroid-master  File: AbstractSyncHandler.java View source code
protected Message wrapXmlInMessage(Session session, SyncContext sync, String xml) throws MessagingException, SyncException {
    Message result = new MimeMessage(session);
    result.setSubject(sync.getCacheEntry().getRemoteId());
    result.setSentDate(sync.getCacheEntry().getRemoteChangedDate());
    result.setFrom(new InternetAddress("kolab-android@dasz.at"));
    result.setRecipient(RecipientType.TO, new InternetAddress("kolab-android@dasz.at"));
    result.setHeader("User-Agent", "kolab-android 0.1");
    result.setHeader("X-Kolab-Type", getMimeType());
    MimeMultipart mp = new MimeMultipart();
    MimeBodyPart txt = new MimeBodyPart();
    txt.setText(getMessageBodyText(sync), "utf-8");
    mp.addBodyPart(txt);
    BodyPart messageBodyPart = new MimeBodyPart();
    DataSource source;
    try {
        source = new ByteArrayDataSource(xml.getBytes("UTF-8"), getMimeType());
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName("kolab.xml");
    mp.addBodyPart(messageBodyPart);
    result.setContent(mp);
    // avoid later change in timestamp when the SEEN flag would be updated
    result.setFlag(Flags.Flag.SEEN, true);
    return result;
}
Example 76
Project: OpenNotification-master  File: SMTPNotificationProvider.java View source code
/**
	 * @param notification
	 * @param sender
	 * @param summary
	 * @param messageText
	 * @param to
	 * @return
	 * @throws NotificationException
	 */
public static Hashtable sendEmail(Device device, Notification notification, NotificationSender sender, String summary, String messageText, String to) throws NotificationException {
    // Get system properties
    Properties props = System.getProperties();
    if (props == null)
        props = new Properties();
    String[] smtpServers = BrokerFactory.getConfigurationBroker().getStringValues("smtp.server");
    if ((smtpServers == null) || (smtpServers.length <= 0)) {
        smtpServers = new String[1];
        smtpServers[0] = "localhost";
    }
    int smtpServerNum = 0;
    boolean succeeded = false;
    int errorNum = 0;
    String error = "";
    String id = "unknown_" + System.currentTimeMillis();
    while ((smtpServerNum < smtpServers.length) && (!succeeded)) {
        try {
            String smtpServer = smtpServers[smtpServerNum];
            BrokerFactory.getLoggingBroker().logDebug("Trying SMTP Server num " + smtpServerNum + ": " + smtpServer + ".");
            smtpServerNum++;
            // Setup mail server
            props.put("mail.smtp.host", smtpServer);
            // Set the "from" address to the bounce address
            if (BrokerFactory.getConfigurationBroker().getBooleanValue("email.bounce.enable", true)) {
                props.put("mail.smtp.from", notification.getUuid() + "_" + device.getUuid() + BrokerFactory.getConfigurationBroker().getStringValue("email.bounce.suffix", "-bounce") + "@" + getDomainPartOfFrom());
                BrokerFactory.getLoggingBroker().logDebug("Bounce address is " + props.get("mail.smtp.from"));
            }
            // Get session
            Session session = Session.getDefaultInstance(props, null);
            session.getProperties().setProperty("mail.smtp.host", smtpServer);
            // Define message
            MimeMessage message = new MimeMessage(session);
            InternetAddress returnAddress = getReturnEmailAddress(device, notification);
            BrokerFactory.getLoggingBroker().logDebug("SMTP from address=" + returnAddress);
            message.setFrom(returnAddress);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            // String[] parts = splitMessage(messageText,
            // device.getMaxCharactersSize(), device.getMaxMessages());
            String[] parts = splitMessage(messageText, 10240, device.getMaxMessages());
            for (int partNum = 0; partNum < parts.length; partNum++) {
                if (parts.length < 2) {
                    message.setSubject(summary);
                } else {
                    message.setSubject((partNum + 1) + ": " + summary);
                }
                message.setText(parts[partNum]);
                if (BrokerFactory.getConfigurationBroker().getBooleanValue("email.attachments.attach", false)) {
                    NotificationMessage[] attachments = notification.getMessages();
                    Multipart attachmentParts = new MimeMultipart();
                    MimeBodyPart attachmentPart = new MimeBodyPart();
                    attachmentPart.setText(parts[partNum]);
                    attachmentParts.addBodyPart(attachmentPart);
                    for (int i = 1; i < attachments.length; i++) {
                        NotificationMessage attachment = attachments[i];
                        if (!attachment.getContentType().equals(NotificationMessage.NOTIFICATION_CONTENT_TYPE)) {
                            attachmentPart = new MimeBodyPart();
                            DataSource source = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
                            attachmentPart.setDataHandler(new DataHandler(source));
                            attachmentPart.setFileName(attachment.getFilename());
                            attachmentParts.addBodyPart(attachmentPart);
                        }
                    }
                    message.setContent(attachmentParts);
                }
                // Send message
                BrokerFactory.getLoggingBroker().logInfo("Sending SMTP Email:\n" + message.toString());
                // Check for STMP authentication
                // If we don't find it, just use the Transport's static
                // methods
                // If we do, use the more complicated method that allows
                // authn
                String smtpUsername = BrokerFactory.getConfigurationBroker().getStringValue("smtp.username", null);
                String smtpPassword = BrokerFactory.getConfigurationBroker().getStringValue("smtp.password", null);
                if ((smtpUsername == null) || (smtpPassword == null)) {
                    Transport.send(message);
                } else {
                    Transport tr = session.getTransport("smtp");
                    tr.connect(smtpServer, smtpUsername, smtpPassword);
                    // don't forget this
                    message.saveChanges();
                    tr.sendMessage(message, message.getAllRecipients());
                    tr.close();
                }
            }
            id = message.getMessageID();
            succeeded = true;
        } catch (AddressException e) {
            e.printStackTrace();
            error = e.getMessage();
            errorNum = NotificationException.FAILED;
            notification.getSender().handleBounce(device);
            BrokerFactory.getLoggingBroker().logError(e);
        } catch (MessagingException e) {
            e.printStackTrace();
            error = e.getMessage();
            errorNum = NotificationException.TEMPORARILY_FAILED;
            BrokerFactory.getLoggingBroker().logError(e);
        }
    }
    if (!succeeded) {
        throw new NotificationException(errorNum, error);
    }
    Hashtable params = new Hashtable();
    params.put("tracking number", id);
    return params;
}
Example 77
Project: pentaho-platform-master  File: Emailer.java View source code
public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");
    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject + "' and the body " + body);
    try {
        // Get a Session object
        Session session;
        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }
        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) {
            //$NON-NLS-1$
            session.setDebug(false);
        }
        final MimeMessage msg;
        if (EMBEDDED_HTML.equals(attachmentMimeType)) {
            //Message is ready
            msg = new MimeMessage(session, attachment);
            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");
                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);
                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }
                msg.setContent(newMultipart);
            }
        } else {
            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();
            if (attachment == null) {
                //$NON-NLS-1$
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED");
                return false;
            }
            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);
            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }
            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);
            // add the Multipart to the message
            msg.setContent(multipart);
        }
        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            //$NON-NLS-1$
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED");
        }
        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }
        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }
        //$NON-NLS-1$
        msg.setHeader("X-Mailer", Emailer.MAILER);
        msg.setSentDate(new Date());
        Transport.send(msg);
        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e);
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e);
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e);
    }
    return false;
}
Example 78
Project: projectforge-webapp-master  File: SendMail.java View source code
private void sendIt(final Mail composedMessage, final String icalContent, final Collection<? extends MailAttachment> attachments) {
    final Session session = Session.getInstance(properties);
    Transport transport = null;
    try {
        final MimeMessage message = new MimeMessage(session);
        if (composedMessage.getFrom() != null) {
            message.setFrom(new InternetAddress(composedMessage.getFrom()));
        } else {
            message.setFrom();
        }
        message.setRecipients(Message.RecipientType.TO, composedMessage.getTo());
        String subject;
        subject = composedMessage.getSubject();
        message.setSubject(subject, sendMailConfig.getCharset());
        message.setSentDate(new Date());
        // create and fill the first message part
        final MimeBodyPart mbp1 = new MimeBodyPart();
        String type = "text/";
        if (StringUtils.isNotBlank(composedMessage.getContentType()) == true) {
            type += composedMessage.getContentType();
            type += "; charset=";
            type += composedMessage.getCharset();
        } else {
            type = "text/html; charset=";
            type += sendMailConfig.getCharset();
        }
        mbp1.setContent(composedMessage.getContent(), type);
        mbp1.setHeader("Content-Transfer-Encoding", "8bit");
        // create the Multipart and its parts to it
        final MimeMultipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        if (StringUtils.isNotBlank(icalContent) == true) {
            final DataSource dataSource = new ByteArrayDataSource(icalContent.getBytes(), "text/plain");
            final MimeBodyPart icalBodyPart = new MimeBodyPart();
            icalBodyPart.setDataHandler(new DataHandler(dataSource));
            final String s = Integer.toString(RandomUtils.nextInt());
            icalBodyPart.setFileName("ICal-" + s + ".ics");
            mp.addBodyPart(icalBodyPart);
        }
        if (attachments != null && attachments.isEmpty() == false) {
            // create an Array of message parts for Attachments
            final MimeBodyPart mbp[] = new MimeBodyPart[attachments.size()];
            // remember you can extend this functionality with META-INF/mime.types
            // See http://docs.oracle.com/javaee/5/api/javax/activation/MimetypesFileTypeMap.html
            final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
            int i = 0;
            for (final MailAttachment attachment : attachments) {
                // create the next message part
                mbp[i] = new MimeBodyPart();
                // only by file name
                String mimeType = mimeTypesMap.getContentType(attachment.getFilename());
                if (StringUtils.isBlank(mimeType)) {
                    mimeType = "application/octet-stream";
                }
                // attach the file to the message
                final DataSource ds = new ByteArrayDataSource(attachment.getContent(), mimeType);
                mbp[i].setDataHandler(new DataHandler(ds));
                mbp[i].setFileName(attachment.getFilename());
                mp.addBodyPart(mbp[i]);
                i++;
            }
        }
        // add the Multipart to the message
        message.setContent(mp);
        // don't forget this
        message.saveChanges();
        transport = session.getTransport();
        if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) {
            transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
    } catch (final MessagingException ex) {
        log.error("While creating and sending message: " + composedMessage.toString(), ex);
        throw new InternalErrorException("mail.error.exception");
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (final MessagingException ex) {
                log.error("While creating and sending message: " + composedMessage.toString(), ex);
                throw new InternalErrorException("mail.error.exception");
            }
        }
    }
    log.info("E-Mail successfully sent: " + composedMessage.toString());
}
Example 79
Project: smart-email-queue-master  File: EmailServiceImpl.java View source code
private void addAttachment(Multipart multipart, Attachments attachment) throws MessagingException {
    MimeBodyPart attachmentPart = new MimeBodyPart();
    attachmentPart.setFileName(attachment.getName());
    if (StringUtils.isNotBlank(attachment.getDescription())) {
        attachmentPart.setDescription(attachment.getDescription());
    }
    if (StringUtils.isNotBlank(attachment.getDisposition())) {
        attachmentPart.setDisposition(attachment.getDisposition());
    }
    DataSource source = new ByteArrayDataSource(attachment.getBlob(), attachment.getContentType());
    attachmentPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachmentPart);
}
Example 80
Project: spring-ws-master  File: AbstractSoap12WebServiceTemplateIntegrationTestCase.java View source code
@Test
public void attachment() {
    template.sendSourceAndReceiveToResult(baseUrl + "/soap/attachment", new StringSource(messagePayload), new WebServiceMessageCallback() {

        @Override
        public void doWithMessage(WebServiceMessage message) throws IOException, TransformerException {
            SoapMessage soapMessage = (SoapMessage) message;
            final String attachmentContent = "content";
            soapMessage.addAttachment("attachment-1", new DataHandler(new ByteArrayDataSource(attachmentContent, "text/plain")));
        }
    }, new StringResult());
}
Example 81
Project: stanbol-master  File: MessageBodyReaderUtils.java View source code
/**
     * Returns content parsed from {@link MediaType#MULTIPART_FORM_DATA}.
     * It iterates over all {@link BodyPart}s and tries to create {@link RequestData}
     * instances. In case the {@link BodyPart#getContentType()} is not present or
     * can not be parsed, the {@link RequestData#getMediaType()} is set to 
     * <code>null</code>. If {@link BodyPart#getInputStream()} is not defined an
     * {@link IllegalArgumentException} is thrown. The {@link BodyPart#getFileName()}
     * is used for {@link RequestData#getName()}. The ordering of the returned
     * Content instances is the same as within the {@link MimeMultipart} instance
     * parsed from the input stream. <p>
     * This Method does NOT load the data into memory, but returns directly the
     * {@link InputStream}s as returned by the {@link BodyPart}s. Therefore
     * it is saved to be used with big attachments.<p>
     * This Method is necessary because within {@link MessageBodyReader} one
     * can not use the usual annotations as used within Resources. so this method
     * allows to access the data directly from the parameters available from the
     * {@link MessageBodyReader#readFrom(Class, Type, java.lang.annotation.Annotation[], MediaType, javax.ws.rs.core.MultivaluedMap, InputStream)}
     * method<p>
     * To test this Method with curl use:
     * <code><pre>
     * curl -v -X POST -F "content=@{dataFile};type={mimeType}" 
     *      {serviceURL}
     * </pre></code>
     * Note that between {contentParam} and the datafile MUST NOT be a '='!
     * @param mimeData the mime encoded data
     * @param mediaType the mediaType (parsed to the {@link ByteArrayDataSource}
     * constructor)
     * @return the contents parsed from the {@link BodyPart}s
     * @throws IOException an any Exception while reading the stream or 
     * {@link MessagingException} exceptions other than {@link ParseException}s
     * @throws IllegalArgumentException If a {@link InputStream} is not available
     * for any {@link BodyPart} or on {@link ParseException}s while reading the
     * MimeData from the stream.
     */
public static List<RequestData> fromMultipart(InputStream mimeData, MediaType mediaType) throws IOException, IllegalArgumentException {
    ByteArrayDataSource ds = new ByteArrayDataSource(mimeData, mediaType.toString());
    List<RequestData> contents = new ArrayList<RequestData>();
    try {
        MimeMultipart data = new MimeMultipart(ds);
        //For now search the first bodypart that fits and only debug the others
        for (int i = 0; i < data.getCount(); i++) {
            BodyPart bp = data.getBodyPart(i);
            String fileName = bp.getFileName();
            MediaType mt;
            try {
                mt = bp.getContentType() != null ? MediaType.valueOf(bp.getContentType()) : null;
            } catch (IllegalArgumentException e) {
                log.warn(String.format("Unable to parse MediaType form Mime Bodypart %s: " + " fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()), e);
                mt = null;
            }
            InputStream stream = bp.getInputStream();
            if (stream == null) {
                throw new IllegalArgumentException(String.format("Unable to get InputStream for Mime Bodypart %s: " + "mediaType %s fileName %s | Disposition %s | Description %s", i + 1, fileName, bp.getDisposition(), bp.getDescription()));
            } else {
                contents.add(new RequestData(mt, bp.getFileName(), stream));
            }
        }
    } catch (ParseException e) {
        throw new IllegalStateException(String.format("Unable to parse data from %s request", MediaType.MULTIPART_FORM_DATA_TYPE), e);
    } catch (MessagingException e) {
        throw new IOException("Exception while reading " + MediaType.MULTIPART_FORM_DATA_TYPE + " request", e);
    }
    return contents;
}
Example 82
Project: tesb-rt-se-master  File: RESTClient.java View source code
/**
     * Creates a XopBean. The image on the disk is included as a byte array, 
     * a DataHandler and java.awt.Image
     * @return the bean
     * @throws Exception
     */
private XopBean createXopBean() throws Exception {
    XopBean xop = new XopBean();
    xop.setName("xopName");
    InputStream is = getClass().getResourceAsStream("/java.jpg");
    byte[] data = IOUtils.readBytesFromStream(is);
    // Pass java.jpg as an array of bytes
    xop.setBytes(data);
    // Wrap java.jpg as a DataHandler
    xop.setDatahandler(new DataHandler(new ByteArrayDataSource(data, "application/octet-stream")));
    if (Boolean.getBoolean("java.awt.headless")) {
        System.out.println("Running headless. Ignoring an Image property.");
    } else {
        xop.setImage(getImage("/java.jpg"));
    }
    return xop;
}
Example 83
Project: triple-master  File: GenericEmailSender.java View source code
@Override
public void sendEmail(final String subject, final String htmlMessage, final File saveGame, final String saveGameName) throws IOException {
    // this is the last step and we create the email to send
    if (m_toAddress == null) {
        throw new IOException("Could not send email, no To address configured");
    }
    final Properties props = new Properties();
    if (getUserName() != null) {
        props.put("mail.smtp.auth", "true");
    }
    if (m_encryption == Encryption.TLS) {
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
    }
    props.put("mail.smtp.host", getHost());
    props.put("mail.smtp.port", getPort());
    props.put("mail.smtp.connectiontimeout", m_timeout);
    props.put("mail.smtp.timeout", m_timeout);
    final String to = m_toAddress;
    final String from = "noreply@triplea-game.org";
    // todo get the turn and player number from the game data
    try {
        final Session session = Session.getInstance(props, null);
        final MimeMessage mimeMessage = new MimeMessage(session);
        // Build the message fields one by one:
        // priority
        mimeMessage.setHeader("X-Priority", "3 (Normal)");
        // from
        mimeMessage.setFrom(new InternetAddress(from));
        // to address
        final StringTokenizer toAddresses = new StringTokenizer(to, " ", false);
        while (toAddresses.hasMoreTokens()) {
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddresses.nextToken().trim()));
        }
        // subject
        mimeMessage.setSubject(m_subjectPrefix + " " + subject);
        final MimeBodyPart bodypart = new MimeBodyPart();
        bodypart.setText(htmlMessage, "UTF-8");
        bodypart.setHeader("Content-Type", "text/html");
        if (saveGame != null) {
            final Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(bodypart);
            // add save game
            final FileInputStream fin = new FileInputStream(saveGame);
            final DataSource source = new ByteArrayDataSource(fin, "application/triplea");
            final BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(saveGameName);
            multipart.addBodyPart(messageBodyPart);
            mimeMessage.setContent(multipart);
        }
        // date
        try {
            mimeMessage.setSentDate(new Date());
        } catch (final Exception e) {
        }
        final Transport transport = session.getTransport("smtp");
        if (getUserName() != null) {
            transport.connect(getHost(), getPort(), getUserName(), getPassword());
        } else {
            transport.connect();
        }
        mimeMessage.saveChanges();
        transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
        transport.close();
    } catch (final MessagingException e) {
        throw new IOException(e.getMessage());
    }
}
Example 84
Project: carbon-commons-master  File: FileLogProvider.java View source code
@Override
public DataHandler downloadLogFile(String logFile, String tenantDomain, String serverKey) throws LogViewerException {
    InputStream is = null;
    ByteArrayDataSource bytArrayDS;
    int tenantId = LoggingUtil.getTenantIdForDomain(tenantDomain);
    try {
        is = getInputStream(logFile, tenantId, serverKey);
        bytArrayDS = new ByteArrayDataSource(is, APPLICATION_TYPE_ZIP);
        return new DataHandler(bytArrayDS);
    } catch (LogViewerException e) {
        log.error("Cannot read InputStream from the file " + logFile, e);
        throw e;
    } catch (IOException e) {
        String msg = "Cannot read file size from the " + logFile;
        log.error(msg, e);
        throw new LogViewerException(msg, e);
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                log.error("Error while closing inputStream of log file", e);
            }
        }
    }
}
Example 85
Project: dwoss-master  File: SalesListingProducerOperation.java View source code
/**
     * Prepare and send filejackets to the specified email address.
     * <p>
     * @param fileJackets files to be send
     */
private void prepareAndSend(List<FileJacket> fileJackets) {
    SubMonitor m = monitorFactory.newSubMonitor("Transfer");
    m.message("sending Mail");
    m.start();
    try {
        ListingMailConfiguration config = listingService.get().listingMailConfiguration();
        MultiPartEmail email = mandator.prepareDirectMail();
        email.setFrom(config.getFromAddress());
        email.addTo(config.getToAddress());
        email.setSubject(config.getSubject());
        email.setMsg(config.toMessage());
        for (FileJacket fj : fileJackets) {
            email.attach(new javax.mail.util.ByteArrayDataSource(fj.getContent(), "application/xls"), fj.getHead() + fj.getSuffix(), "Die Händlerliste für die Marke ");
        }
        email.send();
        m.finish();
    } catch (EmailException e) {
        throw new RuntimeException(e);
    }
}
Example 86
Project: harvester-master  File: ImageQueueConsumer.java View source code
/**
	 * This function convert the base64String encoded image to actual Image and store it in specified directory path
	 * @param base64String text encoded Image ,path Path to store the Image,This process repeats for every received message
	 * @throwsI OException
	 */
public static void WriteImageFromBase64(String base64String, String path) throws IOException {
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] buf = decoder.decodeBuffer(base64String);
    bytearr = new ByteArrayDataSource(buf, "image/jpeg");
    InputStream in = bytearr.getInputStream();
    File file = new File(path);
    byte buf1[] = new byte[1024];
    int len;
    FileOutputStream fos = new FileOutputStream(file);
    while ((len = in.read(buf)) > 0) fos.write(buf, 0, len);
    fos.close();
    in.close();
}
Example 87
Project: mateo-master  File: InformeProveedorController.java View source code
private void enviaCorreo(String tipo, List<InformeProveedor> informes, HttpServletRequest request) throws JRException, MessagingException {
    log.debug("Enviando correo {}", tipo);
    byte[] archivo = null;
    String tipoContenido = null;
    switch(tipo) {
        case "PDF":
            archivo = generaPdf(informes);
            tipoContenido = "application/pdf";
            break;
        case "CSV":
            archivo = generaCsv(informes);
            tipoContenido = "text/csv";
            break;
        case "XLS":
            archivo = generaXls(informes);
            tipoContenido = "application/vnd.ms-excel";
    }
    MimeMessage message = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(ambiente.obtieneUsuario().getUsername());
    String titulo = messageSource.getMessage("informe.lista.label", null, request.getLocale());
    helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[] { titulo }, request.getLocale()));
    helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[] { titulo }, request.getLocale()), true);
    helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
    mailSender.send(message);
}
Example 88
Project: mayocat-shop-master  File: SendEmailsWhenOrderIsPaid.java View source code
/**
     * Sends the actual notification mails.
     *
     * Warning: Since this is done in a spawned thread, so we can't use the web context thread local data from there
     *
     * @param order the order concerned by the notifications mails
     * @param tenant the tenant concerned by the notifications mails
     * @param customerLocale the locale the customer browsed the site in when checking out
     * @param tenantLocale the main locale of the tenant
     * @param withInvoice whether to generate and include a PDF invoice with the notification mail
     */
private void sendNotificationMails(Order order, Tenant tenant, Locale customerLocale, Locale tenantLocale, boolean withInvoice) {
    try {
        Customer customer = order.getCustomer();
        Optional<Address> billingAddress;
        if (order.getBillingAddress() != null) {
            billingAddress = Optional.of(order.getBillingAddress());
        } else {
            billingAddress = Optional.absent();
        }
        Optional<Address> deliveryAddress;
        if (order.getDeliveryAddress() != null) {
            deliveryAddress = Optional.of(order.getDeliveryAddress());
        } else {
            deliveryAddress = Optional.absent();
        }
        Map<String, Object> emailContext = prepareMailContext(order, customer, billingAddress, deliveryAddress, tenant, tenantLocale);
        String customerEmail = customer.getEmail();
        MailTemplate customerNotificationEmail = getCustomerNotificationEmail(tenant, customerEmail, customerLocale);
        MailTemplate tenantNotificationEmail = getTenantNotificationEmail(tenant, tenantLocale);
        // Generate invoice number and add add invoice to email if invoicing is enabled
        if (withInvoice) {
            try {
                // TODO: there should be a way to not load the whole PDF in memory...
                ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
                InvoiceNumber invoiceNumber = invoicingService.getOrCreateInvoiceNumber(order);
                invoicingService.generatePdfInvoice(order, pdfStream);
                MailAttachment attachment = new MailAttachment(new ByteArrayDataSource(pdfStream.toByteArray(), "application/pdf"), "invoice-" + invoiceNumber.getNumber() + ".pdf");
                customerNotificationEmail.addAttachment(attachment);
                tenantNotificationEmail.addAttachment(attachment);
            } catch (InvoicingException e) {
                logger.error("Failed to to generate invoice for email", e);
            }
        }
        sendNotificationMail(customerNotificationEmail, emailContext, tenant);
        sendNotificationMail(tenantNotificationEmail, emailContext, tenant);
    } catch (Exception e) {
        logger.error("Failed to send order notification email when sending email", e);
    }
}
Example 89
Project: PortlandStateJava-master  File: Survey.java View source code
private static MimeBodyPart createXmlAttachment(Student student) {
    byte[] xmlBytes = getXmlBytes(student);
    if (saveStudentXmlFile) {
        writeStudentXmlToFile(xmlBytes, student);
    }
    DataSource ds = new ByteArrayDataSource(xmlBytes, "text/xml");
    DataHandler dh = new DataHandler(ds);
    MimeBodyPart filePart = new MimeBodyPart();
    try {
        String xmlFileTitle = student.getId() + ".xml";
        filePart.setDataHandler(dh);
        filePart.setFileName(xmlFileTitle);
        filePart.setDescription("XML file for " + student.getFullName());
    } catch (MessagingException ex) {
        printErrorMessageAndExit("** Exception with file part", ex);
    }
    return filePart;
}
Example 90
Project: VIVO-Harvester-master  File: ImageQueueConsumer.java View source code
/**
	 * This function convert the base64String encoded image to actual Image and store it in specified directory path
	 * @param base64String text encoded Image ,path Path to store the Image,This process repeats for every received message
	 * @throwsI OException
	 */
public static void WriteImageFromBase64(String base64String, String path) throws IOException {
    BASE64Decoder decoder = new BASE64Decoder();
    byte[] buf = decoder.decodeBuffer(base64String);
    bytearr = new ByteArrayDataSource(buf, "image/jpeg");
    InputStream in = bytearr.getInputStream();
    File file = new File(path);
    byte buf1[] = new byte[1024];
    int len;
    FileOutputStream fos = new FileOutputStream(file);
    while ((len = in.read(buf)) > 0) fos.write(buf, 0, len);
    fos.close();
    in.close();
}
Example 91
Project: ice-master  File: BasicWeeklyCostEmailService.java View source code
private MimeBodyPart constructEmail(int index, ApplicationGroup appGroup, StringBuilder body) throws IOException, MessagingException {
    if (index == 0 && !StringUtils.isEmpty(headerNote))
        body.append(headerNote);
    numberFormatter.setMaximumFractionDigits(1);
    numberFormatter.setMinimumFractionDigits(1);
    File file = createImage(appGroup);
    if (file == null)
        return null;
    DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0);
    String link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end);
    body.append(String.format("<b><h4><a href='%s'>%s</a> Weekly Costs:</h4></b>", link, appGroup.getDisplayName()));
    body.append("<table style=\"border: 1px solid #DDD; border-collapse: collapse\">");
    body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td style=\"border-left: 1px solid #DDD;\"></td>");
    for (int i = 0; i <= accounts.size(); i++) {
        int cols = i == accounts.size() ? 1 : regions.size();
        String accName = i == accounts.size() ? "total" : accounts.get(i).name;
        body.append(String.format("<td style=\"border-left: 1px solid #DDD;font-weight: bold;padding: 4px\" colspan='%d'>", cols)).append(accName).append("</td>");
    }
    body.append("</tr>");
    body.append("<tr style=\"background-color: whiteSmoke;text-align:center\" ><td></td>");
    for (int i = 0; i < accounts.size(); i++) {
        boolean first = true;
        for (Region region : regions) {
            body.append("<td style=\"font-weight: bold;padding: 4px;" + (first ? "border-left: 1px solid #DDD;" : "") + "\">").append(region.name).append("</td>");
            first = false;
        }
    }
    body.append("<td style=\"border-left: 1px solid #DDD;\"></td></tr>");
    Map<String, Double> costs = Maps.newHashMap();
    Interval interval = new Interval(end.minusWeeks(numWeeks), end);
    double[] total = new double[numWeeks];
    for (Product product : products) {
        List<ResourceGroup> resourceGroups = getResourceGroups(appGroup, product);
        if (resourceGroups.size() == 0) {
            continue;
        }
        DataManager dataManager = config.managers.getCostManager(product, ConsolidateType.weekly);
        if (dataManager == null) {
            continue;
        }
        for (int i = 0; i < accounts.size(); i++) {
            List<Account> accountList = Lists.newArrayList(accounts.get(i));
            TagLists tagLists = new TagLists(accountList, regions, null, Lists.newArrayList(product), null, null, resourceGroups);
            Map<Tag, double[]> data = dataManager.getData(interval, tagLists, TagType.Region, AggregateType.none, false);
            for (Tag tag : data.keySet()) {
                for (int week = 0; week < numWeeks; week++) {
                    String key = accounts.get(i) + "|" + tag + "|" + week;
                    if (costs.containsKey(key))
                        costs.put(key, data.get(tag)[week] + costs.get(key));
                    else
                        costs.put(key, data.get(tag)[week]);
                    total[week] += data.get(tag)[week];
                }
            }
        }
    }
    boolean firstLine = true;
    DateTime currentWeekEnd = end;
    for (int week = numWeeks - 1; week >= 0; week--) {
        String weekStr;
        if (week == numWeeks - 1)
            weekStr = "Last week";
        else
            weekStr = (numWeeks - week - 1) + " weeks ago";
        String background = week % 2 == 1 ? "background: whiteSmoke;" : "";
        body.append(String.format("<tr style=\"%s\"><td nowrap style=\"border-left: 1px solid #DDD;padding: 4px\">%s (%s - %s)</td>", background, weekStr, formatter.print(currentWeekEnd.minusWeeks(1)).substring(5), formatter.print(currentWeekEnd).substring(5)));
        for (int i = 0; i < accounts.size(); i++) {
            Account account = accounts.get(i);
            for (int j = 0; j < regions.size(); j++) {
                Region region = regions.get(j);
                String key = account + "|" + region + "|" + week;
                double cost = costs.get(key) == null ? 0 : costs.get(key);
                Double lastCost = week == 0 ? null : costs.get(account + "|" + region + "|" + (week - 1));
                link = getLink("column", ConsolidateType.daily, appGroup, Lists.newArrayList(account), Lists.newArrayList(region), currentWeekEnd.minusWeeks(1), currentWeekEnd);
                body.append(getValueCell(cost, lastCost, link, firstLine));
            }
        }
        link = getLink("column", ConsolidateType.daily, appGroup, accounts, regions, currentWeekEnd.minusWeeks(1), currentWeekEnd);
        body.append(getValueCell(total[week], week == 0 ? null : total[week - 1], link, firstLine));
        body.append("</tr>");
        firstLine = false;
        currentWeekEnd = currentWeekEnd.minusWeeks(1);
    }
    body.append("</table>");
    numberFormatter.setMaximumFractionDigits(0);
    numberFormatter.setMinimumFractionDigits(0);
    if (!StringUtils.isEmpty(throughputMetrics))
        body.append(throughputMetrics);
    body.append("<br><img src=\"cid:image_cid_" + index + "\"><br>");
    for (Map.Entry<String, List<String>> entry : appGroup.data.entrySet()) {
        String product = entry.getKey();
        List<String> selected = entry.getValue();
        if (selected == null || selected.size() == 0)
            continue;
        link = getLink("area", ConsolidateType.hourly, appGroup, accounts, regions, end.minusWeeks(numWeeks), end);
        body.append(String.format("<b><h4>%s in <a href='%s'>%s</a>:</h4></b>", getResourceGroupsDisplayName(product), link, appGroup.getDisplayName()));
        for (String name : selected) body.append("     ").append(name).append("<br>");
    }
    body.append("<hr><br>");
    MimeBodyPart mimeBodyPart = new MimeBodyPart();
    mimeBodyPart.setFileName(file.getName());
    DataSource ds = new ByteArrayDataSource(new FileInputStream(file), "image/png");
    mimeBodyPart.setDataHandler(new DataHandler(ds));
    mimeBodyPart.setHeader("Content-ID", "<image_cid_" + index + ">");
    mimeBodyPart.setHeader("Content-Disposition", "inline");
    mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
    file.delete();
    return mimeBodyPart;
}
Example 92
Project: nifi-master  File: PutEmail.java View source code
@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final FlowFile flowFile = session.get();
    if (flowFile == null) {
        return;
    }
    final Properties properties = this.getMailPropertiesFromFlowFile(context, flowFile);
    final Session mailSession = this.createMailSession(properties);
    final Message message = new MimeMessage(mailSession);
    final ComponentLog logger = getLogger();
    try {
        message.addFrom(toInetAddresses(context, flowFile, FROM));
        message.setRecipients(RecipientType.TO, toInetAddresses(context, flowFile, TO));
        message.setRecipients(RecipientType.CC, toInetAddresses(context, flowFile, CC));
        message.setRecipients(RecipientType.BCC, toInetAddresses(context, flowFile, BCC));
        message.setHeader("X-Mailer", context.getProperty(HEADER_XMAILER).evaluateAttributeExpressions(flowFile).getValue());
        message.setSubject(context.getProperty(SUBJECT).evaluateAttributeExpressions(flowFile).getValue());
        String messageText = context.getProperty(MESSAGE).evaluateAttributeExpressions(flowFile).getValue();
        if (context.getProperty(INCLUDE_ALL_ATTRIBUTES).asBoolean()) {
            messageText = formatAttributes(flowFile, messageText);
        }
        String contentType = context.getProperty(CONTENT_TYPE).evaluateAttributeExpressions(flowFile).getValue();
        message.setContent(messageText, contentType);
        message.setSentDate(new Date());
        if (context.getProperty(ATTACH_FILE).asBoolean()) {
            final MimeBodyPart mimeText = new PreencodedMimeBodyPart("base64");
            mimeText.setDataHandler(new DataHandler(new ByteArrayDataSource(Base64.encodeBase64(messageText.getBytes("UTF-8")), contentType + "; charset=\"utf-8\"")));
            final MimeBodyPart mimeFile = new MimeBodyPart();
            session.read(flowFile, new InputStreamCallback() {

                @Override
                public void process(final InputStream stream) throws IOException {
                    try {
                        mimeFile.setDataHandler(new DataHandler(new ByteArrayDataSource(stream, "application/octet-stream")));
                    } catch (final Exception e) {
                        throw new IOException(e);
                    }
                }
            });
            mimeFile.setFileName(flowFile.getAttribute(CoreAttributes.FILENAME.key()));
            MimeMultipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeText);
            multipart.addBodyPart(mimeFile);
            message.setContent(multipart);
        }
        send(message);
        session.getProvenanceReporter().send(flowFile, "mailto:" + message.getAllRecipients()[0].toString());
        session.transfer(flowFile, REL_SUCCESS);
        logger.info("Sent email as a result of receiving {}", new Object[] { flowFile });
    } catch (final ProcessExceptionMessagingException | IOException |  e) {
        context.yield();
        logger.error("Failed to send email for {}: {}; routing to failure", new Object[] { flowFile, e.getMessage() }, e);
        session.transfer(flowFile, REL_FAILURE);
    }
}
Example 93
Project: pentaho-platform-plugin-reporting-master  File: SimpleEmailComponent.java View source code
private void processSpecificAttachment(final MimeMultipart mixedMultipart, final IContentItem attachmentContent) throws IOException, MessagingException {
    if (attachmentContent != null) {
        final ByteArrayDataSource dataSource = new ByteArrayDataSource(attachmentContent.getInputStream(), attachmentContent.getMimeType());
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
        attachmentBodyPart.setFileName(getAttachmentName());
        mixedMultipart.addBodyPart(attachmentBodyPart);
    }
}
Example 94
Project: rakam-master  File: ScheduledEmailService.java View source code
private void send(ScheduledEmailTask task, FutureCallback<Void> callback) throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart screenPart = new MimeBodyPart();
    String imageId = UUID.randomUUID().toString() + "@" + UUID.randomUUID().toString() + ".mail";
    screenPart.setHeader("Content-ID", "<" + imageId + ">");
    StringWriter writer;
    writer = new StringWriter();
    String path = "/" + task.project_id + "/dashboard/" + task.type_id;
    Map<String, Object> project;
    try (Handle handle = dbi.open()) {
        project = handle.createQuery("select project, api_url from web_user_project where id = :id").bind("id", task.project_id).first();
    }
    template.execute(writer, of("domain", this.siteHost, "session", webUserHttpService.getCookieForUser(task.user_id), "active_project", URLEncoder.encode(encode(of("name", project.get("project"), "apiUrl", project.get("api_url"))), "UTF-8"), "path", path));
    String txtContent = writer.toString();
    ListenableFuture<Void> run = executorService.submit(() -> {
        try {
            URL u = new URL(screenCaptureService.toString() + "/execute");
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Length", String.valueOf(txtContent.length()));
            try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
                wr.write(JsonHelper.encodeAsBytes(ImmutableMap.of("lua_source", txtContent, "timeout", 60)));
            }
            writer.flush();
            byte[] bytes;
            if (conn.getResponseCode() == 200) {
                bytes = ByteStreams.toByteArray(conn.getInputStream());
            } else {
                bytes = ByteStreams.toByteArray(conn.getErrorStream());
                throw new RuntimeException("Error while sending scheduled e-mail", new RuntimeException(new String(bytes)));
            }
            ZonedDateTime dateTime = Instant.now().atZone(ZoneOffset.UTC);
            String month = dateTime.getMonth().getDisplayName(SHORT, US);
            int day = dateTime.getDayOfMonth();
            String weekDay = dateTime.getDayOfWeek().getDisplayName(SHORT, US);
            DataSource dataSource = new ByteArrayDataSource(bytes, "image/png");
            screenPart.setDataHandler(new DataHandler(dataSource));
            screenPart.setFileName("dashboard.png");
            screenPart.setDisposition(MimeBodyPart.INLINE);
            String title = format("[Rakam] %s — %s, %s %d%s", task.name, weekDay, month, day, getDayOfMonthSuffix(day));
            mailSender.sendMail(task.emails, title, "Please view HTML version of the email, it contains the dashboard screenshot that is sent from Rakam UI.", Optional.of("<a href=\"https://" + siteHost + path + "\"> " + "<img alt=\"Rakam dashboard screenshot\" src=\"cid:" + imageId + "\" /></a>" + " <div style=\"color: white;\">Inline dashboard</div> <!-- This div allows the screenshot to be resized in android gmail, and shows as preview text. -->"), Stream.of(screenPart));
            return null;
        } catch (IOExceptionMessagingException |  e) {
            throw Throwables.propagate(e);
        }
    });
    Futures.addCallback(run, callback);
}
Example 95
Project: SpagoBI-Studio-master  File: UploadDatamartTemplateService.java View source code
public void run(IProgressMonitor monitor) throws InvocationTargetException {
    monitor.beginTask("Deploying model files (datamart.jar " + modelFileName + ")", IProgressMonitor.UNKNOWN);
    Template datamartTemplate = new Template();
    Template modelTemplate = new Template();
    // no more passed as separate file
    // Template xmlCalcFieldsTemplate = new Template();
    // defines properties for datamart file
    datamartTemplate.setFileName(datamartFile.getName());
    datamartTemplate.setFolderName(businessModel.getName());
    // create templates content
    FileDataSource fileDataSource = new FileDataSource(datamartFile);
    DataHandler dataHandler = new DataHandler(fileDataSource);
    datamartTemplate.setContent(dataHandler);
    logger.debug("built Datamart template with content data handler");
    // defines properties for sbimodel file
    modelTemplate.setFileName(modelFileName);
    modelTemplate.setFolderName(businessModel.getName());
    // create templates content
    try {
        ByteArrayDataSource byteDataSource = new ByteArrayDataSource(businessModelFile.getContents(), "application/octet-stream");
        dataHandler = new DataHandler(byteDataSource);
        modelTemplate.setContent(dataHandler);
        logger.debug("built Model template with content data handler");
    } catch (Exception e) {
        logger.error("error in getting model template", e);
        throw new InvocationTargetException(e);
    }
    try {
        // null stands for
        spagoBIServerObjects.getServerDocuments().uploadDatamartTemplate(datamartTemplate, null, userDataSource, userCategory);
    // no more passed
    // cfields.xml file
    } catch (RemoteException e2) {
        logger.error("error in uploading datamart", e2);
        throw new InvocationTargetException(e2);
    }
    try {
        spagoBIServerObjects.getServerDocuments().uploadDatamartModel(modelTemplate);
    } catch (RemoteException e3) {
        logger.error("error in uploading model file", e3);
        throw new InvocationTargetException(e3);
    }
    if (documentAlreadyPresent == false) {
        messageStatusDocument = "Detail: QBE Document with label " + businessModel.getName() + " added to server";
    }
    monitor.done();
    if (monitor.isCanceled())
        logger.error("Operation not ended", new InterruptedException("The long running operation was cancelled"));
}
Example 96
Project: VaadinUtils-master  File: JasperManager.java View source code
@Override
public void run() {
    JRSwapFileVirtualizer fileVirtualizer = null;
    CleanupCallback cleanupCallback = null;
    boolean initialized = false;
    try {
        logger.warn("{} permits are available", concurrentLimit.availablePermits());
        concurrentLimit.acquire();
        initialized = true;
        inQueue = false;
        queueEntry.setStatus("Gathering report data phase 1");
        reportProperties.initDBConnection();
        cleanupCallback = reportProperties.getCleanupCallback();
        List<ReportParameter<?>> extraParams = reportProperties.prepareData(params, reportProperties.getReportFileName(), cleanupCallback);
        compileReport();
        if (reportProperties.getCustomReportParameterMap() != null) {
            boundParams.putAll(reportProperties.getCustomReportParameterMap());
        }
        if (extraParams != null) {
            params.removeAll(extraParams);
            params.addAll(extraParams);
        }
        logger.info("Running report " + reportProperties.getReportFileName());
        for (ReportParameter<?> param : params) {
            for (String parameterName : param.getParameterNames()) {
                bindParameter(param, parameterName);
                if (param.displayInreport()) {
                    // populate dynamically added parameters to display user
                    // friendly parameters on the report
                    boundParams.put("ParamDisplay-" + parameterName, param.getDisplayValue(parameterName));
                }
                logger.info(parameterName + " " + param.getValue(parameterName));
            }
        }
        reportProperties.prepareForOutputFormat(exportMethod);
        CustomJRHyperlinkProducerFactory.setUseCustomHyperLinks(true);
        @SuppressWarnings("rawtypes") JRAbstractExporter exporter = null;
        queueEntry.setStatus("Gathering report data phase 2");
        // use file virtualizer to prevent out of heap
        String fileName = "/tmp";
        JRSwapFile file = new JRSwapFile(fileName, 100, 10);
        fileVirtualizer = new JRSwapFileVirtualizer(500, file);
        boundParams.put(JRParameter.REPORT_VIRTUALIZER, fileVirtualizer);
        if (stop) {
            return;
        }
        if (exportMethod == OutputFormat.CSV) {
            boundParams.put(JRParameter.IS_IGNORE_PAGINATION, true);
        }
        JasperPrint jasper_print = fillReport(exportMethod);
        switch(exportMethod) {
            case HTML:
                {
                    exporter = new JRHtmlExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, images);
                    if (VaadinServlet.getCurrent() != null) {
                        String context = VaadinServlet.getCurrent().getServletContext().getContextPath();
                        int contextIndex = Page.getCurrent().getLocation().toString().lastIndexOf(context);
                        String baseurl = Page.getCurrent().getLocation().toString().substring(0, contextIndex + context.length() + 1);
                        String imageUrl = baseurl + "VaadinJasperPrintServlet?image=";
                        exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, imageUrl);
                    } else {
                        logger.warn("Vaadin Servlet doens't have a current context");
                    }
                    break;
                }
            case PDF:
                {
                    exporter = new JRPdfExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    break;
                }
            case CSV:
                {
                    exporter = new JRCsvExporter();
                    exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasper_print);
                    break;
                }
            default:
                {
                    throw new RuntimeException("Unsupported export option " + exportMethod);
                }
        }
        imagesrcs = (images.size() <= 0) ? null : new DataSource[images.size()];
        if (imagesrcs != null) {
            int xi = 0;
            for (Map.Entry<String, byte[]> entry : images.entrySet()) {
                ByteArrayDataSource image = new ByteArrayDataSource(entry.getValue(), "image/gif");
                image.setName(entry.getKey());
                imagesrcs[xi++] = image;
            }
        }
        if (stop) {
            return;
        }
        createPageProgressMonitor(exporter);
        queueEntry.setStatus("Waiting for browser to start streaming");
        progressListener.outputStreamReady();
        if (readerReady.await(10, TimeUnit.SECONDS)) {
            outputStream = new PipedOutputStream(inputStream);
            writerReady.countDown();
            exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream);
            exporter.exportReport();
        } else {
            logger.error("Couldn't attach to reader stream");
        }
        Thread.sleep(750);
        queueEntry.setStatus("Cleaning up");
    } catch (Exception e) {
        logger.error(e, e);
    } finally {
        if (queueEntry != null) {
            jobQueue.remove(queueEntry);
            queueEntry = null;
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            logger.error(e, e);
        }
        if (cleanupCallback != null) {
            try {
                cleanupCallback.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        if (fileVirtualizer != null) {
            try {
                fileVirtualizer.cleanup();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        CustomJRHyperlinkProducerFactory.setUseCustomHyperLinks(false);
        if (initialized) {
            concurrentLimit.release();
            try {
                reportProperties.closeDBConnection();
            } catch (Exception e) {
                logger.error(e, e);
            }
        }
        completeBarrier.countDown();
        if (progressListener != null) {
            progressListener.completed();
        }
    }
}
Example 97
Project: voldemort-master  File: R2Store.java View source code
private List<Versioned<byte[]>> parseGetResponse(ByteString entity) {
    List<Versioned<byte[]>> results = new ArrayList<Versioned<byte[]>>();
    try {
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);
        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);
            String serializedVC = part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
            int contentLength = Integer.parseInt(part.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);
            if (logger.isDebugEnabled()) {
                logger.debug("Received VC : " + serializedVC);
            }
            VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);
            InputStream input = part.getInputStream();
            byte[] bodyPartBytes = new byte[contentLength];
            input.read(bodyPartBytes);
            VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
            results.add(new Versioned<byte[]>(bodyPartBytes, clock));
        }
    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonParseException e) {
        throw new VoldemortException("JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException("JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;
}
Example 98
Project: pentaho-kettle-master  File: Mail.java View source code
private void addAttachedContent(String filename, String fileContent) throws Exception {
    // create a data source
    MimeBodyPart mbp = new MimeBodyPart();
    // get a data Handler to manipulate this file type;
    mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(fileContent.getBytes(), "application/x-any")));
    // include the file in the data source
    mbp.setFileName(filename);
    // add the part with the file in the BodyPart();
    data.parts.addBodyPart(mbp);
}
Example 99
Project: Protocoder-master  File: PNetwork.java View source code
// http://mrbool.com/how-to-work-with-java-mail-api-in-android/27800#ixzz2tulYAG00
@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings) throws AddressException, MessagingException {
    if (emailSettings == null) {
        return;
    }
    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";
    Multipart multiPart;
    String finalString = "";
    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);
    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");
    multiPart = new MimeMultipart();
    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
                MLog.i("check", "sent");
            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    });
    t.start();
}
Example 100
Project: zen-project-master  File: HttpCoreHelper.java View source code
public List<NameValuePair> parseEntityWithDefaultUtf8(final HttpEntity entity) throws IOException {
    // = new LinkedList<NameValuePair>();
    List<NameValuePair> result;
    String contentType = null;
    String charset = UTF_8;
    Header h = entity.getContentType();
    if (h != null) {
        HeaderElement[] elems = h.getElements();
        if (elems.length > 0) {
            HeaderElement elem = elems[0];
            contentType = elem.getName();
            NameValuePair param = elem.getParameterByName("charset");
            if (param != null) {
                charset = param.getValue();
            }
        }
    }
    if (contentType != null && contentType.trim().toLowerCase().startsWith(CT_WWW_FORM_URLENCODED.toLowerCase())) {
        final String content = EntityUtils.toString(entity, charset);
        result = URLEncodedUtils.parse(content, Charset.forName(charset));
    //			parseUrlEncodedParamList(result, content, charset);
    } else {
        result = new LinkedList<NameValuePair>();
        if (isMultipart(entity)) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            entity.writeTo(baos);
            try {
                MimeMultipart mm = new MimeMultipart(new ByteArrayDataSource(baos.toByteArray(), CT_APPLICATION_OCTET_STREAM));
                for (int i = 0; i < mm.getCount(); i++) {
                    BodyPart bp = mm.getBodyPart(i);
                    String name = getBodyPartName(bp);
                    if (name != null) {
                        String value = null;
                        switch(bp.getContentType()) {
                            case CT_TEXT_PLAIN:
                                value = bp.getContent().toString();
                                break;
                            case CT_APPLICATION_OCTET_STREAM:
                                byte[] bytes = IO.readAndClose(bp.getInputStream());
                                value = base64.encodeClassic(bytes);
                                break;
                        }
                        result.add(new BasicNameValuePair(name, value));
                    }
                }
            } catch (// Exception instead of MessagingException (causes failure when building com.nominanuda.springsoy.SoySourceTest... why?)
            Exception // Exception instead of MessagingException (causes failure when building com.nominanuda.springsoy.SoySourceTest... why?)
            e) {
                throw new IOException();
            }
        }
    }
    return result;
}
Example 101
Project: eXist-1.4.x-master  File: SendEmailFunction.java View source code
/**
     * Constructs a mail Object from an XML representation of an email
     *
     * The XML email Representation is expected to look something like this
     *
     * <mail>
     * 	<from></from>
     * 	<reply-to></reply-to>
     * 	<to></to>
     * 	<cc></cc>
     * 	<bcc></bcc>
     * 	<subject></subject>
     * 	<message>
     * 		<text charset="" encoding=""></text>
     * 		<xhtml charset="" encoding=""></xhtml>
     * 		<generic charset="" type="" encoding=""></generic>
     * 	</message>
     * 	<attachment mimetype="" filename=""></attachment>
     * </mail>
     *
     * @param mailElements	The XML mail Node
     * @return		A mail Object representing the XML mail Node
     */
private List<Message> parseMessageElement(Session session, List<Element> mailElements) throws IOException, MessagingException, TransformerException {
    List<Message> mails = new ArrayList<Message>();
    for (Element mailElement : mailElements) {
        //Make sure that message has a Mail node
        if (mailElement.getLocalName().equals("mail")) {
            //New message Object
            // create a message
            MimeMessage msg = new MimeMessage(session);
            ArrayList<InternetAddress> replyTo = new ArrayList<InternetAddress>();
            boolean fromWasSet = false;
            MimeBodyPart body = null;
            Multipart multibody = null;
            ArrayList<MimeBodyPart> attachments = new ArrayList<MimeBodyPart>();
            String firstContent = null;
            String firstContentType = null;
            String firstCharset = null;
            String firstEncoding = null;
            //Get the First Child
            Node child = mailElement.getFirstChild();
            while (child != null) {
                //Parse each of the child nodes
                if (child.getNodeType() == Node.ELEMENT_NODE && child.hasChildNodes()) {
                    if (child.getLocalName().equals("from")) {
                        // set the from and to address
                        InternetAddress[] addressFrom = { new InternetAddress(child.getFirstChild().getNodeValue()) };
                        msg.addFrom(addressFrom);
                        fromWasSet = true;
                    } else if (child.getLocalName().equals("reply-to")) {
                        // As we can only set the reply-to, not add them, let's keep
                        // all of them in a list
                        replyTo.add(new InternetAddress(child.getFirstChild().getNodeValue()));
                        msg.setReplyTo(replyTo.toArray(new InternetAddress[0]));
                    } else if (child.getLocalName().equals("to")) {
                        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(child.getFirstChild().getNodeValue()));
                    } else if (child.getLocalName().equals("cc")) {
                        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(child.getFirstChild().getNodeValue()));
                    } else if (child.getLocalName().equals("bcc")) {
                        msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(child.getFirstChild().getNodeValue()));
                    } else if (child.getLocalName().equals("subject")) {
                        msg.setSubject(child.getFirstChild().getNodeValue());
                    } else if (child.getLocalName().equals("header")) {
                        // Optional : You can also set your custom headers in the Email if you Want
                        msg.addHeader(((Element) child).getAttribute("name"), child.getFirstChild().getNodeValue());
                    } else if (child.getLocalName().equals("message")) {
                        //If the message node, then parse the child text and xhtml nodes
                        Node bodyPart = child.getFirstChild();
                        while (bodyPart != null) {
                            if (bodyPart.getNodeType() != Node.ELEMENT_NODE)
                                continue;
                            Element elementBodyPart = (Element) bodyPart;
                            String content = null;
                            String contentType = null;
                            if (bodyPart.getLocalName().equals("text")) {
                                // Setting the Subject and Content Type
                                content = bodyPart.getFirstChild().getNodeValue();
                                contentType = "plain";
                            } else if (bodyPart.getLocalName().equals("xhtml")) {
                                //Convert everything inside <xhtml></xhtml> to text
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(bodyPart.getFirstChild());
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);
                                content = strWriter.toString();
                                contentType = "html";
                            } else if (bodyPart.getLocalName().equals("generic")) {
                                // Setting the Subject and Content Type
                                content = elementBodyPart.getFirstChild().getNodeValue();
                                contentType = elementBodyPart.getAttribute("type");
                            }
                            // Now, time to store it
                            if (content != null && contentType != null && contentType.length() > 0) {
                                String charset = elementBodyPart.getAttribute("charset");
                                String encoding = elementBodyPart.getAttribute("encoding");
                                if (body != null && multibody == null) {
                                    multibody = new MimeMultipart("alternative");
                                    multibody.addBodyPart(body);
                                }
                                if (charset == null || charset.length() == 0) {
                                    charset = "UTF-8";
                                }
                                if (encoding == null || encoding.length() == 0) {
                                    encoding = "quoted-printable";
                                }
                                if (body == null) {
                                    firstContent = content;
                                    firstCharset = charset;
                                    firstContentType = contentType;
                                    firstEncoding = encoding;
                                }
                                body = new MimeBodyPart();
                                body.setText(content, charset, contentType);
                                if (encoding != null) {
                                    body.setHeader("Content-Transfer-Encoding", encoding);
                                }
                                if (multibody != null)
                                    multibody.addBodyPart(body);
                            }
                            //next body part
                            bodyPart = bodyPart.getNextSibling();
                        }
                    } else if (child.getLocalName().equals("attachment")) {
                        Element attachment = (Element) child;
                        MimeBodyPart part = new MimeBodyPart();
                        StringBuilder content = new StringBuilder();
                        Node attachChild = attachment.getFirstChild();
                        while (attachChild != null) {
                            if (attachChild.getNodeType() == Node.ELEMENT_NODE) {
                                TransformerFactory transFactory = TransformerFactory.newInstance();
                                Transformer transformer = transFactory.newTransformer();
                                DOMSource source = new DOMSource(attachChild);
                                StringWriter strWriter = new StringWriter();
                                StreamResult result = new StreamResult(strWriter);
                                transformer.transform(source, result);
                                content.append(strWriter.toString());
                            } else {
                                content.append(attachChild.getNodeValue());
                            }
                            attachChild = attachChild.getNextSibling();
                        }
                        part.setDataHandler(new DataHandler(new ByteArrayDataSource(content.toString(), attachment.getAttribute("mimetype"))));
                        part.setFileName(attachment.getAttribute("filename"));
                        attachments.add(part);
                    }
                }
                //next node
                child = child.getNextSibling();
            }
            // Lost from
            if (!fromWasSet)
                msg.setFrom();
            // Preparing content and attachments
            if (attachments.size() > 0) {
                if (multibody == null) {
                    multibody = new MimeMultipart();
                    if (body != null) {
                        multibody.addBodyPart(body);
                    }
                }
                for (MimeBodyPart part : attachments) {
                    multibody.addBodyPart(part);
                }
            }
            // And now setting-up content
            if (multibody != null) {
                msg.setContent(multibody);
            } else if (body != null) {
                msg.setText(firstContent, firstCharset, firstContentType);
                if (firstEncoding != null) {
                    msg.setHeader("Content-Transfer-Encoding", firstEncoding);
                }
            }
            msg.saveChanges();
            mails.add(msg);
        }
    }
    return mails;
}