1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.ws.mime;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23 import javax.activation.DataHandler;
24 import javax.activation.DataSource;
25 import javax.activation.FileDataSource;
26
27 import org.springframework.core.io.InputStreamSource;
28 import org.springframework.core.io.Resource;
29 import org.springframework.util.Assert;
30
31
32
33
34
35
36
37 public abstract class AbstractMimeMessage implements MimeMessage {
38
39 public final Attachment addAttachment(String contentId, File file) throws AttachmentException {
40 Assert.hasLength(contentId, "contentId must not be empty");
41 Assert.notNull(file, "File must not be null");
42 DataHandler dataHandler = new DataHandler(new FileDataSource(file));
43 return addAttachment(contentId, dataHandler);
44 }
45
46 public final Attachment addAttachment(String contentId, InputStreamSource inputStreamSource, String contentType) {
47 Assert.hasLength(contentId, "contentId must not be empty");
48 Assert.notNull(inputStreamSource, "InputStreamSource must not be null");
49 if (inputStreamSource instanceof Resource && ((Resource) inputStreamSource).isOpen()) {
50 throw new IllegalArgumentException("Passed-in Resource contains an open stream: invalid argument. " +
51 "MIME requires an InputStreamSource that creates a fresh stream for every call.");
52 }
53 DataHandler dataHandler = new DataHandler(new InputStreamSourceDataSource(inputStreamSource, contentType));
54 return addAttachment(contentId, dataHandler);
55 }
56
57
58
59
60
61
62
63 private static class InputStreamSourceDataSource implements DataSource {
64
65 private final InputStreamSource inputStreamSource;
66
67 private final String contentType;
68
69 public InputStreamSourceDataSource(InputStreamSource inputStreamSource, String contentType) {
70 this.inputStreamSource = inputStreamSource;
71 this.contentType = contentType;
72 }
73
74 public InputStream getInputStream() throws IOException {
75 return inputStreamSource.getInputStream();
76 }
77
78 public OutputStream getOutputStream() {
79 throw new UnsupportedOperationException("Read-only javax.activation.DataSource");
80 }
81
82 public String getContentType() {
83 return contentType;
84 }
85
86 public String getName() {
87 if (inputStreamSource instanceof Resource) {
88 Resource resource = (Resource) inputStreamSource;
89 return resource.getFilename();
90 }
91 else {
92 throw new UnsupportedOperationException("DataSource name not available");
93 }
94 }
95
96 }
97
98 }