Java 类javax.mail.util.ByteArrayDataSource 实例源码

项目:Camel    文件:MailBinding.java   
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (contentType != null) {
        LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part);

        // always store content in a byte array data store to avoid various content type and charset issues
        String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody());
        // use empty data if the body was null for some reason (otherwise there is a NPE)
        data = data != null ? data : "";

        DataSource ds = new ByteArrayDataSource(data, contentType);
        part.setDataHandler(new DataHandler(ds));

        // set the content type header afterwards
        part.setHeader("Content-Type", contentType);
    }

    return contentType;
}
项目:jersey-smime    文件:SignedReader.java   
@Override
public SignedInput readFrom(Class<SignedInput> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> headers, InputStream entityStream) throws IOException, WebApplicationException {
    Class<?> baseType = null;
    Type baseGenericType = null;

    if (genericType instanceof ParameterizedType) {
        ParameterizedType param = (ParameterizedType) genericType;
        baseGenericType = param.getActualTypeArguments()[0];
        baseType = Types.getRawType(baseGenericType);
    }
    try {
        ByteArrayDataSource ds = new ByteArrayDataSource(entityStream, mediaType.toString());
        MimeMultipart mm = new MimeMultipart(ds);
        SignedInputImpl input = new SignedInputImpl();
        input.setType(baseType);
        input.setGenericType(baseGenericType);
        input.setAnnotations(annotations);
        input.setBody(mm);
        input.setProviders(providers);
        return input;
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }

}
项目:carrier    文件:SMTPMessageFactory.java   
/**
 * Creates a list of {@link MimeMessage} attachments using the given incoming e-mail.
 *
 * @param email The parsed e-mail.
 * @return A list containing the attachments, if any.
 * @throws Exception If there is an error while constructing the list of attachments.
 */
