KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > syndication > FeedImportPlugin


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.syndication;
32
33 import com.sun.syndication.feed.synd.SyndCategory;
34 import com.sun.syndication.feed.synd.SyndEntry;
35 import com.sun.syndication.feed.synd.SyndFeed;
36 import com.sun.syndication.feed.module.content.ContentModuleImpl;
37 import com.sun.syndication.feed.module.content.ContentModule;
38 import com.sun.syndication.io.FeedException;
39 import com.sun.syndication.io.SyndFeedInput;
40 import com.sun.syndication.io.XmlReader;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43 import org.blojsom.blog.*;
44 import org.blojsom.fetcher.Fetcher;
45 import org.blojsom.fetcher.FetcherException;
46 import org.blojsom.plugin.PluginException;
47 import org.blojsom.plugin.technorati.TechnoratiTagsPlugin;
48 import org.blojsom.plugin.syndication.module.*;
49 import org.blojsom.plugin.admin.WebAdminPlugin;
50 import org.blojsom.util.BlojsomConstants;
51 import org.blojsom.util.BlojsomMetaDataConstants;
52 import org.blojsom.util.BlojsomUtils;
53
54 import javax.servlet.http.HttpServletRequest JavaDoc;
55 import javax.servlet.http.HttpServletResponse JavaDoc;
56 import java.io.IOException JavaDoc;
57 import java.net.URL JavaDoc;
58 import java.util.List JavaDoc;
59 import java.util.Map JavaDoc;
60
61 /**
62  * Feed import plugin
63  *
64  * @author David Czarnecki
65  * @version $Id: FeedImportPlugin.java,v 1.7 2006/09/26 02:55:19 czarneckid Exp $
66  * @since blojsom 3.0
67  */

