Example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource

List of usage examples for javax.mail.util ByteArrayDataSource ByteArrayDataSource

Introduction

In this page you can find the example usage for javax.mail.util ByteArrayDataSource ByteArrayDataSource.

Prototype

public ByteArrayDataSource(String data, String type) throws IOException 

Source Link

Document

Create a ByteArrayDataSource with data from the specified String and with the specified MIME type.

Usage

From source file:com.threepillar.labs.meeting.email.EmailInviteImpl.java

@Override
public void sendInvite(final String subject, final String description, final Participant from,
        final List<Participant> attendees, final Date startDate, final Date endDate, final String location)
        throws Exception {

    this.properties.put("mail.smtp.socketFactory.port", properties.get("mail.smtp.port"));
    this.properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    this.properties.put("mail.smtp.socketFactory.fallback", "false");

    validate();/*  w w w  .j  a v a2  s .  c  o m*/

    LOG.info("Sending meeting invite");
    LOG.debug("Mail Properties :: " + this.properties);

    Session session;
    if (password != null) {
        session = Session.getInstance(this.properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
    } else {
        session = Session.getInstance(this.properties);
    }

    ICal cal = new ICal(subject, description, from, attendees, startDate, endDate, location);
    cal.init();

    StringBuffer sb = new StringBuffer();
    sb.append(from.getEmail());
    for (Participant bean : attendees) {
        if (sb.length() > 0) {
            sb.append(",");
        }
        sb.append(bean.getEmail());
    }
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from.getEmail()));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(sb.toString()));
    message.setSubject(subject);
    Multipart multipart = new MimeMultipart();
    MimeBodyPart iCal = new MimeBodyPart();
    iCal.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(cal.toByteArray()),
            "text/calendar;method=REQUEST;charset=\"UTF-8\"")));

    LOG.debug("Calender Request :: \n" + cal.toString());

    multipart.addBodyPart(iCal);
    message.setContent(multipart);
    Transport.send(message);
}

From source file:org.wso2.carbon.logging.service.provider.FileLogProvider.java

@Override
public DataHandler downloadLogFile(String logFile, String tenantDomain, String serverKey)
        throws LogViewerException {
    InputStream is = null;/*from ww w  . ja v  a2s  . c  om*/
    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);
            }
        }
    }
}

From source file:org.openehealth.ipf.platform.camel.lbs.cxf.process.LbsCxfHugeFileTest.java

@Test
@Ignore//from   w w w .  j  av  a  2s.  c  o m
public void testHugeFile() throws Exception {
    TrackMemThread memTracker = new TrackMemThread();
    memTracker.start();
    try {
        DataSource dataSourceAttachInfo = new ByteArrayDataSource("Smaller content",
                "application/octet-stream");
        DataHandler dataHandlerAttachInfo = new DataHandler(dataSourceAttachInfo);
        Holder<DataHandler> handlerHolderAttachInfo = new Holder(dataHandlerAttachInfo);

        DataSource dataSourceOneWay = new InputStreamDataSource();
        DataHandler dataHandlerOneWay = new DataHandler(dataSourceOneWay);

        Holder<String> nameHolder = new Holder("Hello Camel!!");
        greeter.postMe(nameHolder, handlerHolderAttachInfo, dataHandlerOneWay);

        assertEquals("resultText", nameHolder.value);
        InputStream resultInputStream = handlerHolderAttachInfo.value.getInputStream();
        try {
            assertTrue(IOUtils.contentEquals(new HugeContentInputStream(), resultInputStream));
        } finally {
            resultInputStream.close();
        }
    } finally {
        memTracker.waitForStop();
        assertTrue("Memory consumption not constant. Difference was: " + memTracker.getDiff(),
                memTracker.getDiff() < 10000);
    }
}

From source file:org.apromore.service.impl.CanoniserServiceImplIntgTest.java

@Test
public void deCanoniseWithIncorrectType() throws IOException {
    String name = "Canonical";
    InputStream cpf = new ByteArrayDataSource(CanonicalNoAnnotationModel.CANONICAL_XML, "text/xml")
            .getInputStream();/*ww w  .  ja  v a 2  s  .co m*/

    try {
        cSrv.deCanonise(name, getTypeFromXML(cpf), null, emptyCanoniserRequest);
        fail();
    } catch (CanoniserException e) {
        assertTrue(e.getCause() instanceof PluginNotFoundException);
    } catch (JAXBException | SAXException e) {
        fail();
    }
}

From source file:org.sventon.mail.MailNotifier.java

/**
 * @param logEntry       Log entry//from  ww  w . j  a v a 2 s  . c om
 * @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;
}

From source file:org.sventon.repository.observer.MailNotifier.java

/**
 * @param logEntry       Log entry/*from ww  w.  ja  v  a2s  . c o m*/
 * @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 SVNLogEntry 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;
}