private List<BodyPart> createMimeMessageAttachments(Email email) throws Exception {

    List<BodyPart> attachments = new LinkedList<>();

    for (Attachment attachment : email.getAttachments()) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        attachmentBodyPart.setFileName(attachment.getAttachmentName());

        byte[] data = ByteStreams.toByteArray(attachment.getIs());
        DataSource source = new ByteArrayDataSource(data, "application/octet-stream");
        attachmentBodyPart.setDataHandler(new DataHandler(source));

        attachments.add(attachmentBodyPart);
    }

    return attachments;
}
项目:IdentityRegistry    文件:EmailUtil.java   
public void sendBugReport(BugReport report) throws MailException, MessagingException {
    MimeMessage message = this.mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setTo(bugReportEmail);
    helper.setFrom(from);
    helper.setSubject(report.getSubject());
    helper.setText(report.getDescription());
    if (report.getAttachments() != null) {
        for (BugReportAttachment attachment : report.getAttachments()) {
            // Decode base64 encoded data
            byte[] data =  Base64.getDecoder().decode(attachment.getData());
            ByteArrayDataSource dataSource = new ByteArrayDataSource(data, attachment.getMimetype());
            helper.addAttachment(attachment.getName(), dataSource);
        }
    }
    this.mailSender.send(message);
}
项目:Camel    文件:CxfMtomConsumerPayloadModeTest.java   
@Test
public void testConsumer() throws Exception {
    if (MtomTestHelper.isAwtHeadless(logger, null)) {
        return;
    }

    context.createProducerTemplate().send("cxf:bean:consumerEndpoint", new Processor() {

        public void process(Exchange exchange) throws Exception {
            exchange.setPattern(ExchangePattern.InOut);
            assertEquals("Get a wrong Content-Type header", "application/xop+xml", exchange.getIn().getHeader("Content-Type"));
            List<Source> elements = new ArrayList<Source>();
            elements.add(new DOMSource(StaxUtils.read(new StringReader(getRequestMessage())).getDocumentElement()));
            CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(),
                elements, null);
            exchange.getIn().setBody(body);
            exchange.getIn().addAttachment(MtomTestHelper.REQ_PHOTO_CID, 
                new DataHandler(new ByteArrayDataSource(MtomTestHelper.REQ_PHOTO_DATA, "application/octet-stream")));

            exchange.getIn().addAttachment(MtomTestHelper.REQ_IMAGE_CID, 
                new DataHandler(new ByteArrayDataSource(MtomTestHelper.requestJpeg, "image/jpeg")));
        }
    });
}
项目:Camel    文件:CxfMtomDisabledConsumerPayloadModeTest.java   
@SuppressWarnings("unchecked")
public void process(Exchange exchange) throws Exception {
    CxfPayload<SoapHeader> in = exchange.getIn().getBody(CxfPayload.class);

    // verify request
    Assert.assertEquals(1, in.getBody().size());

    DataHandler dr = exchange.getIn().getAttachment(MtomTestHelper.REQ_PHOTO_CID);
    Assert.assertEquals("application/octet-stream", dr.getContentType());
    MtomTestHelper.assertEquals(MtomTestHelper.REQ_PHOTO_DATA, IOUtils.readBytesFromStream(dr.getInputStream()));

    dr = exchange.getIn().getAttachment(MtomTestHelper.REQ_IMAGE_CID);
    Assert.assertEquals("image/jpeg", dr.getContentType());
    MtomTestHelper.assertEquals(MtomTestHelper.requestJpeg, IOUtils.readBytesFromStream(dr.getInputStream()));

    // create response
    List<Source> elements = new ArrayList<Source>();
    elements.add(new DOMSource(StaxUtils.read(new StringReader(MtomTestHelper.MTOM_DISABLED_RESP_MESSAGE)).getDocumentElement()));
    CxfPayload<SoapHeader> body = new CxfPayload<SoapHeader>(new ArrayList<SoapHeader>(),
        elements, null);
    exchange.getOut().setBody(body);
    exchange.getOut().addAttachment(MtomTestHelper.RESP_PHOTO_CID, 
        new DataHandler(new ByteArrayDataSource(MtomTestHelper.RESP_PHOTO_DATA, "application/octet-stream")));

    exchange.getOut().addAttachment(MtomTestHelper.RESP_IMAGE_CID, 
        new DataHandler(new ByteArrayDataSource(MtomTestHelper.responseJpeg, "image/jpeg")));

}
项目:Camel    文件:MailBinding.java   
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;
}
项目:Camel    文件:MimeMultipartDataFormatTest.java   
@Test
public void roundtripWithBinaryAttachments() throws IOException {
    String attContentType = "application/binary";
    byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7};
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    DataSource ds = new ByteArrayDataSource(attText, attContentType);
    in.addAttachment(attFileName, new DataHandler(ds));
    Exchange result = template.send("direct:roundtrip", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertArrayEquals(attText, os.toByteArray());
}
项目:Camel    文件:MimeMultipartDataFormatTest.java   
@Test
public void roundtripWithBinaryAttachmentsAndBinaryContent() throws IOException {
    String attContentType = "application/binary";
    byte[] attText = {0, 1, 2, 3, 4, 5, 6, 7};
    String attFileName = "Attachment File Name";
    in.setBody("Body text");
    DataSource ds = new ByteArrayDataSource(attText, attContentType);
    in.addAttachment(attFileName, new DataHandler(ds));
    Exchange result = template.send("direct:roundtripbinarycontent", exchange);
    Message out = result.getOut();
    assertEquals("Body text", out.getBody(String.class));
    assertTrue(out.hasAttachments());
    assertEquals(1, out.getAttachmentNames().size());
    assertThat(out.getAttachmentNames(), hasItem(attFileName));
    DataHandler dh = out.getAttachment(attFileName);
    assertNotNull(dh);
    assertEquals(attContentType, dh.getContentType());
    InputStream is = dh.getInputStream();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    IOHelper.copyAndCloseInput(is, os);
    assertArrayEquals(attText, os.toByteArray());
}
项目:openxds    文件:XdsTest.java   
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;
}
项目:openmeetings    文件:MailHandler.java   
protected MimeMessage appendIcsBody(MimeMessage msg, MailMessage m) throws Exception {
    log.debug("setMessageBody for iCal message");
    // -- Create a new message --
    Multipart multipart = new MimeMultipart();

    Multipart multiBody = new MimeMultipart("alternative");
    BodyPart html = new MimeBodyPart();
    html.setDataHandler(new DataHandler(new ByteArrayDataSource(m.getBody(), "text/html; charset=UTF-8")));
    multiBody.addBodyPart(html);

    BodyPart iCalContent = new MimeBodyPart();
    iCalContent.addHeader("content-class", "urn:content-classes:calendarmessage");
    iCalContent.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
            "text/calendar; charset=UTF-8; method=REQUEST")));
    multiBody.addBodyPart(iCalContent);
    BodyPart body = new MimeBodyPart();
    body.setContent(multiBody);
    multipart.addBodyPart(body);

    BodyPart iCalAttachment = new MimeBodyPart();
    iCalAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(new ByteArrayInputStream(m.getIcs()),
            "application/ics")));
    iCalAttachment.removeHeader("Content-Transfer-Encoding");
    iCalAttachment.addHeader("Content-Transfer-Encoding", "base64");
    iCalAttachment.removeHeader("Content-Type");
    iCalAttachment.addHeader("Content-Type", "application/ics");
    iCalAttachment.setFileName("invite.ics");
    multipart.addBodyPart(iCalAttachment);

    msg.setContent(multipart);
    return msg;
}
项目:muleebmsadapter    文件:AbstractEbMSDAO.java   
private List<DataSource> getAttachments(long messageId) throws DAOException
{
    try
    {
        return simpleJdbcTemplate.query(
            "select name, content_type, content" + 
            " from ebms_attachment" + 
            " where ebms_message_id = ?",
            new ParameterizedRowMapper<DataSource>()
            {
                @Override
                public DataSource mapRow(ResultSet rs, int rowNum) throws SQLException
                {
                    ByteArrayDataSource result = new ByteArrayDataSource(rs.getBytes("content"),rs.getString("content_type"));
                    result.setName(rs.getString("name"));
                    return result;
                }
            },
            messageId
        );
    }
    catch (DataAccessException e)
    {
        throw new DAOException(e);
    }
}
项目:muleebmsadapter    文件:EbMSMessageUtils.java   
public static EbMSMessage ebMSMessageContentToEbMSMessage(CollaborationProtocolAgreement cpa, EbMSMessageContent content, String hostname) throws DatatypeConfigurationException
{
    MessageHeader messageHeader = createMessageHeader(cpa,content.getContext(),hostname);

    AckRequested ackRequested = createAckRequested(cpa,content.getContext());

    Manifest manifest = createManifest();
    for (int i = 0; i < content.getAttachments().size(); i++)
        manifest.getReference().add(createReference(i + 1));

    List<DataSource> attachments = new ArrayList<DataSource>();
    for (EbMSAttachment attachment : content.getAttachments())
    {
        ByteArrayDataSource ds = new ByteArrayDataSource(attachment.getContent(),attachment.getContentType());
        ds.setName(attachment.getName());
        attachments.add(ds);
    }

    return new EbMSMessage(messageHeader,ackRequested,manifest,attachments);
}
项目:Tournament    文件:SmtpMailService.java   
/**
 * Add file attachments to multi part document
 *
 * @param multipart
 * @param attachments
 * @throws MessagingException
 */
