KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > delicious > DailyPostingPlugin


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.plugin.delicious;
32
33 import del.icio.us.Delicious;
34 import del.icio.us.DeliciousUtils;
35 import org.apache.commons.logging.Log;
36 import org.apache.commons.logging.LogFactory;
37 import org.blojsom.blog.Blog;
38 import org.blojsom.blog.Entry;
39 import org.blojsom.event.EventBroadcaster;
40 import org.blojsom.fetcher.Fetcher;
41 import org.blojsom.fetcher.FetcherException;
42 import org.blojsom.plugin.PluginException;
43 import org.blojsom.plugin.admin.event.EntryAddedEvent;
44 import org.blojsom.plugin.velocity.StandaloneVelocityPlugin;
45 import org.blojsom.util.BlojsomMetaDataConstants;
46 import org.blojsom.util.BlojsomUtils;
47
48 import javax.servlet.ServletConfig JavaDoc;
49 import javax.servlet.http.HttpServletRequest JavaDoc;
50 import javax.servlet.http.HttpServletResponse JavaDoc;
51 import java.text.MessageFormat JavaDoc;
52 import java.util.*;
53
54 /**
55  * Plugin to post links from your <a HREF="http://del.icio.us">del.icio.us</a> account to your blog.
56  *
57  * @author David Czarnecki
58  * @version $Id: DailyPostingPlugin.java,v 1.2 2006/09/26 02:55:18 czarneckid Exp $
59  * @since blojsom 3.0
60  */

61 public class DailyPostingPlugin extends StandaloneVelocityPlugin {
62
63     private Log _logger = LogFactory.getLog(DailyPostingPlugin.class);
64
65     // Plugin configuration parameters
66
private static final String JavaDoc DAILY_POSTING_POLL_TIME_IP = "daily-posting-poll-time";
67     private static final int DAILY_POSTING_POLL_TIME_DEFAULT = (1000 * 60 * 60);
68     private int _pollTime = DAILY_POSTING_POLL_TIME_DEFAULT;
69
70     // Template
71
private static final String JavaDoc DAILY_POSTING_TEMPLATE = "org/blojsom/plugin/delicious/daily-posting-template.vm";
72
73     // Context variables
74
private static final String JavaDoc DAILY_POSTING_USERNAME = "DAILY_POSTING_USERNAME";
75     private static final String JavaDoc DAILY_POSTING_POSTS = "DAILY_POSTING_POSTS";
76
77     // Individual configuration parameters
78
private static final String JavaDoc DAILY_POSTING_USERNAME_IP = "daily-posting-username";
79     private static final String JavaDoc DAILY_POSTING_PASSWORD_IP = "daily-posting-password";
80     private static final String JavaDoc DAILY_POSTING_CATEGORY_IP = "daily-posting-category";
81     private static final String JavaDoc DAILY_POSTING_HOUR_IP = "daily-posting-hour";
82     private static final String JavaDoc DAILY_POSTING_TITLE_IP = "daily-posting-title";
83     private static final String JavaDoc DAILY_POSTING_AUTHOR_IP = "daily-posting-author";
84     private static final String JavaDoc DAILY_POSTING_TITLE_DEFAULT = "del.icio.us links for {0}";
85
86     private boolean _finished = false;
87     private DeliciousChecker _checker;
88
89     private String JavaDoc _proxyHost = null;
90     private String JavaDoc _proxyPort = null;
91
92     private Fetcher _fetcher;
93     private ServletConfig JavaDoc _servletConfig;
94     private EventBroadcaster _eventBroadcaster;
95
96     /**
97      * Create a new instance of the daily posting plugin
98      */

99     public DailyPostingPlugin() {
100     }
101
102     /**
103      * Set the {@link Fetcher}
104      *
105      * @param fetcher {@link Fetcher}
106      */

107     public void setFetcher(Fetcher fetcher) {
108         _fetcher = fetcher;
109     }
110
111     /**
112      * Set the {@link ServletConfig} for the fetcher to grab initialization parameters
113      *
114      * @param servletConfig {@link ServletConfig}
115      */

116     public void setServletConfig(ServletConfig JavaDoc servletConfig) {
117         _servletConfig = servletConfig;
118     }
119
120     /**
121      * Set the {@link EventBroadcaster}
122      *
123      * @param eventBroadcaster {@link EventBroadcaster}
124      */

125     public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
126         _eventBroadcaster = eventBroadcaster;
127     }
128
129     /**
130      * Initialize this plugin. This method only called when the plugin is instantiated.
131      *
132      * @throws org.blojsom.plugin.PluginException
133      * If there is an error initializing the plugin
134      */

