KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > campware > cream > modules > scheduledjobs > Pop3Job


1 package org.campware.cream.modules.scheduledjobs;
2
3 /* ====================================================================
4  * Copyright (C) 2003-2005 Media Development Loan Fund
5  *
6  * * contact: contact@campware.org - http://www.campware.org
7  * Campware encourages further development. Please let us know.
8  *
9  * This program is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU General Public Licensede
11  * as published by the Free Software Foundation; either version 2
12  * of the License, or (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22  *
23  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
24  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
27  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
30  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
33  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  * ====================================================================
36  *
37  * This software consists of voluntary contributions made by many
38  * individuals on behalf of the Apache Software Foundation. For more
39  * information on the Apache Software Foundation, please see
40  * <http://www.apache.org/>.
41  */

42
43 //JDK
44
import java.util.Date JavaDoc;
45 import java.text.SimpleDateFormat JavaDoc;
46 import java.text.DateFormat JavaDoc;
47 import java.text.ParsePosition JavaDoc;
48 import java.util.*;
49 import java.text.ParseException JavaDoc;
50 import java.lang.System JavaDoc;
51 import java.io.*;
52 import java.util.Properties JavaDoc;
53 import javax.mail.*;
54 import javax.mail.internet.*;
55
56 //Turbine
57
import org.apache.turbine.Turbine;
58 import org.apache.turbine.modules.ScheduledJob;
59 import org.apache.turbine.services.schedule.JobEntry;
60 import org.apache.commons.logging.Log;
61 import org.apache.commons.logging.LogFactory;
62
63 import org.apache.torque.util.Criteria;
64 import org.apache.torque.util.Transaction;
65 import java.sql.Connection JavaDoc;
66
67 import org.campware.cream.om.InboxEvent;
68 import org.campware.cream.om.InboxEventPeer;
69 import org.campware.cream.om.InboxAttachment;
70 import org.campware.cream.om.Customer;
71 import org.campware.cream.om.CustomerPeer;
72 import org.campware.cream.modules.util.Base64;
73 import java.net.URLEncoder JavaDoc;
74
75 /**
76  * Pop3 Job.
77  *
78  * Retrieve new messages from POP3 server
79  * @author <a HREF="mailto:pandzic@volny.cz">Nenad Pandzic</a>
80  */

