1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.geronimo.mail.handlers;
21
22 import java.awt.datatransfer.DataFlavor;
23 import java.io.ByteArrayOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
27 import java.io.OutputStream;
28 import java.io.OutputStreamWriter;
29 import java.io.StringWriter;
30 import java.io.UnsupportedEncodingException;
31
32 import javax.activation.ActivationDataFlavor;
33 import javax.activation.DataContentHandler;
34 import javax.activation.DataSource;
35 import javax.mail.internet.ContentType;
36 import javax.mail.internet.MimeUtility;
37 import javax.mail.internet.ParseException;
38
39 public class TextHandler implements DataContentHandler {
40
41
42
43 ActivationDataFlavor dataFlavor;
44
45 public TextHandler(){
46 dataFlavor = new ActivationDataFlavor(java.lang.String.class, "text/plain", "Text String");
47 }
48
49
50
51
52
53
54 public TextHandler(ActivationDataFlavor dataFlavor) {
55 this.dataFlavor = dataFlavor;
56 }
57
58
59
60
61
62
63 protected ActivationDataFlavor getDF() {
64 return dataFlavor;
65 }
66
67
68
69
70
71
72 public DataFlavor[] getTransferDataFlavors() {
73 return (new DataFlavor[]{dataFlavor});
74 }
75
76
77
78
79
80
81
82
83
84 public Object getTransferData(DataFlavor dataflavor, DataSource datasource)
85 throws IOException {
86 if (getDF().equals(dataflavor)) {
87 return getContent(datasource);
88 }
89 return null;
90 }
91
92
93
94
95
96
97
98
99 public Object getContent(DataSource datasource) throws IOException {
100 InputStream is = datasource.getInputStream();
101 ByteArrayOutputStream os = new ByteArrayOutputStream();
102
103 int count;
104 byte[] buffer = new byte[1000];
105
106 try {
107 while ((count = is.read(buffer, 0, buffer.length)) > 0) {
108 os.write(buffer, 0, count);
109 }
110 } finally {
111 is.close();
112 }
113 try {
114 return os.toString(getCharSet(datasource.getContentType()));
115 } catch (ParseException e) {
116 throw new UnsupportedEncodingException(e.getMessage());
117 }
118 }
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134 public void writeTo(Object object, String contentType, OutputStream outputstream)
135 throws IOException {
136 OutputStreamWriter os;
137 try {
138 String charset = getCharSet(contentType);
139 os = new OutputStreamWriter(outputstream, charset);
140 } catch (Exception ex) {
141 throw new UnsupportedEncodingException(ex.toString());
142 }
143 String content = (String) object;
144 os.write(content, 0, content.length());
145 os.flush();
146 }
147
148
149
150
151
152
153
154 protected String getCharSet(String contentType) throws ParseException {
155 ContentType type = new ContentType(contentType);
156 String charset = type.getParameter("charset");
157 if (charset == null) {
158 charset = "us-ascii";
159 }
160 return MimeUtility.javaCharset(charset);
161 }
162 }