68 public class FeedImportPlugin extends WebAdminPlugin {
69
70     private Log _logger = LogFactory.getLog(FeedImportPlugin.class);
71
72     // Localization constants
73
private static final String JavaDoc FAILED_FEED_IMPORT_PERMISSION_KEY = "failed.feed.import.permission.text";
74     private static final String JavaDoc FAILED_FEED_IMPORT_ERROR_KEY = "failed.feed.import.error.text";
75     private static final String JavaDoc FAILED_FEED_IMPORT_IO_KEY = "failed.feed.import.io.text";
76
77     // Pages
78
private static final String JavaDoc FEED_IMPORT_PAGE = "/org/blojsom/plugin/syndication/templates/feed-import";
79
80     // Permissions
81
private static final String JavaDoc FEED_IMPORT_PERMISSION = "feed_import_permission";
82
83     // Form items
84
private static final String JavaDoc IMPORT_URL = "import-url";
85
86     // Actions
87
private static final String JavaDoc FEED_IMPORT_ACTION = "feed-import";
88
89     private Fetcher _fetcher;
90
91     /**
92      * Construct a new instance of the Feed import plugin
93      */

94     public FeedImportPlugin() {
95     }
96
97     /**
98      * Return the display name for the plugin
99      *
100      * @return Display name for the plugin
101      */

102     public String JavaDoc getDisplayName() {
103         return "Feed Import plugin";
104     }
105
106     /**
107      * Return the name of the initial editing page for the plugin
108      *
109      * @return Name of the initial editing page for the plugin
110      */

111     public String JavaDoc getInitialPage() {
112         return FEED_IMPORT_PAGE;
113     }
114
115     /**
116      * Set the {@link Fetcher}
117      *
118      * @param fetcher {@link Fetcher}
119      */

120     public void setFetcher(Fetcher fetcher) {
121         _fetcher = fetcher;
122     }
123
124     /**
125      * Process the blog entries
126      *
127      * @param httpServletRequest Request
128      * @param httpServletResponse Response
129      * @param blog {@link Blog} instance
130      * @param context Context
131      * @param entries Blog entries retrieved for the particular request
132      * @return Modified set of blog entries
133      * @throws PluginException If there is an error processing the blog entries
134      */

135     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
136         entries = super.process(httpServletRequest, httpServletResponse, blog, context, entries);
137
138         String JavaDoc page = BlojsomUtils.getRequestValue(BlojsomConstants.PAGE_PARAM, httpServletRequest);
139         String JavaDoc action = BlojsomUtils.getRequestValue(ACTION_PARAM, httpServletRequest);
140
141         String JavaDoc username = getUsernameFromSession(httpServletRequest, blog);
142         if (!checkPermission(blog, null, username, FEED_IMPORT_PERMISSION)) {
143             httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, ADMIN_ADMINISTRATION_PAGE);
144             addOperationResultMessage(context, getAdminResource(FAILED_FEED_IMPORT_PERMISSION_KEY, FAILED_FEED_IMPORT_PERMISSION_KEY, blog.getBlogAdministrationLocale()));
145
146             return entries;
147         }
148
149         if (ADMIN_LOGIN_PAGE.equals(page)) {
150             return entries;
151         } else if (FEED_IMPORT_ACTION.equals(action)) {
152             if (_logger.isDebugEnabled()) {
153                 _logger.debug("User requested feed import action");
154             }
155
156             String JavaDoc importLocation = BlojsomUtils.getRequestValue(IMPORT_URL, httpServletRequest);
157             if (!BlojsomUtils.checkNullOrBlank(importLocation)) {
158                 try {
159                     URL JavaDoc importURL = new URL JavaDoc(importLocation);
160                     SyndFeedInput input = new SyndFeedInput();
161                     SyndFeed feed = input.build(new XmlReader(importURL));
162                     SyndEntry entry;
163
164                     List JavaDoc feedEntries = feed.getEntries();
165
166                     StringBuffer JavaDoc statusMessage = new StringBuffer JavaDoc();
167
168                     if (feedEntries.size() > 0) {
169                         statusMessage.append("<p>");
170
171                         for (int i = 0; i < feedEntries.size(); i++) {
172                             entry = (SyndEntry) feedEntries.get(i);
173
174                             List JavaDoc entryCategories = entry.getCategories();
175
176                             Category category;
177                             category = _fetcher.newCategory();
178                             String JavaDoc categoryName = "/";
179                             if (entryCategories.size() > 0) {
180                                 categoryName = ((SyndCategory) entryCategories.get(0)).getName();
181                                 categoryName = categoryName.replaceAll("[+]", " ");
182                                 if (categoryName != null) {
183                                     if (!categoryName.startsWith("/")) {
184                                         categoryName = "/" + categoryName;
185                                     }
186
187                                     if (!categoryName.endsWith("/")) {
188                                         categoryName += "/";
189                                     }
190                                 }
191                             }
192
193                             try {
194                                 category = _fetcher.loadCategory(blog, categoryName);
195                                 if (category == null) {
196                                     category = _fetcher.newCategory();
197                                     category.setBlogId(blog.getId());
198                                     category.setName(categoryName);
199                                     category.setDescription(categoryName.replaceAll("/", " "));
200                                 }
201                             } catch (FetcherException e) {
202                                 if (_logger.isErrorEnabled()) {
203                                     _logger.error(e);
204                                 }
205
206                                 category.setBlogId(blog.getId());
207                                 category.setName(categoryName);
208                             }
209
210                             try {
211                                 _fetcher.saveCategory(blog, category);
212                                 _fetcher.loadCategory(blog, category);
213                             } catch (FetcherException e) {
214                                 _logger.error(e);
215                                 statusMessage.append(e.getMessage()).append("<br />");
216                             }
217
218                             Entry newEntry;
219                             newEntry = _fetcher.newEntry();
220
221                             newEntry.setBlogId(blog.getId());
222                             newEntry.setTitle(entry.getTitle());
223                             newEntry.setBlogCategoryId(category.getId());
224                             newEntry.setBlogCategory(category);
225                             newEntry.setDescription(entry.getDescription().getValue());
226                             newEntry.setDate(entry.getPublishedDate());
227                             newEntry.setModifiedDate(entry.getUpdatedDate());
228                             newEntry.setStatus(BlojsomMetaDataConstants.PUBLISHED_STATUS);
229
230                             BlojsomImplementation blojsomImplementation = (BlojsomImplementation) entry.getModule(Blojsom.BLOJSOM_URI);
231                             if (blojsomImplementation != null) {
232                                 if (blojsomImplementation.getAuthor() != null) {
233                                     newEntry.setAuthor(blojsomImplementation.getAuthor());
234                                 }
235
236                                 if (blojsomImplementation.getTechnoratiTags() != null) {
237                                     Map JavaDoc metadata = newEntry.getMetaData();
238                                     metadata.put(TechnoratiTagsPlugin.METADATA_TECHNORATI_TAGS, blojsomImplementation.getTechnoratiTags());
239                                     newEntry.setMetaData(metadata);
240                                 }
241
242                                 if (blojsomImplementation.getPostSlug() != null) {
243                                     newEntry.setPostSlug(blojsomImplementation.getPostSlug());
244                                 }
245
246                                 // Handle responses
247
if (blojsomImplementation.getAllowsComments()) {
248                                     newEntry.setAllowComments(new Integer JavaDoc(1));
249                                 } else {
250                                     newEntry.setAllowComments(new Integer JavaDoc(0));
251                                 }
252
253                                 if (blojsomImplementation.getAllowsTrackbacks()) {
254                                     newEntry.setAllowTrackbacks(new Integer JavaDoc(1));
255                                 } else {
256                                     newEntry.setAllowTrackbacks(new Integer JavaDoc(0));
257                                 }
258
259                                 if (blojsomImplementation.getAllowsPingbacks()) {
260                                     newEntry.setAllowPingbacks(new Integer JavaDoc(1));
261                                 } else {
262                                     newEntry.setAllowPingbacks(new Integer JavaDoc(0));
263                                 }
264
265                                 if (blojsomImplementation.getMetadata() != null && blojsomImplementation.getMetadata().size() > 0) {
266                                     Map JavaDoc metadataForEntry = newEntry.getMetaData();
267                                     List JavaDoc metadataItems = blojsomImplementation.getMetadata();
268                                     for (int j = 0; j < metadataItems.size(); j++) {
269                                         Metadata metadata = (Metadata) metadataItems.get(j);
270
271                                         if (metadata.getKey() != null) {
272                                             metadataForEntry.put(metadata.getKey(), metadata.getValue());
273                                         }
274                                     }
275
276                                     newEntry.setMetaData(metadataForEntry);
277                                 }
278                             }
279
280                             ContentModuleImpl contentModule = (ContentModuleImpl) entry.getModule(ContentModule.URI);
281                             if (contentModule != null) {
282                                 List JavaDoc encodeds = contentModule.getEncodeds();
283                                 if (encodeds != null && encodeds.size() > 0) {
284                                     newEntry.setDescription("");
285
286                                     StringBuffer JavaDoc description = new StringBuffer JavaDoc();
287                                     for (int j = 0; j < encodeds.size(); j++) {
288                                         String JavaDoc encodedContent = (String JavaDoc) encodeds.get(j);
289                                         description.append(encodedContent).append(BlojsomConstants.LINE_SEPARATOR);
290                                     }
291
292                                     newEntry.setDescription(description.toString());
293                                 }
294                             }
295
296                             try {
297                                 _fetcher.saveEntry(blog, newEntry);
298                                 _fetcher.loadEntry(blog, newEntry);
299
300                                 if (blojsomImplementation != null) {
301                                     if (blojsomImplementation.getComments() != null && blojsomImplementation.getComments().size() > 0) {
302                                         List JavaDoc comments = blojsomImplementation.getComments();
303                                         for (int j = 0; j < comments.size(); j++) {
304                                             SimpleComment simpleComment = (SimpleComment) comments.get(j);
305                                             Comment comment = _fetcher.newComment();
306
307                                             comment.setAuthor(simpleComment.getAuthor());
308                                             comment.setAuthorEmail(simpleComment.getAuthorEmail());
309                                             comment.setAuthorURL(simpleComment.getAuthorURL());
310                                             comment.setComment(simpleComment.getComment());
311                                             comment.setCommentDate(simpleComment.getCommentDate());
312                                             comment.setIp(simpleComment.getIp());
313                                             comment.setStatus(simpleComment.getStatus());
314                                             comment.setBlogId(blog.getId());
315                                             comment.setBlogEntryId(newEntry.getId());
316
317                                             if (simpleComment.getMetadata() != null && simpleComment.getMetadata().size() > 0) {
318                                                 Map JavaDoc metadataForComment = comment.getMetaData();
319                                                 List JavaDoc metadataItems = simpleComment.getMetadata();
320                                                 for (int k = 0; k < metadataItems.size(); k++) {
321                                                     Metadata metadata = (Metadata) metadataItems.get(k);
322
323                                                     if (metadata.getKey() != null) {
324                                                         metadataForComment.put(metadata.getKey(), metadata.getValue());
325                                                     }
326                                                 }
327
328                                                 comment.setMetaData(metadataForComment);
329                                             }
330
331                                             _fetcher.saveComment(blog, comment);
332                                         }
333                                     }
334
335                                     if (blojsomImplementation.getTrackbacks() != null && blojsomImplementation.getTrackbacks().size() > 0) {
336                                         List JavaDoc trackbacks = blojsomImplementation.getTrackbacks();
337                                         for (int j = 0; j < trackbacks.size(); j++) {
338                                             SimpleTrackback simpleTrackback = (SimpleTrackback) trackbacks.get(j);
339                                             Trackback trackback = _fetcher.newTrackback();
340
341                                             trackback.setBlogName(simpleTrackback.getBlogName());
342                                             trackback.setExcerpt(simpleTrackback.getExcerpt());
343                                             trackback.setUrl(simpleTrackback.getUrl());
344                                             trackback.setTitle(simpleTrackback.getTitle());
345                                             trackback.setIp(simpleTrackback.getIp());
346                                             trackback.setTrackbackDate(simpleTrackback.getTrackbackDate());
347                                             trackback.setStatus(simpleTrackback.getStatus());
348                                             trackback.setBlogEntryId(newEntry.getId());
349                                             trackback.setBlogId(blog.getId());
350
351                                             if (simpleTrackback.getMetadata() != null && simpleTrackback.getMetadata().size() > 0) {
352                                                 Map JavaDoc metadataForTrackback = trackback.getMetaData();
353                                                 List JavaDoc metadataItems = simpleTrackback.getMetadata();
354                                                 for (int k = 0; k < metadataItems.size(); k++) {
355                                                     Metadata metadata = (Metadata) metadataItems.get(k);
356
357                                                     if (metadata.getKey() != null) {
358                                                         metadataForTrackback.put(metadata.getKey(), metadata.getValue());
359                                                     }
360                                                 }
361
362                                                 trackback.setMetaData(metadataForTrackback);
363                                             }
364
365                                             _fetcher.saveTrackback(blog, trackback);
366                                         }
367                                     }
368
369                                     if (blojsomImplementation.getPingbacks() != null && blojsomImplementation.getPingbacks().size() > 0) {
370                                         List JavaDoc pingbacks = blojsomImplementation.getPingbacks();
371                                         for (int j = 0; j < pingbacks.size(); j++) {
372                                             SimplePingback simplePingback = (SimplePingback) pingbacks.get(j);
373                                             Pingback pingback = _fetcher.newPingback();
374
375                                             pingback.setBlogName(simplePingback.getBlogName());
376                                             pingback.setExcerpt(simplePingback.getExcerpt());
377                                             pingback.setUrl(simplePingback.getUrl());
378                                             pingback.setTitle(simplePingback.getTitle());
379                                             pingback.setIp(simplePingback.getIp());
380                                             pingback.setTrackbackDate(simplePingback.getPingbackDate());
381                                             pingback.setStatus(simplePingback.getStatus());
382                                             pingback.setSourceURI(simplePingback.getSourceURI());
383                                             pingback.setTargetURI(simplePingback.getTargetURI());
384                                             pingback.setBlogEntryId(newEntry.getId());
385                                             pingback.setBlogId(blog.getId());
386
387                                             if (simplePingback.getMetadata() != null && simplePingback.getMetadata().size() > 0) {
388                                                 Map JavaDoc metadataForPingback = pingback.getMetaData();
389                                                 List JavaDoc metadataItems = simplePingback.getMetadata();
390                                                 for (int k = 0; k < metadataItems.size(); k++) {
391                                                     Metadata metadata = (Metadata) metadataItems.get(k);
392
393                                                     if (metadata.getKey() != null) {
394                                                         metadataForPingback.put(metadata.getKey(), metadata.getValue());
395                                                     }
396                                                 }
397
398                                                 pingback.setMetaData(metadataForPingback);
399                                             }
400
401                                             _fetcher.savePingback(blog, pingback);
402                                         }
403                                     }
404                                 }
405                             } catch (FetcherException e) {
406                                 _logger.error(e);
407                                 statusMessage.append(e.getMessage()).append("<br />");
408                             }
409                         }
410
411                         statusMessage.append(("</p>"));
412                     }
413
414                     String JavaDoc status = "Successfully imported " + feedEntries.size() + " entries";
415                     if (statusMessage.length() > 0) {
416                         status += "<br /> " + statusMessage.toString();
417                     }
418
419                     addOperationResultMessage(context, status);
420                 } catch (FeedException e) {
421                     e.printStackTrace();
422                     _logger.error(e);
423
424                     addOperationResultMessage(context, formatAdminResource(FAILED_FEED_IMPORT_ERROR_KEY, FAILED_FEED_IMPORT_ERROR_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[]{e.getMessage()}));
425                 } catch (IOException JavaDoc e) {
426                     _logger.error(e);
427
428                     addOperationResultMessage(context, formatAdminResource(FAILED_FEED_IMPORT_IO_KEY, FAILED_FEED_IMPORT_IO_KEY, blog.getBlogAdministrationLocale(), new Object JavaDoc[]{e.getMessage()}));
429                 } catch (RuntimeException JavaDoc e) {
430                     e.printStackTrace();
431                 }
432             }
433         }
434
435         httpServletRequest.setAttribute(BlojsomConstants.PAGE_PARAM, FEED_IMPORT_PAGE);
436
437         return entries;
438     }
439 }
440
Popular Tags