01: package org.bouncycastle.mail.smime.handlers;
02:
03: import java.awt.datatransfer.DataFlavor;
04: import java.io.BufferedInputStream;
05: import java.io.IOException;
06: import java.io.InputStream;
07: import java.io.OutputStream;
08:
09: import javax.activation.ActivationDataFlavor;
10: import javax.activation.DataContentHandler;
11: import javax.activation.DataSource;
12: import javax.mail.MessagingException;
13: import javax.mail.internet.MimeBodyPart;
14:
15: import org.bouncycastle.mail.smime.SMIMEStreamingProcessor;
16:
17: public class PKCS7ContentHandler implements DataContentHandler {
18: private final ActivationDataFlavor _adf;
19: private final DataFlavor[] _dfs;
20:
21: PKCS7ContentHandler(ActivationDataFlavor adf, DataFlavor[] dfs) {
22: _adf = adf;
23: _dfs = dfs;
24: }
25:
26: public Object getContent(DataSource ds) throws IOException {
27: return ds.getInputStream();
28: }
29:
30: public Object getTransferData(DataFlavor df, DataSource ds)
31: throws IOException {
32: if (_adf.equals(df)) {
33: return getContent(ds);
34: } else {
35: return null;
36: }
37: }
38:
39: public DataFlavor[] getTransferDataFlavors() {
40: return _dfs;
41: }
42:
43: public void writeTo(Object obj, String mimeType, OutputStream os)
44: throws IOException {
45: if (obj instanceof MimeBodyPart) {
46: try {
47: ((MimeBodyPart) obj).writeTo(os);
48: } catch (MessagingException ex) {
49: throw new IOException(ex.getMessage());
50: }
51: } else if (obj instanceof byte[]) {
52: os.write((byte[]) obj);
53: } else if (obj instanceof InputStream) {
54: int b;
55: InputStream in = (InputStream) obj;
56:
57: if (!(in instanceof BufferedInputStream)) {
58: in = new BufferedInputStream(in);
59: }
60:
61: while ((b = in.read()) >= 0) {
62: os.write(b);
63: }
64: } else if (obj instanceof SMIMEStreamingProcessor) {
65: SMIMEStreamingProcessor processor = (SMIMEStreamingProcessor) obj;
66:
67: processor.write(os);
68: } else {
69: // TODO it would be even nicer if we could attach the object to the exception
70: // as well since in deeply nested messages, it is not always clear which
71: // part caused the problem. Thus I guess we would have to subclass the
72: // IOException
73:
74: throw new IOException("unknown object in writeTo " + obj);
75: }
76: }
77: }
|