Java Examples for org.springframework.core.io.InputStreamSource

The following java examples will help you to understand the usage of org.springframework.core.io.InputStreamSource. These source code samples are taken from different open source projects.

Example 1
Project: cas-master  File: X509CredentialFactory.java View source code
@Override
public Credential fromRequestBody(final MultiValueMap<String, String> requestBody) {
    final String cert = requestBody.getFirst(CERTIFICATE);
    LOGGER.debug("Certificate in the request body: [{}]", cert);
    if (StringUtils.isBlank(cert)) {
        return super.fromRequestBody(requestBody);
    }
    final InputStream is = new ByteArrayInputStream(cert.getBytes());
    final InputStreamSource iso = new InputStreamResource(is);
    final X509Certificate certificate = CertUtils.readCertificate(iso);
    final X509CertificateCredential credential = new X509CertificateCredential(new X509Certificate[] { certificate });
    credential.setCertificate(certificate);
    return credential;
}
Example 2
Project: spring-ws-master  File: AbstractSoap11MessageTestCase.java View source code
@Override
public void testWriteToTransportResponseAttachment() throws Exception {
    InputStreamSource inputStreamSource = new ByteArrayResource("contents".getBytes("UTF-8"));
    soapMessage.addAttachment("contentId", inputStreamSource, "text/plain");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    MockTransportOutputStream tos = new MockTransportOutputStream(bos);
    soapMessage.writeTo(tos);
    String contentType = tos.getHeaders().get("Content-Type");
    assertTrue("Content-Type for attachment message does not contains multipart/related", contentType.indexOf("multipart/related") != -1);
    assertTrue("Content-Type for attachment message does not contains type=\"text/xml\"", contentType.indexOf("type=\"text/xml\"") != -1);
}
Example 3
Project: niolex-common-utils-master  File: EmailUtil.java View source code
/**
     * Send an email.
     * 同步发送指定参数的邮件
     *
     * @param from the email sender
     * @param tos the email receiver list
     * @param title the email title
     * @param text the email body
     * @param attachments a list of files attachments
     * @param priority priority from 1-5 the smaller is higher
     * @param isHtml is the text in HTML format or not
     * @param encoding the encoding of email, i.e. "GBK"、"UTF-8"
     * @throws MailException in case of failure when sending the message
     * @throws MessagingException if failed to create multi-part email message
     */
public static void sendMail(String from, List<String> tos, String title, String text, List<File> attachments, String priority, boolean isHtml, String encoding) throws MailException, MessagingException {
    List<Pair<String, InputStreamSource>> att = null;
    if (attachments != null) {
        att = Lists.newArrayList();
        for (File file : attachments) {
            InputStreamSource source = new FileSystemResource(file);
            Pair<String, InputStreamSource> pair = Pair.create(file.getName(), source);
            att.add(pair);
        }
    }
    String[] toArr = null;
    if (tos != null) {
        toArr = tos.toArray(new String[tos.size()]);
    }
    sendMail(from, toArr, null, title, text, att, priority, isHtml, encoding);
}
Example 4
Project: lemon-master  File: MailHelper.java View source code
protected MailDTO sendRealMail(MailDTO mailDto, MailServerInfo mailServerInfo) {
    String from = mailDto.getFrom();
    String to = mailDto.getTo();
    String cc = mailDto.getCc();
    String bcc = mailDto.getBcc();
    String subject = mailDto.getSubject();
    String content = mailDto.getContent();
    to = to.replaceAll("\n", ",").replaceAll(";", ",");
    if (StringUtils.isBlank(cc)) {
        cc = null;
    } else {
        cc = cc.replaceAll("\n", ",").replaceAll(";", ",");
    }
    if (StringUtils.isBlank(bcc)) {
        bcc = null;
    } else {
        bcc = bcc.replaceAll("\n", ",").replaceAll(";", ",");
    }
    logger.debug("from : {}, to : {}", from, to);
    logger.debug("cc : {}, bcc : {}", cc, bcc);
    logger.debug("subject : {}", subject);
    try {
        JavaMailSender javaMailSender = mailServerInfo.getJavaMailSender();
        MimeMessage msg = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
        helper.setFrom(from);
        helper.setSubject(subject);
        helper.setTo(InternetAddress.parse(to));
        helper.setText(content, true);
        if (StringUtils.isNotBlank(cc)) {
            helper.setCc(InternetAddress.parse(cc));
        }
        if (StringUtils.isNotBlank(bcc)) {
            helper.setBcc(InternetAddress.parse(bcc));
        }
        for (Map.Entry<String, InputStreamSource> entry : mailDto.getInlines().entrySet()) {
            helper.addInline(entry.getKey(), entry.getValue(), "image/png");
        }
        for (Map.Entry<String, InputStreamSource> entry : mailDto.getAttachments().entrySet()) {
            helper.addAttachment(entry.getKey(), entry.getValue());
        }
        javaMailSender.send(msg);
        logger.debug("send mail from {} to {}", from, to);
        mailDto.setSuccess(true);
    } catch (Exception e) {
        logger.error("send mail error", e);
        mailDto.setSuccess(false);
        if (e.getCause() != null) {
            mailDto.setException(e.getCause());
        } else {
            mailDto.setException(e);
        }
    }
    return mailDto;
}
Example 5
Project: balerocms-enterprise-master  File: EmailService.java View source code
/*
     * Send HTML mail with attachment.
     */
