KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > roller > presentation > RollerContext


1 package org.roller.presentation;
2
3 import java.io.BufferedReader JavaDoc;
4 import java.io.File JavaDoc;
5 import java.io.FileNotFoundException JavaDoc;
6 import java.io.FileReader JavaDoc;
7 import java.io.FilenameFilter JavaDoc;
8 import java.io.IOException JavaDoc;
9 import java.io.InputStream JavaDoc;
10 import java.net.MalformedURLException JavaDoc;
11 import java.net.URL JavaDoc;
12 import java.sql.Connection JavaDoc;
13 import java.sql.SQLException JavaDoc;
14 import java.util.HashMap JavaDoc;
15 import java.util.Properties JavaDoc;
16 import java.util.TimerTask JavaDoc;
17
18 import javax.naming.InitialContext JavaDoc;
19 import javax.naming.NamingException JavaDoc;
20 import javax.servlet.ServletContext JavaDoc;
21 import javax.servlet.ServletContextEvent JavaDoc;
22 import javax.servlet.ServletContextListener JavaDoc;
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpSessionEvent JavaDoc;
25 import javax.sql.DataSource JavaDoc;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29 import org.apache.struts.util.RequestUtils;
30 import org.roller.RollerException;
31 import org.roller.config.RollerConfig;
32 import org.roller.model.RefererManager;
33 import org.roller.model.Roller;
34 import org.roller.model.RollerFactory;
35 import org.roller.model.RollerSpellCheck;
36 import org.roller.model.ScheduledTask;
37 import org.roller.pojos.UserData;
38 import org.roller.pojos.WeblogEntryData;
39 import org.roller.presentation.velocity.CommentAuthenticator;
40 import org.roller.presentation.velocity.ContextLoader;
41 import org.roller.presentation.velocity.DefaultCommentAuthenticator;
42 import org.roller.presentation.website.ThemeCache;
43 import org.roller.presentation.pings.PingQueueTask;
44 import org.roller.util.DateUtil;
45 import org.roller.util.StringUtils;
46 import org.roller.util.Utilities;
47
48 import EDU.oswego.cs.dl.util.concurrent.SynchronizedInt;
49 import org.roller.config.RollerRuntimeConfig;
50 import org.roller.config.PingConfig;
51
52 //////////////////////////////////////////////////////////////////////////////
53
/**
54  * Responds to app init/destroy events and holds Roller instance.
55  * @web.listener
56  */

