KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > velocity > ExportRss


1 package org.roller.presentation.velocity;
2
3 import org.apache.velocity.Template;
4 import org.apache.velocity.VelocityContext;
5 import org.apache.velocity.app.VelocityEngine;
6 import org.apache.velocity.exception.ParseErrorException;
7 import org.apache.velocity.exception.ResourceNotFoundException;
8 import org.roller.RollerException;
9 import org.roller.model.RollerFactory;
10 import org.roller.pojos.UserData;
11 import org.roller.pojos.WebsiteData;
12 import org.roller.presentation.RollerContext;
13 import org.roller.util.RegexUtil;
14 import org.roller.util.StringUtils;
15 import org.roller.util.Utilities;
16
17 import java.io.File JavaDoc;
18 import java.io.FileNotFoundException JavaDoc;
19 import java.io.FileOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.StringWriter JavaDoc;
22 import java.text.SimpleDateFormat JavaDoc;
23 import java.util.Collection JavaDoc;
24 import java.util.Date JavaDoc;
25 import java.util.Locale JavaDoc;
26 import java.util.Properties JavaDoc;
27 import java.util.TimeZone JavaDoc;
28
29 /**
30  * Does a lot of the same work as ContextLoader in preparing
31  * a VelocityContext for parsing. However, it is ignorant of
32  * any HttpServletRequest related features, and so has
33  * considerably trimmed down information.
34  *
35  * Created on Mar 25, 2004
36  * @author lance.lavandowska
37  */

