1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.geronimo.javamail.handlers;
18
19 import java.awt.datatransfer.DataFlavor;
20 import java.awt.datatransfer.UnsupportedFlavorException;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.InputStreamReader;
24 import java.io.OutputStream;
25 import java.io.OutputStreamWriter;
26 import java.io.Reader;
27 import java.io.UnsupportedEncodingException;
28
29 import javax.activation.DataContentHandler;
30 import javax.activation.DataSource;
31
32 import javax.mail.internet.ContentType;
33 import javax.mail.internet.MimeUtility;
34
35
36
37
38 public class AbstractTextHandler implements DataContentHandler {
39 private final DataFlavor flavour;
40
41 public AbstractTextHandler(DataFlavor flavour) {
42 this.flavour = flavour;
43 }
44
45 public DataFlavor[] getTransferDataFlavors() {
46 return new DataFlavor[] {flavour};
47 }
48
49 public Object getTransferData(DataFlavor dataFlavor, DataSource dataSource) throws UnsupportedFlavorException, IOException {
50 return flavour.equals(dataFlavor) ? getContent(dataSource) : null;
51 }
52
53
54
55
56
57
58
59
60
61
62 public Object getContent(DataSource ds) throws IOException {
63 InputStream is = ds.getInputStream();
64 InputStreamReader reader;
65
66
67 try {
68 String charset = getCharSet(ds.getContentType());
69 reader = new InputStreamReader(is, charset);
70 } catch (Exception ex) {
71 throw new UnsupportedEncodingException(ex.toString());
72 }
73 StringBuffer result = new StringBuffer(1024);
74 char[] buffer = new char[32768];
75 int count;
76 while ((count = reader.read(buffer)) > 0) {
77 result.append(buffer, 0, count);
78 }
79 return result.toString();
80 }
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96 public void writeTo(Object o, String contentType, OutputStream outputstream) throws IOException {
97 String s;
98 if (o instanceof String) {
99 s = (String) o;
100 } else if (o != null) {
101 s = o.toString();
102 } else {
103 return;
104 }
105
106
107 OutputStreamWriter writer;
108 try {
109 String charset = getCharSet(contentType);
110 writer = new OutputStreamWriter(outputstream, charset);
111 } catch (Exception ex) {
112 ex.printStackTrace();
113 throw new UnsupportedEncodingException(ex.toString());
114 }
115 writer.write(s);
116 writer.flush();
117 }
118
119
120
121
122
123
124
125
126 protected String getCharSet(String contentType) throws Exception {
127 ContentType type = new ContentType(contentType);
128 String charset = type.getParameter("charset");
129 if (charset == null) {
130 charset = "us-ascii";
131 }
132 return MimeUtility.javaCharset(charset);
133 }
134 }