Switch from javax.mail to net.jaekl.qd.SendMail.
[cfb.git] / test / net / jaekl / qd / util / SmtpConversationMock.java
1 package net.jaekl.qd.util;
2
3 import java.nio.charset.Charset;
4
5 public class SmtpConversationMock {
6         private InputStreamMock m_is;
7         private OutputStreamMock m_os;
8         
9         String[][] m_responses;
10         
11         private class Listener implements OutputStreamMock.Listener {
12                 @Override
13                 public void onWrite(int b) {
14                         String stream = m_os.mock_getContent(Charset.forName(FileMock.UTF_8));
15                         if (stream.endsWith("\r\n")) {
16                                 int pos = stream.lastIndexOf("\r\n", stream.length() - 3);
17                                 if (pos < 0) {
18                                         pos = -2;
19                                 }
20                                 String cmd = stream.substring(pos + 2);
21                                 String reply = replyFor(cmd);
22                                 if (null != reply) {
23                                         m_is.mock_append("\r\n" + reply + "\r\n", Charset.forName(FileMock.UTF_8));
24                                 }
25                         }
26                 }
27                 
28                 private String replyFor(String cmd) {
29                         for (int idx = 0; idx < m_responses.length; ++idx) {
30                                 if (cmd.startsWith(m_responses[idx][0])) {
31                                         return m_responses[idx][1];
32                                 }
33                         }
34                         return null;    // no canned response for this input
35                 }
36         }
37         
38         // responses:  array of 2-tuples of Strings { {input, output}, {input, output}, ... }
39         public SmtpConversationMock(String init, String[][] responses) {
40                 assert(null != responses);
41                 
42                 m_is = new InputStreamMock();
43                 m_os = new OutputStreamMock();
44                 
45                 m_responses = responses.clone();
46                 
47                 Listener listener = new Listener();
48                 m_os.mock_setListener(listener);
49                 
50                 m_is.mock_reset(init.getBytes(Charset.forName(FileMock.UTF_8)));
51         }
52         
53         public InputStreamMock getInputStream() { return m_is; }
54         public OutputStreamMock getOutputStream() { return m_os; }
55         
56 }