KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > snipsnap > util > mail > PostDaemon


1 /*
2  * This file is part of "SnipSnap Wiki/Weblog".
3  *
4  * Copyright (c) 2002 Stephan J. Schmidt, Matthias L. Jugel
5  * All Rights Reserved.
6  *
7  * Please visit http://snipsnap.org/ for updates and contact.
8  *
9  * --LICENSE NOTICE--
10  * This pr ogram is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License
12  * as published by the Free Software Foundation; either version 2
13  * of the License, or (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23  * --LICENSE NOTICE--
24  */

25
26 package org.snipsnap.util.mail;
27
28 import org.radeox.util.logging.Logger;
29 import org.snipsnap.app.Application;
30 import org.snipsnap.app.ApplicationManager;
31 import org.snipsnap.config.Configuration;
32 import org.snipsnap.config.ConfigurationManager;
33 import org.snipsnap.container.Components;
34 import org.snipsnap.snip.Blog;
35 import org.snipsnap.snip.BlogKit;
36 import org.snipsnap.snip.SnipSpaceFactory;
37 import org.snipsnap.snip.Snip;
38 import org.snipsnap.user.User;
39 import org.snipsnap.user.UserManagerFactory;
40 import org.snipsnap.net.FileUploadServlet;
41
42 import javax.mail.Address JavaDoc;
43 import javax.mail.Flags JavaDoc;
44 import javax.mail.Folder JavaDoc;
45 import javax.mail.Message JavaDoc;
46 import javax.mail.MessagingException JavaDoc;
47 import javax.mail.Multipart JavaDoc;
48 import javax.mail.Part JavaDoc;
49 import javax.mail.Session JavaDoc;
50 import javax.mail.Store JavaDoc;
51 import java.io.File JavaDoc;
52 import java.io.FileOutputStream JavaDoc;
53 import java.io.IOException JavaDoc;
54 import java.io.InputStream JavaDoc;
55 import java.io.StringWriter JavaDoc;
56 import java.io.Writer JavaDoc;
57 import java.util.HashMap JavaDoc;
58 import java.util.Iterator JavaDoc;
59 import java.util.Map JavaDoc;
60 import java.util.Properties JavaDoc;
61 import java.util.Timer JavaDoc;
62 import java.util.TimerTask JavaDoc;
63 import java.util.Date JavaDoc;
64 import java.util.Calendar JavaDoc;
65
66 /**
67  * Automatically reads post from a source (e.g. Pop3) and
68  * posts them to a weblog (or Snip).
69  *
70  * @author Stephan J. Schmidt
71  * @version $Id: PostDaemon.java 1616 2004-05-26 10:41:42Z leo $
72  */