135     public void init() throws PluginException {
136         super.init();
137
138         String JavaDoc pollTime = _servletConfig.getInitParameter(DAILY_POSTING_POLL_TIME_IP);
139         if (BlojsomUtils.checkNullOrBlank(pollTime)) {
140             _pollTime = DAILY_POSTING_POLL_TIME_DEFAULT;
141         } else {
142             try {
143                 _pollTime = Integer.parseInt(pollTime);
144                 if (_pollTime < DAILY_POSTING_POLL_TIME_DEFAULT) {
145                     _pollTime = DAILY_POSTING_POLL_TIME_DEFAULT;
146                 }
147             } catch (NumberFormatException JavaDoc e) {
148                 _pollTime = DAILY_POSTING_POLL_TIME_DEFAULT;
149             }
150         }
151
152         try {
153             _proxyHost = System.getProperty("http.proxyHost");
154             _proxyPort = System.getProperty("http.proxyPort");
155         } catch (Exception JavaDoc e) {
156             _logger.error(e);
157         }
158
159         _checker = new DeliciousChecker();
160         _checker.setDaemon(true);
161         _checker.start();
162     }
163
164     /**
165      * Process the blog entries
166      *
167      * @param httpServletRequest Request
168      * @param httpServletResponse Response
169      * @param blog {@link Blog} instance
170      * @param context Context
171      * @param entries Blog entries retrieved for the particular request
172      * @return Modified set of blog entries
173      * @throws PluginException If there is an error processing the blog entries
174      */

175     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map context, Entry[] entries) throws PluginException {
176         return entries;
177     }
178
179     /**
180      * Perform any cleanup for the plugin. Called after {@link #process}.
181      *
182      * @throws org.blojsom.plugin.PluginException
183      * If there is an error performing cleanup for this plugin
184      */

185     public void cleanup() throws PluginException {
186     }
187
188     /**
189      * Called when BlojsomServlet is taken out of service
190      *
191      * @throws org.blojsom.plugin.PluginException
192      * If there is an error in finalizing this plugin
193      */

194     public void destroy() throws PluginException {
195         _finished = true;
196     }
197
198     /**
199      * Checker thread for posting to del.icio.us
200      */

