KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > j2biz > blogunity > web > actions > my > ExportFeedAction


1 /*
2  * $Id: ExportFeedAction.java,v 1.10 2005/01/17 21:35:43 michelson Exp $
3  *
4  * Copyright (c) 2004 j2biz Group, http://www.j2biz.com
5  * Koeln / Duesseldorf , Germany
6  *
7  * @author Max Kalina
8  *
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23  *
24  */

25
26 package com.j2biz.blogunity.web.actions.my;
27
28 import java.io.File JavaDoc;
29 import java.io.FileInputStream JavaDoc;
30 import java.io.FileOutputStream JavaDoc;
31 import java.io.FileWriter JavaDoc;
32 import java.io.IOException JavaDoc;
33 import java.text.DateFormat JavaDoc;
34 import java.text.SimpleDateFormat JavaDoc;
35 import java.util.ArrayList JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.List JavaDoc;
38 import java.util.zip.GZIPOutputStream JavaDoc;
39 import java.util.zip.ZipEntry JavaDoc;
40 import java.util.zip.ZipOutputStream JavaDoc;
41
42 import javax.servlet.ServletOutputStream JavaDoc;
43 import javax.servlet.http.HttpServletRequest JavaDoc;
44 import javax.servlet.http.HttpServletResponse JavaDoc;
45
46 import org.apache.commons.lang.StringUtils;
47 import org.apache.commons.logging.Log;
48 import org.apache.commons.logging.LogFactory;
49
50 import com.j2biz.blogunity.BlogunityManager;
51 import com.j2biz.blogunity.dao.BlogDAO;
52 import com.j2biz.blogunity.exception.BlogunityException;
53 import com.j2biz.blogunity.i18n.I18N;
54 import com.j2biz.blogunity.i18n.I18NStatusFactory;
55 import com.j2biz.blogunity.pojo.Blog;
56 import com.j2biz.blogunity.pojo.Category;
57 import com.j2biz.blogunity.pojo.Entry;
58 import com.j2biz.blogunity.web.IActionResult;
59 import com.sun.syndication.feed.synd.SyndCategory;
60 import com.sun.syndication.feed.synd.SyndCategoryImpl;
61 import com.sun.syndication.feed.synd.SyndContent;
62 import com.sun.syndication.feed.synd.SyndContentImpl;
63 import com.sun.syndication.feed.synd.SyndEntry;
64 import com.sun.syndication.feed.synd.SyndEntryImpl;
65 import com.sun.syndication.feed.synd.SyndFeed;
66 import com.sun.syndication.feed.synd.SyndFeedImpl;
67 import com.sun.syndication.io.SyndFeedOutput;
68
69 /**
70  * @author michelson
71  * @version $$
72  * @since 0.1
73  *
74  *
75  */