81 public class Pop3Job extends ScheduledJob
82 {
83     /** Logging */
84     private static Log log = LogFactory.getLog(Pop3Job.class);
85
86     private int taskcount = 0;
87
88     /**
89      * Constructor
90      */

91      public Pop3Job()
92      {
93          //do Task initialization here
94
}
95
96
97     /**
98      * Run the Jobentry from the scheduler queue.
99      * From ScheduledJob.
100      *
101      * @param job The job to run.
102      */

103     public void run( JobEntry job ) throws Exception JavaDoc
104     {
105         // First we resolve online subscriptions
106
doReceiveMessages();
107     }
108
109
110     private void doReceiveMessages() throws Exception JavaDoc{
111
112
113           log.debug("Checking mail ");
114
115         String JavaDoc host = Turbine.getConfiguration().getString("mail.pop3.host");
116         String JavaDoc username = Turbine.getConfiguration().getString("mail.pop3.user");
117         String JavaDoc password = Turbine.getConfiguration().getString("mail.pop3.password");
118
119         // Create empty properties
120
Properties JavaDoc props = new Properties JavaDoc();
121
122         // Get session
123
Session session = Session.getDefaultInstance(props, null);
124
125         // Get the store
126
Store store = session.getStore("pop3");
127
128         // Connect to store
129
store.connect(host, username, password);
130
131         // Get folder
132
Folder folder = store.getFolder("INBOX");
133
134         // Open read-only
135
folder.open(Folder.READ_WRITE);
136
137         // Get attributes & flags for all messages
138
//
139
Message[] messages = folder.getMessages();
140         FetchProfile fp = new FetchProfile();
141         fp.add(FetchProfile.Item.ENVELOPE);
142         fp.add(FetchProfile.Item.FLAGS);
143         fp.add("X-Mailer");
144         folder.fetch(messages, fp);
145
146         for (int i = 0; i < messages.length; i++) {
147             
148             log.debug("Retrieving message "+i);
149
150             // Process each message
151
//
152
InboxEvent entry = new InboxEvent();
153             Address fromAddress= new InternetAddress();
154             String JavaDoc from= new String JavaDoc();
155             String JavaDoc name= new String JavaDoc();
156             String JavaDoc email= new String JavaDoc();
157             String JavaDoc replyTo= new String JavaDoc();
158             String JavaDoc subject= new String JavaDoc();
159             String JavaDoc content= new String JavaDoc();
160             Date JavaDoc sentDate= new Date JavaDoc();
161             int emailformat= 10;
162
163             Message m = messages[i];
164
165             // and now, handle the content
166
Object JavaDoc o = m.getContent();
167
168             // find content type
169
if (m.isMimeType("text/plain")) {
170                 content = "<PRE style=\"font-size: 12px;\">" + (String JavaDoc)o + "</PRE>";
171                 emailformat=10;
172             } else if (m.isMimeType("text/html")) {
173                 content = (String JavaDoc)o;
174                 emailformat=20;
175             } else if (m.isMimeType("text/*")) {
176                 content = (String JavaDoc)o;
177                 emailformat=30;
178             } else if (m.isMimeType("multipart/alternative")) {
179                 try {
180                       content = handleAlternative(o, content);
181                       emailformat=20;
182                     }
183                     catch (Exception JavaDoc ex) {
184                       content="Problem with the message format. Messssage has left on the email server.";
185                       emailformat=50;
186                       log.error(ex.getMessage(),ex);
187                     }
188             } else if (m.isMimeType("multipart/*")) {
189                 try {
190                   content = handleMulitipart(o, content, entry);
191                   emailformat=40;
192                 }
193                 catch (Exception JavaDoc ex) {
194                   content="Problem with the message format. Messssage has left on the email server.";
195                   emailformat=50;
196                   log.error(ex.getMessage(),ex);
197                 }
198             } else {
199                 content="Problem with the message format. Messssage has left on the email server.";
200                 emailformat=50;
201                 log.debug("Could not handle properly");
202             }
203
204             email= ((InternetAddress)m.getFrom()[0]).getAddress();
205             name= ((InternetAddress)m.getFrom()[0]).getPersonal();
206             replyTo= ((InternetAddress)m.getReplyTo()[0]).getAddress();
207             sentDate= m.getSentDate();
208             subject= m.getSubject();
209
210             log.debug("Got message "+email+" "+name+" "+subject+" "+content);
211
212
213             // find if customer exists
214
Criteria criteria = new Criteria();
215             criteria.add(CustomerPeer.EMAIL, (Object JavaDoc)email, Criteria.EQUAL);
216             if (CustomerPeer.doSelect(criteria).size()>0){
217                log.debug("From known customer");
218                Customer myDistrib = (Customer) CustomerPeer.doSelect(criteria).get(0);
219                entry.setCustomerId(myDistrib.getCustomerId());
220             }
221
222             entry.setInboxEventCode(getTempCode());
223             entry.setEventType(10);
224             entry.setEventChannel(10);
225             entry.setEmailFormat(emailformat);
226             entry.setSubject(subject);
227             entry.setSenderEmail(email);
228             entry.setSenderName(name);
229             entry.setSenderReplyTo(replyTo);
230             entry.setSentTime(sentDate);
231             entry.setBody(content);
232             entry.setIssuedDate(new Date JavaDoc());
233             entry.setCreatedBy("system");
234             entry.setCreated(new Date JavaDoc());
235             entry.setModifiedBy("system");
236             entry.setModified(new Date JavaDoc());
237
238             Connection JavaDoc conn = Transaction.begin(InboxEventPeer.DATABASE_NAME);
239             boolean success = false;
240             try {
241                 entry.save(conn);
242                 entry.setInboxEventCode(getRowCode("IE", entry.getInboxEventId()));
243                 entry.save(conn);
244                 Transaction.commit(conn);
245                 success = true;
246             } finally {
247                 log.debug("Succcessfully stored in db: "+success);
248                 if (!success) Transaction.safeRollback(conn);
249             }
250
251             if (emailformat!=50){
252                 m.setFlag(Flags.Flag.DELETED, true);
253             }
254         }
255
256         // Close pop3 connection
257
folder.close(true);
258         store.close();
259
260     }
261
262     private String JavaDoc handleAlternative(Object JavaDoc o, String JavaDoc content) throws Exception JavaDoc{
263
264         Multipart multipart = (Multipart) o;
265         for (int k=0, n=multipart.getCount(); k<n; k++) {
266             Part part = multipart.getBodyPart(k);
267             MimeBodyPart mbp = (MimeBodyPart)part;
268
269             if (mbp.isMimeType("text/html")) {
270                 log.debug("---------------> Handle html alternative. ");
271                 content += (String JavaDoc)part.getContent();
272             }
273
274           }
275           
276           return content;
277     }
278
279     private String JavaDoc handleMulitipart(Object JavaDoc o, String JavaDoc content, InboxEvent inboxentry) throws Exception JavaDoc{
280
281         Multipart multipart = (Multipart) o;
282
283         for (int k=0, n=multipart.getCount(); k<n; k++) {
284
285             Part part = multipart.getBodyPart(k);
286             String JavaDoc disposition = part.getDisposition();
287             MimeBodyPart mbp = (MimeBodyPart)part;
288
289             if ((disposition != null) && (disposition.equals(Part.ATTACHMENT))){
290               log.debug("---------------> Saving File "+part.getFileName()+" "+part.getContent());
291               saveAttachment(part, inboxentry);
292
293             }else{
294               // Check if plain
295
if (mbp.isMimeType("text/plain")) {
296                 log.debug("---------------> Handle plain. ");
297                 content += "<PRE style=\"font-size: 12px;\">" + (String JavaDoc)part.getContent() + "</PRE>";
298                 // Check if html
299
} else if (mbp.isMimeType("text/html")) {
300                 log.debug("---------------> Handle plain. ");
301                 content += (String JavaDoc)part.getContent();
302               } else {
303                 // Special non-attachment cases here of
304
// image/gif, text/html, ...
305
log.debug("---------------> Special non-attachment cases "+" "+part.getContentType());
306                 if ( mbp.isMimeType("multipart/*") ){
307                   Object JavaDoc ob = part.getContent();
308                   content = this.handleMulitipart(ob, content, inboxentry)+ "\n\n" + content;
309                 }else{
310                   saveAttachment(part, inboxentry);
311                 }
312               }
313             }
314           }
315           
316           return content;
317     }
318
319     private void saveAttachment(Part part, InboxEvent inboxentry) throws Exception JavaDoc{
320         
321         MimeBodyPart mbp = (MimeBodyPart)part;
322         String JavaDoc fileName= mbp.getFileName();
323         String JavaDoc fileType= mbp.getContentType();
324         String JavaDoc fileId= mbp.getContentID();
325         String JavaDoc fileEncoding= mbp.getEncoding();
326         String JavaDoc attContent;
327
328         if (fileName==null || fileName.length()<2){
329             fileName= new String JavaDoc("Unknown");
330             if (fileType.indexOf("name")>0){
331                 int i = fileType.indexOf("name");
332                 int j = fileType.indexOf("\"", i+1);
333                 if (j!=-1){
334                     int k = fileType.indexOf("\"", j+1);
335                     if (k!=-1){
336                         fileName= fileType.substring(j+1, k);
337                     }
338                     
339                 } else {
340                     int k = fileType.indexOf(";", i+1);
341                     if (k!=-1){
342                         fileName= fileType.substring(i+5, k);
343                         
344                     }else{
345                         fileName= fileType.substring(i+5, fileType.length());
346                     }
347                 
348                 }
349             }
350         }
351         
352         InboxAttachment entryItem= new InboxAttachment();
353         
354         entryItem.setFileName(fileName);
355         if (fileType!=null) entryItem.setContentType(fileType);
356
357         if (mbp.getContent() instanceof InputStream){
358             InputStream is = new Base64.InputStream(mbp.getInputStream(), Base64.ENCODE);
359
360             BufferedReader reader = new BufferedReader(new InputStreamReader(is));
361
362             StringBuffer JavaDoc att = new StringBuffer JavaDoc();
363             String JavaDoc thisLine=reader.readLine();
364
365             while (thisLine!=null) {
366                att.append(thisLine);
367                thisLine=reader.readLine();
368             }
369
370             attContent= att.toString();
371 // MimeUtility.encode(part.getOutputStream(), "base64");
372
// attachments += saveFile(part.getFileName(), part.getInputStream());
373

374         }else{
375             attContent = part.getContent().toString() ;
376         }
377
378         
379         entryItem.setContent(attContent);
380         entryItem.setContentId(fileId);
381         
382         inboxentry.addInboxAttachment(entryItem);
383         
384     }
385
386     private String JavaDoc saveFile(String JavaDoc filename,InputStream stream){
387
388     String JavaDoc pf = this.getClass().getResource("Pop3Job.class").getPath();
389     pf = pf.substring(0, pf.indexOf("/cream"));
390     String JavaDoc attachments_url = "/cream/attachments/";//TurbineResources.getString("attachments.web.location");
391
String JavaDoc attachments_fs = pf+attachments_url;//TurbineResources.getString("attachments.fs.location");
392
attachments_fs = java.net.URLDecoder.decode(attachments_fs);
393
394
395     String JavaDoc url = "";
396     File file = new File(attachments_fs+filename);
397
398       for (int i=0; file.exists(); i++) {
399         file = new File(attachments_fs+i+filename);
400         filename = i+filename;
401       }
402
403       try {
404         file.createNewFile();
405       } catch (IOException ex1) {
406         ex1.printStackTrace();
407         return "";
408       }
409
410       log.debug("----- FILE CREATED "+file.exists()+" "+file.getAbsolutePath()+" "+file.canWrite());
411
412       url = "<a HREF='"+attachments_url+filename+"' target='_blank'>"+filename+"</a><br>";
413
414       try {
415         FileOutputStream FOS = new FileOutputStream(file);
416
417         byte b[] = new byte[16 * 1024];
418         for (; ; ) {
419           int bytes = stream.read(b);
420           if (bytes < 0) {
421             break;
422           }
423           if (bytes > 0) {
424             FOS.write(b, 0, bytes);
425           }
426         }
427         FOS.close();
428         stream.close();
429       } catch (Exception JavaDoc ex) {
430         ex.printStackTrace();
431         return "";
432       }
433
434       return url;
435     }
436
437
438     private String JavaDoc getTempCode()
439     {
440         Date JavaDoc currDate= new Date JavaDoc();
441         return Integer.toString(currDate.hashCode());
442     }
443
444     private String JavaDoc getRowCode(String JavaDoc s, int i)
445     {
446         String JavaDoc is= new String JavaDoc();
447
448         is= Integer.toString(i);
449         while (is.length()<7)
450         {
451             is="0" + is;
452         }
453
454         is= s + is;
455         return is;
456     }
457
458     private String JavaDoc formatDate(Date JavaDoc d)
459     {
460         SimpleDateFormat JavaDoc formatter = new SimpleDateFormat JavaDoc ("dd.MM.yyyy");
461         return formatter.format(d);
462     }
463
464
465 }
466
Popular Tags