KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > website > actions > ThemeEditorAction


1 package org.roller.presentation.website.actions;
2
3 import org.apache.commons.logging.Log;
4 import org.apache.commons.logging.LogFactory;
5 import org.apache.struts.action.ActionError;
6 import org.apache.struts.action.ActionErrors;
7 import org.apache.struts.action.ActionForm;
8 import org.apache.struts.action.ActionForward;
9 import org.apache.struts.action.ActionMapping;
10 import org.apache.struts.actions.DispatchAction;
11 import org.roller.RollerException;
12 import org.roller.model.UserManager;
13 import org.roller.pojos.PageData;
14 import org.roller.pojos.UserData;
15 import org.roller.pojos.WebsiteData;
16 import org.roller.presentation.RollerContext;
17 import org.roller.presentation.RollerRequest;
18 import org.roller.presentation.pagecache.PageCacheFilter;
19 import org.roller.presentation.velocity.PreviewResourceLoader;
20 import org.roller.presentation.website.ThemeCache;
21 import org.roller.presentation.website.formbeans.ThemeEditorForm;
22
23 import java.io.BufferedReader JavaDoc;
24 import java.io.FileReader JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.util.Date JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29
30 import javax.servlet.ServletContext JavaDoc;
31 import javax.servlet.ServletException JavaDoc;
32 import javax.servlet.http.HttpServletRequest JavaDoc;
33 import javax.servlet.http.HttpServletResponse JavaDoc;
34 import javax.servlet.http.HttpSession JavaDoc;
35
36 import org.roller.config.RollerRuntimeConfig;
37
38
39 /////////////////////////////////////////////////////////////////////////////
40

41 /**
42  * Actions for theme chooser page.
43  *
44  * @author llavandowska
45  *
46  * @struts.action name="themeEditorForm" path="/editor/themeEditor"
47  * scope="session" parameter="method"
48  *
49  * @struts.action-forward name="editTheme.page" path="/website/theme-editor.jsp"
50  */