76 public class ExportFeedAction extends MyAbstractAction {
77     /**
78      * Logger for this class
79      */

80     private static final Log log = LogFactory.getLog(ExportFeedAction.class);
81
82     private static final String JavaDoc MIME_TYPE = "application/xml; charset=UTF-8";
83
84     private static final String JavaDoc DATE_FORMAT = "yyyy-MM-dd";
85
86     /*
87      * (non-Javadoc)
88      *
89      * @see com.j2biz.blogunity.web.actions.AbstractAction#execute(javax.servlet.http.HttpServletRequest,
90      * javax.servlet.http.HttpServletResponse)
91      */

92     public IActionResult execute(HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
93             throws BlogunityException {
94
95         String JavaDoc blogid = request.getParameter("blogid");
96         if (StringUtils.isEmpty(blogid)) { throw new BlogunityException(I18NStatusFactory.create(
97                 I18N.ERRORS.ID_NOT_SETTED, "Blog")); }
98
99         String JavaDoc feedType = request.getParameter("type");
100         if (StringUtils.isEmpty(feedType))
101                 throw new BlogunityException(I18NStatusFactory
102                         .create(I18N.ERRORS.FEED_TYPE_NOT_SETTED));
103
104         String JavaDoc compression = request.getParameter("compression");
105         if (StringUtils.isEmpty(compression)) {
106             compression = "none";
107         }
108
109         Blog blog = null;
110         try {
111             blog = (new BlogDAO()).getBlogByID(Long.parseLong(blogid));
112         } catch (Exception JavaDoc e1) {
113             blog = null;
114         }
115         if (blog == null)
116                 throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.NOT_FOUND));
117
118         if (blog.getFounder().getId().longValue() != user.getId().longValue()
119                 && !user.isAdministrator())
120                 throw new BlogunityException(I18NStatusFactory
121                         .create(I18N.ERRORS.USER_NOT_AUTHORIZED_FOR_EXECUTION));
122
123         try {
124             SyndFeed feed = getFeed(request, blog);
125             feed.setFeedType(feedType);
126             response.setContentType(MIME_TYPE);
127
128             SyndFeedOutput output = new SyndFeedOutput();
129
130             String JavaDoc filename = blog.getUrlName();
131             if (compression.equals("zip")) {
132                 filename += "-" + feedType + ".zip";
133             } else if (compression.equals("gzip")) {
134                 filename += "-" + feedType + ".gz";
135             } else {
136                 filename += "-" + feedType + ".xml";
137             }
138
139             response.setHeader("Content-disposition", "attachment; filename=" + filename);
140             response.setContentType("application/Octet-stream");
141
142             if (compression.equals("zip") || compression.equals("gzip")) {
143                 File JavaDoc temp = writeFeedToTempFile(feed, blog);
144                 File JavaDoc compressedFile;
145
146                 if (compression.equals("zip")) {
147                     compressedFile = zipTempFile(temp);
148                 } else {
149                     compressedFile = gzipTempFile(temp);
150                 }
151
152                 removeTempFile(temp);
153
154                 ServletOutputStream JavaDoc op = response.getOutputStream();
155                 FileInputStream JavaDoc in = new FileInputStream JavaDoc(compressedFile);
156
157                 int length = 0;
158                 byte[] buf = new byte[4096];
159                 while ((in != null) && ((length = in.read(buf)) != -1)) {
160                     // the data has already been read into buf
161
op.write(buf, 0, length);
162                 }
163                 in.close();
164
165                 // and remove temporary file
166
removeTempFile(compressedFile);
167
168             } else {
169                 output.output(feed, response.getWriter());
170             }
171
172         } catch (Exception JavaDoc ex) {
173             log.error("Error generating blog!", ex);
174             throw new BlogunityException(I18NStatusFactory.create(
175                     I18N.ERRORS.COULD_NOT_GENERATE_FEED, ex));
176         }
177
178         // return null because we have no forward here
179
return null;
180     }
181
182     private synchronized File JavaDoc zipTempFile(File JavaDoc tempFile) throws BlogunityException {
183         try {
184
185             File JavaDoc zippedFile = new File JavaDoc(BlogunityManager.getSystemConfiguration().getTempDir(),
186                     tempFile.getName() + ".zip");
187
188             ZipOutputStream JavaDoc zos = new ZipOutputStream JavaDoc(new FileOutputStream JavaDoc(zippedFile));
189
190             byte[] readBuffer = new byte[2156];
191             int bytesIn = 0;
192
193             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(tempFile);
194             ZipEntry JavaDoc anEntry = new ZipEntry JavaDoc(tempFile.getName());
195
196             // place the zip entry in the ZipOutputStream object
197
zos.putNextEntry(anEntry);
198             //now write the content of the file to the ZipOutputStream
199
while ((bytesIn = fis.read(readBuffer)) != -1) {
200                 zos.write(readBuffer, 0, bytesIn);
201             }
202             //close the Stream
203
fis.close();
204             zos.close();
205
206             return zippedFile;
207
208         } catch (Exception JavaDoc e) {
209
210             throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.FEED_ZIP_FAILED, e));
211
212         }
213     }
214
215     private synchronized File JavaDoc gzipTempFile(File JavaDoc tempFile) throws BlogunityException {
216         try {
217
218             File JavaDoc gzippedFile = new File JavaDoc(BlogunityManager.getSystemConfiguration().getTempDir(),
219                     tempFile.getName() + ".gz");
220
221             GZIPOutputStream JavaDoc zos = new GZIPOutputStream JavaDoc(new FileOutputStream JavaDoc(gzippedFile));
222
223             byte[] readBuffer = new byte[2156];
224             int bytesIn = 0;
225
226             FileInputStream JavaDoc fis = new FileInputStream JavaDoc(tempFile);
227
228             //now write the content of the file to the ZipOutputStream
229
while ((bytesIn = fis.read(readBuffer)) != -1) {
230                 zos.write(readBuffer, 0, bytesIn);
231             }
232             //close the Stream
233
fis.close();
234             zos.close();
235
236             return gzippedFile;
237
238         } catch (Exception JavaDoc e) {
239             throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.FEED_GZIP_FAILED, e));
240         }
241     }
242
243     private synchronized File JavaDoc writeFeedToTempFile(SyndFeed feed, Blog b) throws BlogunityException {
244         String JavaDoc tempDir = BlogunityManager.getSystemConfiguration().getTempDir();
245         File JavaDoc tempFile = new File JavaDoc(tempDir, b.getUrlName() + "_" + System.currentTimeMillis()
246                 + ".xml");
247
248         if (!tempFile.exists()) {
249             boolean result;
250             try {
251                 result = tempFile.createNewFile();
252             } catch (IOException JavaDoc e) {
253                 throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.CREATE_DIRECTORY,
254                         tempFile.getAbsolutePath(), e));
255
256             }
257             if (!result) { throw new BlogunityException(I18NStatusFactory.create(
258                     I18N.ERRORS.CREATE_DIRECTORY, tempFile.getAbsolutePath())); }
259         } else {
260             throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.CREATE_DIRECTORY,
261                     tempFile.getAbsolutePath()));
262         }
263
264         try {
265             FileWriter JavaDoc writer = new FileWriter JavaDoc(tempFile);
266             SyndFeedOutput output = new SyndFeedOutput();
267             output.output(feed, writer);
268             writer.close();
269
270         } catch (Exception JavaDoc e) {
271             throw new BlogunityException(I18NStatusFactory.create(I18N.ERRORS.WRITE_DIRECTORY,
272                     tempFile.getAbsolutePath(), e));
273
274         }
275
276         return tempFile;
277     }
278
279     private synchronized void removeTempFile(File JavaDoc tempFile) throws BlogunityException {
280         boolean result = tempFile.delete();
281         if (!result) { throw new BlogunityException(I18NStatusFactory.create(
282                 I18N.ERRORS.DELETE_DIRECTORY, tempFile.getAbsolutePath())); }
283
284     }
285
286     private SyndFeed getFeed(HttpServletRequest JavaDoc request, Blog b) throws BlogunityException {
287
288         DateFormat JavaDoc dateParser = new SimpleDateFormat JavaDoc(DATE_FORMAT);
289
290         SyndFeed feed = new SyndFeedImpl();
291
292         String JavaDoc blogUrl = BlogunityManager.getBase() + "/blogs/" + b.getUrlName();
293
294         feed.setTitle(b.getUrlName());
295         feed.setLink(blogUrl);
296         feed.setDescription((b.getDescription() != null) ? b.getDescription() : "");
297         feed.setCopyright("Copyright by " + b.getFounder().getNickname());
298         feed.setAuthor(b.getFounder().getNickname());
299         feed.setPublishedDate(b.getLastModified());
300
301         // fill categories
302
List JavaDoc categories = new ArrayList JavaDoc();
303         for (Iterator JavaDoc i = b.getCategories().iterator(); i.hasNext();) {
304             Category cat = (Category) i.next();
305             SyndCategory c = new SyndCategoryImpl();
306             c.setName(cat.getName());
307             categories.add(c);
308
309         }
310         feed.setCategories(categories);
311
312         // fill entries
313
List JavaDoc syndEntries = new ArrayList JavaDoc();
314
315         for (Iterator JavaDoc i = b.getEntries().iterator(); i.hasNext();) {
316             Entry JavaDoc entry = (Entry JavaDoc) i.next();
317
318             SyndEntry e = new SyndEntryImpl();
319             e.setTitle(entry.getTitle());
320
321             e.setLink(blogUrl + entry.getPermalink());
322             e.setPublishedDate(entry.getCreateTime());
323
324             SyndContent description = new SyndContentImpl();
325             description.setType("text/html");
326             String JavaDoc value = "";
327             if (StringUtils.isNotEmpty(entry.getExcerpt())) value = entry.getExcerpt() + "<br/>"
328                     + entry.getBody();
329             else
330                 value = entry.getBody();
331
332             description.setValue(value);
333             e.setDescription(description);
334             syndEntries.add(e);
335
336         }
337
338         feed.setEntries(syndEntries);
339
340         return feed;
341     }
342 }
Popular Tags