• Main Page
  • Related Pages
  • Classes
  • Files
  • File List

MessageStore.java

Go to the documentation of this file.
00001 
00002 import java.io.BufferedReader;
00003 import java.io.IOException;
00004 import java.io.InputStream;
00005 import java.io.InputStreamReader;
00006 import java.util.Properties;
00007 
00008 import javax.mail.BodyPart;
00009 import javax.mail.Folder;
00010 import javax.mail.Message;
00011 import javax.mail.MessagingException;
00012 import javax.mail.NoSuchProviderException;
00013 import javax.mail.Part;
00014 import javax.mail.Session;
00015 import javax.mail.Store;
00016 import javax.mail.Message.RecipientType;
00017 import javax.mail.internet.AddressException;
00018 import javax.mail.internet.InternetAddress;
00019 import javax.mail.internet.MimeMultipart;
00020 
00021 /**
00022  *  @author Mikica B Kocic
00023  */
00024 public class MessageStore implements Runnable
00025 {
00026     /**
00027      *  Rendering context for the message store
00028      */
00029     private GetMailApp parent;
00030 
00031     /**
00032      *  POP3 server name or IP address
00033      */
00034     private String popServer;
00035 
00036     /**
00037      *  User ID on the POP3 server
00038      */
00039     private String username;
00040 
00041     /**
00042      *  User's password on the POP3 server
00043      */
00044     private String password;
00045     
00046     /**
00047      *  Indicates whether to include contents of the messages in the dump
00048      */
00049     private boolean showContents;
00050 
00051     /**
00052      *  Output buffer where messages are dumped to
00053      */
00054     public StringBuffer outs = new StringBuffer ();
00055 
00056     /**
00057      *  Javamail message store
00058      */
00059     private Store store = null;
00060 
00061     /**
00062      *  Javamail message folder
00063      */
00064     private Folder folder = null;
00065 
00066     /**
00067      *  Creates instance of the class and starts worker thread immediately
00068      *  to receive messages
00069      *  
00070      *  @param  parent       rendering context where to write result
00071      *  @param  popServer    host name or IP address of the POP3 server
00072      *  @param  username     user ID on the server
00073      *  @param  password     user's password on the server
00074      *  @param  showContents show contents of the messages (or only headers)
00075      */
00076     public MessageStore( GetMailApp parent, 
00077             String popServer, String username, String password,
00078             boolean showContents
00079             )
00080     {
00081         this.parent    = parent;
00082         this.popServer = popServer;
00083         this.username  = username;
00084         this.password  = password;
00085         this.showContents = showContents;
00086         
00087         new Thread( this ).start ();
00088     }
00089 
00090     /**
00091      *  Opens messages store (authenticates to server) and opens the INBOX folder
00092      *  in the store
00093      */
00094     private void open () 
00095     {
00096         println( "<html><head><title>Email from " + popServer + "</title></head><body>" );
00097         
00098         try
00099         {
00100             Properties props = System.getProperties ();
00101             Session session = Session.getDefaultInstance( props, null );
00102     
00103             store = session.getStore( "pop3" );
00104             store.connect( popServer, username, password );
00105     
00106             folder = store.getDefaultFolder ();
00107             folder = folder.getFolder( "INBOX" );
00108     
00109             folder.open( Folder.READ_ONLY );
00110         }
00111         catch( NoSuchProviderException e )
00112         {
00113             println( "<h3>Error: No Such Provider Exception while connecting...</h3>" );
00114             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00115         }
00116         catch( MessagingException e )
00117         {
00118             println( "<h3>Error: Messaging Exception while connecting...</h3>" );
00119             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00120         }
00121     }
00122 
00123     /**
00124      *  Closes connection to message store
00125      */
00126     private void close ()
00127     {
00128         /* Close the connection 
00129          * but don't remove the messages from the server
00130          */
00131         
00132         if ( folder != null ) {
00133             try {
00134                 folder.close( false );
00135             } catch( MessagingException e ) {
00136                 /* ignored */
00137             }
00138         }
00139         
00140         if ( store != null ) {
00141             try {
00142                 store.close ();
00143             } catch( MessagingException e ) {
00144                 /* ignored */
00145             }
00146         }
00147         
00148         println( "</body></html>" );
00149     }
00150 
00151     /**
00152      *  Dumps all messages to the output buffer
00153      *  
00154      *  @param  showContents  show contents of the messages or not (i.e. only headers)
00155      */
00156     private void dumpAll( boolean showContents )
00157     {
00158         if ( folder == null ) {
00159             return;
00160         }
00161         
00162         try 
00163         {
00164             Message[] msgs = folder.getMessages ();
00165 
00166             if ( msgs != null && msgs.length > 0 )
00167             {
00168                 int current = 0; // count messages
00169                 for( Message m : folder.getMessages () )
00170                 {
00171                     ++current;
00172 
00173                     /* Show progress..
00174                      */
00175                     StringBuffer str = new StringBuffer ();
00176                     str.append( "<html><header></header><body><h3>Receiving message " ) 
00177                        .append( current )
00178                        .append( " of " )
00179                        .append( msgs.length )
00180                        .append( "...</h3>" )
00181                        .append( current >= msgs.length ?
00182                                "<p>Receiving completed. Rendering information...</p>" : "" )
00183                        .append( "</body></html>");
00184                     
00185                     parent.onGetMessagesCompleted( str );
00186                     
00187                     /* Dump header + contents optionally
00188                      */
00189                     printHeader( m );
00190                     if ( showContents ) {
00191                         printContents( m );
00192                     }
00193                 }
00194             }
00195             else
00196             {
00197                 println( "<html><header></header><body><h3>Receiving completed</h3>" ); 
00198                 println( "<div style='color:#800000;font-weight:bold;'>No messages.</div>" );
00199             }
00200         }    
00201         catch( MessagingException e )
00202         {
00203             println( "<h3>Error: Messaging Exception while retrieving...</h3>" );
00204             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00205         }
00206         
00207     }
00208 
00209     /**
00210      *  Appends new-line to output buffer
00211      */
00212     private MessageStore println ()
00213     {
00214         outs.append( "\n" );
00215         return this;
00216     }
00217 
00218     /**
00219      *  Appends message to output buffer
00220      */
00221     private MessageStore print( String str )
00222     {
00223         outs.append( str != null ? str : "" );
00224         return this;
00225     }
00226     
00227     /**
00228      *  Appends message terminated with new-line to output buffer
00229      */
00230     private MessageStore println( String str )
00231     {
00232         outs.append( str != null ? str : "" ).append( "\n" );
00233         return this;
00234     }
00235     
00236     /**
00237      *  Cleans message text from HTML entities (i.e. escapes HTML entities)
00238      *  and appends message to the output buffer
00239      */
00240     private MessageStore printEscHtml( String str )
00241     {
00242         if ( str == null ) {
00243             return this;
00244         }
00245 
00246         outs.append( str.replaceAll( "&",  "&amp;"  )
00247                         .replaceAll( "<",  "&lt;"   )
00248                         .replaceAll( ">",  "&gt;"   )
00249                         .replaceAll( "\"", "&quot;" ) );
00250         return this;
00251     }
00252     
00253     /**
00254      *  Dumps HTML formatted message header to the output buffer
00255      */
00256     private void printHeader( Message message )
00257     {
00258         try
00259         {
00260             println( "<hr />" );
00261             
00262             /* Begins table
00263              */
00264             println( "<table border='0' bgcolor='#F0F0FF' width='100%'>" );
00265 
00266             /* Shows header FROM:
00267              */
00268             InternetAddress[] aList = null;
00269             try {
00270                 aList = (InternetAddress[])( message.getFrom() );
00271             } catch( AddressException e ) {
00272                 /* ignored */
00273             }
00274 
00275             if ( aList != null )
00276             {
00277                 int count = 0;
00278                 print( "<tr><td style='font-weight:bold' width='120'>&nbsp;From:</td>" );
00279                 print( "<td style='font-weight:bold'>" );
00280                 
00281                 for ( InternetAddress a : aList )
00282                 {
00283                     if ( ++count > 1 ) {
00284                         print( "; " );
00285                     }
00286                     String from = a.getPersonal ();
00287                     if ( from == null ) {
00288                         printEscHtml( a.getAddress () );
00289                     } else {
00290                         printEscHtml( from + " <" + a.getAddress () + ">" );
00291                     }
00292                 }
00293 
00294                 println( "</td></tr>" );
00295             }
00296             
00297             /* Shows header SUBJECT:
00298              */
00299             if ( message.getSubject () != null ) 
00300             {
00301                 print( "<tr><td style='font-weight:bold'>&nbsp;Subject:</td>" );
00302                 print( "<td style='font-weight:bold'>" );
00303                 printEscHtml( message.getSubject() );
00304                 println( "</td></tr>" );
00305             }
00306 
00307             /* Shows header TO:
00308              */
00309             aList = null;
00310             try {
00311                 aList = (InternetAddress[])( message.getRecipients( RecipientType.TO ) );
00312             } catch( AddressException e ) {
00313                 /* ignored */
00314             }
00315 
00316             if ( aList != null ) 
00317             {
00318                 int count = 0;
00319                 print( "<tr><td style='font-weight:bold'>&nbsp;To:</td>" );
00320                 print( "<td>" );
00321                 
00322                 for ( InternetAddress a : aList )
00323                 {
00324                     if ( ++count > 1 ) {
00325                         print( "; " );
00326                     }
00327                     String to = a.getPersonal ();
00328                     if ( to == null ) {
00329                         printEscHtml( a.getAddress () );
00330                     } else {
00331                         printEscHtml( to + " <" + a.getAddress () + ">" );
00332                     }
00333                 }
00334 
00335                 println( "</td></tr>" );
00336             }
00337             
00338             /* Shows header RECEIVED:
00339              */
00340             java.util.Date sent = message.getSentDate ();
00341 
00342             if ( sent != null ) {
00343                 print( "<tr><td style='font-weight:bold'>&nbsp;Sent:</td><td>" );
00344                 printEscHtml( sent.toString () );
00345                 println( "</td></tr>" );
00346             }
00347 
00348             /* Shows header CONTENT TYPE:
00349              */
00350             String contentType = message.getContentType ();
00351 
00352             if ( contentType != null ) {
00353                 print( "<tr><td style='font-weight:bold'>&nbsp;Content Type:</td>" );
00354                 print( "<td><code>" );
00355                 printEscHtml( contentType );
00356                 println( "</code></td></tr>" );
00357             }
00358 
00359             /* Display disposition (attachments etc.)
00360              */
00361             if ( message.getContent () != null 
00362                     && ( message.getContent() instanceof MimeMultipart ) )
00363                {
00364                    MimeMultipart multipart = (MimeMultipart)message.getContent ();
00365 
00366                    for( int i = 0; i < multipart.getCount(); i++ )
00367                    { 
00368                        BodyPart bodyPart = multipart.getBodyPart( i );
00369                        String disposition = bodyPart.getDisposition ();
00370 
00371                        if ( disposition == null ) {
00372                            /* no disposition */
00373                        }
00374                        else if ( disposition.equalsIgnoreCase( Part.INLINE ) ) {
00375                            print( "<tr><td style='font-weight:bold'>&nbsp;Attachment:</td>" );
00376                            print( "<td>Inline: <code>" );
00377                            printEscHtml( bodyPart.getContentType () );
00378                            println( "</code></td></tr>" );
00379                        }
00380                        else if ( disposition.equalsIgnoreCase( Part.ATTACHMENT ) ) {
00381                            print( "<tr><td style='font-weight:bold'>&nbsp;Attachment:</td>" );
00382                            print( "<td>File: <code>" );
00383                            printEscHtml( bodyPart.getFileName () );
00384                            println( "</code></td></tr>" );
00385                        }
00386                    }
00387                }
00388 
00389             /* Finishes the table
00390              */
00391             println( "</table>" );
00392         }
00393         catch( MessagingException e )
00394         {
00395             println( "</table>" );
00396             println( "<hr />" );
00397             println( "<h3>Error: Messaging Exception while displaying header...</h3>" );
00398             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00399         }
00400         catch( IOException e ) 
00401         {
00402             println( "</table>" );
00403             println( "<hr />" );
00404             println( "<h3>Error: I/O Exception while displaying header...</h3>" );
00405             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00406         }
00407 
00408     }
00409 
00410     /**
00411      *  Dumps HTML escaped message content to the output buffer
00412      */
00413     private void printContents( Message message )
00414     {
00415         try
00416         {
00417             Part messagePart = message;
00418 
00419             println( "<hr />" );
00420             
00421             print( "<table border='0' bgcolor='#FFFFF0' width='100%'>"
00422                     + "<tr><td style='font-size:18;font-weight:bold'>"
00423                     + "Message Content</td></tr><tr><td><pre>" );
00424            
00425             InputStream inputStream = messagePart.getInputStream ();
00426             BufferedReader reader = new BufferedReader(
00427                     new InputStreamReader( inputStream ) );
00428 
00429             for( String str = reader.readLine(); str != null; str = reader.readLine() )
00430             {
00431                 printEscHtml( str ).println ();
00432             }
00433 
00434             println( "</pre></td></tr></table>" );
00435         }
00436         catch( MessagingException e )
00437         {
00438             println( "</pre></td></tr></table>" );
00439             println( "<h3>Error: Messaging Exception while displaying contents...</h3>" );
00440             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00441         }
00442         catch( IOException e )
00443         {
00444             println( "</pre>" );
00445             println( "<h3>Error: I/O Exception while displaying contents...</h3>" );
00446             println( "<pre style='color:red'>" + e.toString () + "</pre>" );
00447         }
00448     }
00449 
00450     /**
00451      *  Message store receiving worker thread. 
00452      *  Opens the store, dumps all messages and closes the store.
00453      *  At the end, renders output buffer in parent's context.
00454      */
00455     @Override
00456     public void run ()
00457     {
00458         this.open ();
00459         this.dumpAll( showContents );
00460         this.close ();
00461         parent.onGetMessagesCompleted( this.outs );
00462     }
00463 }

Generated on Thu Dec 16 2010 12:29:31 for Get Mail Client by  doxygen 1.7.2