1 package org.roller.presentation; 2 3 import java.io.BufferedReader ; 4 import java.io.File ; 5 import java.io.FileNotFoundException ; 6 import java.io.FileReader ; 7 import java.io.FilenameFilter ; 8 import java.io.IOException ; 9 import java.io.InputStream ; 10 import java.net.MalformedURLException ; 11 import java.net.URL ; 12 import java.sql.Connection ; 13 import java.sql.SQLException ; 14 import java.util.HashMap ; 15 import java.util.Properties ; 16 import java.util.TimerTask ; 17 18 import javax.naming.InitialContext ; 19 import javax.naming.NamingException ; 20 import javax.servlet.ServletContext ; 21 import javax.servlet.ServletContextEvent ; 22 import javax.servlet.ServletContextListener ; 23 import javax.servlet.http.HttpServletRequest ; 24 import javax.servlet.http.HttpSessionEvent ; 25 import javax.sql.DataSource ; 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 57 public class RollerContext implements ServletContextListener 58 { 59 private static Log mLogger = 60 LogFactory.getFactory().getInstance(RollerContext.class); 61 62 private String mVersion = null; 63 private String mBuildTime = null; 64 private String mBuildUser = null; 65 66 public static final String ROLLER_KEY = "session.roller"; 67 public static final String ROLLER_CONTEXT = "roller.context"; 68 public static final String USER_RESOURCES = "/resources"; 69 public static final String VERSION_KEY = "org.roller.version"; 70 public static final String MEMDEBUG_KEY = "org.roller.memdebug"; 71 public static final String INDEX_MGR_KEY = "org.roller.indexMgr"; 72 public static final String HTTP_PORT = "http_port"; 73 public static final String HTTPS_PORT = "https_port"; 74 public static final String HTTPS_HEADER_NAME = "https_header_name"; 75 public static final String HTTPS_HEADER_VALUE = "https_header_value"; 76 private static final String HOURLY_TASK_KEY = "roller.hourly.tasks"; 77 private static final String DAILY_TASK_KEY = "roller.daily.tasks"; 78 79 private static final String ROLLER_IMPL_KEY 80 = "org.roller.persistence"; 81 82 private static final String ROLLER_COMMENT_AUTH_KEY 83 = "org.roller.commentAuthenticatorClass"; 84 85 private static ServletContext 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 94 public RollerContext() 95 { 96 super(); 97 Properties props = new Properties (); 98 try 99 { 100 props.load(getClass().getResourceAsStream("/version.properties")); 101 } 102 catch (IOException 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 113 public static RollerContext getRollerContext(ServletContext sc) 114 { 115 return (RollerContext) sc.getAttribute(ROLLER_CONTEXT); 117 } 118 119 121 public static RollerContext getRollerContext(HttpServletRequest req) 122 { 123 ServletContext sc = RollerContext.getServletContext(); 125 return (RollerContext) sc.getAttribute(ROLLER_CONTEXT); 126 } 127 128 130 public void contextDestroyed(ServletContextEvent sce) 131 { 132 RollerFactory.getRoller().shutdown(); 133 } 134 135 140 public void contextInitialized(ServletContextEvent sce) 141 { 142 if (mLogger.isDebugEnabled()) 143 { 144 mLogger.debug("RollerContext initializing"); 145 } 146 147 mContext = sce.getServletContext(); 149 mContext.setAttribute(ROLLER_CONTEXT, this); 150 151 try 152 { 153 String ctxPath = mContext.getRealPath("/"); 155 if(!ctxPath.endsWith(File.separator)) 156 ctxPath += File.separator + "resources"; 157 else 158 ctxPath += "resources"; 159 160 RollerConfig.setUploadsDir(ctxPath); 169 170 171 Roller roller = RollerFactory.getRoller(); 172 173 roller.begin(UserData.SYSTEM_USER); 174 175 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 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 t) 201 { 202 mLogger.fatal("RollerContext initialization failed", t); 203 } 204 } 205 206 207 private void setupRollerProperties() throws RollerException 208 { 209 Roller mRoller = RollerFactory.getRoller(); 211 mRoller.getPropertiesManager(); 212 } 213 214 215 private void setupScheduledTasks(ServletContext context, Roller roller) 216 throws RollerException, InstantiationException , 217 IllegalAccessException , ClassNotFoundException 218 { 219 String hourlyString = RollerConfig.getProperty("tasks.hourly"); 221 if (hourlyString != null && hourlyString.trim().length() > 0) 222 { 223 String [] 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 )task); 232 } 233 } 234 235 String dailyString = RollerConfig.getProperty("tasks.daily"); 237 if (dailyString != null && dailyString.trim().length() > 0) 238 { 239 String [] 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 )task); 248 } 249 } 250 } 251 252 private void initializePingFeatures(Roller roller) throws RollerException { 254 PingConfig.initializeCommonTargets(); 256 if (PingConfig.getDisallowCustomTargets()) { 258 mLogger.info("Custom ping targets have been disallowed. Removing any existing custom targets."); 259 roller.getPingTargetManager().removeAllCustomPingTargets(); 260 } 261 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 private void setupPingQueueTask(Roller roller) throws RollerException 271 { 272 long intervalMins = PingConfig.getQueueProcessingIntervalMins(); 273 if (intervalMins == 0) { 274 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 PingQueueTask pingQueueTask = new PingQueueTask(); 284 pingQueueTask.init(this, intervalMins); 285 286 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 ic = new InitialContext (); 296 DataSource ds = (DataSource )ic.lookup("java:comp/env/jdbc/rollerdb"); 297 Connection con = ds.getConnection(); 298 RollerFactory.getRoller().upgradeDatabase(con); 299 con.close(); 300 } 301 catch (NamingException e) 302 { 303 mLogger.warn("Unable to access DataSource", e); 304 } 305 catch (SQLException e) 306 { 307 mLogger.warn(e); 308 } 309 } 310 311 316 private void setupPagePlugins() 317 { 318 if (mLogger.isDebugEnabled()) 319 { 320 mLogger.debug("Initialize PagePlugins"); 321 } 322 ContextLoader.initializePagePlugins(mContext); 323 324 } 325 326 329 private void setupRefererManager(Roller roller) 330 { 331 try 332 { 333 final RefererManager refManager = roller.getRefererManager(); 335 refManager.checkForTurnover(false, null); 336 337 } 342 catch (RollerException e) 343 { 344 mLogger.warn("Couldn't schedule referer turnover task", e); 345 } 346 } 347 348 350 private void setupIndexManager(Roller roller) throws RollerException 351 { 352 roller.getIndexManager(); 353 } 354 355 public void sessionCreated(HttpSessionEvent 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 372 public void sessionDestroyed(HttpSessionEvent 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 389 393 public static Roller getRoller(HttpServletRequest req) 394 { 395 return RollerFactory.getRoller(); 396 } 397 398 400 403 public Authenticator getAuthenticator() 404 { 405 if (mAuthenticator == null) 406 { 407 try 408 { 409 Class authClass = 410 Class.forName(RollerConfig.getProperty("authenticator.classname")); 411 mAuthenticator = (Authenticator) authClass.newInstance(); 412 } 413 catch (Exception e) 414 { 415 if (!(e instanceof NullPointerException )) 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 436 453 454 458 public static String getUploadDir(ServletContext app) 459 { 460 String uploaddir = null; 462 try 463 { 464 uploaddir = RollerFactory.getRoller().getFileManager().getUploadDir(); 465 } 466 catch(Exception e) {} 467 468 return uploaddir; 469 } 470 471 475 public static String getUploadPath(ServletContext app) 476 { 477 String uploadurl = null; 479 try { 480 uploadurl = RollerFactory.getRoller().getFileManager().getUploadUrl(); 481 } catch(Exception e) {} 482 483 return uploadurl; 484 } 485 486 490 524 525 541 542 544 548 594 595 597 601 private void setupSpellChecker() 602 { 603 InputStream is = null; 604 try 605 { 606 is = mContext.getResourceAsStream("/WEB-INF/english.0"); 607 RollerSpellCheck.init(is); 608 } 609 catch (Exception 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 e) 622 { 623 e.printStackTrace(); 624 } 625 } 626 } 627 } 628 629 633 public String getContextUrl(HttpServletRequest request, String username) 634 { 635 String url = this.getContextUrl(request); 636 if (username != null) 637 { 638 url = url + "/page/" + username; 639 } 640 return url; 641 } 642 643 645 public String getContextUrl(HttpServletRequest request) 646 { 647 String url = request.getContextPath(); 648 if (url.endsWith("/")) 649 { 650 url = url.substring(0, url.length() - 1); 651 } 652 return url; 653 } 654 655 657 public String getAbsoluteContextUrl(HttpServletRequest request) 658 { 659 String url = RollerRuntimeConfig.getProperty("site.absoluteurl"); 660 661 if (url == null || url.trim().length() == 0) 662 { 663 try 664 { 665 URL absURL = RequestUtils.absoluteURL(request, "/"); 666 url = absURL.toString(); 667 } 668 catch (MalformedURLException 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 684 688 public String getAbsoluteContextUrl() 689 { 690 return (String ) mContext.getAttribute("org.roller.absoluteContextURL"); 691 } 692 693 695 public String createEntryPermalink( 696 WeblogEntryData entry, 697 HttpServletRequest request, 698 boolean absolute) 699 { 700 String link = null; 701 try 702 { 703 String baseUrl = null; 704 if (absolute) 705 { 706 baseUrl = getAbsoluteContextUrl(request); 707 } 708 else 709 { 710 baseUrl = getContextUrl(request); 711 } 712 713 String 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 e) 726 { 727 mLogger.error("Unexpected exception", e); 728 } 729 return link; 730 } 731 732 739 public String getThemePath(String theme) 740 { 741 String themespath = RollerRuntimeConfig.getProperty("users.themes.path"); 742 743 return mContext.getRealPath( 745 "/" + themespath + "/" + theme); 746 } 747 748 755 public String [] getThemeNames() 756 { 757 String themespath = RollerRuntimeConfig.getProperty("users.themes.path"); 758 759 String themesPath = 760 mContext.getRealPath("/" + themespath); 761 File themeDir = new File (themesPath); 762 return themeDir.list(new FilenameFilter () 763 { 764 public boolean accept(File dir, String name) 765 { 766 File file = 767 new File (dir.getAbsolutePath() + File.separator + name); 768 return file.isDirectory(); 769 } 770 }); 771 } 772 773 778 public static ServletContext getServletContext() 779 { 780 return mContext; 781 } 782 783 794 public HashMap readThemeMacros(String themeName) 795 throws FileNotFoundException , IOException 796 { 797 if (mLogger.isDebugEnabled()) 798 { 799 mLogger.debug("themeName=" + themeName); 800 } 801 802 String pageName = null; 804 String themeDir = this.getThemePath(themeName); 805 String [] children = getThemeFilenames(themeDir); 806 HashMap pages = new HashMap (); 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 rdr = null; 821 try 822 { 823 rdr = new BufferedReader ( 824 new FileReader ( 825 themeDir + File.separator + children[i])); 826 String line = null; 827 StringBuffer sb = new StringBuffer (); 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 848 public static String [] getThemeFilenames(String themeDir) 849 { 850 ThemeCache themeCache = ThemeCache.getInstance(); 851 if (themeCache.getFileList(themeDir) != null) 852 { 853 return themeCache.getFileList(themeDir); 854 } 855 856 File dir = new File (themeDir); 857 FilenameFilter filter = new FilenameFilter () 858 { 859 public boolean accept(File dir, String name) 860 { 861 return name.endsWith(".vm"); 862 } 863 }; 864 String [] children = dir.list(filter); 865 themeCache.setFileList(themeDir, children); 866 return children; 867 } 868 869 871 872 public String getRollerVersion() 873 { 874 return mVersion; 875 } 876 877 879 880 public String getRollerBuildTime() 881 { 882 return mBuildTime; 883 } 884 885 887 888 public String getRollerBuildUser() 889 { 890 return mBuildUser; 891 } 892 893 895 public static CommentAuthenticator getCommentAuthenticator() 896 { 897 if (mCommentAuthenticator == null) 898 { 899 String name = RollerConfig.getProperty("comment.authenticator.classname"); 900 try 901 { 902 Class clazz = Class.forName(name); 903 mCommentAuthenticator=(CommentAuthenticator)clazz.newInstance(); 904 } 905 catch (Exception e) 906 { 907 mLogger.error(e); 908 mCommentAuthenticator = new DefaultCommentAuthenticator(); 909 } 910 } 911 return mCommentAuthenticator; 912 } 913 } 914 | Popular Tags |