From source file:se.inera.axel.shs.camel.ShsMessageDataFormatTest.java

@DirtiesContext
@Test//from   ww  w.jav  a 2s  .c om
public void testMarshalPdf() throws Exception {
    Assert.assertNotNull(testShsMessage);
    Assert.assertNotNull(testPdfFile);

    testShsMessage.getDataParts().remove(0);
    DataPart dataPart = new DataPart(
            new DataHandler(new ByteArrayDataSource(testPdfFile.getInputStream(), "application/xml")));
    dataPart.setContentType("application/xml");
    dataPart.setFileName(testPdfFile.getFilename());
    dataPart.setTransferEncoding("base64");
    dataPart.setDataPartType("pdf");

    testShsMessage.getDataParts().add(dataPart);

    resultEndpoint.expectedMessageCount(1);
    template.sendBody("direct:marshalRoundtrip", testShsMessage);

    resultEndpoint.assertIsSatisfied();
    List<Exchange> exchanges = resultEndpoint.getReceivedExchanges();
    Exchange exchange = exchanges.get(0);

    ShsMessage shsMessage = exchange.getIn().getMandatoryBody(ShsMessage.class);

    Assert.assertNotSame(shsMessage, testShsMessage);

    ShsLabel label = shsMessage.getLabel();

    Assert.assertNotNull(label, "label should not be null");

    Assert.assertEquals(label.getSubject(), testShsMessage.getLabel().getSubject());
    Assert.assertEquals(label.getDatetime().toString(), testShsMessage.getLabel().getDatetime().toString());

    Assert.assertNotNull(testShsMessage.getDataParts());
    DataPart dataPartResponse = testShsMessage.getDataParts().get(0);

    Assert.assertTrue(isSame(testPdfFile.getInputStream(), dataPartResponse.getDataHandler().getInputStream()),
            "Response data stream is not same as source data stream");
}

From source file:mitm.application.djigzo.ca.PFXMailBuilder.java

private void replacePFX(MimeMessage message) throws MessagingException {
    Multipart mp;//from w  ww . ja va  2  s  .  c  o m

    try {
        mp = (Multipart) message.getContent();
    } catch (IOException e) {
        throw new MessagingException("Error getting message content.", e);
    }

    BodyPart pfxPart = null;

    /*
     * Fallback in case the template does not contain a DjigzoHeader.MARKER
     */
    BodyPart octetStreamPart = null;

    /*
     * Try to find the first attachment with X-Djigzo-Marker attachment header which should be the attachment
     * we should replace (we should replace the content and keep the headers)
     */
    for (int i = 0; i < mp.getCount(); i++) {
        BodyPart part = mp.getBodyPart(i);

        if (ArrayUtils.contains(part.getHeader(DjigzoHeader.MARKER), DjigzoHeader.ATTACHMENT_MARKER_VALUE)) {
            pfxPart = part;

            break;
        }

        /*
         * Fallback scanning for octet-stream in case the template does not contain a DjigzoHeader.MARKER
         */
        if (part.isMimeType("application/octet-stream")) {
            octetStreamPart = part;
        }
    }

    if (pfxPart == null) {
        if (octetStreamPart != null) {
            logger.info("Marker not found. Using ocet-stream instead.");

            /*
             * Use the octet-stream part
             */
            pfxPart = octetStreamPart;
        } else {
            throw new MessagingException("Unable to find the attachment part in the template.");
        }
    }

    pfxPart.setDataHandler(new DataHandler(new ByteArrayDataSource(pfx, "application/octet-stream")));
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.ws.impl.MultimediaWSDaoTestBase.java

protected BlackboardMultimediaResponse createRepoMultimedia() throws Exception {
    InputStream is = new ByteArrayInputStream("fdsdfsfsdadsfasfda".getBytes());
    ByteArrayDataSource rawData = new ByteArrayDataSource(is, "video/mpeg");
    DataHandler dataHandler = new DataHandler(rawData);

    BlackboardMultimediaResponse uploadRepositoryMultimedia = dao.uploadRepositoryMultimedia(user.getEmail(),
            "test.mpeg", "aliens", dataHandler);
    multimedias.add(uploadRepositoryMultimedia.getMultimediaId());
    return uploadRepositoryMultimedia;
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Uncompresses message data*/
public byte[] decompressData(AS2MessageInfo info, byte[] data, String contentType) throws Exception {
    MimeBodyPart compressedPart = new MimeBodyPart();
    compressedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    compressedPart.setHeader("content-type", contentType);
    return (this.decompressData(info, new SMIMECompressed(compressedPart), compressedPart.getSize()));
}