73
74 public class PostDaemon extends TimerTask JavaDoc {
75   private final static int INTERVAl = 5;
76
77   private static PostDaemon postDaemon;
78
79   public static synchronized PostDaemon getInstance() {
80     if (null == postDaemon) {
81       postDaemon = new PostDaemon();
82     }
83     return postDaemon;
84   }
85
86   private Timer JavaDoc pop3Timer;
87   private Map JavaDoc pop3Tasks = new HashMap JavaDoc();
88
89   /**
90    * Create new post daemon and start execution.
91    */

92   protected PostDaemon() {
93     pop3Timer = new Timer JavaDoc();
94     pop3Timer.schedule(this, INTERVAl * 60 * 1000, INTERVAl * 60 * 1000);
95   }
96
97   /**
98    * Execute mobile/email posts.
99    */

100   public void run() {
101     ConfigurationManager configManager = ConfigurationManager.getInstance();
102     Iterator JavaDoc oids = configManager.getOids();
103     Logger.debug("PostDaemon: checking for mail-to-blog posts ...");
104
105
106     while (oids.hasNext()) {
107       String JavaDoc appOid = (String JavaDoc) oids.next();
108       Configuration config = configManager.getConfiguration(appOid);
109
110
111       int minutes = -1;
112       try {
113         minutes = Integer.parseInt(config.getMailPop3Interval());
114       } catch (NumberFormatException JavaDoc e) {
115         Logger.warn("PostDaemon: interval is not a number: " + config.getMailPop3Interval());
116       }
117       String JavaDoc pop3Host = config.getMailPop3Host();
118       String JavaDoc pop3User = config.getMailPop3User();
119       String JavaDoc pop3Pass = config.getMailPop3Password();
120       String JavaDoc mailPass = config.getMailBlogPassword();
121
122       Date JavaDoc date = new Date JavaDoc();
123       Long JavaDoc executionTime = (Long JavaDoc) pop3Tasks.get(appOid);
124       if (minutes >= 5 && null != pop3Host && null != pop3User && null != mailPass) {
125         if (null == executionTime || executionTime.longValue() <= date.getTime()) {
126           Logger.debug("PostDaemon: processing "+pop3Host+":"+pop3User);
127           // only execute if the settings allow it
128
Application.get().storeObject(Application.OID, appOid);
129           Application.get().setConfiguration(config);
130
131           process(pop3Host, pop3User, pop3Pass, mailPass);
132
133           // set new execution point by adding current time and interval
134
pop3Tasks.put(appOid, new Long JavaDoc(date.getTime() + (minutes * 60 * 1000)));
135         }
136       }
137     }
138   }
139
140   private void process(String JavaDoc pop3Host, String JavaDoc pop3User, String JavaDoc pop3Pass, String JavaDoc mailPass) {
141     try {
142       // Create empty properties
143
Properties JavaDoc props = new Properties JavaDoc();
144
145       // Get session
146
Session JavaDoc session = Session.getDefaultInstance(props, null);
147
148       // Get the store
149
Store JavaDoc store = session.getStore("pop3");
150       store.connect(pop3Host, pop3User, pop3Pass);
151
152       // Get folder
153
Folder JavaDoc folder = store.getFolder("INBOX");
154       folder.open(Folder.READ_WRITE);
155
156       // Get directory
157
Message JavaDoc message[] = folder.getMessages();
158
159       String JavaDoc name = BlogKit.getPostName();
160
161       for (int i = 0, n = message.length; i < n; i++) {
162         if(message[i].getFlags().contains(Flags.Flag.DELETED)) {
163           continue;
164         }
165         
166         StringWriter JavaDoc writer = new StringWriter JavaDoc();
167
168         Logger.debug(i + ": " + message[i].getFrom()[0]
169                      + "\t" + message[i].getSubject());
170         Logger.debug(message[i].getContentType());
171
172         Address JavaDoc sender = message[i].getFrom()[0];
173         String JavaDoc title = message[i].getSubject();
174         if (title != null && title.startsWith(mailPass)) {
175           // only correct sender
176
// cut password from title
177
title = title.substring(mailPass.length()).trim();
178
179           try {
180             String JavaDoc contentType = message[i].getContentType();
181             if (contentType.startsWith("text/plain")) {
182               writer.write((String JavaDoc) message[i].getContent());
183             } else if (contentType.startsWith("image/")) {
184               processImage(writer, message[i], name);
185             } else if (contentType.startsWith("multipart/")) {
186               // process multipart message
187
processMultipart(writer, (Multipart JavaDoc) message[i].getContent(), name);
188             }
189
190             // BUG
191
Application app = Application.get();
192             ApplicationManager appManager = (ApplicationManager) Components.getComponent(ApplicationManager.class);
193             String JavaDoc appOid = appManager.getApplication("/");
194             app.storeObject(Application.OID, appOid);
195             String JavaDoc user = app.getConfiguration().getAdminLogin();
196             Logger.debug(user);
197             Logger.debug((String JavaDoc) app.getObject(Application.OID));
198             User admin = UserManagerFactory.getInstance().load(user);
199             Logger.debug(admin.toString());
200             app.setUser(admin);
201             Blog blog = SnipSpaceFactory.getInstance().getBlog();
202             Logger.debug("PostDaemon: posting '"+title);
203
204             Snip blogSnip = blog.post(writer.getBuffer().toString(), title);
205
206           } catch (Exception JavaDoc e) {
207             Logger.warn("PostDaemon Error:", e);
208           } finally {
209             // Delete message, either because we processed it or we couldn't
210
// process it
211
message[i].setFlag(Flags.Flag.DELETED, true);
212           }
213         } else {
214           Logger.warn("PostDaemon: wrong mail blog password: "+title);
215         }
216       }
217       // Close connection
218
folder.close(true);
219       store.close();
220     } catch (Exception JavaDoc e) {
221       Logger.warn("PostDaemon Error", e);
222     }
223
224   }
225
226   public void processImage(Writer JavaDoc writer, Part JavaDoc part, String JavaDoc name) throws MessagingException JavaDoc, IOException JavaDoc {
227     writer.write("{image:");
228     writer.write(FileUploadServlet.getCanonicalFileName(part.getFileName()));
229     storeImage(part, name);
230     writer.write("}");
231   }
232
233   public void processMultipart(Writer JavaDoc writer, Multipart JavaDoc mp, String JavaDoc name) throws MessagingException JavaDoc {
234     for (int j = 0; j < mp.getCount(); j++) {
235       try {
236         Part JavaDoc part = mp.getBodyPart(j);
237         Logger.debug("Disposition=" + part.getDisposition());
238         String JavaDoc contentType = part.getContentType();
239         Logger.debug("content-type=" + contentType);
240         Logger.debug("Object=" + part);
241         if (contentType.startsWith("text/plain")) {
242           writer.write((String JavaDoc) part.getContent());
243         } else if (contentType.startsWith("image/")) {
244           processImage(writer, part, name);
245         } else if (contentType.startsWith("multipart/")) {
246           processMultipart(writer, (Multipart JavaDoc) part.getContent(), name);
247         }
248       } catch (Exception JavaDoc e) {
249         Logger.warn("PostDaemon: Error reading message", e);
250       }
251     }
252   }
253
254   public void storeImage(Part JavaDoc part, String JavaDoc name) {
255     try {
256       if (part != null && part.getFileName() != null) {
257         Configuration config = Application.get().getConfiguration();
258         File JavaDoc imageDir = new File JavaDoc(config.getFilePath(), "images");
259         File JavaDoc file = new File JavaDoc(imageDir, "image-" + name + "-" + part.getFileName());
260         Logger.debug("Uploading '" + part.getFileName() + "' to '" + file.getAbsolutePath() + "'");
261         FileOutputStream JavaDoc out = new FileOutputStream JavaDoc(file);
262         InputStream JavaDoc in = part.getInputStream();
263         byte[] buf = new byte[4096];
264         int length = 0;
265         while ((length = in.read(buf)) != -1) {
266           out.write(buf, 0, length);
267         }
268         out.close();
269         in.close();
270       } else {
271         Logger.warn("PostDaemon: Error processing mail");
272       }
273     } catch (IOException JavaDoc e) {
274       Logger.warn("PostDaemon: Error processing mail", e);
275     } catch (MessagingException JavaDoc e) {
276       Logger.warn("PostDaemon: Error processing mail", e);
277     }
278
279   }
280
281 }
282
Popular Tags