Source Code Cross Referenced for ImapProtocolImpl.java in  » Chat » claros-intouch » org » claros » commons » mail » protocols » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Chat » claros intouch » org.claros.commons.mail.protocols 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        package org.claros.commons.mail.protocols;
002:
003:        import java.io.ByteArrayInputStream;
004:        import java.io.IOException;
005:        import java.net.ConnectException;
006:        import java.util.ArrayList;
007:        import java.util.Collections;
008:        import java.util.HashMap;
009:        import java.util.Iterator;
010:        import java.util.Locale;
011:        import java.util.Map;
012:        import java.util.Properties;
013:
014:        import javax.mail.FetchProfile;
015:        import javax.mail.Flags;
016:        import javax.mail.Folder;
017:        import javax.mail.FolderNotFoundException;
018:        import javax.mail.Message;
019:        import javax.mail.MessagingException;
020:        import javax.mail.NoSuchProviderException;
021:        import javax.mail.Session;
022:        import javax.mail.Store;
023:        import javax.mail.internet.MimeMessage;
024:
025:        import org.apache.commons.logging.Log;
026:        import org.apache.commons.logging.LogFactory;
027:        import org.claros.commons.auth.models.AuthProfile;
028:        import org.claros.commons.exception.SystemException;
029:        import org.claros.commons.mail.exception.ConnectionException;
030:        import org.claros.commons.mail.exception.MailboxActionException;
031:        import org.claros.commons.mail.exception.ServerDownException;
032:        import org.claros.commons.mail.models.ConnectionMetaHandler;
033:        import org.claros.commons.mail.models.ConnectionProfile;
034:        import org.claros.commons.mail.models.EmailHeader;
035:        import org.claros.commons.mail.models.EmailSensitivity;
036:        import org.claros.commons.mail.utility.Constants;
037:        import org.claros.commons.mail.utility.Utility;
038:        import org.claros.commons.utility.Formatter;
039:
040:        /**
041:         * @author Umut Gokbayrak
042:         */
043:        public class ImapProtocolImpl implements  Protocol {
044:            private static Log log = LogFactory.getLog(ImapProtocolImpl.class);
045:            private String folder;
046:            private ConnectionProfile profile;
047:            private AuthProfile auth;
048:            private ConnectionMetaHandler handler;
049:            private static final Locale loc = new Locale("en", "US");
050:            private static Map imapFolders = Collections
051:                    .synchronizedMap(new HashMap());
052:
053:            /**
054:             * 
055:             * @param profile
056:             * @param auth
057:             * @param handler
058:             */
059:            ImapProtocolImpl(ConnectionProfile profile, AuthProfile auth,
060:                    ConnectionMetaHandler handler, String folder) {
061:                this .profile = profile;
062:                this .auth = auth;
063:                this .handler = handler;
064:                this .folder = folder;
065:
066:                if (imapFolders.get(auth.getUsername()) == null) {
067:                    HashMap imapUserFolders = new HashMap();
068:                    imapFolders.put(auth.getUsername(), imapUserFolders);
069:                }
070:
071:                if (this .folder == null
072:                        || this .folder.trim().equals("")
073:                        || this .folder.toLowerCase(loc).equals(
074:                                Constants.FOLDER_INBOX(profile)
075:                                        .toLowerCase(loc))) {
076:                    this .folder = Constants.FOLDER_INBOX(profile);
077:                } else {
078:                    if (!this .folder.startsWith(profile.getFolderNameSpace())) {
079:                        this .folder = profile.getFolderNameSpace()
080:                                + this .folder;
081:                    }
082:                }
083:            }
084:
085:            /**
086:             * 
087:             * @return
088:             * @throws Exception
089:             */
090:            public Folder getFolder() throws Exception {
091:                return getImapFolder(true);
092:            }
093:
094:            /**
095:             * 
096:             * @return
097:             * @throws Exception
098:             */
099:            public Folder getImapFolder(boolean useCache) throws Exception {
100:                Folder myFold = null;
101:                if (folder == null) {
102:                    folder = Constants.FOLDER_INBOX(profile);
103:                }
104:
105:                if (folder != null && handler != null) {
106:                    Store store = handler.getStore();
107:                    if (store == null || !store.isConnected()) {
108:                        log.debug("Connection is closed. Restoring it...");
109:                        handler = connect(Constants.CONNECTION_READ_WRITE);
110:                        log.debug("Connection re-established");
111:                    }
112:
113:                    HashMap imapUserFolders = null;
114:                    if (useCache) {
115:                        imapUserFolders = (HashMap) imapFolders.get(auth
116:                                .getUsername());
117:                        myFold = (Folder) imapUserFolders.get(folder);
118:                    }
119:                    if (myFold == null) {
120:                        myFold = handler.getStore().getFolder(folder);
121:                    }
122:                    if (!myFold.isOpen()) {
123:                        try {
124:                            log.debug("Folder :" + folder
125:                                    + " is closed. Opening.");
126:                            myFold.open(Constants.CONNECTION_READ_WRITE);
127:                            log.debug("Folder is open.");
128:                        } catch (Throwable e) {
129:                            log.debug("nevermind go on");
130:                            // nevermind go on...
131:                        }
132:                    }
133:                    if (useCache) {
134:                        try {
135:                            imapUserFolders.put(folder, myFold);
136:                            imapFolders
137:                                    .put(auth.getUsername(), imapUserFolders);
138:                        } catch (Exception e) {
139:                            e.printStackTrace();
140:                        }
141:                    }
142:                }
143:                return myFold;
144:            }
145:
146:            /* (non-Javadoc)
147:             * @see org.claros.commons.mail.protocols.Protocol#connect(int)
148:             */
149:            public ConnectionMetaHandler connect(int connectType)
150:                    throws SystemException, ConnectionException,
151:                    ServerDownException {
152:                Folder fold = null;
153:                try {
154:                    if (handler == null || handler.getStore() == null
155:                            || !handler.getStore().isConnected()) {
156:                        Properties props = new Properties();
157:                        //				props.setProperty("mail.imap.separatestoreconnection", "true");
158:                        //				props.setProperty("mail.imap.connectionpoolsize", "0");
159:                        //				props.setProperty("mail.imap.connectionpooltimeout", "100");
160:
161:                        //				props.setProperty("mail.debug", "true");
162:                        Session session = Session.getDefaultInstance(props);
163:                        log.debug("session instance initiated");
164:                        handler = new ConnectionMetaHandler();
165:                        handler.setStore(session
166:                                .getStore(profile.getProtocol()));
167:                        log.debug("session store set. protocol is: "
168:                                + profile.getProtocol());
169:                        handler.getStore().connect(profile.getFetchServer(),
170:                                profile.getIFetchPort(), auth.getUsername(),
171:                                auth.getPassword());
172:                        if (handler.getStore().isConnected()) {
173:                            log.debug("Store has been connected... Successful");
174:                        } else {
175:                            log.warn("Connection unsuccessfull...!!");
176:                        }
177:                    }
178:                    fold = handler.getStore().getFolder(
179:                            Constants.FOLDER_INBOX(profile));
180:
181:                    HashMap imapUserFolders = (HashMap) imapFolders.get(auth
182:                            .getUsername());
183:                    imapUserFolders.put("INBOX", fold);
184:                    imapFolders.put(auth.getUsername(), imapUserFolders);
185:
186:                    handler.setMbox(fold);
187:                    log.debug("Got mailbox folder. Folder is: "
188:                            + fold.getFullName());
189:                    handler.setTotalMessagesCount(fold.getMessageCount());
190:                    log.debug("Message Count:"
191:                            + handler.getTotalMessagesCount());
192:                } catch (FolderNotFoundException e) {
193:                    log
194:                            .fatal(profile.getProtocol()
195:                                    + " cannot identify the INBOX folder. Please check your folder-namespace variable at config.xml.");
196:                    throw new SystemException(e);
197:                } catch (NoSuchProviderException e) {
198:                    log.fatal(profile.getProtocol()
199:                            + " provider could not be found.");
200:                    throw new SystemException(e);
201:                } catch (MessagingException e) {
202:                    Exception ne = e.getNextException();
203:                    if (ne != null) {
204:                        if (ne instanceof  ConnectException
205:                                || ne instanceof  IOException) {
206:                            throw new ServerDownException(
207:                                    "Server is unreachable.");
208:                        }
209:                    }
210:                    log.error("Connection could not be established."
211:                            + e.getMessage());
212:                    //			throw new ConnectionException(e);
213:                } catch (Exception e) {
214:                    log.error("An unknown exception while connect.", e);
215:                }
216:                return handler;
217:            }
218:
219:            /* (non-Javadoc)
220:             * @see org.claros.commons.mail.protocols.Protocol#deleteMessages(int[])
221:             */
222:            public ConnectionMetaHandler deleteMessages(int[] messageIds)
223:                    throws MailboxActionException, SystemException,
224:                    ConnectionException {
225:                Folder fold = null;
226:                try {
227:                    fold = getFolder();
228:                    if (messageIds != null && messageIds.length > 0) {
229:                        for (int i = 0; i < messageIds.length; i++) {
230:                            try {
231:                                if (messageIds[i] > 0) {
232:                                    Message msg = fold
233:                                            .getMessage(messageIds[i]);
234:                                    msg.setFlag(Flags.Flag.DELETED, true);
235:                                }
236:                            } catch (Exception e) {
237:                                log.debug("error while deleting messsage", e);
238:                            }
239:                        }
240:                        fold.expunge();
241:                    }
242:                } catch (MessagingException e) {
243:                    log.error("Could not delete message ids: " + messageIds, e);
244:                    throw new MailboxActionException(e);
245:                } catch (IndexOutOfBoundsException e) {
246:                    log.error(
247:                            "Maybe you are double clicking the delete button",
248:                            e);
249:                } catch (Exception e) {
250:                    log.error("Could not delete message ids: " + messageIds, e);
251:                    throw new MailboxActionException(e);
252:                } finally {
253:                    closeFolder(fold);
254:                    //			disconnect();
255:                }
256:                return handler;
257:            }
258:
259:            /**
260:             * Fetches all e-mail headers from the server, with appropriate
261:             * fields already set.
262:             * @param handler
263:             * @return ArrayList of MessageHeaders
264:             * @throws ConnectionException
265:             */
266:            public ArrayList fetchAllHeaders() throws SystemException,
267:                    ConnectionException {
268:                ArrayList headers = new ArrayList();
269:                Folder fold = null;
270:                try {
271:                    fold = getFolder();
272:                    EmailHeader header = null;
273:
274:                    Message[] msgs = fold.getMessages();
275:                    FetchProfile fp = new FetchProfile();
276:                    fp.add(FetchProfile.Item.ENVELOPE);
277:                    fp.add(FetchProfile.Item.FLAGS);
278:                    fp.add(FetchProfile.Item.CONTENT_INFO);
279:                    fp.add("Size");
280:                    fp.add("Date");
281:                    fp.add("Disposition-Notification-To");
282:                    fp.add("X-Priority");
283:                    fp.add("X-MSMail-Priority");
284:                    fp.add("Sensitivity");
285:                    fold.fetch(msgs, fp);
286:
287:                    Message msg = null;
288:                    for (int i = 0; i < msgs.length; i++) {
289:                        try {
290:                            header = new EmailHeader();
291:                            msg = msgs[i];
292:
293:                            header
294:                                    .setMultipart((msg
295:                                            .isMimeType("multipart/*")) ? true
296:                                            : false);
297:                            header.setMessageId(i + 1);
298:                            header.setFrom(msg.getFrom());
299:                            header.setTo(msg
300:                                    .getRecipients(Message.RecipientType.TO));
301:                            header.setCc(msg
302:                                    .getRecipients(Message.RecipientType.CC));
303:                            header.setBcc(msg
304:                                    .getRecipients(Message.RecipientType.BCC));
305:                            header.setDate(msg.getSentDate());
306:                            header.setReplyTo(msg.getReplyTo());
307:                            header.setSize(msg.getSize());
308:                            header
309:                                    .setSubject(org.claros.commons.utility.Utility
310:                                            .updateTRChars(msg.getSubject()));
311:
312:                            // now set the human readables.
313:                            header.setDateShown(Formatter.formatDate(header
314:                                    .getDate(), "dd.MM.yyyy HH:mm"));
315:                            header
316:                                    .setFromShown(org.claros.commons.utility.Utility
317:                                            .updateTRChars(Utility
318:                                                    .addressArrToStringShort(header
319:                                                            .getFrom())));
320:                            header.setToShown(Utility
321:                                    .addressArrToStringShort(header.getTo()));
322:                            header.setCcShown(Utility
323:                                    .addressArrToStringShort(header.getCc()));
324:                            header.setSizeShown(Utility
325:                                    .sizeToHumanReadable(header.getSize()));
326:
327:                            org.claros.commons.mail.parser.MessageParser
328:                                    .setHeaders(msg, header);
329:
330:                            boolean deleted = false;
331:                            if (profile.getProtocol().equals(Constants.IMAP)) {
332:                                Flags.Flag flags[] = msg.getFlags()
333:                                        .getSystemFlags();
334:                                if (flags != null) {
335:                                    Flags.Flag flag = null;
336:                                    for (int m = 0; m < flags.length; m++) {
337:                                        flag = flags[m];
338:                                        if (flag.equals(Flags.Flag.SEEN)) {
339:                                            header
340:                                                    .setUnread(new Boolean(
341:                                                            false));
342:                                        }
343:
344:                                        if (flag.equals(Flags.Flag.DELETED)) {
345:                                            deleted = true;
346:                                        }
347:                                    }
348:                                }
349:                            }
350:                            if (header.getUnread() == null) {
351:                                header.setUnread(new Boolean(true));
352:                            }
353:
354:                            // it is time to add it to the arraylist
355:                            if (!deleted) {
356:                                headers.add(header);
357:                            }
358:                        } catch (MessagingException e1) {
359:                            log
360:                                    .error(
361:                                            "Could not parse headers of e-mail. Message might be defuncted or illegal formatted.",
362:                                            e1);
363:                        }
364:                    }
365:                } catch (MessagingException e) {
366:                    log
367:                            .error(
368:                                    "Could not fetch message headers. Is mbox connection still alive???",
369:                                    e);
370:                    //			throw new ConnectionException(e);
371:                } catch (Exception e) {
372:                    log
373:                            .error(
374:                                    "Could not fetch message headers. Is mbox connection still alive???",
375:                                    e);
376:                    //			throw new ConnectionException(e);
377:                }
378:                return headers;
379:            }
380:
381:            /**
382:             * Fetches and returns message headers as message objects.
383:             * @return
384:             * @throws SystemException
385:             * @throws ConnectionException
386:             */
387:            public ArrayList fetchAllHeadersAsMessages()
388:                    throws SystemException, ConnectionException {
389:                ArrayList headers = null;
390:                Folder fold = null;
391:                try {
392:                    headers = new ArrayList();
393:                    fold = getFolder();
394:                    Message[] msgs = fold.getMessages();
395:                    FetchProfile fp = new FetchProfile();
396:                    fp.add(FetchProfile.Item.ENVELOPE);
397:                    fp.add(FetchProfile.Item.FLAGS);
398:                    fp.add(FetchProfile.Item.CONTENT_INFO);
399:                    fp.add("Size");
400:                    fp.add("Date");
401:                    fold.fetch(msgs, fp);
402:
403:                    Message msg = null;
404:                    for (int i = 0; i < msgs.length; i++) {
405:                        try {
406:                            msg = msgs[i];
407:
408:                            boolean deleted = false;
409:                            Flags.Flag flags[] = msg.getFlags()
410:                                    .getSystemFlags();
411:                            if (flags != null) {
412:                                Flags.Flag flag = null;
413:                                for (int m = 0; m < flags.length; m++) {
414:                                    flag = flags[m];
415:                                    if (flag.equals(Flags.Flag.DELETED)) {
416:                                        deleted = true;
417:                                    }
418:                                }
419:                            }
420:                            if (!deleted) {
421:                                headers.add(msg);
422:                            }
423:                        } catch (Exception e) {
424:                            log.debug("probably an error fetching list", e);
425:                        }
426:                    }
427:                } catch (MessagingException e) {
428:                    log
429:                            .error(
430:                                    "Could not fetch message headers. Is mbox connection still alive???",
431:                                    e);
432:                    throw new ConnectionException(e);
433:                } catch (Exception e) {
434:                    log
435:                            .error(
436:                                    "Could not fetch message headers. Is mbox connection still alive???",
437:                                    e);
438:                    throw new ConnectionException(e);
439:                }
440:                return headers;
441:            }
442:
443:            /**
444:             * 
445:             */
446:            public Message getMessage(int messageId)
447:                    throws MailboxActionException, SystemException,
448:                    ConnectionException, Exception {
449:                Message msg = null;
450:                Folder fold = null;
451:                try {
452:                    try {
453:                        fold = getFolder();
454:                        msg = fold.getMessage(messageId);
455:                    } catch (MessagingException e) {
456:                        log
457:                                .error(
458:                                        "Could not fetch message body from remote server.",
459:                                        e);
460:                        throw new MailboxActionException(e);
461:                    }
462:                } catch (Exception e) {
463:                    throw e;
464:                }
465:                return msg;
466:            }
467:
468:            /**
469:             * Disconnects the previously opened data connection if
470:             * the connection is still alive.
471:             * @param handler
472:             */
473:            public void disconnect() {
474:                try {
475:                    HashMap imapUserFolders = (HashMap) imapFolders.get(auth
476:                            .getUsername());
477:                    Iterator iter = imapUserFolders.keySet().iterator();
478:                    Folder tmp = null;
479:                    while (iter.hasNext()) {
480:                        try {
481:                            tmp = (Folder) imapUserFolders.get((String) iter
482:                                    .next());
483:                            closeFolder(tmp);
484:                            tmp = null;
485:                        } catch (Throwable e) {
486:                            log.debug("Unable to close folder:" + tmp);
487:                        }
488:                    }
489:                    imapFolders.put(auth.getUsername(), new HashMap());
490:                } catch (Throwable e1) {
491:                }
492:
493:                try {
494:                    handler.getStore().close();
495:                } catch (Exception e) {
496:                    e.printStackTrace();
497:                }
498:            }
499:
500:            /**
501:             * 
502:             * @param msgId
503:             * @throws Exception
504:             */
505:            public void markAsRead(Long msgId) throws Exception {
506:                Folder f = getFolder();
507:                try {
508:                    Message msg = f.getMessage(msgId.intValue());
509:                    msg.setFlag(Flags.Flag.SEEN, true);
510:                } catch (MessagingException e) {
511:                    log.warn("Marking as Read not worked.", e);
512:                }
513:            }
514:
515:            /**
516:             * 
517:             * @param buff
518:             * @throws Exception
519:             */
520:            public void appendEmail(byte[] buff) throws Exception {
521:                Properties props = new Properties();
522:                Session session = Session.getDefaultInstance(props);
523:                ByteArrayInputStream bis = new ByteArrayInputStream(buff);
524:                MimeMessage msg = new MimeMessage(session, bis);
525:                msg.setFlag(Flags.Flag.SEEN, true);
526:
527:                ProtocolFactory factory = new ProtocolFactory(profile, auth,
528:                        handler);
529:                ImapProtocolImpl imap = (ImapProtocolImpl) factory
530:                        .getImap(folder);
531:                Folder f = imap.getFolder();
532:
533:                try {
534:                    f.appendMessages(new Message[] { msg });
535:                } catch (MessagingException e) {
536:                    log.warn(
537:                            "appenging msg to folder : " + folder + " failed.",
538:                            e);
539:                } finally {
540:                    bis.close();
541:                }
542:            }
543:
544:            /**
545:             * 
546:             * @param msgId
547:             * @param destFolder
548:             * @throws Exception
549:             */
550:            public void moveEmail(Long msgId, String destFolder)
551:                    throws Exception {
552:                ProtocolFactory factory = new ProtocolFactory(profile, auth,
553:                        handler);
554:                ImapProtocolImpl fromProtocol = (ImapProtocolImpl) factory
555:                        .getImap(folder);
556:                ImapProtocolImpl destProtocol = (ImapProtocolImpl) factory
557:                        .getImap(destFolder);
558:                Folder from = fromProtocol.getFolder();
559:                Folder dest = null;
560:
561:                try {
562:                    Message msg = fromProtocol.getMessage(msgId.intValue());
563:                    if (msg != null) {
564:                        // because of the buggy imap servers lost the connection after getMessage
565:                        // we need to check if the folder is open or not. 
566:                        // (Do not use uw-imapd, it sucks!!!)
567:                        from = fromProtocol.getFolder();
568:                        dest = destProtocol.getFolder();
569:                        from.copyMessages(new Message[] { msg }, dest);
570:                        // deleteMessages(new int[] {msg.getMessageNumber()});
571:                        flagAsDeleted(new int[] { msg.getMessageNumber() });
572:                    }
573:                } catch (IndexOutOfBoundsException e) {
574:                    log.debug("Index kaçtı. Moving message to folder : "
575:                            + destFolder + " failed.", e);
576:                } catch (Exception e) {
577:                    log.warn("Moving message to folder : " + destFolder
578:                            + " failed.", e);
579:                }
580:            }
581:
582:            /**
583:             * 
584:             * @param messageIds
585:             * @param destFolder
586:             * @throws Exception
587:             */
588:            public void moveEmails(int messageIds[], String destFolder)
589:                    throws Exception {
590:                ProtocolFactory factory = new ProtocolFactory(profile, auth,
591:                        handler);
592:                ImapProtocolImpl fromProtocol = (ImapProtocolImpl) factory
593:                        .getImap(folder);
594:                ImapProtocolImpl destProtocol = (ImapProtocolImpl) factory
595:                        .getImap(destFolder);
596:                Folder from = fromProtocol.getFolder();
597:                Folder dest = null;
598:
599:                try {
600:                    Message msg = null;
601:
602:                    int counter = 0;
603:                    dest = destProtocol.getFolder();
604:                    Message msgs[] = new MimeMessage[messageIds.length];
605:
606:                    // copy messages to destination folder first
607:                    for (int i = 0; i < messageIds.length; i++) {
608:                        try {
609:                            msg = fromProtocol.getMessage(messageIds[i]);
610:
611:                            if (msg != null) {
612:                                msgs[counter] = msg;
613:                                counter++;
614:                            }
615:                        } catch (Exception e) {
616:                            log.debug("error while copying messages", e);
617:                        }
618:                    }
619:
620:                    from.copyMessages(msgs, dest);
621:                    // now delete the processed messages all at a time.
622:                    // deleteMessages(messageIds);
623:                    flagAsDeleted(messageIds);
624:                } catch (IndexOutOfBoundsException e) {
625:                    log.debug("Index kaçtı. Moving message to folder : "
626:                            + destFolder + " failed.", e);
627:                } catch (Exception e) {
628:                    log.warn("Moving message to folder : " + destFolder
629:                            + " failed.", e);
630:                }
631:            }
632:
633:            /**
634:             * 
635:             * @param messageIds
636:             * @param destFolders
637:             * @throws Exception
638:             */
639:            public void moveEmails(int messageIds[], String destFolders[])
640:                    throws Exception {
641:                ProtocolFactory factory = new ProtocolFactory(profile, auth,
642:                        handler);
643:                ImapProtocolImpl fromProtocol = (ImapProtocolImpl) factory
644:                        .getImap(folder);
645:                Folder from = fromProtocol.getFolder();
646:                Folder dest = null;
647:
648:                try {
649:                    Message msg = null;
650:                    // copy messages to destination folder first
651:                    for (int i = 0; i < messageIds.length; i++) {
652:                        try {
653:                            msg = fromProtocol.getMessage(messageIds[i]);
654:                            ImapProtocolImpl destProtocol = (ImapProtocolImpl) factory
655:                                    .getImap(destFolders[i]);
656:                            dest = destProtocol.getFolder();
657:                            from.copyMessages(new Message[] { msg }, dest);
658:                        } catch (Exception e) {
659:                            log.debug("error while copying messages", e);
660:                        }
661:                    }
662:
663:                    // now delete the processed messages all at a time.
664:                    // deleteMessages(messageIds);
665:                    flagAsDeleted(messageIds);
666:
667:                } catch (Exception e) {
668:                    log.warn("Moving message failed.", e);
669:                }
670:            }
671:
672:            /**
673:             * @return
674:             */
675:            public Folder[] listFolders() throws Exception {
676:                ProtocolFactory factory = new ProtocolFactory(profile, auth,
677:                        handler);
678:                ImapProtocolImpl protocol = (ImapProtocolImpl) factory
679:                        .getImap(folder);
680:                Folder f = protocol.getFolder();
681:
682:                Folder parent = null;
683:                Folder[] folders = null;
684:
685:                try {
686:                    parent = f.getParent();
687:                    folders = parent.listSubscribed("*");
688:                } catch (MessagingException e) {
689:                    log.warn("Cannot get folder list.");
690:                } finally {
691:                    // closeFolder(parent);
692:                }
693:                return folders;
694:            }
695:
696:            /**
697:             * 
698:             * @param f
699:             */
700:            public void closeFolder(Folder f) {
701:                if (f != null) {
702:                    try {
703:                        if (f.isOpen()) {
704:                            f.close(true);
705:                            log.info("Folder: " + f.getName()
706:                                    + " was open and now closed.");
707:
708:                            HashMap imapUserFolders = (HashMap) imapFolders
709:                                    .get(auth.getUsername());
710:                            imapUserFolders.put(folder, null);
711:                            imapFolders
712:                                    .put(auth.getUsername(), imapUserFolders);
713:                        } else {
714:                            log.info("Folder: " + f.getName()
715:                                    + " was already closed.");
716:                        }
717:                    } catch (MessagingException e) {
718:                        log.info("Error while closing folder: " + f.getName(),
719:                                e);
720:                    }
721:                }
722:            }
723:
724:            /**
725:             * 
726:             */
727:            public void createFolder() throws Exception {
728:                Folder f = getFolder();
729:                try {
730:                    if (!f.exists()) {
731:                        f.create(Folder.HOLDS_MESSAGES);
732:                        f.setSubscribed(true);
733:                    } else {
734:                        if (!f.isSubscribed()) {
735:                            f.setSubscribed(true);
736:                        }
737:                    }
738:                } catch (MessagingException e) {
739:                    log.warn("Could not create folder: " + f.getName());
740:                }
741:            }
742:
743:            /**
744:             * @return
745:             */
746:            public int getUnreadMessageCount() throws Exception {
747:                Folder f = getFolder();
748:
749:                if (f.exists()) {
750:                    return f.getUnreadMessageCount();
751:                }
752:                return 0;
753:            }
754:
755:            /**
756:             * @return
757:             */
758:            public int getTotalMessageCount() throws Exception {
759:                Folder f = getFolder();
760:
761:                if (f.exists()) {
762:                    return f.getMessageCount();
763:                }
764:                return 0;
765:            }
766:
767:            /**
768:             * 
769:             */
770:            public void emptyFolder() throws Exception {
771:                Folder f = getFolder();
772:
773:                try {
774:                    Message msgs[] = f.getMessages();
775:                    FetchProfile fp = new FetchProfile();
776:                    fp.add(FetchProfile.Item.ENVELOPE);
777:                    f.fetch(msgs, fp);
778:
779:                    int ids[] = new int[msgs.length];
780:                    for (int i = 0; i < msgs.length; i++) {
781:                        ids[i] = msgs[i].getMessageNumber();
782:                    }
783:                    if (ids.length > 0) {
784:                        flagAsDeleted(ids);
785:                        // deleteMessages(ids);
786:                    }
787:                } catch (Exception e) {
788:                    log.warn("Could not delete all messages in folder: "
789:                            + folder);
790:                }
791:            }
792:
793:            /**
794:             * 
795:             */
796:            public void flagAsDeleted(int[] messageIds) throws Exception {
797:                Folder fold = null;
798:                try {
799:                    fold = getFolder();
800:                    if (messageIds != null && messageIds.length > 0) {
801:                        for (int i = 0; i < messageIds.length; i++) {
802:                            try {
803:                                if (messageIds[i] > 0) {
804:                                    Message msg = fold
805:                                            .getMessage(messageIds[i]);
806:                                    msg.setFlag(Flags.Flag.SEEN, true);
807:                                    msg.setFlag(Flags.Flag.DELETED, true);
808:                                }
809:                            } catch (Exception e) {
810:                                log.debug("error while deleting messsage", e);
811:                            }
812:                        }
813:                    }
814:                } catch (MessagingException e) {
815:                    log.error("Could not delete message ids: " + messageIds, e);
816:                    throw new MailboxActionException(e);
817:                } catch (IndexOutOfBoundsException e) {
818:                    log
819:                            .warn(
820:                                    "Maybe you are double clicking the delete button. do it a little bit slowly :) ",
821:                                    e);
822:                } catch (Exception e) {
823:                    log.error("Could not delete message ids: " + messageIds, e);
824:                    throw new MailboxActionException(e);
825:                }
826:            }
827:
828:            /**
829:             * 
830:             */
831:            public void deleteFolder() throws Exception {
832:                Folder f = getFolder();
833:                f.setSubscribed(false);
834:                closeFolder(f);
835:                f.delete(true);
836:            }
837:
838:            /**
839:             * @param newName
840:             */
841:            public void renameFolder(String newName) throws Exception {
842:                Folder fOld = getFolder();
843:                Folder fNew = handler.getStore().getFolder(
844:                        profile.getFolderNameSpace() + newName);
845:                closeFolder(fOld);
846:                fOld.renameTo(fNew);
847:                fNew.setSubscribed(true);
848:            }
849:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.