org.springframework.core.io.InputStreamSource Java Examples

The following examples show how to use org.springframework.core.io.InputStreamSource. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MessageService.java    From flash-waimai with MIT License 6 votes vote down vote up
private void sendEmailMessage(String tplCode, String from, String to, String cc, String title,
                              String content,MessageTemplate messageTemplate,
                              String attachmentFilename, InputStreamSource inputStreamSource){
    try {
        EmailSender emailSender = getEmailSender(messageTemplate);
        boolean isSuccess = false;
        if(inputStreamSource!=null){
            isSuccess = emailSender.sendEmail(from, to, cc, title, content,attachmentFilename,inputStreamSource);
        }else {
              isSuccess = emailSender.sendEmail(from, to, cc, title, content);
        }
        saveMessage(1, tplCode, to, content, isSuccess);
    }catch (Exception e){
        logger.error(e.getMessage(), e);
        saveMessage(1, tplCode, to, content, false);
    }
}
 
Example #2
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create an Activation Framework DataSource for the given InputStreamSource.
 * @param inputStreamSource the InputStreamSource (typically a Spring Resource)
 * @param contentType the content type
 * @param name the name of the DataSource
 * @return the Activation Framework DataSource
 */
protected DataSource createDataSource(
	final InputStreamSource inputStreamSource, final String contentType, final String name) {

	return new DataSource() {
		@Override
		public InputStream getInputStream() throws IOException {
			return inputStreamSource.getInputStream();
		}
		@Override
		public OutputStream getOutputStream() {
			throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
		}
		@Override
		public String getContentType() {
			return contentType;
		}
		@Override
		public String getName() {
			return name;
		}
	};
}
 
Example #3
Source File: MimeMessageHelper.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create an Activation Framework DataSource for the given InputStreamSource.
 * @param inputStreamSource the InputStreamSource (typically a Spring Resource)
 * @param contentType the content type
 * @param name the name of the DataSource
 * @return the Activation Framework DataSource
 */
protected DataSource createDataSource(
	final InputStreamSource inputStreamSource, final String contentType, final String name) {

	return new DataSource() {
		@Override
		public InputStream getInputStream() throws IOException {
			return inputStreamSource.getInputStream();
		}
		@Override
		public OutputStream getOutputStream() {
			throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
		}
		@Override
		public String getContentType() {
			return contentType;
		}
		@Override
		public String getName() {
			return name;
		}
	};
}
 
Example #4
Source File: MimeMessageHelper.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create an Activation Framework DataSource for the given InputStreamSource.
 * @param inputStreamSource the InputStreamSource (typically a Spring Resource)
 * @param contentType the content type
 * @param name the name of the DataSource
 * @return the Activation Framework DataSource
 */
protected DataSource createDataSource(
	final InputStreamSource inputStreamSource, final String contentType, final String name) {

	return new DataSource() {
		@Override
		public InputStream getInputStream() throws IOException {
			return inputStreamSource.getInputStream();
		}
		@Override
		public OutputStream getOutputStream() {
			throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
		}
		@Override
		public String getContentType() {
			return contentType;
		}
		@Override
		public String getName() {
			return name;
		}
	};
}
 
Example #5
Source File: DefaultEmailSender.java    From flash-waimai with MIT License 6 votes vote down vote up
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        if(StringUtils.isNotEmpty(cc)) {
            helper.setCc(cc);
        }
        helper.setSubject(title);
        helper.setText(content, true);
        if(inputStreamSource!=null) {
            helper.addAttachment(attachmentFilename, inputStreamSource);
        }
        javaMailSender.send(message);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #6
Source File: MessageService.java    From web-flash with MIT License 6 votes vote down vote up
private void sendEmailMessage(String tplCode, String from, String to, String cc, String title,
                              String content,MessageTemplate messageTemplate,
                              String attachmentFilename, InputStreamSource inputStreamSource){
    try {
        EmailSender emailSender = getEmailSender(messageTemplate);
        boolean isSuccess = false;
        if(inputStreamSource!=null){
            isSuccess = emailSender.sendEmail(from, to, cc, title, content,attachmentFilename,inputStreamSource);
        }else {
              isSuccess = emailSender.sendEmail(from, to, cc, title, content);
        }
        saveMessage(1, tplCode, to, content, isSuccess);
    }catch (Exception e){
        logger.error(e.getMessage(), e);
        saveMessage(1, tplCode, to, content, false);
    }
}
 