public void sendMailWithAttachment(final String recipientName, final String recipientEmail, final String attachmentFileName, final byte[] attachmentBytes, final String attachmentContentType, final Locale locale) throws MessagingException {
    // Prepare the evaluation context
    final Context ctx = new Context(locale);
    ctx.setVariable("name", recipientName);
    ctx.setVariable("subscriptionDate", new Date());
    ctx.setVariable("hobbies", Arrays.asList("Cinema", "Sports", "Music"));
    // Prepare message using a Spring helper
    final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
    final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, /* multipart */
    "UTF-8");
    message.setSubject("Example HTML email with attachment");
    message.setFrom("thymeleaf@example.com");
    message.setTo(recipientEmail);
    // Create the HTML body using Thymeleaf
    final String htmlContent = this.templateEngine.process("email-withattachment.html", ctx);
    message.setText(htmlContent, true);
    // Add the attachment
    final InputStreamSource attachmentSource = new ByteArrayResource(attachmentBytes);
    message.addAttachment(attachmentFileName, attachmentSource, attachmentContentType);
    // Send mail
    this.mailSender.send(mimeMessage);
}
Example 6
Project: konekti-master  File: MailServiceImpl.java View source code
@Override
public void sendMessage(String emailFrom, String emailTo, String subject, String template, HashMap<String, Object> staticResources, HashMap<String, Object> dynamicResources) throws Exception {
    String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, template, "UTF-8", dynamicResources);
    // configure mail helper
    MimeMessage message = javaMailSender.createMimeMessage();
    // configure multipart email configuration: css and images inside
    MimeMessageHelper helper = new MimeMessageHelper(message, true);
    helper.setFrom(emailFrom);
    helper.setTo(emailTo);
    helper.setSubject(subject);
    // configure html email
    helper.setText(text, true);
    Iterator<String> iter = staticResources.keySet().iterator();
    while (iter.hasNext()) {
        String key = (String) iter.next();
        InputStreamSource val = (InputStreamSource) staticResources.get(key);
        helper.addInline(key, val, "text/html");
    }
    // send message in OSGi envirotment
    ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(javax.mail.Session.class.getClassLoader());
        javaMailSender.send(message);
    } catch (Exception e) {
        throw new Exception(e);
    } finally {
        Thread.currentThread().setContextClassLoader(oldClassLoader);
    }
}
Example 7
Project: citrus-master  File: SchemaBaseTests.java View source code
@Test
public void constructor_inputStreamSource() {
    try {
        new SchemaBaseImpl((InputStreamSource) null);
        fail();
    } catch (IllegalArgumentException e) {
        assertThat(e, exception("no InputStreamSource provided"));
    }
    schema = new SchemaBaseImpl(source);
    assertFalse(schema.isParsed());
    assertFalse(schema.isAnalyzed());
    assertFalse(schema.isEverTransformed());
    assertNull(schema.getDocumentField());
    assertNull(schema.getTransformedData());
}
Example 8
Project: spring-framework-2.5.x-master  File: MimeMessageHelper.java View source code
/**
	 * Add an inline element to the MimeMessage, taking the content from an
	 * <code>org.springframework.core.InputStreamResource</code>, and
	 * specifying the content type explicitly.
	 * <p>You can determine the content type for any given filename via a Java
	 * Activation Framework's FileTypeMap, for example the one held by this helper.
	 * <p>Note that the InputStream returned by the InputStreamSource implementation
	 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
	 * <code>getInputStream()</code> multiple times.
	 * <p><b>NOTE:</b> Invoke <code>addInline</code> <i>after</i> <code>setText</code>;
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param contentId the content ID to use. Will end up as "Content-ID" header
	 * in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
	 * Can be referenced in HTML source via src="cid:myId" expressions.
	 * @param inputStreamSource the resource to take the content from
	 * @param contentType the content type to use for the element
	 * @throws MessagingException in case of errors
	 * @see #setText
	 * @see #getFileTypeMap
	 * @see #addInline(String, org.springframework.core.io.Resource)
	 * @see #addInline(String, javax.activation.DataSource)
	 */