38 public class ExportRss
39 {
40     private VelocityEngine ve = null;
41     private VelocityContext ctx = null;
42     private UserData user = null;
43     private boolean exportAtom;
44     
45     private static final String JavaDoc RSS_TEMPLATE = "org/roller/presentation/velocity/export_rss.vm";
46     private static final String JavaDoc ATOM_TEMPLATE = "org/roller/presentation/velocity/export_atom.vm";
47     
48     public ExportRss(WebsiteData website) throws Exception JavaDoc
49     {
50         Properties JavaDoc props = new Properties JavaDoc();
51         props.load(RollerContext.getServletContext().
52                    getResourceAsStream("/WEB-INF/velocity.properties"));
53         ve = new VelocityEngine();
54         ve.info("*******************************************");
55         ve.info("Initializing VelocityEngine for ExportRss");
56         ve.init( props );
57         ve.info("Done initializing VelocityEngine for ExportRss");
58         ve.info("************************************************");
59         
60         ctx = new VelocityContext();
61         
62         user = website.getUser();
63         RollerContext rollerCtx = RollerContext.getRollerContext(
64                                       RollerContext.getServletContext());
65         loadPageHelper();
66         
67         loadDates(website);
68         
69         loadWebsiteInfo(rollerCtx, website);
70
71         loadTheRest(rollerCtx);
72     }
73     
74     public void setExportAtom(boolean atom)
75     {
76         exportAtom = atom;
77     }
78     
79     /**
80      * Export the given entries using export_rss.vm.
81      *
82      * @param entries
83      * @throws ResourceNotFoundException
84      * @throws ParseErrorException
85      * @throws Exception
86      */

87     public void exportEntries(Collection JavaDoc entries, String JavaDoc fileName) throws ResourceNotFoundException, ParseErrorException, Exception JavaDoc
88     {
89         ctx.put("entries", entries);
90         
91         String JavaDoc templateFile = RSS_TEMPLATE;
92         if (exportAtom) templateFile = ATOM_TEMPLATE;
93         Template template = ve.getTemplate( templateFile, "utf-8" );
94         StringWriter JavaDoc sw = new StringWriter JavaDoc();
95         template.merge(ctx, sw);
96         
97         writeResultsToFile((String JavaDoc)ctx.get("uploadPath"), sw, fileName);
98     }
99
100     /**
101      * @param sw
102      */

103     private void writeResultsToFile(String JavaDoc filePath, StringWriter JavaDoc sw, String JavaDoc fileName)
104         throws RollerException, IOException JavaDoc
105     {
106         filePath += "/" + user.getUserName();
107         new java.io.File JavaDoc( filePath ).mkdirs(); // create dir path on drive
108

109         filePath += "/" + fileName;
110         
111         File JavaDoc outputFile = new java.io.File JavaDoc( filePath );
112         FileOutputStream JavaDoc out = null;
113         try
114         {
115             //outputFile.createNewFile();
116
out = new FileOutputStream JavaDoc( outputFile );
117             out.write( sw.toString().getBytes() );
118             out.flush();
119         }
120         catch ( FileNotFoundException JavaDoc e )
121         {
122             throw new RollerException( "Unable to write to: " + outputFile.getAbsolutePath(), e );
123         }
124         finally
125         {
126             try
127             {
128                 if ( out != null )
129                 {
130                     out.close();
131                 }
132             }
133             catch ( java.io.IOException JavaDoc ioe )
134             {
135                 System.err.println( "ExportRss unable to close OutputStream" );
136             }
137         }
138     }
139
140     /**
141      * Load miscellaneous values into the Context.
142      * @param rollerCtx
143      */

144     private void loadTheRest(RollerContext rollerCtx)
145     {
146         ctx.put("utilities", new Utilities() );
147         ctx.put("stringUtils", new StringUtils() );
148         ctx.put("entryLength", new Integer JavaDoc(-1));
149     }
150
151     /**
152      * Load information pertaining to the Website and
153      * its associated User.
154      * @param rollerCtx
155      */

156     private void loadWebsiteInfo(RollerContext rollerCtx, WebsiteData website)
157     {
158         ctx.put("website", website);
159         ctx.put("userName", user.getUserName() );
160         ctx.put("fullName", user.getFullName() );
161         ctx.put("emailAddress", user.getEmailAddress() );
162
163         ctx.put("encodedEmail", RegexUtil.encode(user.getEmailAddress()));
164         ctx.put("obfuscatedEmail", RegexUtil.obfuscateEmail(user.getEmailAddress()));
165
166         
167         // custom figureResourcePath() due to no "request" object
168
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
169         String JavaDoc uploadDir = null;
170         try {
171             uploadDir = RollerFactory.getRoller().getFileManager().getUploadDir();
172         } catch(Exception JavaDoc e) {}
173
174         ctx.put("uploadPath", uploadDir);
175     }
176
177     /**
178      * Load time-related information.
179      * @param website
180      */

181     private void loadDates(WebsiteData website)
182     {
183         try
184         {
185             // Add current time and last updated times to context
186
Date JavaDoc updateTime = RollerFactory.getRoller().getWeblogManager()
187             .getWeblogLastPublishTime( user.getUserName(), null );
188             ctx.put("updateTime", updateTime);
189         }
190         catch (RollerException e)
191         {
192             ctx.put("updateTime", new Date JavaDoc());
193         }
194         ctx.put("now", new Date JavaDoc());
195         
196         // setup Locale for future rendering
197
Locale JavaDoc locale = website.getLocaleInstance();
198         ctx.put("locale", locale);
199         
200         // setup Timezone for future rendering
201
ctx.put("timezone", website.getTimeZoneInstance());
202
203         // date formats need to be run through the Localized
204
// SimpleDateFormat and pulled back out as localized patterns.
205
SimpleDateFormat JavaDoc sdf = new SimpleDateFormat JavaDoc("yyyyMMdd", locale);
206         sdf.setTimeZone( (TimeZone JavaDoc)ctx.get("timezone") );
207         ctx.put("plainFormat", sdf.toLocalizedPattern());
208         
209         sdf.applyPattern("EEEE MMMM dd, yyyy");
210         ctx.put("toStringFormat", sdf.toLocalizedPattern());
211         
212         sdf.applyPattern("MMM dd yyyy, hh:mm:ss a z");
213         ctx.put("timestampFormat", sdf.toLocalizedPattern());
214         
215         ctx.put("dateFormatter", sdf );
216     }
217     /**
218      * Create a PageHelper. Note that will have no values
219      * necessary in parsing a Web request (such as /page) -
220      * it is only useful for the restricted export_rss.vm
221      * and has no PagePlugins either. We want the exported
222      * Entry.text to be the raw values.
223      */

224     private void loadPageHelper()
225     {
226         // Add Velocity page helper to context
227
PageHelper pageHelper = new PageHelper(null, null, ctx);
228         // set no PagePlugins - we *do not* want to render them.
229
ctx.put("pageHelper", pageHelper );
230     }
231 }
232
Popular Tags