]> WPIA git - gigi.git/blob - util-testing/org/cacert/gigi/email/TestEmailProvider.java
Doc: TestEmailReveiver
[gigi.git] / util-testing / org / cacert / gigi / email / TestEmailProvider.java
1 package org.cacert.gigi.email;
2
3 import java.io.DataInputStream;
4 import java.io.DataOutputStream;
5 import java.io.IOException;
6 import java.net.InetAddress;
7 import java.net.ServerSocket;
8 import java.net.Socket;
9 import java.util.Properties;
10
11 /**
12  * This class intercepts emails so that the test cases can evaluate them
13  * automatically.
14  */
15 public class TestEmailProvider extends EmailProvider {
16
17     private ServerSocket servs;
18
19     private Socket client;
20
21     private DataOutputStream out;
22
23     private DataInputStream in;
24
25     protected TestEmailProvider(Properties props) {
26         try {
27             servs = new ServerSocket(Integer.parseInt(props.getProperty("emailProvider.port")), 10, InetAddress.getByName("127.0.0.1"));
28         } catch (IOException e) {
29             e.printStackTrace();
30         }
31     }
32
33     @Override
34     public synchronized void sendmail(String to, String subject, String message, String from, String replyto, String toname, String fromname, String errorsto, boolean extra) throws IOException {
35         while (true) {
36             assureLocalConnection();
37             try {
38                 out.writeUTF("mail");
39                 write(to);
40                 write(subject);
41                 write(message);
42                 write(from);
43                 write(replyto);
44                 out.flush();
45                 return;
46             } catch (IOException e) {
47                 client = null;
48             }
49         }
50     }
51
52     private void assureLocalConnection() throws IOException {
53         if (out != null) {
54             try {
55                 out.writeUTF("ping");
56             } catch (IOException e) {
57                 client = null;
58             }
59         }
60         if (client == null || client.isClosed()) {
61             client = servs.accept();
62             out = new DataOutputStream(client.getOutputStream());
63             in = new DataInputStream(client.getInputStream());
64         }
65     }
66
67     @Override
68     public synchronized String checkEmailServer(int forUid, String address) throws IOException {
69         while (true) {
70             assureLocalConnection();
71             try {
72                 out.writeUTF("challengeAddrBox");
73                 out.writeUTF(address);
74                 return in.readUTF();
75             } catch (IOException e) {
76                 client = null;
77             }
78         }
79     }
80
81     private void write(String to) throws IOException {
82         if (to == null) {
83             out.writeUTF("<null>");
84         } else {
85             out.writeUTF(to);
86         }
87     }
88
89 }