201     private class DeliciousChecker extends Thread JavaDoc {
202
203         /**
204          * Allocates a new <code>Thread</code> object. This constructor has
205          * the same effect as <code>Thread(null, null,</code>
206          * <i>gname</i><code>)</code>, where <b><i>gname</i></b> is
207          * a newly generated name. Automatically generated names are of the
208          * form <code>"Thread-"+</code><i>n</i>, where <i>n</i> is an integer.
209          *
210          * @see Thread#Thread(ThreadGroup,
211                 * Runnable, String)
212          */

213         public DeliciousChecker() {
214             super();
215         }
216
217         /**
218          * If this thread was constructed using a separate
219          * <code>Runnable</code> run object, then that
220          * <code>Runnable</code> object's <code>run</code> method is called;
221          * otherwise, this method does nothing and returns.
222          * <p/>
223          * Subclasses of <code>Thread</code> should override this method.
224          *
225          * @see Thread#start()
226          * @see Thread#stop()
227          * @see Thread#Thread(ThreadGroup,
228                 * Runnable, String)
229          * @see Runnable#run()
230          */

231         public void run() {
232             try {
233                 while (!_finished) {
234                     String JavaDoc[] blogIDs = _fetcher.loadBlogIDs();
235
236                     Blog blog;
237                     String JavaDoc blogID;
238
239                     for (int i = 0; i < blogIDs.length; i++) {
240                         blogID = blogIDs[i];
241
242                         try {
243                             blog = _fetcher.loadBlog(blogID);
244
245                             String JavaDoc postingCategory = blog.getProperty(DAILY_POSTING_CATEGORY_IP);
246                             String JavaDoc deliciousUsername = blog.getProperty(DAILY_POSTING_USERNAME_IP);
247                             String JavaDoc deliciousPassword = blog.getProperty(DAILY_POSTING_PASSWORD_IP);
248                             String JavaDoc postingHour = blog.getProperty(DAILY_POSTING_HOUR_IP);
249                             String JavaDoc postTitle = blog.getProperty(DAILY_POSTING_TITLE_IP);
250                             String JavaDoc postingAuthor = blog.getProperty(DAILY_POSTING_AUTHOR_IP);
251
252                             if (BlojsomUtils.checkNullOrBlank(postTitle)) {
253                                 postTitle = DAILY_POSTING_TITLE_DEFAULT;
254                             }
255
256                             if (BlojsomUtils.checkNullOrBlank(postingCategory) ||
257                                     BlojsomUtils.checkNullOrBlank(deliciousPassword) ||
258                                     BlojsomUtils.checkNullOrBlank(deliciousUsername) ||
259                                     BlojsomUtils.checkNullOrBlank(postingHour)) {
260                             } else {
261                                 Date now = new Date();
262                                 Calendar calendar = Calendar.getInstance();
263                                 calendar.setTime(now);
264                                 int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
265
266                                 try {
267                                     int hourToPost = Integer.parseInt(postingHour);
268                                     if (hourToPost == currentHour) {
269                                         Delicious delicious = new Delicious(deliciousUsername, deliciousPassword);
270                                         if (_proxyHost != null && _proxyPort != null) {
271                                             delicious.setProxyConfiguration(_proxyHost, Integer.parseInt(_proxyPort));
272                                         }
273
274                                         List posts = delicious.getPostsForDate(null, now);
275                                         if (posts.size() > 0) {
276                                             HashMap deliciousContext = new HashMap();
277                                             deliciousContext.put(DAILY_POSTING_USERNAME, deliciousUsername);
278                                             deliciousContext.put(DAILY_POSTING_POSTS, posts);
279
280                                             String JavaDoc renderedLinkTemplate = mergeTemplate(DAILY_POSTING_TEMPLATE, blog, deliciousContext);
281
282                                             // Create the blog entry
283
String JavaDoc nowAsString = DeliciousUtils.getDeliciousDate(now);
284                                             postingCategory = BlojsomUtils.normalize(postingCategory);
285
286                                             Entry entry;
287                                             entry = _fetcher.newEntry();
288
289                                             String JavaDoc title = MessageFormat.format(postTitle, new Object JavaDoc[]{nowAsString, deliciousUsername});
290                                             entry.setBlogId(blog.getId());
291                                             entry.setTitle(title);
292                                             entry.setDescription(renderedLinkTemplate);
293                                             entry.setDate(new Date());
294                                             entry.setStatus(BlojsomMetaDataConstants.NEW_STATUS);
295                                             entry.setBlogCategoryId(Integer.valueOf(postingCategory));
296                                             try {
297                                                 if (_fetcher.loadUser(blog, postingAuthor) != null) {
298                                                     entry.setAuthor(postingAuthor);
299                                                 }
300                                             } catch (FetcherException e) {
301                                             }
302
303                                             _fetcher.saveEntry(blog, entry);
304
305                                             _eventBroadcaster.broadcastEvent(new EntryAddedEvent(this, new Date(), entry, blog));
306                                             if (_logger.isDebugEnabled()) {
307                                                 _logger.debug("Posted del.icio.us links for: " + blog.getBlogId() + " using: " + deliciousUsername);
308                                             }
309                                         }
310                                     }
311                                 } catch (NumberFormatException JavaDoc e) {
312                                 }
313                             }
314                         } catch (FetcherException e) {
315                             if (_logger.isErrorEnabled()) {
316                                 _logger.error(e);
317                             }
318                         }
319                     }
320
321                     sleep(_pollTime);
322                 }
323             } catch (InterruptedException JavaDoc e) {
324                 if (_logger.isErrorEnabled()) {
325                     _logger.error(e);
326                 }
327             } catch (FetcherException e) {
328                 if (_logger.isErrorEnabled()) {
329                     _logger.error(e);
330                 }
331             }
332         }
333     }
334 }
Popular Tags