51 public class ThemeEditorAction extends DispatchAction
52 {
53     private static final String JavaDoc SESSION_TEMPLATE = "weblog.template";
54     private static final String JavaDoc LAST_THEME = "weblog.prev.theme";
55     private static Log mLogger =
56         LogFactory.getFactory().getInstance(ThemeEditorAction.class);
57     private ThemeCache themeCache = ThemeCache.getInstance();
58     
59     /**
60      * Take user to edit theme page.
61      *
62      * @param mapping Struts action mapping.
63      * @param form Theme editor form bean.
64      * @param request Servlet request.
65      * @param response Servlet response.
66      * @return Forward to edit-website page.
67      * @throws IOException
68      * @throws ServletException
69      */

70     //-----------------------------------------------------------------------
71
public ActionForward edit(
72         ActionMapping mapping,
73         ActionForm form,
74         HttpServletRequest JavaDoc request,
75         HttpServletResponse JavaDoc response)
76         throws IOException JavaDoc, ServletException JavaDoc
77     {
78         ActionErrors errors = new ActionErrors();
79         ActionForward forward = mapping.findForward("editTheme.page");
80         try
81         {
82             RollerRequest rreq = RollerRequest.getRollerRequest(request);
83             if ( rreq.isUserAuthorizedToEdit() )
84             {
85                 loadThemes( rreq, errors, true);
86                 ThemeEditorForm teForm = (ThemeEditorForm)form;
87                 
88                 teForm.setThemeName(null); // start fresh
89

90                 if (mLogger.isDebugEnabled())
91                 {
92                     mLogger.debug("loaded themes, form="+teForm);
93                 }
94                 
95 // // if a custom template has been previewed already,
96
// // it'll be in memory.
97
// String template =
98
// (String)request.getSession().getAttribute(SESSION_TEMPLATE);
99
//
100
// if (mLogger.isDebugEnabled())
101
// {
102
// mLogger.debug("got template="+template);
103
// }
104
//
105
// if (StringUtils.isNotEmpty(template))
106
// {
107
// // load the template in memory
108
// teForm.setThemeTemplate( template );
109
//
110
// if (mLogger.isDebugEnabled())
111
// {
112
// mLogger.debug("set template");
113
// }
114
// }
115
// // otherwise the "custom" template will need be loaded
116
// // from the current page.
117
// else
118
// {
119

120                 // clear any previously set themes
121
clearThemePages(rreq,
122                     (String JavaDoc)request.getSession(true).getAttribute(LAST_THEME));
123                                 
124                  // load the current default page
125
PageData page = getDefaultPage( rreq );
126                     teForm.setThemeTemplate( page.getTemplate() );
127                     
128                     
129                 //}
130
}
131             else
132             {
133                 forward = mapping.findForward("access-denied");
134             }
135         }
136         catch (Exception JavaDoc e)
137         {
138             mLogger.error("ERROR in action",e);
139             throw new ServletException JavaDoc(e);
140         }
141         return forward;
142     }
143
144     //-----------------------------------------------------------------------
145
/**
146      * Load the template/theme to be previewed. The template must be stashed
147      * in PreviewResourceLoader so that PreviewServlet can find it.
148      *
149      * @param mapping Struts action mapping.
150      * @param form Theme editor form bean.
151      * @param request Servlet request.
152      * @param response Servlet response.
153      * @return Forward to edit-website page.
154      * @throws IOException
155      * @throws ServletException
156      */

157     public ActionForward preview(
158         ActionMapping mapping,
159         ActionForm form,
160         HttpServletRequest JavaDoc request,
161         HttpServletResponse JavaDoc response)
162         throws IOException JavaDoc, ServletException JavaDoc
163     {
164         ActionErrors errors = new ActionErrors();
165         ActionForward forward = mapping.findForward("editTheme.page");
166         try
167         {
168             RollerRequest rreq = RollerRequest.getRollerRequest(request);
169             if ( rreq.isUserAuthorizedToEdit() )
170             {
171                 HttpSession JavaDoc session = request.getSession();
172                 ThemeEditorForm teForm = (ThemeEditorForm)form;
173                 
174                 String JavaDoc theme = teForm.getThemeName();
175                 ServletContext JavaDoc ctx = rreq.getServletContext();
176                 RollerContext rollerContext =
177                     RollerContext.getRollerContext( ctx );
178                                       
179                 boolean showCustom = false;
180                 if ( !"Custom".equals( theme ) )
181                 {
182                     // if it isn't a custom template, load it from file
183
String JavaDoc sb = this.readTheme(rollerContext, theme);
184                     teForm.setThemeTemplate( sb );
185
186                     // clear any previously set themes
187
clearThemePages(rreq,
188                         (String JavaDoc) session.getAttribute(LAST_THEME));
189                                            
190                     setThemePages(rreq, theme);
191                     session.setAttribute(LAST_THEME, theme);
192                 }
193                 else
194                 {
195                     showCustom = true;
196                     clearThemePages(rreq,
197                         (String JavaDoc) session.getAttribute(LAST_THEME));
198                         
199                     session.removeAttribute(LAST_THEME);
200                     //session.removeAttribute(SESSION_TEMPLATE);
201

202                    //UserData ud = rreq.getUser();
203
//PreviewResourceLoader.clearAllTemplates( ud.getUserName());
204
}
205                 loadThemes( rreq, errors, showCustom);
206
207                 // put the template where PreviewServlet
208
// will be able to find it
209
PageData page = getDefaultPage( rreq );
210                 PreviewResourceLoader.setTemplate(page.getId(),
211                     teForm.getThemeTemplate(), rreq.getUser().getUserName() );
212                 
213                 // save the template in session for later editing
214
session.setAttribute(SESSION_TEMPLATE,
215                     teForm.getThemeTemplate() );
216             }
217             else
218             {
219                 forward = mapping.findForward("access-denied");
220             }
221         }
222         catch (Exception JavaDoc e)
223         {
224             mLogger.error("ERROR in action",e);
225             throw new ServletException JavaDoc(e);
226         }
227         return forward;
228     }
229
230     //-----------------------------------------------------------------------
231
/**
232      * Save the selected Theme or edited template as the Weblog pages template.
233      *
234      * @param mapping Struts action mapping.
235      * @param form Theme editor form bean.
236      * @param request Servlet request.
237      * @param response Servlet response.
238      * @return Forward to edit-website page.
239      * @throws IOException
240      * @throws ServletException
241      */

242     public ActionForward save(
243         ActionMapping mapping,
244         ActionForm form,
245         HttpServletRequest JavaDoc request,
246         HttpServletResponse JavaDoc response)
247         throws IOException JavaDoc, ServletException JavaDoc
248     {
249         ActionErrors errors = new ActionErrors();
250         ActionForward forward = mapping.findForward("editTheme.page");
251         try
252         {
253             RollerRequest rreq = RollerRequest.getRollerRequest(request);
254             if ( rreq.isUserAuthorizedToEdit() )
255             {
256                 loadThemes( rreq, errors, true);
257                 ThemeEditorForm teForm = (ThemeEditorForm)form;
258                 String JavaDoc theme = teForm.getThemeName();
259                 ServletContext JavaDoc ctx = rreq.getServletContext();
260                 RollerContext rollerContext =
261                                 RollerContext.getRollerContext( ctx );
262                     
263                 // load the template either from the Form
264
// or from the disk (if its a stock Theme).
265
String JavaDoc template = "";
266                 if ( "Custom".equals( theme ) )
267                 {
268                     // use the edited template
269
template = teForm.getThemeTemplate();
270                 }
271                 else
272                 {
273                     // Figure path to new user theme
274
String JavaDoc sb = this.readTheme(rollerContext, theme);
275                     template = sb;
276                 }
277
278                 // we'll need the User
279
UserData ud = rreq.getUser();
280
281                 // clear the places holding onto the template
282
PreviewResourceLoader.clearAllTemplates(ud.getUserName());
283                 request.getSession().removeAttribute(SESSION_TEMPLATE);
284
285                 // store the template in the page
286
UserManager mgr = rreq.getRoller().getUserManager();
287                 PageData page = getDefaultPage( rreq );
288
289                 page.setTemplate( template );
290                 mgr.storePage( page);
291                 
292                 saveThemePages( rreq, theme);
293                 
294                 // put them into the PreviewResourceLoader also
295
setThemePages(rreq, theme);
296
297                 // clear the page cache
298
PageCacheFilter.removeFromCache( request, ud );
299                 teForm.setThemeName("Custom");
300             }
301             else
302             {
303                 forward = mapping.findForward("access-denied");
304             }
305         }
306         catch (Exception JavaDoc e)
307         {
308             mLogger.error("ERROR in action",e);
309             throw new ServletException JavaDoc(e);
310         }
311         return forward;
312     }
313     
314
315     /**
316      * Cancel choosing of theme.
317      *
318      * @param mapping Struts action mapping.
319      * @param form Theme editor form bean.
320      * @param request Servlet request.
321      * @param response Servlet response.
322      * @return Forward to edit-website page.
323      * @throws IOException
324      * @throws ServletException
325      */

326     public ActionForward cancel(
327         ActionMapping mapping,
328         ActionForm form,
329         HttpServletRequest JavaDoc request,
330         HttpServletResponse JavaDoc response)
331         throws IOException JavaDoc, ServletException JavaDoc
332     {
333         ActionForward forward = mapping.findForward("editTheme");
334         try
335         {
336             RollerRequest rreq = RollerRequest.getRollerRequest(request);
337             if ( rreq.isUserAuthorizedToEdit() )
338             {
339                 // clear the page cache
340
UserData ud = rreq.getUser();
341                 PageCacheFilter.removeFromCache( request, ud );
342                 ThemeEditorForm teForm = (ThemeEditorForm)form;
343                                 
344                 // clear the places holding onto the template
345
PreviewResourceLoader.clearAllTemplates( ud.getUserName() );
346                 request.getSession().removeAttribute(SESSION_TEMPLATE);
347                 teForm.setThemeName("Custom");
348             }
349             else
350             {
351                 forward = mapping.findForward("access-denied");
352             }
353         }
354         catch (Exception JavaDoc e)
355         {
356             mLogger.error("ERROR in action",e);
357             throw new ServletException JavaDoc(e);
358         }
359         return forward;
360     }
361     
362     /**
363      * Load the Themes from disk ONCE per user session.
364      *
365      * @param rreq
366      * @param errors
367      */

368     private void loadThemes(
369         RollerRequest rreq, ActionErrors errors, boolean listCustom)
370     {
371         HttpSession JavaDoc session = rreq.getRequest().getSession(false);
372         try
373         {
374             // Figure path to new user templates
375
ServletContext JavaDoc ctx = rreq.getServletContext();
376             String JavaDoc[] themes = null;
377             if (ctx.getAttribute("themeStore") != null)
378             {
379                 themes = (String JavaDoc[]) ctx.getAttribute("themeStore");
380             }
381             else
382             {
383                 RollerContext rollerContext =
384                                 RollerContext.getRollerContext( ctx );
385                 themes = rollerContext.getThemeNames();
386                 ctx.setAttribute("themeStore", themes);
387             }
388             
389             // need to insert "Custom" as the top theme.
390
// "Custom" means the hand-edited template.
391
if (listCustom)
392             {
393                 // probably should use arraycopy here?
394
String JavaDoc[] themes2 = new String JavaDoc[ themes.length+1 ];
395                 themes2[0] = "Custom";
396                 for (int i=1; i<themes2.length; i++)
397                 {
398                     themes2[i] = themes[i-1];
399                 }
400                 themes = themes2;
401             }
402             session.setAttribute( "themes", themes );
403         }
404         catch (Exception JavaDoc e)
405         {
406             errors.add(ActionErrors.GLOBAL_ERROR,
407                 new ActionError("error.editing.user", e.toString()));
408         }
409     }
410     
411     /**
412      * Get the Default Page for the website specified by request.
413      *
414      * @param rreq
415      * @return PageData
416      */

417     private PageData getDefaultPage(RollerRequest rreq) throws RollerException
418     {
419         try
420         {
421             UserData ud = rreq.getUser();
422             UserManager mgr = rreq.getRoller().getUserManager();
423             WebsiteData wd = mgr.getWebsite( ud.getUserName() );
424             String JavaDoc defaultPageId = wd.getDefaultPageId();
425             return mgr.retrievePage( defaultPageId );
426         }
427         catch (Exception JavaDoc e)
428         {
429             mLogger.error("ERROR in action",e);
430             throw new RollerException( e );
431         }
432     }
433     
434     /**
435      * Loads theme into preview resource loader.
436      *
437      * @param rreq
438      * @param theme
439      * @throws RollerException
440      */

441     private void setThemePages( RollerRequest rreq, String JavaDoc theme )
442        throws RollerException
443     {
444         RollerContext rollerContext =
445            RollerContext.getRollerContext(rreq.getRequest());
446            
447         try
448         {
449             UserData ud = rreq.getUser();
450             UserManager mgr = rreq.getRoller().getUserManager();
451             String JavaDoc username = ud.getUserName();
452         
453             HashMap JavaDoc pages = rollerContext.readThemeMacros(theme);
454             Iterator JavaDoc iter = pages.keySet().iterator();
455             while ( iter.hasNext() )
456             {
457                 String JavaDoc pageName = (String JavaDoc) iter.next();
458                 String JavaDoc sb = (String JavaDoc)pages.get( pageName );
459     
460                 PageData page = mgr.getPageByName( rreq.getWebsite(), pageName );
461                 if (page != null)
462                 {
463                     PreviewResourceLoader.setTemplate(page.getId(),sb,username);
464                 }
465                 else
466                 {
467                     PreviewResourceLoader.setTemplate(pageName, sb, username);
468                 }
469             }
470         }
471         catch (Exception JavaDoc e)
472         {
473             mLogger.error("ERROR in action",e);
474             throw new RollerException( e );
475         }
476         
477     }
478     
479     /**
480      * Clears users preview theme from the preview resource loader.
481      *
482      * @param rreq
483      * @param theme
484      * @throws RollerException
485      */

486     private void clearThemePages( RollerRequest rreq, String JavaDoc theme )
487        throws RollerException
488     {
489         if (mLogger.isDebugEnabled())
490         {
491             mLogger.debug("theme="+theme);
492         }
493         
494         if (theme == null) return;
495         
496         RollerContext rollerContext =
497            RollerContext.getRollerContext(rreq.getRequest());
498            
499         try
500         {
501             UserData ud = rreq.getUser();
502             UserManager mgr = rreq.getRoller().getUserManager();
503             String JavaDoc username = ud.getUserName();
504         
505             String JavaDoc themeDir = rollerContext.getThemePath(theme);
506             String JavaDoc[] children = RollerContext.getThemeFilenames(themeDir);
507             
508             // Custom theme won't have any files
509
if (children == null) return;
510                     
511             for (int i = 0; i < children.length; i++)
512             {
513                 String JavaDoc pageName = children[i].substring(
514                     0,children[i].length()-3);
515     
516                 PageData page = mgr.getPageByName(rreq.getWebsite(), pageName);
517                 if (page != null)
518                 {
519                     PreviewResourceLoader.clearTemplate( page.getId() );
520                 }
521                 else
522                 {
523                     PreviewResourceLoader.clearTemplate( pageName );
524                 }
525             }
526         }
527         catch (Exception JavaDoc e)
528         {
529             if (mLogger.isDebugEnabled())
530             {
531                 mLogger.debug("clearThemePages error: ", e);
532             }
533             
534             throw new RollerException( e );
535         }
536         
537     }
538     
539     /**
540      * Reads theme pages from disk and saves them as pages in website of
541      * the user specified by the RollerRequest.
542      *
543      * @param rreq Request wrapper.
544      * @param theme Name of theme to save.
545      * @throws RollerException
546      */

547     private void saveThemePages( RollerRequest rreq, String JavaDoc theme )
548        throws RollerException
549     {
550         RollerContext rollerContext =
551            RollerContext.getRollerContext(rreq.getRequest());
552            
553         try
554         {
555             UserData ud = rreq.getUser();
556             UserManager mgr = rreq.getRoller().getUserManager();
557             String JavaDoc username = ud.getUserName();
558             WebsiteData website = mgr.getWebsite( username );
559         
560             HashMap JavaDoc pages = rollerContext.readThemeMacros(theme);
561             Iterator JavaDoc iter = pages.keySet().iterator();
562             while ( iter.hasNext() )
563             {
564                 String JavaDoc pageName = (String JavaDoc) iter.next();
565                 String JavaDoc pageContent = (String JavaDoc)pages.get( pageName );
566     
567                 PageData page = mgr.getPageByName( rreq.getWebsite(), pageName );
568                 if (page != null)
569                 {
570                     // User already has page by that name, so overwrite it.
571
page.setTemplate( pageContent );
572                 }
573                 else
574                 {
575                     // User does not have page by that name, so create new page.
576
page = new PageData( null,
577                         website, // website
578
pageName, // name
579
pageName, // description
580
pageName, // link
581
pageContent, // template
582
new Date JavaDoc() // updateTime
583
);
584                     mgr.storePage( page );
585                 }
586             }
587             rreq.getRoller().commit();
588         }
589         catch (Exception JavaDoc e)
590         {
591             mLogger.error("ERROR in action",e);
592             throw new RollerException( e );
593         }
594         
595     }
596     
597     /**
598      * Read the 'Weblog.vm' file for a theme and return it as a String.
599      *
600      * @param ctx Roller context.
601      * @param theme Name of theme.
602      * @return Theme in the form of a string.
603      * @throws RollerException
604      */

605     public String JavaDoc readTheme(RollerContext ctx, String JavaDoc theme)
606         throws RollerException
607     {
608         String JavaDoc fileName = "Weblog.vm";
609         if (themeCache.getFromCache(theme, fileName) != null)
610         {
611             return themeCache.getFromCache(theme, fileName);
612         }
613         
614         String JavaDoc themesDir = RollerRuntimeConfig.getProperty("users.themes.path");
615         
616         String JavaDoc themeFile = RollerContext.getServletContext(
617             ).getRealPath( "/" + themesDir
618             + "/" + theme + "/" + fileName );
619                         
620         // Import weblog page template from specified theme
621
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
622         BufferedReader JavaDoc rdr = null;
623         try
624         {
625             rdr = new BufferedReader JavaDoc(
626                                     new FileReader JavaDoc(themeFile));
627             String JavaDoc line = null;
628             while ( null != (line = rdr.readLine()) )
629             {
630                 sb.append( line );
631                 sb.append("\n");
632             }
633             themeCache.putIntoCache(theme, fileName, sb.toString());
634         }
635         catch (Exception JavaDoc e)
636         {
637             mLogger.error("themeFile:" + themeFile, e);
638             throw new RollerException( e );
639         }
640         finally
641         {
642             try {
643                 if (rdr != null) rdr.close();
644             } catch (IOException JavaDoc ioe) {
645                 mLogger.warn("unable to close " + themeFile);
646             }
647         }
648         
649         return sb.toString();
650     }
651 }
652
Popular Tags