Example #7
Source File: DefaultEmailSender.java    From web-flash with MIT License 6 votes vote down vote up
@Override
public boolean sendEmail(String from, String to, String cc, String title, String content, String attachmentFilename, InputStreamSource inputStreamSource) {
    MimeMessage message = null;
    try {
        message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        if(StringUtil.isNotEmpty(cc)) {
            helper.setCc(cc);
        }
        helper.setSubject(title);
        helper.setText(content, true);
        if(inputStreamSource!=null) {
            helper.addAttachment(attachmentFilename, inputStreamSource);
        }
        javaMailSender.send(message);
        return true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}
 
Example #8
Source File: MimeMessageHelper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create an Activation Framework DataSource for the given InputStreamSource.
 * @param inputStreamSource the InputStreamSource (typically a Spring Resource)
 * @param contentType the content type
 * @param name the name of the DataSource
 * @return the Activation Framework DataSource
 */
protected DataSource createDataSource(
	final InputStreamSource inputStreamSource, final String contentType, final String name) {

	return new DataSource() {
		@Override
		public InputStream getInputStream() throws IOException {
			return inputStreamSource.getInputStream();
		}
		@Override
		public OutputStream getOutputStream() {
			throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
		}
		@Override
		public String getContentType() {
			return contentType;
		}
		@Override
		public String getName() {
			return name;
		}
	};
}
 
Example #9
Source File: MessageService.java    From web-flash with MIT License 5 votes vote down vote up
public void sendTplEmail(String tplCode, String from, String to, String cc, String title,
                         String attachmentFilename, InputStreamSource inputStreamSource,
                         Map<String, Object> dataMap) {
    MessageTemplate messageTemplate = messagetemplateRepository.findByCode(tplCode);
    String content = getContent(messageTemplate.getContent(), dataMap);
    sendEmailMessage(tplCode,from,to,cc,title,content,messageTemplate,attachmentFilename,inputStreamSource);
}
 
Example #10
Source File: DownloadController.java    From cymbal with Apache License 2.0 5 votes vote down vote up
@GetMapping(value = "/download/{fileName}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
@ResponseBody
public InputStreamSource downloadTemplate(final HttpServletRequest request, final HttpServletResponse response,
        @PathVariable String fileName) {
    if ("Template".equalsIgnoreCase(fileName)) {
        response.setHeader("Content-Disposition", "attachment;filename=node-upload-template.xlsx");
        return new InputStreamResource(this.getFileInputStream("static/doc/node-upload-template.xlsx"));
    } else if ("help-doc".equalsIgnoreCase(fileName)) {
        response.setHeader("Content-Disposition", "attachment;filename=cymbal-manual.docx");
        return new InputStreamResource(this.getFileInputStream("static/doc/cymbal-manual.docx"));
    }
    return null;
}
 
Example #11
Source File: MailService.java    From spring-boot-101 with Apache License 2.0 5 votes vote down vote up
/**
 * 发送带附件的邮件
 * @param to 收件人列表
 * @param subject 邮件标题
 * @param content 邮件内容
 * @param inputStreamSource 附件streamSource,可以这样获得:new ByteArrayResource(ByteArrayOutputStream.toByteArray());
 * @param fileName 附件的文件名
 */
public void sendAttachmentsMail(String to, String subject, String content, InputStreamSource inputStreamSource, String fileName){
	MimeMessage message = sender.createMimeMessage();

	try {
		MimeMessageHelper helper = setInfoByHelper(to, subject, content, message);

		helper.addAttachment(fileName, inputStreamSource);

		sender.send(message);
		logger.debug("带附件的邮件已经发送。");
	} catch (MessagingException e) {
		logger.error("发送带附件的邮件时发生异常!", e);
	}
}
 
Example #12
Source File: DefaultEmailNotifier.java    From jetlinks-community with Apache License 2.0 5 votes vote down vote up
protected Mono<InputStreamSource> convertResource(String resource) {
    if (resource.startsWith("http")) {
        return WebClient.create()
            .get()
            .uri(resource)
            .accept(MediaType.APPLICATION_OCTET_STREAM)
            .exchange()
            .flatMap(rep -> rep.bodyToMono(Resource.class));
    } else {
        try {
            return Mono.just(new InputStreamResource(new FileInputStream(resource)));
        } catch (FileNotFoundException e) {
            return Mono.error(e);
        }
    }
}
 
Example #13
Source File: MessageService.java    From flash-waimai with MIT License 5 votes vote down vote up
public void sendTplEmail(String tplCode, String from, String to, String cc, String title,
                         String attachmentFilename, InputStreamSource inputStreamSource,
                         Map<String, Object> dataMap) {
    MessageTemplate messageTemplate = messagetemplateRepository.findByCode(tplCode);
    String content = getContent(messageTemplate.getContent(), dataMap);
    sendEmailMessage(tplCode,from,to,cc,title,content,messageTemplate,attachmentFilename,inputStreamSource);
}
 
Example #14
Source File: WxWebUtils.java    From FastBootWeixin with Apache License 2.0 5 votes vote down vote up
/**
 * 暂时只支持这几种类型
 *
 * @param paramType
 * @return the result
 */
public static boolean isMutlipart(Class paramType) {
    return (byte[].class == paramType ||
            InputStream.class.isAssignableFrom(paramType) ||
            Reader.class.isAssignableFrom(paramType) ||
            File.class.isAssignableFrom(paramType) ||
            InputStreamSource.class.isAssignableFrom(paramType));
}
 
Example #15
Source File: SmbFileTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testSmbToByteArrayInputStream() throws Exception{
	TimeCounter t = new TimeCounter("testSmbToByteArrayInputStream");
	t.start();
	String path = "smb://administrator:[email protected]/install/ftp/新建文本文档.txt";
	InputStreamSource ins = new SmbToByteArrayInputStreamSource(path);
	List<String> list = FileUtils.readAsList(ins.getInputStream());
	for(String str : list){
		System.out.println(str);
	}
	t.stop();
	
}
 
Example #16
Source File: MailService.java    From tutorial with MIT License 5 votes vote down vote up
/**
 * 发送HTML格式,带有附件的邮件
 * @param to
 * @param subject
 * @param body
 * @param attachmentName
 * @param iss
 * @throws MessagingException
 */
public void sendHtmlEmailWithAttachment(String to, String subject, String body, String attachmentName, InputStreamSource iss) throws MessagingException {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
    helper.setFrom(sender);
    helper.setTo(to);
    helper.setSubject(subject);
    helper.setText(body, true);
    // 可以增加多个附件,每个附件调用addAttachement
    helper.addAttachment(attachmentName, iss);

    mailSender.send(mimeMessage);

}
 
Example #17
Source File: IntegrationTestApp.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private XmlSuite loadSuite(String suitePath, InputStreamSource resource) throws IOException {
    IFileParser<XmlSuite> parser = getParser(suitePath);
    try (InputStream inputStream = resource.getInputStream()) {
        XmlSuite xmlSuite = parser.parse(suitePath, inputStream, true);
        xmlSuite.setParallel(XmlSuite.ParallelMode.getValidParallel(parallel));
        xmlSuite.setThreadCount(threadCount);
        xmlSuite.setTimeOut(timeOut);
        LOG.info("Test are running in: {} type of parallel mode, thread count: {} and with test timeout: {}", parallel.toUpperCase(), threadCount, timeOut);
        return xmlSuite;
    }
}
 
Example #18
Source File: SmbFileTest.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Test
public void testCopyToLocal() throws Exception{
	TimeCounter t = new TimeCounter("testCopyToLocal");
	t.start();
	String path = "smb://administrator:[email protected]/install/ftp/email-attachements/批量受理模板2-20140911102904-023442.xlsx";
	InputStreamSource ins = new SmbToByteArrayInputStreamSource(path);
	FileUtils.writeInputStreamTo(ins.getInputStream(), "D:/email-attachements", "smbexcel.xls");
	
}
 
Example #19
Source File: MailDTO.java    From lemon with Apache License 2.0 4 votes vote down vote up
public void addInline(String name, InputStreamSource inline) {
    inlines.put(name, inline);
}
 
Example #20
Source File: MailTests.java    From spring-boot-101 with Apache License 2.0 4 votes vote down vote up
@Test
public void sendMailWithExcel() throws IOException {
	String[] headers = {"col1","col2","col3"};
	// 声明一个工作薄
	HSSFWorkbook wb = new HSSFWorkbook();
	// 生成一个表格
	HSSFSheet sheet = wb.createSheet();
	HSSFRow row = sheet.createRow(0);
	for (int i = 0; i < headers.length; i++) {
		HSSFCell cell = row.createCell(i);
		cell.setCellValue(headers[i]);
	}
	int rowIndex = 1;

	for(int j=0; j<3; j++){
		row = sheet.createRow(rowIndex);
		rowIndex++;
		HSSFCell cell1 = row.createCell(0);
		cell1.setCellValue(j);
		cell1 = row.createCell(1);
		cell1.setCellValue(j+1);
		cell1 = row.createCell(2);
		cell1.setCellValue(j+2);
	}
	for (int i = 0; i < headers.length; i++) {
		sheet.autoSizeColumn(i);
	}

	ByteArrayOutputStream os = new ByteArrayOutputStream(1000);
	wb.write(os);
	wb.close();

	InputStreamSource iss = new ByteArrayResource(os.toByteArray());
	os.close();

	mailService.sendAttachmentsMail("[email protected]",
			"attachmentMail subject",
			"I have an attachment",
			iss, "abc1.xlsx");

}
 
Example #21
Source File: MailDTO.java    From lemon with Apache License 2.0 4 votes vote down vote up
public void setInlines(Map<String, InputStreamSource> inlines) {
    this.inlines = inlines;
}
 
Example #22
Source File: ResourceInputSource.java    From jadira with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a ResourceInputSource for the given {@link InputStreamSource}
 * @param streamSource The InputStreamSource to be parsed
 * @throws IOException Indicates a problem in accessing the underlying stream
 */
public ResourceInputSource(InputStreamSource streamSource) throws IOException {
    setByteStream(streamSource.getInputStream());

    this.streamSource = streamSource;
}
 
Example #23
Source File: MailDTO.java    From lemon with Apache License 2.0 4 votes vote down vote up
public Map<String, InputStreamSource> getAttachments() {
    return attachments;
}
 
Example #24
Source File: MailDTO.java    From lemon with Apache License 2.0 4 votes vote down vote up
public void setAttachments(Map<String, InputStreamSource> attachments) {
    this.attachments = attachments;
}
 
Example #25
Source File: MailDTO.java    From lemon with Apache License 2.0 4 votes vote down vote up
public void addAttachment(String name, InputStreamSource attachment) {
    attachments.put(name, attachment);
}
 
Example #26
Source File: MailDTO.java    From lemon with Apache License 2.0 4 votes vote down vote up
public Map<String, InputStreamSource> getInlines() {
    return inlines;
}
 
Example #27
Source File: MimeMessageHelper.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Add an attachment to the MimeMessage, taking the content from an
 * {@code org.springframework.core.io.InputStreamResource}.
 * <p>The content type will be determined by the given filename for
 * the attachment. Thus, any content source will be fine, including
 * temporary files with arbitrary filenames.
 * <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.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail
 * @param inputStreamSource the resource to take the content from
 * (all of Spring's Resource implementations can be passed in here)
 * @throws MessagingException in case of errors
 * @see #addAttachment(String, java.io.File)
 * @see #addAttachment(String, javax.activation.DataSource)
 * @see org.springframework.core.io.Resource
 */
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
		throws MessagingException {

	String contentType = getFileTypeMap().getContentType(attachmentFilename);
	addAttachment(attachmentFilename, inputStreamSource, contentType);
}
 
Example #28
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Add an attachment to the MimeMessage, taking the content from an
 * {@code org.springframework.core.io.InputStreamResource}.
 * <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.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail
 * @param inputStreamSource the resource to take the content from
 * (all of Spring's Resource implementations can be passed in here)
 * @param contentType the content type to use for the element
 * @throws MessagingException in case of errors
 * @see #addAttachment(String, java.io.File)
 * @see #addAttachment(String, javax.activation.DataSource)
 * @see org.springframework.core.io.Resource
 */
public void addAttachment(
		String attachmentFilename, 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, attachmentFilename);
	addAttachment(attachmentFilename, dataSource);
}
 
Example #29
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * Add an attachment to the MimeMessage, taking the content from an
 * {@code org.springframework.core.io.InputStreamResource}.
 * <p>The content type will be determined by the given filename for
 * the attachment. Thus, any content source will be fine, including
 * temporary files with arbitrary filenames.
 * <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.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail
 * @param inputStreamSource the resource to take the content from
 * (all of Spring's Resource implementations can be passed in here)
 * @throws MessagingException in case of errors
 * @see #addAttachment(String, java.io.File)
 * @see #addAttachment(String, javax.activation.DataSource)
 * @see org.springframework.core.io.Resource
 */
public void addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)
		throws MessagingException {

	String contentType = getFileTypeMap().getContentType(attachmentFilename);
	addAttachment(attachmentFilename, inputStreamSource, contentType);
}
 
Example #30
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.0 3 votes vote down vote up
/**
 * 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" -> "&lt;myId&gt;".
 * 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);
}