1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package org.apache.james.transport.mailets.listservcommands;
23
24
25 import javax.activation.DataSource;
26
27 import java.io.BufferedInputStream;
28 import java.io.BufferedOutputStream;
29 import java.io.ByteArrayInputStream;
30 import java.io.ByteArrayOutputStream;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.io.UnsupportedEncodingException;
35
36
37
38
39
40
41
42
43
44
45 public class MailDataSource implements DataSource {
46
47 protected static final int DEFAULT_BUF_SIZE = 0x2000;
48
49 protected static final String DEFAULT_ENCODING = "iso-8859-1";
50 protected static final String DEFAULT_NAME = "HtmlMailDataSource";
51
52 protected byte[] data;
53 protected String contentType;
54
55
56
57
58 public MailDataSource(InputStream inputStream, String contentType) throws IOException {
59 this.contentType = contentType;
60
61 ByteArrayOutputStream baos = new ByteArrayOutputStream();
62 copyStream(inputStream, baos);
63 data = baos.toByteArray();
64 }
65
66
67
68
69 public MailDataSource(byte[] data, String contentType) {
70 this.contentType = contentType;
71 this.data = data;
72 }
73
74
75
76
77 public MailDataSource(String data, String contentType) throws UnsupportedEncodingException {
78 this.contentType = contentType;
79 this.data = data.getBytes(DEFAULT_ENCODING);
80 }
81
82
83
84
85 public InputStream getInputStream() throws IOException {
86 if (data == null)
87 throw new IOException("no data");
88 return new ByteArrayInputStream(data);
89 }
90
91
92
93
94 public OutputStream getOutputStream() throws IOException {
95 throw new IOException("getOutputStream() isn't implemented");
96 }
97
98
99
100
101 public String getContentType() {
102 return contentType;
103 }
104
105
106
107
108 public String getName() {
109 return DEFAULT_NAME;
110 }
111
112 protected static int copyStream(InputStream inputStream, OutputStream outputStream) throws IOException {
113 inputStream = new BufferedInputStream(inputStream);
114 outputStream = new BufferedOutputStream(outputStream);
115
116 byte[] bbuf = new byte[DEFAULT_BUF_SIZE];
117 int len;
118 int totalBytes = 0;
119 while ((len = inputStream.read(bbuf)) != -1) {
120 outputStream.write(bbuf, 0, len);
121 totalBytes += len;
122 }
123 outputStream.flush();
124 return totalBytes;
125 }
126 }
127