private static void addFileAttachments(MimeMultipart multipart, List<MailAttachmentPO> attachments)
                throws MessagingException
{
    for (MailAttachmentPO attachment : attachments)
    {
        if (null == attachment.getCid() || attachment.getCid().isEmpty())
        {
            DataSource byteDataSource = new ByteArrayDataSource(attachment.getContent(), attachment.getMimeType());

            DataHandler attachementDataHandler = new DataHandler(byteDataSource);

            BodyPart memoryBodyPart = new MimeBodyPart();

            memoryBodyPart.setDataHandler(attachementDataHandler);

            memoryBodyPart.setFileName(attachment.getName());

            // Add part to multi-part
            multipart.addBodyPart(memoryBodyPart);
        }
    }
}
项目:blynk-server    文件:GMailClient.java   
private void attachCSV(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    StringBuilder sb = new StringBuilder();
    for (QrHolder qrHolder : attachmentData) {
        sb.append(qrHolder.token)
        .append(",")
        .append(qrHolder.deviceId)
        .append(",")
        .append(qrHolder.dashId)
        .append("\n");
    }
    MimeBodyPart attachmentsPart = new MimeBodyPart();
    ByteArrayDataSource source = new ByteArrayDataSource(sb.toString(), "text/csv");
    attachmentsPart.setDataHandler(new DataHandler(source));
    attachmentsPart.setFileName("tokens.csv");

    multipart.addBodyPart(attachmentsPart);
}
项目:Lapwing    文件:ITSProcessorImpl.java   
@Override
public SOAPResponse check(SOAPRequest input) throws ServerException {

    Pipeline pipeline = new Pipeline();
    byte[] annotatedFile;
    try {
        Input ltinput = new Input();
        ltinput.setData(input.getData().getInputStream());
        ltinput.setEncoding(input.getEncoding());
        ltinput.setSrcLocale(input.getSource());
        ltinput.setTgtLocale(input.getTarget());
        Output output = pipeline.check(ltinput);
        SOAPResponse response = new SOAPResponse();
        annotatedFile = IOUtils.readBytesFromStream(output.getData());
        DataSource responseFile = new ByteArrayDataSource(annotatedFile,
                ITSProcessorImpl.OUTPUT_MIME_TYPE);
        DataHandler handler = new DataHandler(responseFile);
        response.setData(handler);
        response.setEncoding(output.getEncoding());
        return response;
    } catch (Exception e) {
        throw new ServerException(e);
    }

}
项目:openhim-mediator-xds    文件:XDSbMimeProcessorActor.java   
private void parseMimeMessage(String msg, String contentType) throws IOException, MessagingException, SOAPPartNotFound, UnprocessableContentFound {
    mimeMessage = new MimeMultipart(new ByteArrayDataSource(msg, contentType));
    for (int i=0; i<mimeMessage.getCount(); i++) {
        BodyPart part = mimeMessage.getBodyPart(i);

        if (part.getContentType().contains("application/soap+xml")) {
            _soapPart = getValue(part);
        } else {
            _documents.add(getValue(part));
        }
    }

    if (_soapPart==null) {
        throw new SOAPPartNotFound();
    }
}
项目:xltestview-plugin    文件:XLTestServerImplTest.java   
private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException {
    assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1");
    assertEquals(request.getHeader("accept"), "application/json; charset=utf-8");
    assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4=");
    assertThat(request.getHeader("Content-Length"), is(nullValue()));
    assertThat(request.getHeader("Transfer-Encoding"), is("chunked"));
    assertThat(request.getChunkSizes().get(0), greaterThan(0));
    assertThat(request.getChunkSizes().size(), greaterThan(0));

    assertTrue(request.getBodySize() > 0);

    ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed");
    MimeMultipart mp = new MimeMultipart(bads);
    assertTrue(request.getBodySize() > 0);

    assertEquals(mp.getCount(), 2);
    assertEquals(mp.getContentType(), "multipart/mixed");

    // TODO could do additional checks on metadata content
    BodyPart bodyPart1 = mp.getBodyPart(0);
    assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8");

    BodyPart bodyPart2 = mp.getBodyPart(1);
    assertEquals(bodyPart2.getContentType(), "application/zip");
}
项目:cleverbus    文件:EmailServiceCamelSmtpImpl.java   
@Override
public void sendEmail(final Email email) {
    Assert.notNull(email, "email can not be null");
    Assert.notEmpty(email.getRecipients(), "email must have at least one recipients");
    Assert.hasText(email.getSubject(), "subject in email can not be empty");
    Assert.hasText(email.getBody(), "body in email can not be empty");

    producerTemplate.send("smtp://" + smtp, new Processor() {
        @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(), "*/*")));
                }
            }
        }
    });
}
项目:elasticsearch-imap    文件:AttachmentMapperTest.java   
@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));

}
项目:camel-agent    文件:MailBinding.java   
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;
}
项目:camel-agent    文件:MailBinding.java   
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange)
    throws MessagingException, IOException {

    String contentType = determineContentType(configuration, exchange);

    if (contentType != null) {
        LOG.trace("Using Content-Type {} for BodyPart: {}", contentType, part);

        // always store content in a byte array data store to avoid various content type and charset issues
        String data = exchange.getContext().getTypeConverter().tryConvertTo(String.class, exchange.getIn().getBody());
        // use empty data if the body was null for some reason (otherwise there is a NPE)
        data = data != null ? data : "";

        DataSource ds = new ByteArrayDataSource(data, contentType);
        part.setDataHandler(new DataHandler(ds));

        // set the content type header afterwards
        part.setHeader("Content-Type", contentType);
    }

    return contentType;
}
项目:PortlandStateJava    文件:Survey.java   
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;
}
项目:extemporal    文件:EmailTestPlatform.java   
protected boolean transmitEmail(String to, ByteBuffer msgContent, Message emailSkeleton)
{
    try {
        if (emailSkeleton == null) {
            emailSkeleton = new MimeMessage(mSession);
            emailSkeleton.setFrom(new InternetAddress(mEndpoint));
            emailSkeleton.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        }

        byte[] mc = new byte[msgContent.remaining()];
        msgContent.get(mc);
        ByteArrayDataSource dSrc = new ByteArrayDataSource(mc, "application/octet-stream");
        emailSkeleton.setDataHandler(new DataHandler(dSrc));

        final Transport channel = mSession.getTransport(mSmtpAccountURN);
        channel.connect();  // throws if can't connect
        channel.sendMessage(emailSkeleton, emailSkeleton.getRecipients(Message.RecipientType.TO));
        channel.close();
    }
    catch (MessagingException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
项目:dropwizard-jaxws    文件:JAXWSEnvironmentTest.java   
@Test
public void publishEndpointWithMtom() throws Exception {

    jaxwsEnvironment.publishEndpoint(
            new EndpointBuilder("local://path", service)
                    .enableMtom());

    verify(mockInvokerBuilder).create(any(), any(Invoker.class));

    byte[] response = testutils.invokeBytes("local://path", LocalTransportFactory.TRANSPORT_ID, soapRequest.getBytes());

    verify(mockInvoker).invoke(any(Exchange.class), any());

    MimeMultipart mimeMultipart = new MimeMultipart(new ByteArrayDataSource(response,
            "application/xop+xml; charset=UTF-8; type=\"text/xml\""));
    assertThat(mimeMultipart.getCount(), equalTo(1));
    testutils.assertValid("/soap:Envelope/soap:Body/a:fooResponse",
            StaxUtils.read(mimeMultipart.getBodyPart(0).getInputStream()));
}
项目:dropwizard-jaxws    文件:AccessMtomServiceResource.java   
@GET
@Timed
public String getFoo() {

    ObjectFactory of = new ObjectFactory();
    Hello h = of.createHello();
    h.setTitle("Hello");
    h.setBinary(new DataHandler(new ByteArrayDataSource("test".getBytes(), "text/plain")));

    HelloResponse hr = mtomServiceClient.hello(h);

    try {
        return "Hello response: " + hr.getTitle() + ", " +
                IOUtils.readStringFromStream(hr.getBinary().getInputStream());
    }
    catch (IOException e) {
        throw new RuntimeException(e);
    }
}
项目:jersey-smime    文件:SignedTest.java   
@Test
public void testOutput2() throws Exception {
    SMIMESignedGenerator gen = new SMIMESignedGenerator();
    SignerInfoGenerator signer = new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC").build("SHA1WITHRSA", privateKey, cert);
    gen.addSignerInfoGenerator(signer);

    MimeMultipart mp = gen.generate(createMsg());

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mp.writeTo(os);

    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    String contentType = mp.getContentType();
    contentType = contentType.replace("\r\n", "").replace("\t", " ");

    ByteArrayDataSource ds = new ByteArrayDataSource(is, contentType);
    MimeMultipart mm = new MimeMultipart(ds);
    MimeBodyPart part = (MimeBodyPart) mm.getBodyPart(0);


}
项目:logistimo-web-service    文件:EmailService.java   
private void addAttachment(Multipart mp, byte[] attachmentData, String mimeType, String filename)
    throws MessagingException {
  if (mp == null) {
    return;
  }
  ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentData, mimeType);
  MimeBodyPart attachment = new MimeBodyPart();
  attachment.setFileName(filename);
  attachment.setDataHandler(new DataHandler(dataSrc));
  ///attachment.setContent( attachmentData, mimeType );
  mp.addBodyPart(attachment);
}
项目:logistimo-web-service    文件:EmailService.java   
private void addAttachmentStream(Multipart mp, InputStream attachmentStream, String mimeType,
                                 String filename, BodyPart message)
    throws MessagingException, IOException {
  if (mp == null) {
    return;
  }
  ByteArrayDataSource dataSrc = new ByteArrayDataSource(attachmentStream, mimeType);
  MimeBodyPart attachment = new MimeBodyPart();
  attachment.setFileName(filename);
  attachment.setDataHandler(new DataHandler(dataSrc));
  ///attachment.setContent( attachmentData, mimeType );
  mp.addBodyPart(message);
  mp.addBodyPart(attachment);
}
项目:chronos    文件:CallableQuery.java   
@CoverageIgnore
private static DataSource createAttachment(PersistentResultSet results) {
  try {
    String text = makeAttachmentText(results);
    DataSource source = new ByteArrayDataSource(text, TSV);
    return source;
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
项目:openex-worker    文件:EmailAttacher.java   
@SuppressWarnings({"unused", "unchecked"})
public void process(Exchange exchange) {
    List<EmailAttachment> filesContent = (List) exchange.getProperty(ATTACHMENTS_CONTENT, new ArrayList<>());
    for (EmailAttachment attachment : filesContent) {
        ByteArrayDataSource bds = new ByteArrayDataSource(attachment.getData(), attachment.getContentType());
        exchange.getIn().addAttachmentObject(attachment.getName(), new DefaultAttachment(bds));
    }
}
项目:SoapUI-Cookbook    文件:InvoicePortImpl.java   
public void getInvoice(javax.xml.ws.Holder<java.lang.String> invoiceNo,
        javax.xml.ws.Holder<java.lang.String> company,
        javax.xml.ws.Holder<java.lang.Double> amount,
        javax.xml.ws.Holder<javax.activation.DataHandler> file) {

    LOG.info("Executing operation getInvoice");
    System.out.println("Invoice no: "+invoiceNo.value);

    try {
        company.value = "company";
        System.out.println("Company: "+company.value);
        amount.value = 100d;
        System.out.println("Amount: "+amount);

        String attachmentFileName = "/temp/invoice1.pdf";
        System.out.println("Attachment: "+attachmentFileName);
        File attachment = new File(attachmentFileName);
        InputStream attachmentInputStream = new FileInputStream(attachment);
        ByteArrayOutputStream responseOutputStream = new ByteArrayOutputStream();
        copyInputStreamToOutputStream(attachmentInputStream,
                responseOutputStream);
        System.out.println("Attachment size: "
                + responseOutputStream.size());
        attachmentInputStream.close();
        file.value = new DataHandler(new ByteArrayDataSource(
                responseOutputStream.toByteArray(), "application/pdf"));

    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}
项目:qianworks-meican    文件:MimeMessageParser.java   
/**
 * Parses the MimePart to create a DataSource.
 *
 * @param part   the current part to be processed
 * @return the DataSource
 * @throws MessagingException creating the DataSource failed
 * @throws IOException        creating the DataSource failed
 */
private static DataSource createDataSource(final MimePart part)
        throws MessagingException, IOException {
    final DataHandler dataHandler = part.getDataHandler();
    final DataSource dataSource = dataHandler.getDataSource();
    final String contentType = getBaseMimeType(dataSource.getContentType());
    final byte[] content = MimeMessageParser.getContent(dataSource.getInputStream());
    final ByteArrayDataSource result = new ByteArrayDataSource(content, contentType);
    final String dataSourceName = getDataSourceName(part, dataSource);

    result.setName(dataSourceName);
    return result;
}
项目:Camel    文件:MimeMultipartDataFormat.java   
private void writeBodyPart(byte[] bodyContent, Part part, ContentType contentType) throws MessagingException {
    DataSource ds = new ByteArrayDataSource(bodyContent, contentType.toString());
    part.setDataHandler(new DataHandler(ds));
    part.setHeader(CONTENT_TYPE, contentType.toString());
    if (contentType.match("text/*")) {
        part.setHeader(CONTENT_TRANSFER_ENCODING, "8bit");
    } else if (binaryContent) {
        part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
    } else {
        part.setHeader(CONTENT_TRANSFER_ENCODING, "base64");
    }
}
项目:metaworks_framework    文件:MessageCreator.java   
public MimeMessagePreparator buildMimeMessagePreparator(final Map<String, Object> props) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @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);
            }
        }
    };
    return preparator;

}