public void addInline(String contentId, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
    Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
    if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
        throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " + "JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
    }
    DataSource dataSource = createDataSource(inputStreamSource, contentType, "inline");
    addInline(contentId, dataSource);
}
Example 9
Project: common_utils-master  File: EmailService.java View source code
/**
     * 处理附件
     *
     * @param emailVo
     * @param msgHelper
     * @throws javax.mail.MessagingException
     */
private void handlerAttachments(EmailVo emailVo, MimeMessageHelper msgHelper) throws MessagingException {
    if (emailVo.getAttachmentVos() != null) {
        // 检查附件
        for (AttachmentVo attachmentVo : emailVo.getAttachmentVos()) {
            File attachment = attachmentVo.getAttachment();
            if (attachment == null) {
                InputStream inputStream = attachmentVo.getAttachmentInputStream();
                if (attachmentVo.getAttachmentName() == null) {
                    attachmentVo.setAttachmentName(new Date().toString());
                }
                InputStreamSource inputStreamSource = new InputStreamResource(inputStream);
                msgHelper.addAttachment(attachmentVo.getAttachmentName(), inputStreamSource);
            } else {
                if (attachmentVo.getAttachmentName() == null) {
                    attachmentVo.setAttachmentName(attachment.getName());
                }
                try {
                    msgHelper.addAttachment(MimeUtility.encodeWord(attachmentVo.getAttachmentName()), attachment);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
Example 10
Project: spring-framework-master  File: MimeMessageHelper.java View source code
/**
	 * Add an inline element to the MimeMessage, taking the content from an
	 * {@code org.springframework.core.InputStreamResource}, and
	 * specifying the content type explicitly.
	 * <p>You can determine the content type for any given filename via a Java
	 * Activation Framework's FileTypeMap, for example the one held by this helper.
	 * <p>Note that the InputStream returned by the InputStreamSource implementation
	 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
	 * {@code getInputStream()} multiple times.
	 * <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@code setText};
	 * else, mail readers might not be able to resolve inline references correctly.
	 * @param contentId the content ID to use. Will end up as "Content-ID" header
	 * in the body part, surrounded by angle brackets: e.g. "myId" -> "<myId>".
	 * Can be referenced in HTML source via src="cid:myId" expressions.
	 * @param inputStreamSource the resource to take the content from
	 * @param contentType the content type to use for the element
	 * @throws MessagingException in case of errors
	 * @see #setText
	 * @see #getFileTypeMap
	 * @see #addInline(String, org.springframework.core.io.Resource)
	 * @see #addInline(String, javax.activation.DataSource)
	 */
public void addInline(String contentId, InputStreamSource inputStreamSource, String contentType) throws MessagingException {
    Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
    if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
        throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " + "JavaMail requires an InputStreamSource that creates a fresh stream for every call.");
    }
    DataSource dataSource = createDataSource(inputStreamSource, contentType, "inline");
    addInline(contentId, dataSource);
}
Example 11
Project: RMT-master  File: Notification.java View source code
public InputStreamSource getInputStreamSource() {
    return new ByteArrayResource(data);
}
Example 12
Project: appverse-web-master  File: AttachmentDTO.java View source code
public InputStreamSource getAttachment() {
    return attachment;
}
Example 13
Project: jadira-master  File: ResourceInputSource.java View source code
/**
     * Return the associated {@link InputStreamSource}, if any
     * @return The InputStreamSource
     */
public InputStreamSource getStreamSource() {
    return streamSource;
}