-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPOP3Client.java
More file actions
468 lines (424 loc) · 14.5 KB
/
Copy pathPOP3Client.java
File metadata and controls
468 lines (424 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.sql.Connection;
import java.util.*;
public class POP3Client
{
private Socket socket;
private boolean debug = false;
private BufferedReader reader;
private PrintWriter writer;
private static final int DEFAULT_PORT = 110;
public boolean isDebug()
{
return debug;
}
public void setDebug(boolean debug)
{
this.debug = debug;
}
public int connect(String host, int port) throws IOException
{
socket = new Socket();
try
{
socket.connect(new InetSocketAddress(host, port));
} catch (IOException ex)
{
return 0;
}
reader = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
if (debug)
{
System.out.println("Connected to the host");
}
readResponseLine();
return 1;
}
public int connect(String host) throws IOException
{
return connect(host, DEFAULT_PORT);
}
public boolean isConnected()
{
return socket != null && socket.isConnected();
}
public void disconnect() throws IOException
{
if (!isConnected())
throw new IllegalStateException("Not connected to a host");
socket.close();
reader = null;
writer = null;
if (debug)
System.out.println("Disconnected from the host");
}
protected String readResponseLine() throws IOException
{
String response;
try
{
response = reader.readLine();
} catch (Exception ex)
{
return "Server has returned an error";
}
if (debug)
{
System.out.println("DEBUG [in] : " + response);
}
if (response.startsWith("-ERR"))
{
//throw new RuntimeException("Server has returned an error: " + response.replaceFirst("-ERR ", ""));
return "Server has returned an error: " + response.replaceFirst("-ERR ", "");
}
return response;
}
private String sendCommand(String command) throws IOException
{
if (debug)
{
System.out.println("DEBUG [out]: " + command);
}
writer.println(command);
return readResponseLine();
}
private int login(String username, String password) throws IOException
{
if (sendCommand("USER " + username).startsWith("Server has returned an error")
|| sendCommand("PASS " + password).startsWith("Server has returned an error"))
return 0;
else
return 1;
}
private void logout() throws IOException
{
sendCommand("QUIT");
}
private int getNumberOfNewMessages() throws IOException
{
String response = sendCommand("STAT");
if (response.startsWith("Server has returned an error"))
return -1;
String[] values = response.split(" ");
if (debug)
System.out.println(response);
return Integer.parseInt(values[1]);
}
public class Message
{
private final Map<String, List<String>> headers;
private final String body;
private Message(Map<String, List<String>> headers, String body)
{
this.headers = Collections.unmodifiableMap(headers);
this.body = body;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
}
private Message getMessage(int i) throws IOException
{
String response = sendCommand("RETR " + i);
Map<String, List<String>> headers = new HashMap<String, List<String>>();
String headerName = null;
while ((response = readResponseLine()).length() != 0)
{
if (response.startsWith("\t"))
{
continue; //no process of multiline headers
}
int colonPosition = response.indexOf(":");
headerName = response.substring(0, colonPosition);
String headerValue;
if (headerName.length() > colonPosition)
{
headerValue = response.substring(colonPosition + 2);
} else {
headerValue = "";
}
List<String> headerValues = headers.get(headerName);
if (headerValues == null)
{
headerValues = new ArrayList<String>();
headers.put(headerName, headerValues);
}
headerValues.add(headerValue);
}
// process body
StringBuilder bodyBuilder = new StringBuilder();
while (!(response = readResponseLine()).equals("."))
{
bodyBuilder.append(response + "\n");
}
return new Message(headers, bodyBuilder.toString());
}
public List<Message> getMessages() throws IOException
{
int numOfMessages = getNumberOfNewMessages();
List<Message> messageList = new ArrayList<Message>();
for (int i = 1; i <= numOfMessages; i++) {
messageList.add(getMessage(i));
}
return messageList;
}
private int getList() throws IOException
{
String response = sendCommand("LIST");
if (response.startsWith("Server has returned an error"))
return -1;
if (debug)
System.out.println(response);
String[] values = response.split(" ");
System.out.println(values[1] + " " + values[2]);
while (!(response = readResponseLine()).equals("."))
System.out.println(response);
return 1;
}
//STAT command, returns -1 upon error
public int cmdStat(POP3Client client)
{
int temp;
try
{
temp = client.getNumberOfNewMessages();
} catch (IOException ex)
{
return -1;
}
if (temp == -1)
{
return -1;
} else
{
System.out.println("Number of new emails: " + temp);
return 0;
}
}
// LIST command, returns -1 if a wrong integer was entered, -2 if connection was lost
public int cmdList(POP3Client client, BufferedReader lr)
{
int temp;
System.out.println("Enter message number (0 for no arguments): ");
try
{
temp = Integer.parseInt(lr.readLine());
if (temp == 0)
{
if (client.getList() == -1)
{
return -2;
}
} else
{
System.out.println(client.sendCommand("LIST " + temp));
return 0;
}
} catch (NumberFormatException ex)
{
return -1;
} catch (IOException ex)
{
return -2;
}
return 0;
}
//RETR command, returns -1 if a message with this number does not exist, -2 if a wrong integer was entered, -3 if connection to server was lost
public int cmdRetr(POP3Client client, BufferedReader lr)
{
int temp;
System.out.println("Enter message number: ");
try
{
temp = Integer.parseInt(lr.readLine());
int x = client.getNumberOfNewMessages();
if (temp > x || temp < 1)
{
return -1;
}
System.out.println(client.getMessage(temp).getBody());
}
catch (NumberFormatException ex)
{
return -2;
} catch (IOException ex)
{
return -3;
}
return 0;
}
//DELE command, returns -1 if a message with this number does not exist, -2 if a wrong integer was entered, -3 if connection to server was lost
public int cmdDele(POP3Client client, BufferedReader lr)
{
int temp, x;
System.out.println("Enter message number: ");
try
{
temp = Integer.parseInt(lr.readLine());
x = client.getNumberOfNewMessages();
if (temp > x || temp < 0)
{
return -1;
}
if (client.sendCommand("DELE " + temp).startsWith("Server has returned an error"))
{
return -3;
}
} catch (NumberFormatException ex)
{
return -2;
} catch (IOException ex)
{
return -3;
}
return 0;
}
// Noop command, returns -1 if the server returned an error
public int cmdNoop(POP3Client client)
{
try
{
if (client.sendCommand("NOOP").startsWith("Server has returned an error"))
{
return -1;
}
} catch (IOException ex)
{
return -1;
}
return 0;
}
// RSET command, return -1 if the server returned an error
public int cmdRset(POP3Client client)
{
try
{
if (client.sendCommand("RSET").startsWith("Server has returned an error"))
{
return -1;
}
}catch (IOException ex)
{
return -1;
}
return 0;
}
public static void main(String[] args) throws IOException
{
POP3Client client = new POP3Client();
client.setDebug(false); // <----------------- set this to true to see debugging info
BufferedReader lr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter host: ");
if (client.connect(lr.readLine()) == 0)
{
System.out.println("Failed to connect to host, exiting");
} else
{
System.out.println("Enter login and password: ");
if (client.login(lr.readLine(), lr.readLine()) == 0)
{
System.out.println("Failed to log in, exiting");
}
else
{
int x;
int temp = 0;
do
{
x = 0;
System.out.println("[1] for STAT\n" +
"[2] for LIST\n" +
"[3] for RETR\n" +
"[4] for DELE\n" +
"[5] for NOOP\n" +
"[6] for RSET\n" +
"[9] for QUIT\n");
try
{
x = Integer.parseInt(lr.readLine());
if (x > 10 || x < 0)
System.out.println("A wrong integer was entered, try again\n");
} catch (NumberFormatException ex)
{
System.out.println("A wrong integer was entered, try again\n");
x = -1;
}
switch(x)
{
case 1: // STAT
if (client.cmdStat(client) == -1)
{
System.out.println("The server has returned and error, exiting...");
x = 9;
}
break;
case 2: // LIST
temp = client.cmdList(client, lr);
if (temp == -1)
{
System.out.println("A wrong integer was entered\n");
} else if (temp == -2)
{
System.out.println("The server has returned and error, exiting...");
x = 9;
}
break;
case 3: // RETR [msg]
temp = client.cmdRetr(client, lr);
if (temp == -1)
{
System.out.println("A message with this number does not exist\n");
} else if (temp == -2)
{
System.out.println("A wrong integer was entered\n");
} else if (temp == -3)
{
System.out.println("The server has returned and error, exiting...");
x = 9;
}
break;
case 4: // DELE [msg]
temp = client.cmdDele(client, lr);
if (temp == -1)
{
System.out.println("A message with this number does not exist\n");
} else if (temp == -2)
{
System.out.println("A wrong integer was entered\n");
} else if (temp == -3)
{
System.out.println("The server has returned and error, exiting...");
x = 9;
}
break;
case 5: // NOOP
temp = client.cmdNoop(client);
if (temp == -1)
{
System.out.println("The server has returned and error, exiting...");
x = 9;
}
break;
case 6: // RSET
temp = client.cmdRset(client);
if (temp == -1)
{
System.out.println("The server has returned and error, exiting...");
x = 9;
}
break;
}
} while (x != 9);
client.logout();
client.disconnect();
}
}
}
}