Debian Codegraph @

demo/src/main/java/internal/testidle.java

raw
1 /*
2 * Copyright (c) 1997, 2020 Oracle and/or its affiliates. All rights reserved.
3 *
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Distribution License v. 1.0, which is available at
6 * http://www.eclipse.org/org/documents/edl-v10.php.
7 *
8 * SPDX-License-Identifier: BSD-3-Clause
9 */
10
11 import java.util.*;
12 import java.util.concurrent.atomic.*;
13 import java.io.*;
14 import jakarta.mail.*;
15 import jakarta.mail.event.*;
16 import jakarta.mail.internet.*;
17 import jakarta.activation.*;
18
19 import com.sun.mail.imap.*;
20
21 /**
22 * Test program for IDLE support in IMAP provider.
23 *
24 * Run several threads that access the folder's connection
25 * while another thread runs the IDLE command. A timer
26 * thread checks that each thread is making progress, to
27 * detect deadlock.
28 *
29 * XXX - Should have another thread add messages to the folder
30 * to test the new message notification works properly.
31 */
32 public class testidle {
33
34 public static Store store;
35 public static Folder folder;
36 public static boolean showStructure = false;
37 public static boolean saveAttachments = false;
38 public static int attnum = 0;
39 public static int totalTime;
40
41 public static final AtomicBoolean stop = new AtomicBoolean(false);
42 public static final AtomicInteger folderProgress = new AtomicInteger();
43 public static final AtomicInteger msgProgress = new AtomicInteger();
44
45 public static void main(String argv[]) {
46 if (argv.length != 5) {
47 System.out.println(
48 "Usage: testidle <host> <user> <password> <mbox> <time>");
49 System.exit(1);
50 }
51
52 try {
53 Properties props = System.getProperties();
54
55 // Get a Session object
56 Session session = Session.getInstance(props, null);
57 // session.setDebug(true);
58
59 // Get a Store object
60 store = session.getStore("imap");
61
62 store.addStoreListener(new StoreListener() {
63 public void notification(StoreEvent e) {
64 System.out.println("StoreEvent: type " +
65 e.getMessageType() + ", message " +
66 e.getMessage());
67 }
68 });
69
70 // Connect
71 store.connect(argv[0], argv[1], argv[2]);
72
73 // Open a Folder
74 folder = store.getFolder(argv[3]);
75 if (folder == null || !folder.exists()) {
76 System.out.println("Invalid folder");
77 System.exit(1);
78 }
79
80 folder.open(Folder.READ_WRITE);
81
82 // Add messageCountListener to listen for new messages
83 folder.addMessageCountListener(new MessageCountAdapter() {
84 public void messagesAdded(MessageCountEvent ev) {
85 Message[] msgs = ev.getMessages();
86 System.out.println("Got " + msgs.length + " new messages");
87
88 // Just dump out the new messages
89 for (int i = 0; i < msgs.length; i++) {
90 try {
91 System.out.println("-----");
92 System.out.println("Message " +
93 msgs[i].getMessageNumber() + ":");
94 msgs[i].writeTo(System.out);
95 } catch (IOException ioex) {
96 ioex.printStackTrace();
97 } catch (MessagingException mex) {
98 mex.printStackTrace();
99 }
100 }
101 }
102 });
103
104 totalTime = Integer.parseInt(argv[4]);
105
106 new Thread("timer") {
107 public void run() {
108 timer();
109 }
110 }.start();
111
112 new Thread("message reader") {
113 public void run() {
114 readMessages();
115 }
116 }.start();
117
118 new Thread("folder reader") {
119 public void run() {
120 readFolder();
121 }
122 }.start();
123
124 new Thread("store idle") {
125 public void run() {
126 storeIdle();
127 }
128 }.start();
129
130
131 /*
132 * make sure two threads running idle works properly
133 new Thread("idle") {
134 public void run() {
135 try {
136 doIdle();
137 } catch (MessagingException mex) { }
138 }
139 }.start();
140 */
141
142 doIdle();
143
144 System.out.println("connected " + store.isConnected());
145
146 } catch (Exception ex) {
147 ex.printStackTrace();
148 }
149 }
150
151 /**
152 * Run the idle command until told to stop.
153 */
154 public static void doIdle() throws MessagingException {
155 boolean supportsIdle = false;
156 try {
157 if (folder instanceof IMAPFolder) {
158 IMAPFolder f = (IMAPFolder)folder;
159 f.idle();
160 supportsIdle = true;
161 }
162 } catch (FolderClosedException fex) {
163 throw fex;
164 } catch (MessagingException mex) {
165 supportsIdle = false;
166 }
167 while (!stop.get()) {
168 if (supportsIdle && folder instanceof IMAPFolder) {
169 IMAPFolder f = (IMAPFolder)folder;
170 f.idle();
171 /*
172 System.out.println("IDLE done in " +
173 Thread.currentThread().getName());
174 */
175 } else {
176 try {
177 Thread.sleep(1000); // sleep for 1000 milliseconds
178 } catch (InterruptedException ex) { }
179
180 // This is to force the IMAP server to send us
181 // EXISTS notifications.
182 folder.getMessageCount();
183 }
184 }
185 }
186
187 /**
188 * Monitor progress of threads and tell them to stop
189 * when their time is up.
190 */
191 public static void timer() {
192 long tend = System.currentTimeMillis() + totalTime;
193 int fpcnt = folderProgress.get();
194 int mpcnt = msgProgress.get();
195 while (System.currentTimeMillis() < tend) {
196 try {
197 Thread.sleep(1000);
198 } catch (InterruptedException ex) { }
199 int nfpcnt = folderProgress.get();
200 int nmpcnt = msgProgress.get();
201 if (!(nfpcnt > fpcnt && nmpcnt > mpcnt)) {
202 System.out.println("THREAD STUCK?");
203 System.out.printf("fpcnt %d nfpcnt %d\n", fpcnt, nfpcnt);
204 System.out.printf("mpcnt %d nmpcnt %d\n", mpcnt, nmpcnt);
205 }
206 fpcnt = nfpcnt;
207 mpcnt = nmpcnt;
208 }
209 System.out.println("STOPPING");
210 stop.set(true);
211 try {
212 folder.getUnreadMessageCount(); // force IDLE to terminate
213 } catch (MessagingException mex) { }
214 }
215
216 /**
217 * Read all the messages in the folder and access all their content.
218 */
219 public static void readMessages() {
220 try {
221 while (!stop.get()) {
222 int cnt = folder.getMessageCount();
223 for (int i = 1; i <= cnt; i++) {
224 //System.out.println("dump " + i);
225 Message msg = folder.getMessage(i);
226 dumpEnvelope(msg);
227 msgProgress.incrementAndGet();
228 try {
229 Thread.sleep(25);
230 } catch (InterruptedException ex) { }
231 }
232 }
233 System.out.println("messages DONE");
234 } catch (Exception ex) {
235 System.out.println(ex);
236 }
237 }
238
239 /**
240 * Perform folder commands to compete with the message
241 * access commands.
242 */
243 public static void readFolder() {
244 try {
245 while (!stop.get()) {
246 int cnt = folder.getUnreadMessageCount();
247 store.isConnected(); // poke the store too
248 folderProgress.incrementAndGet();
249 try {
250 Thread.sleep(100);
251 } catch (InterruptedException ex) { }
252 }
253 System.out.println("folder DONE");
254 } catch (MessagingException mex) {
255 System.out.println(mex);
256 }
257 }
258
259 /**
260 * Run the idle command until told to stop.
261 */
262 public static void storeIdle() {
263 boolean supportsIdle = false;
264 try {
265 if (store instanceof IMAPStore) {
266 IMAPStore s = (IMAPStore)store;
267 s.idle();
268 supportsIdle = true;
269 }
270 } catch (MessagingException mex) {
271 supportsIdle = false;
272 }
273 try {
274 while (!stop.get()) {
275 if (supportsIdle && store instanceof IMAPStore) {
276 IMAPStore s = (IMAPStore)store;
277 s.idle();
278 /*
279 */
280 System.out.println("IDLE done in " +
281 Thread.currentThread().getName());
282 /*
283 */
284 } else {
285 try {
286 Thread.sleep(1000); // sleep for 1000 milliseconds
287 } catch (InterruptedException ex) { }
288 }
289 }
290 } catch (MessagingException mex) {
291 System.out.println(mex);
292 }
293 }
294
295 /**
296 * Dump contents of message part.
297 * (Copied from msgshow.java)
298 */
299 public static void dumpPart(Part p) throws Exception {
300 if (p instanceof Message)
301 dumpEnvelope((Message)p);
302
303 /** Dump input stream ..
304
305 InputStream is = p.getInputStream();
306 // If "is" is not already buffered, wrap a BufferedInputStream
307 // around it.
308 if (!(is instanceof BufferedInputStream))
309 is = new BufferedInputStream(is);
310 int c;
311 while ((c = is.read()) != -1)
312 System.out.write(c);
313
314 **/
315
316 String ct = p.getContentType();
317 try {
318 pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
319 } catch (ParseException pex) {
320 pr("BAD CONTENT-TYPE: " + ct);
321 }
322 String filename = p.getFileName();
323 if (filename != null)
324 pr("FILENAME: " + filename);
325
326 /*
327 * Using isMimeType to determine the content type avoids
328 * fetching the actual content data until we need it.
329 */
330 if (p.isMimeType("text/plain")) {
331 pr("This is plain text");
332 pr("---------------------------");
333 if (!showStructure && !saveAttachments)
334 System.out.println((String)p.getContent());
335 } else if (p.isMimeType("multipart/*")) {
336 pr("This is a Multipart");
337 pr("---------------------------");
338 Multipart mp = (Multipart)p.getContent();
339 level++;
340 int count = mp.getCount();
341 for (int i = 0; i < count; i++)
342 dumpPart(mp.getBodyPart(i));
343 level--;
344 } else if (p.isMimeType("message/rfc822")) {
345 pr("This is a Nested Message");
346 pr("---------------------------");
347 level++;
348 dumpPart((Part)p.getContent());
349 level--;
350 } else {
351 if (!showStructure && !saveAttachments) {
352 /*
353 * If we actually want to see the data, and it's not a
354 * MIME type we know, fetch it and check its Java type.
355 */
356 Object o = p.getContent();
357 if (o instanceof String) {
358 pr("This is a string");
359 pr("---------------------------");
360 System.out.println((String)o);
361 } else if (o instanceof InputStream) {
362 pr("This is just an input stream");
363 pr("---------------------------");
364 InputStream is = (InputStream)o;
365 int c;
366 while ((c = is.read()) != -1)
367 System.out.write(c);
368 } else {
369 pr("This is an unknown type");
370 pr("---------------------------");
371 pr(o.toString());
372 }
373 } else {
374 // just a separator
375 pr("---------------------------");
376 }
377 }
378
379 /*
380 * If we're saving attachments, write out anything that
381 * looks like an attachment into an appropriately named
382 * file. Don't overwrite existing files to prevent
383 * mistakes.
384 */
385 if (saveAttachments && level != 0 && !p.isMimeType("multipart/*")) {
386 String disp = p.getDisposition();
387 // many mailers don't include a Content-Disposition
388 if (disp == null || disp.equalsIgnoreCase(Part.ATTACHMENT)) {
389 if (filename == null)
390 filename = "Attachment" + attnum++;
391 pr("Saving attachment to file " + filename);
392 try {
393 File f = new File(filename);
394 if (f.exists())
395 // XXX - could try a series of names
396 throw new IOException("file exists");
397 ((MimeBodyPart)p).saveFile(f);
398 } catch (IOException ex) {
399 pr("Failed to save attachment: " + ex);
400 }
401 pr("---------------------------");
402 }
403 }
404 }
405
406 public static void dumpEnvelope(Message m) throws Exception {
407 pr("This is the message envelope");
408 pr("---------------------------");
409 Address[] a;
410 // FROM
411 if ((a = m.getFrom()) != null) {
412 for (int j = 0; j < a.length; j++)
413 pr("FROM: " + a[j].toString());
414 }
415
416 // TO
417 if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
418 for (int j = 0; j < a.length; j++) {
419 pr("TO: " + a[j].toString());
420 InternetAddress ia = (InternetAddress)a[j];
421 if (ia.isGroup()) {
422 InternetAddress[] aa = ia.getGroup(false);
423 for (int k = 0; k < aa.length; k++)
424 pr(" GROUP: " + aa[k].toString());
425 }
426 }
427 }
428
429 // SUBJECT
430 pr("SUBJECT: " + m.getSubject());
431
432 // DATE
433 Date d = m.getSentDate();
434 pr("SendDate: " +
435 (d != null ? d.toString() : "UNKNOWN"));
436
437 // FLAGS
438 Flags flags = m.getFlags();
439 StringBuffer sb = new StringBuffer();
440 Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
441
442 boolean first = true;
443 for (int i = 0; i < sf.length; i++) {
444 String s;
445 Flags.Flag f = sf[i];
446 if (f == Flags.Flag.ANSWERED)
447 s = "\\Answered";
448 else if (f == Flags.Flag.DELETED)
449 s = "\\Deleted";
450 else if (f == Flags.Flag.DRAFT)
451 s = "\\Draft";
452 else if (f == Flags.Flag.FLAGGED)
453 s = "\\Flagged";
454 else if (f == Flags.Flag.RECENT)
455 s = "\\Recent";
456 else if (f == Flags.Flag.SEEN)
457 s = "\\Seen";
458 else
459 continue; // skip it
460 if (first)
461 first = false;
462 else
463 sb.append(' ');
464 sb.append(s);
465 }
466
467 String[] uf = flags.getUserFlags(); // get the user flag strings
468 for (int i = 0; i < uf.length; i++) {
469 if (first)
470 first = false;
471 else
472 sb.append(' ');
473 sb.append(uf[i]);
474 }
475 pr("FLAGS: " + sb.toString());
476
477 // X-MAILER
478 String[] hdrs = m.getHeader("X-Mailer");
479 if (hdrs != null)
480 pr("X-Mailer: " + hdrs[0]);
481 else
482 pr("X-Mailer NOT available");
483 }
484
485 static String indentStr = " ";
486 static int level = 0;
487
488 /**
489 * Print a, possibly indented, string.
490 */
491 public static void pr(String s) {
492 /*
493 if (showStructure)
494 System.out.print(indentStr.substring(0, level * 2));
495 System.out.println(s);
496 */
497 }
498 }