57 public class RollerContext implements ServletContextListener JavaDoc
58 {
59     private static Log mLogger =
60         LogFactory.getFactory().getInstance(RollerContext.class);
61
62     private String JavaDoc mVersion = null;
63     private String JavaDoc mBuildTime = null;
64     private String JavaDoc mBuildUser = null;
65
66     public static final String JavaDoc ROLLER_KEY = "session.roller";
67     public static final String JavaDoc ROLLER_CONTEXT = "roller.context";
68     public static final String JavaDoc USER_RESOURCES = "/resources";
69     public static final String JavaDoc VERSION_KEY = "org.roller.version";
70     public static final String JavaDoc MEMDEBUG_KEY = "org.roller.memdebug";
71     public static final String JavaDoc INDEX_MGR_KEY = "org.roller.indexMgr";
72     public static final String JavaDoc HTTP_PORT = "http_port";
73     public static final String JavaDoc HTTPS_PORT = "https_port";
74     public static final String JavaDoc HTTPS_HEADER_NAME = "https_header_name";
75     public static final String JavaDoc HTTPS_HEADER_VALUE = "https_header_value";
76     private static final String JavaDoc HOURLY_TASK_KEY = "roller.hourly.tasks";
77     private static final String JavaDoc DAILY_TASK_KEY = "roller.daily.tasks";
78     
79     private static final String JavaDoc ROLLER_IMPL_KEY
80         = "org.roller.persistence";
81     
82     private static final String JavaDoc ROLLER_COMMENT_AUTH_KEY
83         = "org.roller.commentAuthenticatorClass";
84
85     private static ServletContext JavaDoc mContext = null;
86     private static Authenticator mAuthenticator = null;
87     private static CommentAuthenticator mCommentAuthenticator = null;
88     private final SynchronizedInt mSessionCount = new SynchronizedInt(0);
89     private boolean mMemDebug = false;
90
91     /**
92      * Constructor for RollerContext.
93      */

94     public RollerContext()
95     {
96         super();
97         Properties JavaDoc props = new Properties JavaDoc();
98         try
99         {
100             props.load(getClass().getResourceAsStream("/version.properties"));
101         }
102         catch (IOException JavaDoc e)
103         {
104             mLogger.error("version.properties not found", e);
105         }
106         mVersion = props.getProperty("ro.version", "UNKNOWN");
107         mBuildTime = props.getProperty("ro.buildTime", "UNKNOWN");
108         mBuildUser = props.getProperty("ro.buildUser", "UNKNOWN");
109     }
110
111     //-----------------------------------------------------------------------
112
/* Returns Roller instance for specified app */
113     public static RollerContext getRollerContext(ServletContext JavaDoc sc)
114     {
115         // get roller from servlet context
116
return (RollerContext) sc.getAttribute(ROLLER_CONTEXT);
117     }
118
119     //-----------------------------------------------------------------------
120
/* Returns Roller instance for specified app */
121     public static RollerContext getRollerContext(HttpServletRequest JavaDoc req)
122     {
123         // get roller from servlet context
124
ServletContext JavaDoc sc = RollerContext.getServletContext();
125         return (RollerContext) sc.getAttribute(ROLLER_CONTEXT);
126     }
127
128     //-----------------------------------------------------------------------
129
/** Responds to app-destroy by saving the indexManager's information */
130     public void contextDestroyed(ServletContextEvent JavaDoc sce)
131     {
132         RollerFactory.getRoller().shutdown();
133     }
134
135     //-----------------------------------------------------------------------
136
/**
137      * Responds to context initialization event by processing context
138      * paramters for easy access by the rest of the application.
139      */

140     public void contextInitialized(ServletContextEvent JavaDoc sce)
141     {
142         if (mLogger.isDebugEnabled())
143         {
144             mLogger.debug("RollerContext initializing");
145         }
146
147         // Save context in self and self in context
148
mContext = sce.getServletContext();
149         mContext.setAttribute(ROLLER_CONTEXT, this);
150
151         try
152         {
153             // get the *real* path to <context>/resources
154
String JavaDoc ctxPath = mContext.getRealPath("/");
155             if(!ctxPath.endsWith(File.separator))
156                 ctxPath += File.separator + "resources";
157             else
158                 ctxPath += "resources";
159             
160             // try setting the uploads path to <context>/resources
161
// NOTE: this should go away at some point
162
// we leave it here for now to allow users to keep writing
163
// uploads into their webapp context, but this is a bad idea
164
//
165
// also, the RollerConfig.setUploadsDir() method is smart
166
// enough to disregard this call unless the uploads.path
167
// is set to ${webapp.context}
168
RollerConfig.setUploadsDir(ctxPath);
169             
170             
171             Roller roller = RollerFactory.getRoller();
172             
173             roller.begin(UserData.SYSTEM_USER);
174             
175             //setupRollerConfig();
176
setupRollerProperties();
177             upgradeDatabaseIfNeeded();
178             setupSpellChecker();
179             setupPagePlugins();
180             setupIndexManager(roller);
181             setupRefererManager(roller);
182             initializePingFeatures(roller);
183             setupPingQueueTask(roller);
184             setupScheduledTasks(mContext, roller);
185             
186             roller.commit();
187             roller.release();
188             
189             String JavaDoc flag = RollerConfig.getProperty("debug.memory.enabled");
190             if (flag != null && !flag.equalsIgnoreCase("false"))
191             {
192                 mMemDebug = true;
193             }
194
195             if (mLogger.isDebugEnabled())
196             {
197                 mLogger.debug("RollerContext initialization complete");
198             }
199         }
200         catch (Throwable JavaDoc t)
201         {
202             mLogger.fatal("RollerContext initialization failed", t);
203         }
204     }
205
206     
207     private void setupRollerProperties() throws RollerException
208     {
209         // init property manager by creating it
210
Roller mRoller = RollerFactory.getRoller();
211         mRoller.getPropertiesManager();
212     }
213
214     /** Setup daily and hourly tasks specified in web.xml */
215     private void setupScheduledTasks(ServletContext JavaDoc context, Roller roller)
216         throws RollerException, InstantiationException JavaDoc,
217                IllegalAccessException JavaDoc, ClassNotFoundException JavaDoc
218     {
219         // setup the hourly tasks
220
String JavaDoc hourlyString = RollerConfig.getProperty("tasks.hourly");
221         if (hourlyString != null && hourlyString.trim().length() > 0)
222         {
223             String JavaDoc[] hourlyTasks = StringUtils.stripAll(
224                     StringUtils.split(hourlyString, ",") );
225             for (int i=0; i<hourlyTasks.length; i++)
226             {
227                 mLogger.info("Setting hourly task: "+hourlyTasks[i]);
228                 ScheduledTask task =
229                     (ScheduledTask)Class.forName(hourlyTasks[i]).newInstance();
230                 task.init(roller, mContext.getRealPath("/"));
231                 roller.getThreadManager().scheduleHourlyTimerTask((TimerTask JavaDoc)task);
232             }
233         }
234         
235         // setup the daily tasks
236
String JavaDoc dailyString = RollerConfig.getProperty("tasks.daily");
237         if (dailyString != null && dailyString.trim().length() > 0)
238         {
239             String JavaDoc[] dailyTasks = StringUtils.stripAll(
240                     StringUtils.split(dailyString, ",") );
241             for (int j=0; j<dailyTasks.length; j++)
242             {
243                 mLogger.info("Setting daily task: "+dailyTasks[j]);
244                 ScheduledTask task =
245                     (ScheduledTask)Class.forName(dailyTasks[j]).newInstance();
246                 task.init(roller, mContext.getRealPath("/"));
247                 roller.getThreadManager().scheduleDailyTimerTask((TimerTask JavaDoc)task);
248             }
249         }
250     }
251
252     // Initialize ping features
253
private void initializePingFeatures(Roller roller) throws RollerException {
254         // Initialize common targets from the configuration
255
PingConfig.initializeCommonTargets();
256         // Remove csutom ping targets if they have been disallowed
257
if (PingConfig.getDisallowCustomTargets()) {
258             mLogger.info("Custom ping targets have been disallowed. Removing any existing custom targets.");
259             roller.getPingTargetManager().removeAllCustomPingTargets();
260         }
261         // Remove all autoping configurations if ping usage has been disabled.
262
if (PingConfig.getDisablePingUsage()) {
263             mLogger.info("Ping usage has been disabled. Removing any existing auto ping configurations.");
264             roller.getAutopingManager().removeAllAutoPings();
265         }
266     }
267
268
269     // Set up the ping queue processing task
270
private void setupPingQueueTask(Roller roller) throws RollerException
271     {
272         long intervalMins = PingConfig.getQueueProcessingIntervalMins();
273         if (intervalMins == 0) {
274             // Ping queue processing interval of 0 indicates that ping queue processing is disabled on this host.
275
// This provides a crude way to disable running the ping queue task on some servers if there are
276
// multiple servers in a cluster sharing a db. Exclusion should really be handled dynamically but isn't.
277
mLogger.warn("Ping queue processing interval is zero; processing from the ping queue will be disabled on this server.");
278             mLogger.warn("Please make sure that ping queue processing is configured to run on one server in the cluster.");
279             return;
280         }
281
282         // Set up the task
283
PingQueueTask pingQueueTask = new PingQueueTask();
284         pingQueueTask.init(this, intervalMins);
285
286         // Schedule it at the appropriate interval, delay start for one interval.
287
mLogger.info("Scheduling ping queue task to run at " + intervalMins + " minute intervals.");
288         roller.getThreadManager().scheduleFixedRateTimerTask(pingQueueTask, intervalMins, intervalMins);
289     }
290
291     protected void upgradeDatabaseIfNeeded() throws RollerException
292     {
293         try
294         {
295             InitialContext JavaDoc ic = new InitialContext JavaDoc();
296             DataSource JavaDoc ds = (DataSource JavaDoc)ic.lookup("java:comp/env/jdbc/rollerdb");
297             Connection JavaDoc con = ds.getConnection();
298             RollerFactory.getRoller().upgradeDatabase(con);
299             con.close();
300         }
301         catch (NamingException JavaDoc e)
302         {
303             mLogger.warn("Unable to access DataSource", e);
304         }
305         catch (SQLException JavaDoc e)
306         {
307             mLogger.warn(e);
308         }
309     }
310
311     //------------------------------------------------------------------------
312
/**
313      * Initialize the configured PagePlugins
314      * @param mContext
315      */

316     private void setupPagePlugins()
317     {
318         if (mLogger.isDebugEnabled())
319         {
320             mLogger.debug("Initialize PagePlugins");
321         }
322         ContextLoader.initializePagePlugins(mContext);
323
324     }
325
326     /**
327      * Add TurnoverReferersTask to run on a schedule.
328      */

329     private void setupRefererManager(Roller roller)
330     {
331         try
332         {
333             // Check for turnover when we first start
334
final RefererManager refManager = roller.getRefererManager();
335             refManager.checkForTurnover(false, null);
336
337             // Schedule a check every day, starting at end of today
338
//TurnoverReferersTask task = new TurnoverReferersTask();
339
//task.init(roller, mContext.getRealPath("/"));
340
//roller.getThreadManager().scheduleDailyTimerTask(task);
341
}
342         catch (RollerException e)
343         {
344             mLogger.warn("Couldn't schedule referer turnover task", e);
345         }
346     }
347
348     //------------------------------------------------------------------------
349

350     private void setupIndexManager(Roller roller) throws RollerException
351     {
352         roller.getIndexManager();
353     }
354
355     public void sessionCreated(HttpSessionEvent JavaDoc se)
356     {
357         if (mMemDebug)
358         {
359             mSessionCount.increment();
360             mContext.log(
361                 "Roller:SESSION_CREATED:count="
362                     + mSessionCount
363                     + ":freemem="
364                     + Runtime.getRuntime().freeMemory()
365                     + ":totmem="
366                     + Runtime.getRuntime().totalMemory());
367         }
368     }
369
370     //------------------------------------------------------------------------
371

372     public void sessionDestroyed(HttpSessionEvent JavaDoc se)
373     {
374         if (mMemDebug)
375         {
376             mSessionCount.decrement();
377             mContext.log(
378                 "Roller:SESSION_DESTROY:count="
379                     + mSessionCount
380                     + ":freemem="
381                     + Runtime.getRuntime().freeMemory()
382                     + ":totalmem="
383                     + Runtime.getRuntime().totalMemory());
384         }
385     }
386
387     //------------------------------------------------------------------------
388

389     /**
390      * Get an instance of Roller from the RollerFactory.
391      * If one does not exist, tell Factory to create new one.
392      */

393     public static Roller getRoller(HttpServletRequest JavaDoc req)
394     {
395         return RollerFactory.getRoller();
396     }
397
398     //------------------------------------------------------------------------
399

400     /**
401      * Get authenticator
402      */

403     public Authenticator getAuthenticator()
404     {
405         if (mAuthenticator == null)
406         {
407             try
408             {
409                 Class JavaDoc authClass =
410                     Class.forName(RollerConfig.getProperty("authenticator.classname"));
411                 mAuthenticator = (Authenticator) authClass.newInstance();
412             }
413             catch (Exception JavaDoc e)
414             {
415                 // this isn't an ERROR if no authenticatorClass was specified
416
if (!(e instanceof NullPointerException JavaDoc))
417                 {
418                     mLogger.error("ERROR creating authenticator, using default", e);
419                 }
420                 else
421                 {
422                     mLogger.debug("No authenticator specified, using DefaultAuthenticator");
423                 }
424                 mAuthenticator = new DefaultAuthenticator();
425             }
426         }
427         return mAuthenticator;
428     }
429
430     //-----------------------------------------------------------------------
431
/**
432      * Returns RollerConfig object. Changed so that it always tries
433      * to fetch from the database first. If it should error, return
434      * the stored copy.
435      */

436     /* not available anymore ... use the new config classes instead -- Allen G
437     public RollerConfigData getRollerConfig()
438     {
439         if (mConfig == null)
440         {
441             try
442             {
443                     mConfig = getRoller(null).getConfigManager().getRollerConfig();
444                 }
445             catch (RollerException e)
446             {
447                 mLogger.error("Unable to get RollerConfig from database");
448                 }
449         }
450         return mConfig;
451     }
452     */

453
454     //-----------------------------------------------------------------------
455
/**
456      * Gets the hard-drive location of the upload directory.
457      */

458     public static String JavaDoc getUploadDir(ServletContext JavaDoc app)
459     {
460         // ACK ... this really isn't the right place for this lookup!!
461
String JavaDoc uploaddir = null;
462         try
463         {
464             uploaddir = RollerFactory.getRoller().getFileManager().getUploadDir();
465         }
466         catch(Exception JavaDoc e) {}
467         
468         return uploaddir;
469     }
470
471     //-----------------------------------------------------------------------
472
/**
473      * Gets the base url for the upload directory.
474      */

475     public static String JavaDoc getUploadPath(ServletContext JavaDoc app)
476     {
477         // ACK ... why do this here??
478
String JavaDoc uploadurl = null;
479         try {
480             uploadurl = RollerFactory.getRoller().getFileManager().getUploadUrl();
481         } catch(Exception JavaDoc e) {}
482         
483         return uploadurl;
484     }
485
486     //-----------------------------------------------------------------------
487
/**
488      * Read Roller configuration parameters from roller-config.xml.
489      */

490     /* no longer needed now that we have a new config system -- Allen G.
491     private void setupRollerConfig() throws RollerException
492     {
493         mConfig = getRoller(null).getConfigManager().getRollerConfig();
494         if (mConfig == null)
495         {
496             // No entry in the rollerconfig table means that we are upgading to
497             // Roller 0.9.9. To upgrade, we need to read the values from the
498             // existing roller-config.xml and write them to the rollerconfig table.
499             String configPath = getConfigPath();
500             mConfig = getRoller(null).getConfigManager().readFromFile(configPath);
501             
502             // Roller 0.9.9 uses roles for security, so create an admin role for
503             // each of the admin users listed in the roller-config.xml file.
504             String adminUsers[] = mConfig.adminUsersArray();
505             for (int i=0; i<adminUsers.length; i++)
506             {
507                 UserData user =
508                     getRoller(null).getUserManager().getUser(adminUsers[i]);
509                 if (user != null)
510                 {
511                     RoleData role = new RoleData(null, user, "admin");
512                     role.save();
513                 }
514             }
515             
516             // By setting the database version to null here, we ensure that the
517             // rest of the database tables will be upgraded to 0.9.9.
518             mConfig.setDatabaseVersion(null);
519             
520             saveRollerConfig(mConfig);
521         }
522     }
523     */

524     
525     //-----------------------------------------------------------------------
526
/* Unused method ... this is the wrong place for this anyways -- Allen G.
527     public void saveRollerConfig(RollerConfigData rConfig) throws RollerException
528     {
529         mConfig = rConfig;
530         
531         // save database copy
532         //getRoller(null).begin(); // begin already called by RequestFilter
533         getRoller(null).getConfigManager().storeRollerConfig(rConfig);
534         getRoller(null).commit();
535         
536         // save file copy
537         OldRollerConfig rConfigFile = new OldRollerConfig(rConfig);
538         rConfigFile.writeConfig(getConfigPath());
539     }
540     */

541     
542     //-----------------------------------------------------------------------
543

544     /**
545      * Determine where we should read/write roller-config.xml to.
546      * A file in ${user.home} overrides one in WEB-INF.
547      */

548     /* Unused old method -- Allen G.
549     public String getConfigPath()
550     {
551         String configPath =
552             System.getProperty("user.home")
553                 + File.separator
554                 + "roller-config.xml";
555
556         if (mLogger.isDebugEnabled())
557         {
558             mLogger.debug(
559                 "Looking for roller-config.xml at '" + configPath + "'");
560         }
561
562         boolean configFoundInHomeDir;
563         try
564         {
565             configFoundInHomeDir = new File(configPath).exists();
566         }
567         catch (SecurityException se)
568         {
569             configFoundInHomeDir = false;
570             mLogger.info("Permission denied at '" + configPath + "'");
571         }
572         if (!configFoundInHomeDir)
573         {
574             // No config found in user.home, store it in WEB-INF instead.
575             if (mLogger.isDebugEnabled())
576             {
577                 mLogger.debug("File not found: '" + configPath);
578             }
579
580             String root = mContext.getRealPath("/");
581             configPath =
582                 root
583                     + File.separator
584                     + "WEB-INF"
585                     + File.separator
586                     + "roller-config.xml";
587         }
588
589         mLogger.info("Using roller-config.xml at '" + configPath + "'");
590
591         return configPath;
592     }
593     */

594     
595     //-----------------------------------------------------------------------
596

597     /**
598      * RollerSpellCheck must be initialized with a dictionary file
599      * so that it can return valid a SpellChecker.
600      */

601     private void setupSpellChecker()
602     {
603         InputStream JavaDoc is = null;
604         try
605         {
606             is = mContext.getResourceAsStream("/WEB-INF/english.0");
607             RollerSpellCheck.init(is);
608         }
609         catch (Exception JavaDoc e)
610         {
611             mContext.log("ERROR reading dictionary file");
612         }
613         finally
614         {
615             if (is != null)
616             {
617                 try
618                 {
619                     is.close();
620                 }
621                 catch (Exception JavaDoc e)
622                 {
623                     e.printStackTrace();
624                 }
625             }
626         }
627     }
628
629     //-----------------------------------------------------------------------
630
/**
631      * Returns the full url for the website of the specified username.
632      */

633     public String JavaDoc getContextUrl(HttpServletRequest JavaDoc request, String JavaDoc username)
634     {
635         String JavaDoc url = this.getContextUrl(request);
636         if (username != null)
637         {
638             url = url + "/page/" + username;
639         }
640         return url;
641     }
642
643     //-----------------------------------------------------------------------
644
/** Get absolute URL of Roller context */
645     public String JavaDoc getContextUrl(HttpServletRequest JavaDoc request)
646     {
647         String JavaDoc url = request.getContextPath();
648         if (url.endsWith("/"))
649         {
650             url = url.substring(0, url.length() - 1);
651         }
652         return url;
653     }
654
655     //-----------------------------------------------------------------------
656
/** Get absolute URL of Roller context */
657     public String JavaDoc getAbsoluteContextUrl(HttpServletRequest JavaDoc request)
658     {
659         String JavaDoc url = RollerRuntimeConfig.getProperty("site.absoluteurl");
660         
661         if (url == null || url.trim().length() == 0)
662         {
663             try
664             {
665                 URL JavaDoc absURL = RequestUtils.absoluteURL(request, "/");
666                 url = absURL.toString();
667             }
668             catch (MalformedURLException JavaDoc e)
669             {
670                 url = "/";
671                 mLogger.error("ERROR: forming absolute URL", e);
672             }
673         }
674         if (url.endsWith("/"))
675         {
676             url = url.substring(0, url.length() - 1);
677         }
678         mContext.setAttribute("org.roller.absoluteContextURL", url);
679         return url;
680     }
681
682     //-----------------------------------------------------------------------
683

684     /**
685      * For use by MetaWeblog API.
686      * @return Context URL or null if not initialized yet.
687      */

688     public String JavaDoc getAbsoluteContextUrl()
689     {
690         return (String JavaDoc) mContext.getAttribute("org.roller.absoluteContextURL");
691     }
692
693     //-----------------------------------------------------------------------
694

695     public String JavaDoc createEntryPermalink(
696         WeblogEntryData entry,
697         HttpServletRequest JavaDoc request,
698         boolean absolute)
699     {
700         String JavaDoc link = null;
701         try
702         {
703             String JavaDoc baseUrl = null;
704             if (absolute)
705             {
706                 baseUrl = getAbsoluteContextUrl(request);
707             }
708             else
709             {
710                 baseUrl = getContextUrl(request);
711             }
712
713             String JavaDoc dayString = DateUtil.format8chars(entry.getPubTime());
714
715             UserData ud = entry.getWebsite().getUser();
716
717             link =
718                 Utilities.escapeHTML(
719                     baseUrl
720                         + "/page/"
721                         + ud.getUserName()
722                         + "?entry="
723                         + entry.getAnchor());
724         }
725         catch (Exception JavaDoc e)
726         {
727             mLogger.error("Unexpected exception", e);
728         }
729         return link;
730     }
731
732     //-----------------------------------------------------------------------
733
/**
734      * Return the real filepath to the theme.
735      *
736      * @param theme
737      * @return String
738      */

739     public String JavaDoc getThemePath(String JavaDoc theme)
740     {
741         String JavaDoc themespath = RollerRuntimeConfig.getProperty("users.themes.path");
742
743         // Figure path to new user theme
744
return mContext.getRealPath(
745             "/" + themespath + "/" + theme);
746     }
747
748     //-----------------------------------------------------------------------
749
/**
750      * Get the list of Theme names. This consists
751      * of the directories under the /themes directory.
752      *
753      * @return String[]
754      */

755     public String JavaDoc[] getThemeNames()
756     {
757         String JavaDoc themespath = RollerRuntimeConfig.getProperty("users.themes.path");
758         
759         String JavaDoc themesPath =
760             mContext.getRealPath("/" + themespath);
761         File JavaDoc themeDir = new File JavaDoc(themesPath);
762         return themeDir.list(new FilenameFilter JavaDoc()
763         {
764             public boolean accept(File JavaDoc dir, String JavaDoc name)
765             {
766                 File JavaDoc file =
767                     new File JavaDoc(dir.getAbsolutePath() + File.separator + name);
768                 return file.isDirectory();
769             }
770         });
771     }
772
773     //-----------------------------------------------------------------------
774
/**
775      * Returns the mContext.
776      * @return ServletContext
777      */

778     public static ServletContext JavaDoc getServletContext()
779     {
780         return mContext;
781     }
782
783     //-----------------------------------------------------------------------
784
/**
785      * Reads the Theme files from harddisk (if necessary) and places them into a
786      * ThemeCache. If the requested Theme's pages are already in the cache,
787      * return them instead.
788      *
789      * @param themeName
790      * @return HashMap
791      * @throws FileNotFoundException
792      * @throws IOException
793      */

794     public HashMap JavaDoc readThemeMacros(String JavaDoc themeName)
795         throws FileNotFoundException JavaDoc, IOException JavaDoc
796     {
797         if (mLogger.isDebugEnabled())
798         {
799             mLogger.debug("themeName=" + themeName);
800         }
801
802         // Load all Velocity templates from root directory of the theme
803
String JavaDoc pageName = null;
804         String JavaDoc themeDir = this.getThemePath(themeName);
805         String JavaDoc[] children = getThemeFilenames(themeDir);
806         HashMap JavaDoc pages = new HashMap JavaDoc();
807         ThemeCache themeCache = ThemeCache.getInstance();
808         for (int i = 0; i < children.length; i++)
809         {
810             pageName = children[i].substring(0, children[i].length() - 3);
811
812             if (themeCache.getFromCache(themeName, pageName) != null)
813             {
814                 pages.put(
815                     pageName,
816                     themeCache.getFromCache(themeName, pageName));
817             }
818             else
819             {
820                 BufferedReader JavaDoc rdr = null;
821                 try
822                 {
823                     rdr = new BufferedReader JavaDoc(
824                         new FileReader JavaDoc(
825                             themeDir + File.separator + children[i]));
826                     String JavaDoc line = null;
827                     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
828                     while (null != (line = rdr.readLine()))
829                     {
830                         sb.append(line);
831                         sb.append("\n");
832                     }
833     
834                     pages.put(pageName, sb.toString());
835                     themeCache.putIntoCache(themeName, pageName, sb.toString());
836                 }
837                 finally
838                 {
839                     if (rdr != null) rdr.close();
840                 }
841             }
842         }
843         return pages;
844     }
845
846     //-----------------------------------------------------------------------
847

848     public static String JavaDoc[] getThemeFilenames(String JavaDoc themeDir)
849     {
850         ThemeCache themeCache = ThemeCache.getInstance();
851         if (themeCache.getFileList(themeDir) != null)
852         {
853             return themeCache.getFileList(themeDir);
854         }
855
856         File JavaDoc dir = new File JavaDoc(themeDir);
857         FilenameFilter JavaDoc filter = new FilenameFilter JavaDoc()
858         {
859             public boolean accept(File JavaDoc dir, String JavaDoc name)
860             {
861                 return name.endsWith(".vm");
862             }
863         };
864         String JavaDoc[] children = dir.list(filter);
865         themeCache.setFileList(themeDir, children);
866         return children;
867     }
868
869     //-----------------------------------------------------------------------
870

871     /** Roller version */
872     public String JavaDoc getRollerVersion()
873     {
874         return mVersion;
875     }
876
877     //-----------------------------------------------------------------------
878

879     /** Roller build time */
880     public String JavaDoc getRollerBuildTime()
881     {
882         return mBuildTime;
883     }
884
885     //-----------------------------------------------------------------------
886

887     /** Get username that built Roller */
888     public String JavaDoc getRollerBuildUser()
889     {
890         return mBuildUser;
891     }
892
893     //-----------------------------------------------------------------------
894

895     public static CommentAuthenticator getCommentAuthenticator()
896     {
897         if (mCommentAuthenticator == null)
898         {
899             String JavaDoc name = RollerConfig.getProperty("comment.authenticator.classname");
900             try
901             {
902                 Class JavaDoc clazz = Class.forName(name);
903                 mCommentAuthenticator=(CommentAuthenticator)clazz.newInstance();
904             }
905             catch (Exception JavaDoc e)
906             {
907                 mLogger.error(e);
908                 mCommentAuthenticator = new DefaultCommentAuthenticator();
909             }
910         }
911         return mCommentAuthenticator;
912     }
913 }
914
Popular Tags