You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@roller.apache.org by sn...@apache.org on 2005/06/08 18:06:46 UTC
svn commit: r189602 [17/50] - in /incubator/roller/trunk: ./ contrib/
contrib/lib/ contrib/plugins/ contrib/plugins/src/ contrib/plugins/src/org/
contrib/plugins/src/org/roller/ contrib/plugins/src/org/roller/presentation/
contrib/plugins/src/org/roller/presentation/velocity/
contrib/plugins/src/org/roller/presentation/velocity/plugins/
contrib/plugins/src/org/roller/presentation/velocity/plugins/acronyms/
contrib/plugins/src/org/roller/presentation/velocity/plugins/bookmarks/
contrib/plugins/src/org/roller/presentation/velocity/plugins/email/
contrib/plugins/src/org/roller/presentation/velocity/plugins/jspwiki/
contrib/plugins/src/org/roller/presentation/velocity/plugins/radeox/
contrib/plugins/src/org/roller/presentation/velocity/plugins/readmore/
contrib/plugins/src/org/roller/presentation/velocity/plugins/smileys/
contrib/plugins/src/org/roller/presentation/velocity/plugins/textile/ docs/
docs/images/ docs/installguide/ docs/installguide/old/ docs/userguide/
docs/userguide/images/ docs/userguide/old/ metadata/ metadata/database/
metadata/database/hibernate/ metadata/xdoclet/ personal/ personal/eclipse/
personal/testing/ src/ src/org/ src/org/roller/ src/org/roller/business/
src/org/roller/business/hibernate/ src/org/roller/business/utils/
src/org/roller/model/ src/org/roller/pojos/ src/org/roller/presentation/
src/org/roller/presentation/atom/ src/org/roller/presentation/bookmarks/
src/org/roller/presentation/bookmarks/actions/
src/org/roller/presentation/bookmarks/formbeans/
src/org/roller/presentation/bookmarks/tags/
src/org/roller/presentation/filters/ src/org/roller/presentation/forms/
src/org/roller/presentation/newsfeeds/ src/org/roller/presentation/pagecache/
src/org/roller/presentation/pagecache/rollercache/
src/org/roller/presentation/tags/ src/org/roller/presentation/tags/calendar/
src/org/roller/presentation/tags/menu/
src/org/roller/presentation/velocity/ src/org/roller/presentation/weblog/
src/org/roller/presentation/weblog/actions/
src/org/roller/presentation/weblog/formbeans/
src/org/roller/presentation/weblog/search/
src/org/roller/presentation/weblog/search/operations/
src/org/roller/presentation/weblog/tags/ src/org/roller/presentation/website/
src/org/roller/presentation/website/actions/
src/org/roller/presentation/website/formbeans/
src/org/roller/presentation/website/tags/
src/org/roller/presentation/xmlrpc/ src/org/roller/util/ tests/ tests/org/
tests/org/roller/ tests/org/roller/business/ tests/org/roller/model/
tests/org/roller/persistence/ tests/org/roller/presentation/
tests/org/roller/presentation/atom/ tests/org/roller/presentation/bookmarks/
tests/org/roller/presentation/velocity/
tests/org/roller/presentation/velocity/plugins/
tests/org/roller/presentation/velocity/plugins/smileys/
tests/org/roller/presentation/velocity/plugins/textile/
tests/org/roller/presentation/xmlrpc/ tests/org/roller/util/ tools/
tools/buildtime/ tools/buildtime/mockrunner-0.2.6/
tools/buildtime/mockrunner-0.2.6/lib/ tools/buildtime/tomcat-4.1.24/
tools/buildtime/xdoclet-1.2/ tools/buildtime/xdoclet-1.2/lib/
tools/hibernate-2.1/ tools/hibernate-2.1/lib/ tools/lib/
tools/standard-1.0.3/ tools/standard-1.0.3/lib/ tools/standard-1.0.3/tld/
tools/struts-1.1/ tools/struts-1.1/lib/ web/ web/WEB-INF/
web/WEB-INF/classes/ web/WEB-INF/classes/flavors/
web/WEB-INF/classes/themes/ web/bookmarks/ web/images/ web/images/editor/
web/images/midas/ web/images/preview/ web/images/smileys/ web/tags/
web/templates/ web/theme/ web/theme/images/ web/theme/lavender/
web/theme/scripts/ web/theme/scripts/classes/ web/themes/ web/themes/basic/
web/themes/berkley/ web/themes/berkley/images/ web/themes/cheb/
web/themes/cheb/images/ web/themes/cheb/scripts/ web/themes/clean/
web/themes/currency-i18n/ web/themes/currency-i18n/images/
web/themes/currency/ web/themes/currency/images/ web/themes/grey2/
web/themes/moonshine/ web/themes/pacifica/ web/themes/robot/
web/themes/rolling/ web/themes/rolling/images/ web/themes/sotto/
web/themes/sotto/images/ web/themes/sotto/styles/ web/themes/sunsets/
web/themes/sunsets/images/ web/themes/sunsets/scripts/
web/themes/sunsets/styles/ web/themes/werner/ web/themes/x2/
web/themes/x2/images/ web/themes/x2/scripts/ web/themes/x2/styles/
web/weblog/ web/website/
Added: incubator/roller/trunk/src/org/roller/presentation/RollerContext.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/presentation/RollerContext.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/presentation/RollerContext.java (added)
+++ incubator/roller/trunk/src/org/roller/presentation/RollerContext.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,861 @@
+package org.roller.presentation;
+
+import EDU.oswego.cs.dl.util.concurrent.SynchronizedInt;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.struts.util.RequestUtils;
+import org.roller.RollerException;
+import org.roller.model.RefererManager;
+import org.roller.model.Roller;
+import org.roller.model.RollerFactory;
+import org.roller.model.RollerSpellCheck;
+import org.roller.pojos.RollerConfig;
+import org.roller.pojos.UserData;
+import org.roller.pojos.WeblogEntryData;
+import org.roller.presentation.velocity.ContextLoader;
+import org.roller.presentation.weblog.search.IndexManager;
+import org.roller.presentation.weblog.search.operations.RebuildUserIndexOperation;
+import org.roller.presentation.website.ThemeCache;
+import org.roller.util.DateUtil;
+import org.roller.util.RollerConfigFile;
+import org.roller.util.StringUtils;
+import org.roller.util.ThreadManager;
+import org.roller.util.Utilities;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Properties;
+
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.servlet.ServletContext;
+import javax.servlet.ServletContextEvent;
+import javax.servlet.ServletContextListener;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSessionEvent;
+import javax.sql.DataSource;
+
+//////////////////////////////////////////////////////////////////////////////
+/**
+ * Responds to app init/destroy events and holds Roller instance.
+ * @web.listener
+ */
+public class RollerContext implements ServletContextListener
+{
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(RollerContext.class);
+
+ private String mVersion = null;
+ private String mBuildTime = null;
+ private String mBuildUser = null;
+
+ private IndexManager mIndexManager = null;
+ private ThreadManager mThreadManager = null;
+ private static String mCastorXML = null;
+
+ public static final String ROLLER_KEY = "session.roller";
+ public static final String ROLLER_CONTEXT = "roller.context";
+ public static final String USER_RESOURCES = "/resources";
+ public static final String VERSION_KEY = "org.roller.version";
+ public static final String USER_DISPLAY_BEAN_KEY = "org.roller.users";
+ public static final String MEMDEBUG_KEY = "org.roller.memdebug";
+ public static final String INDEX_MGR_KEY = "org.roller.indexMgr";
+ private static final String ROLLER_IMPL_KEY = "org.roller.persistence";
+
+ private static ServletContext mContext = null;
+ private static Authenticator mAuthenticator = null;
+ private RollerConfig mConfig = null;
+ private final SynchronizedInt mSessionCount = new SynchronizedInt(0);
+ private boolean mMemDebug = false;
+
+ /**
+ * Constructor for RollerContext.
+ */
+ public RollerContext()
+ {
+ super();
+ Properties props = new Properties();
+ try
+ {
+ props.load(getClass().getResourceAsStream("/version.properties"));
+ }
+ catch (IOException e)
+ {
+ mLogger.error("version.properties not found", e);
+ }
+ mVersion = props.getProperty("ro.version", "UNKNOWN");
+ mBuildTime = props.getProperty("ro.buildTime", "UNKNOWN");
+ mBuildUser = props.getProperty("ro.buildUser", "UNKNOWN");
+ }
+
+ //-----------------------------------------------------------------------
+ /* Returns Roller instance for specified app */
+ public static RollerContext getRollerContext(ServletContext sc)
+ {
+ // get roller from servlet context
+ return (RollerContext) sc.getAttribute(ROLLER_CONTEXT);
+ }
+
+ //-----------------------------------------------------------------------
+ /* Returns Roller instance for specified app */
+ public static RollerContext getRollerContext(HttpServletRequest req)
+ {
+ // get roller from servlet context
+ ServletContext sc = RollerContext.getServletContext();
+ return (RollerContext) sc.getAttribute(ROLLER_CONTEXT);
+ }
+
+ //-----------------------------------------------------------------------
+ /** Responds to app-destroy by saving the indexManager's information */
+ public void contextDestroyed(ServletContextEvent sce)
+ {
+ mIndexManager.dispose();
+ mThreadManager.shutdown();
+ RollerFactory.getRoller().shutdown();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Responds to context initialization event by processing context
+ * paramters for easy access by the rest of the application.
+ */
+ public void contextInitialized(ServletContextEvent sce)
+ {
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("RollerContext initializing");
+ }
+
+ // Save context in self and self in context
+ mContext = sce.getServletContext();
+ mContext.setAttribute(ROLLER_CONTEXT, this);
+
+ try
+ {
+ mCastorXML = "";
+ String rollerImplClass = mContext.getInitParameter(ROLLER_IMPL_KEY);
+ if (rollerImplClass != null && rollerImplClass.indexOf("castor") > -1)
+ {
+ mCastorXML = mContext.getResource("/WEB-INF/database.xml").toString();
+ }
+ RollerFactory.setRoller(rollerImplClass, mCastorXML);
+
+ setupRollerConfig();
+
+ upgradeDatabaseIfNeeded();
+
+ setupSpellChecker();
+
+ setupThreadManager();
+
+ setupIndexManager();
+
+ setupPagePlugins();
+
+ setupRefererManager();
+
+ setupBlacklistUpdater();
+
+ String flag = mContext.getInitParameter(MEMDEBUG_KEY);
+ if (flag != null && !flag.equalsIgnoreCase("false"))
+ {
+ mMemDebug = true;
+ }
+
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("RollerContext initialization complete");
+ }
+ }
+ catch (Throwable t)
+ {
+ mLogger.fatal("RollerContext initialization failed", t);
+ }
+ }
+
+ private void upgradeDatabaseIfNeeded() throws RollerException
+ {
+ try
+ {
+ InitialContext ic = new InitialContext();
+ DataSource ds = (DataSource)ic.lookup("java:comp/env/jdbc/rollerdb");
+ Connection con = ds.getConnection();
+ RollerFactory.getRoller().upgradeDatabase(con);
+ con.close();
+ }
+ catch (NamingException e)
+ {
+ mLogger.warn("Unable to access DataSource", e);
+ }
+ catch (SQLException e)
+ {
+ mLogger.warn(e);
+ }
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Initialize the configured PagePlugins
+ * @param mContext
+ */
+ private void setupPagePlugins()
+ {
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("Initialize PagePlugins");
+ }
+ ContextLoader.initializePagePlugins(mContext);
+
+ }
+
+ /**
+ * Add TurnoverReferersTask to run on a schedule.
+ */
+ private void setupRefererManager()
+ {
+ try
+ {
+ final RefererManager refManager =
+ RollerFactory.getRoller().getRefererManager();
+
+ refManager.setThreadManager(mThreadManager);
+
+ // Check for turnover when we first start
+ refManager.checkForTurnover(false, null);
+
+ // Schedule a check every day, starting at end of today
+ mThreadManager.scheduleDailyTimerTask(
+ new TurnoverReferersTask(refManager));
+
+ }
+ catch (RollerException e)
+ {
+ mLogger.warn("Couldn't schedule referer turnover task", e);
+ }
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Add BlacklistUpdateTask to run on a schedule.
+ */
+ private void setupBlacklistUpdater()
+ {
+ mThreadManager.scheduleDailyTimerTask(new BlacklistUpdateTask(mConfig.getUploadDir()));
+ }
+
+ //------------------------------------------------------------------------
+
+ private void setupThreadManager()
+ {
+ mThreadManager = new ThreadManager();
+ }
+
+ private void setupIndexManager()
+ {
+ String indexDir = getRollerConfig().getIndexDir();
+
+ if (indexDir.indexOf("${user.home}") != -1)
+ {
+ indexDir =
+ StringUtils.replace(
+ indexDir,
+ "${user.home}",
+ System.getProperty("user.home"));
+ }
+
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("index dir: " + indexDir);
+ }
+
+ mIndexManager = new IndexManager(indexDir, mThreadManager);
+
+ if (mIndexManager.isInconsistentAtStartup())
+ {
+ mLogger.info(
+ "Index was inconsistent. Rebuilding index in the background...");
+ mIndexManager.scheduleIndexOperation(
+ new RebuildUserIndexOperation(null));
+ }
+
+ }
+
+ public IndexManager getIndexManager()
+ {
+ return mIndexManager;
+ }
+
+ public ThreadManager getThreadManager()
+ {
+ return mThreadManager;
+ }
+
+ public void sessionCreated(HttpSessionEvent se)
+ {
+ if (mMemDebug)
+ {
+ mSessionCount.increment();
+ mContext.log(
+ "Roller:SESSION_CREATED:count="
+ + mSessionCount
+ + ":freemem="
+ + Runtime.getRuntime().freeMemory()
+ + ":totmem="
+ + Runtime.getRuntime().totalMemory());
+ }
+ }
+
+ //------------------------------------------------------------------------
+
+ public void sessionDestroyed(HttpSessionEvent se)
+ {
+ if (mMemDebug)
+ {
+ mSessionCount.decrement();
+ mContext.log(
+ "Roller:SESSION_DESTROY:count="
+ + mSessionCount
+ + ":freemem="
+ + Runtime.getRuntime().freeMemory()
+ + ":totalmem="
+ + Runtime.getRuntime().totalMemory());
+ }
+ }
+
+ //------------------------------------------------------------------------
+
+ /**
+ * Get an instance of Roller from the RollerFactory.
+ * If one does not exist, tell Factory to create new one.
+ */
+ public static Roller getRoller(HttpServletRequest req)
+ {
+ Roller roller = RollerFactory.getRoller();
+ if (roller == null)
+ {
+ RollerFactory.setRoller(
+ mContext.getInitParameter(ROLLER_IMPL_KEY),
+ mCastorXML);
+ roller = RollerFactory.getRoller();
+ }
+ return roller;
+ }
+
+ //------------------------------------------------------------------------
+
+ /**
+ * Get authenticator
+ */
+ public Authenticator getAuthenticator()
+ {
+ if (mAuthenticator == null)
+ {
+ try
+ {
+ Class authClass =
+ Class.forName(
+ mContext.getInitParameter(
+ "org.roller.authenticatorClass"));
+ mAuthenticator = (Authenticator) authClass.newInstance();
+ }
+ catch (Exception e)
+ {
+ // this isn't an ERROR if no authenticatorClass was specified
+ if (!(e instanceof NullPointerException))
+ {
+ mLogger.error("ERROR creating authenticator, using default", e);
+ }
+ else
+ {
+ mLogger.debug("No authenticator specified, using DefaultAuthenticator");
+ }
+ mAuthenticator = new DefaultAuthenticator();
+ }
+ }
+ return mAuthenticator;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns RollerConfig object. Changed so that it always tries
+ * to fetch from the database first. If it should error, return
+ * the stored copy.
+ */
+ public RollerConfig getRollerConfig()
+ {
+ if (mConfig == null)
+ {
+ try
+ {
+ mConfig = getRoller(null).getConfigManager().getRollerConfig();
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("Unable to get RollerConfig from database");
+ }
+ }
+ return mConfig;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the hard-drive location of the upload directory.
+ */
+ public static String getUploadDir(ServletContext app)
+ {
+ RollerConfig rollerConfig =
+ RollerContext.getRollerContext(app).getRollerConfig();
+ // if the app doesn't have a value, figure it out
+ // from the ServletContext
+ if (StringUtils.isEmpty(rollerConfig.getUploadDir()))
+ {
+ try
+ {
+ // ServletContext getRealPath() vs. getResource()
+ //
+ // The getResource() returns a paths rooted at c:\localhost
+ // on my machine and I cannot figure out how to configure
+ // it to do otherwise (I'm using Tomcat 4.0.4).
+ //
+ // Is getResource() the right thing and if so, how do you
+ // configure getResource() to point at your out-of-context
+ // resources? Do you use the Tomcat server.xml <Resources> tag?
+ // My attempts at this failed and I couldn't Google an example.
+ //
+ // Anyhow...
+ //
+ // getRealPath() should work for everybody since we are
+ // already assuming (for now) that we are not deployed-as
+ // and running from a WAR.
+
+ String dir =
+ app.getRealPath(RollerContext.USER_RESOURCES) + "/";
+
+ //java.net.URL path = app.getResource(
+ //RollerContext.USER_RESOURCES );
+ // String dir = path.getPath() + "/";
+
+ return dir;
+ }
+ //catch (java.net.MalformedURLException mue)
+ catch (Exception mue)
+ {
+ System.err.println("Unable to load app.getResource()");
+ }
+ return null;
+ }
+
+ // otherwise return the value in app
+ String path = rollerConfig.getUploadDir();
+ if (!path.endsWith("/") && !path.endsWith("\\"))
+ {
+ path = path + "/";
+ }
+ return path;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the base url for the upload directory.
+ */
+ public static String getUploadPath(ServletContext app)
+ {
+ RollerConfig rollerConfig =
+ RollerContext.getRollerContext(app).getRollerConfig();
+ // if the app doesn't have a value, figure it out
+ // from the ServletContext
+ if (StringUtils.isEmpty(rollerConfig.getUploadPath()))
+ {
+ return RollerContext.USER_RESOURCES;
+ }
+
+ // otherwise return the value in app
+ String path = rollerConfig.getUploadPath();
+ if (path.endsWith("/") || path.endsWith("\\"))
+ {
+ path = path.substring(0, path.length() - 1);
+ }
+ return path;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Read Roller configuration parameters from roller-config.xml.
+ */
+ private void setupRollerConfig() throws RollerException
+ {
+ mConfig = getRoller(null).getConfigManager().getRollerConfig();
+
+ if (mConfig == null)
+ {
+ mConfig = getRoller(null).getConfigManager().readFromFile(getConfigPath());
+ saveRollerConfig(mConfig);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ public void saveRollerConfig(RollerConfig rConfig) throws RollerException
+ {
+ mConfig = rConfig;
+
+ // save database copy
+ //getRoller(null).begin(); // begin already called by RequestFilter
+ getRoller(null).getConfigManager().storeRollerConfig(rConfig);
+ getRoller(null).commit();
+
+ // save file copy
+ RollerConfigFile rConfigFile = new RollerConfigFile(rConfig);
+ rConfigFile.writeConfig(getConfigPath());
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Determine where we should read/write roller-config.xml to.
+ * A file in ${user.home} overrides one in WEB-INF.
+ */
+ public String getConfigPath()
+ {
+ String configPath =
+ System.getProperty("user.home")
+ + File.separator
+ + "roller-config.xml";
+
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug(
+ "Looking for roller-config.xml at '" + configPath + "'");
+ }
+
+ if (!new File(configPath).exists())
+ {
+ // No config found in user.home, store it in WEB-INF instead.
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("File not found: '" + configPath);
+ }
+
+ String root = mContext.getRealPath("/");
+ configPath =
+ root
+ + File.separator
+ + "WEB-INF"
+ + File.separator
+ + "roller-config.xml";
+ }
+
+ mLogger.info("Using roller-config.xml at '" + configPath + "'");
+
+ return configPath;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * RollerSpellCheck must be initialized with a dictionary file
+ * so that it can return valid a SpellChecker.
+ */
+ private void setupSpellChecker()
+ {
+ InputStream is = null;
+ try
+ {
+ is = mContext.getResourceAsStream("/WEB-INF/english.0");
+ RollerSpellCheck.init(is);
+ }
+ catch (Exception e)
+ {
+ mContext.log("ERROR reading dictionary file");
+ }
+ finally
+ {
+ if (is != null)
+ {
+ try
+ {
+ is.close();
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns the full url for the website of the specified username.
+ */
+ public String getContextUrl(HttpServletRequest request, String username)
+ {
+ String url = this.getContextUrl(request);
+ if (username != null)
+ {
+ url = url + "/page/" + username;
+ }
+ return url;
+ }
+
+ //-----------------------------------------------------------------------
+ /** Get absolute URL of Roller context */
+ public String getContextUrl(HttpServletRequest request)
+ {
+ String url = request.getContextPath();
+ if (url.endsWith("/"))
+ {
+ url = url.substring(0, url.length() - 1);
+ }
+ return url;
+ }
+
+ //-----------------------------------------------------------------------
+ /** Get absolute URL of Roller context */
+ public String getAbsoluteContextUrl(HttpServletRequest request)
+ {
+ String url = getRollerConfig().getAbsoluteURL();
+ if (url == null || url.trim().length() == 0)
+ {
+ try
+ {
+ URL absURL = RequestUtils.absoluteURL(request, "/");
+ url = absURL.toString();
+ }
+ catch (MalformedURLException e)
+ {
+ mLogger.error("ERROR: forming absolute URL", e);
+ }
+ }
+ if (url.endsWith("/"))
+ {
+ url = url.substring(0, url.length() - 1);
+ }
+ mContext.setAttribute("org.roller.absoluteContextURL", url);
+ return url;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * For use by MetaWeblog API.
+ * @return Context URL or null if not initialized yet.
+ */
+ public String getAbsoluteContextUrl()
+ {
+ return (String) mContext.getAttribute("org.roller.absoluteContextURL");
+ }
+
+ //-----------------------------------------------------------------------
+
+ public String createEntryPermalink(
+ WeblogEntryData entry,
+ HttpServletRequest request,
+ boolean absolute)
+ {
+ String link = null;
+ try
+ {
+ String baseUrl = null;
+ if (absolute)
+ {
+ baseUrl = getAbsoluteContextUrl(request);
+ }
+ else
+ {
+ baseUrl = getContextUrl(request);
+ }
+
+ String dayString = DateUtil.format8chars(entry.getPubTime());
+
+ UserData ud = entry.getWebsite().getUser();
+
+ link =
+ Utilities.escapeHTML(
+ baseUrl
+ + "/page/"
+ + ud.getUserName()
+ + "/"
+ + dayString
+ + "#"
+ + entry.getAnchor());
+ }
+ catch (Exception e)
+ {
+ mLogger.error("Unexpected exception", e);
+ }
+ return link;
+ }
+
+ //-----------------------------------------------------------------------
+
+ public void refreshUserDisplayBeans()
+ {
+ mContext.removeAttribute(USER_DISPLAY_BEAN_KEY);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Return the real filepath to the theme.
+ *
+ * @param theme
+ * @return String
+ */
+ public String getThemePath(String theme)
+ {
+ RollerConfig rollerConfig = this.getRollerConfig();
+
+ // Figure path to new user theme
+ return mContext.getRealPath(
+ "/" + rollerConfig.getUserThemes() + "/" + theme);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Get the list of Theme names. This consists
+ * of the directories under the /themes directory.
+ *
+ * @return String[]
+ */
+ public String[] getThemeNames()
+ {
+ RollerConfig rollerConfig = this.getRollerConfig();
+ String themesPath =
+ mContext.getRealPath("/" + rollerConfig.getUserThemes());
+ File themeDir = new File(themesPath);
+ return themeDir.list(new FilenameFilter()
+ {
+ public boolean accept(File dir, String name)
+ {
+ File file =
+ new File(dir.getAbsolutePath() + File.separator + name);
+ return file.isDirectory();
+ }
+ });
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Returns the mContext.
+ * @return ServletContext
+ */
+ public static ServletContext getServletContext()
+ {
+ return mContext;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Reads the Theme files from harddisk (if necessary) and places them into a
+ * ThemeCache. If the requested Theme's pages are already in the cache,
+ * return them instead.
+ *
+ * @param themeName
+ * @return HashMap
+ * @throws FileNotFoundException
+ * @throws IOException
+ */
+ public HashMap readThemeMacros(String themeName)
+ throws FileNotFoundException, IOException
+ {
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("themeName=" + themeName);
+ }
+
+ // Load all Velocity templates from root directory of the theme
+ String pageName = null;
+ String themeDir = this.getThemePath(themeName);
+ String[] children = getThemeFilenames(themeDir);
+ HashMap pages = new HashMap();
+ ThemeCache themeCache = ThemeCache.getInstance();
+ for (int i = 0; i < children.length; i++)
+ {
+ pageName = children[i].substring(0, children[i].length() - 3);
+
+ if (themeCache.getFromCache(themeName, pageName) != null)
+ {
+ pages.put(
+ pageName,
+ themeCache.getFromCache(themeName, pageName));
+ }
+ else
+ {
+ BufferedReader rdr =
+ new BufferedReader(
+ new FileReader(
+ themeDir + File.separator + children[i]));
+ String line = null;
+ StringBuffer sb = new StringBuffer();
+ while (null != (line = rdr.readLine()))
+ {
+ sb.append(line);
+ sb.append("\n");
+ }
+
+ pages.put(pageName, sb.toString());
+ themeCache.putIntoCache(themeName, pageName, sb.toString());
+ }
+ }
+ return pages;
+ }
+
+ //-----------------------------------------------------------------------
+
+ public static String[] getThemeFilenames(String themeDir)
+ {
+ ThemeCache themeCache = ThemeCache.getInstance();
+ if (themeCache.getFileList(themeDir) != null)
+ {
+ return themeCache.getFileList(themeDir);
+ }
+
+ File dir = new File(themeDir);
+ FilenameFilter filter = new FilenameFilter()
+ {
+ public boolean accept(File dir, String name)
+ {
+ return name.endsWith(".vm");
+ }
+ };
+ String[] children = dir.list(filter);
+ themeCache.setFileList(themeDir, children);
+ return children;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /** Roller version */
+ public String getRollerVersion()
+ {
+ return mVersion;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /** Roller build time */
+ public String getRollerBuildTime()
+ {
+ return mBuildTime;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /** Get username that built Roller */
+ public String getRollerBuildUser()
+ {
+ return mBuildUser;
+ }
+
+
+}
Added: incubator/roller/trunk/src/org/roller/presentation/RollerRequest.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/presentation/RollerRequest.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/presentation/RollerRequest.java (added)
+++ incubator/roller/trunk/src/org/roller/presentation/RollerRequest.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,884 @@
+
+package org.roller.presentation;
+
+import org.apache.commons.lang.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.roller.RollerException;
+import org.roller.model.ParsedRequest;
+import org.roller.model.Roller;
+import org.roller.model.UserManager;
+import org.roller.model.WeblogManager;
+import org.roller.pojos.BookmarkData;
+import org.roller.pojos.FolderData;
+import org.roller.pojos.PageData;
+import org.roller.pojos.UserData;
+import org.roller.pojos.WeblogCategoryData;
+import org.roller.pojos.WeblogEntryData;
+import org.roller.pojos.WebsiteData;
+import org.roller.util.DateUtil;
+import org.roller.util.Utilities;
+
+import java.text.ParsePosition;
+import java.text.SimpleDateFormat;
+import java.util.Calendar;
+import java.util.Date;
+
+import javax.servlet.ServletContext;
+import javax.servlet.ServletRequest;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.jsp.PageContext;
+
+//////////////////////////////////////////////////////////////////////////////
+/**
+ * Access to objects and values specified by request. Parses out arguments from
+ * request URL needed for various parts of Roller and makes them available via
+ * getter methods.
+ * <br/><br/>
+ *
+ * These forms of pathinfo get special support:
+ * <br/><br/>
+ *
+ * <pre>
+ * [username] - get default page for user for today's date
+ * [username]/[date] - get default page for user for specified date
+ * [username]/[pagelink] - get specified page for today's date
+ * [username]/[pagelink]/[date] - get specified page for specified date
+ * [username]/[pagelink]/[anchor] - get specified page & entry (by anchor)
+ * [username]/[pagelink]/[date]/[anchor] - get specified page & entry (by anchor)
+ * </pre>
+ *
+ * @author David M Johnson
+ */
+public class RollerRequest implements ParsedRequest
+{
+ //----------------------------------------------------------------- Fields
+
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(RollerRequest.class);
+
+ private BookmarkData mBookmark;
+ private ServletContext mContext = null;
+ private Date mDate = null;
+ private String mDateString = null;
+ private String mPathInfo = null;
+ private String mPageLink = null;
+ private PageData mPage;
+ private PageContext mPageContext = null;
+ private HttpServletRequest mRequest = null;
+ private WebsiteData mWebsite;
+ private WeblogEntryData mWeblogEntry;
+ private WeblogCategoryData mWeblogCategory;
+ private boolean mIsDateSpecified = false;
+
+ private static ThreadLocal mRollerRequestTLS = new ThreadLocal();
+
+ public static final String ANCHOR_KEY = "anchor";
+ public static final String USERNAME_KEY = "username";
+ public static final String WEBSITEID_KEY = "websiteid";
+ public static final String FOLDERID_KEY = "folderid";
+ public static final String PARENTID_KEY = "parentid";
+ public static final String NEWSFEEDID_KEY = "feedid";
+ public static final String PAGEID_KEY = "pageid";
+ public static final String PAGELINK_KEY = "pagelink";
+ public static final String EXCERPTS_KEY = "excerpts";
+ public static final String BOOKMARKID_KEY = "bookmarkid";
+ public static final String REFERERID_KEY = "refid";
+ public static final String WEBLOGENTRYID_KEY = "entryid";
+ public static final String WEBLOGENTRY_COUNT = "count";
+ public static final String WEBLOGCATEGORYNAME_KEY = "catname";
+ public static final String WEBLOGCATEGORYID_KEY = "catid";
+ public static final String WEBLOGENTRIES_KEY = "entries";
+ public static final String WEBLOGDAY_KEY = "day";
+ public static final String WEBLOGCOMMENTID_KEY = "catid";
+ public static final String LOGIN_COOKIE = "sessionId";
+
+ private static final String ROLLER_REQUEST = "roller_request";
+
+ private SimpleDateFormat mFmt = DateUtil.get8charDateFormat();
+
+ //----------------------------------------------------------- Constructors
+
+ /** Construct Roller request for a Servlet request */
+ public RollerRequest( HttpServletRequest req, ServletContext ctx )
+ throws RollerException
+ {
+ mRequest = req;
+ mContext = ctx;
+ init();
+ }
+
+ //------------------------------------------------------------------------
+ /** Convenience */
+ public RollerRequest( ServletRequest req, ServletContext ctx )
+ throws RollerException
+ {
+ mRequest = (HttpServletRequest)req;
+ mContext = ctx;
+ init();
+ }
+
+ //------------------------------------------------------------------------
+ public RollerRequest( PageContext pCtx) throws RollerException
+ {
+ mRequest = (HttpServletRequest) pCtx.getRequest();
+ mContext = pCtx.getServletContext();
+ mPageContext = pCtx;
+ init();
+ }
+
+ //------------------------------------------------------------------------
+ private void init() throws RollerException
+ {
+ mRollerRequestTLS.set(this);
+
+ // path info may be null, (e.g. on JSP error page)
+ mPathInfo = mRequest.getPathInfo();
+ mPathInfo = (mPathInfo!=null) ? mPathInfo : "";
+
+ String[] pathInfo = StringUtils.split(mPathInfo,"/");
+ if ( pathInfo.length > 0 )
+ {
+ // Parse pathInfo and throw exception if it is invalid
+ if (!"j_security_check".equals(pathInfo[0]))
+ {
+ parsePathInfo( pathInfo );
+ return;
+ }
+ }
+
+ // Parse user, page, and entry from request params if possible
+ parseRequestParams();
+ }
+
+ //------------------------------------------------------------------------
+ /** Parse pathInfo and throw exception if it is invalid */
+ private void parsePathInfo( String[] pathInfo ) throws RollerException
+ {
+ try
+ {
+ // If there is any path info, it must be in one of the
+ // below formats or the request is considered to be invalid.
+ //
+ // /username
+ // /username/datestring
+ // /username/pagelink
+ // /username/pagelink/datestring
+ // /username/pagelink/anchor (specific entry)
+ // /username/pagelink/datestring/anchor (specific entry)
+ UserManager userMgr = getRoller().getUserManager();
+ mWebsite = userMgr.getWebsite(pathInfo[0]);
+ if (mWebsite != null)
+ {
+ if ( pathInfo.length == 1 )
+ {
+ // we have the /username form of URL
+ mDate = getDate(true);
+ mDateString = DateUtil.format8chars(mDate);
+ mPage = userMgr.retrievePage(mWebsite.getDefaultPageId());
+ }
+ else if ( pathInfo.length == 2 )
+ {
+ mDate = parseDate(pathInfo[1]);
+ if ( mDate == null ) // pre-jdk1.4 --> || mDate.getYear() <= 70 )
+ {
+ // we have the /username/pagelink form of URL
+ mDate = getDate(true);
+ mDateString = DateUtil.format8chars(mDate);
+ mPageLink = pathInfo[1];
+ mPage = userMgr.getPageByLink(mWebsite, pathInfo[1]);
+ }
+ else
+ {
+ // we have the /username/datestring form of URL
+ mDateString = pathInfo[1];
+ mPage = userMgr.retrievePage(mWebsite.getDefaultPageId());
+ mIsDateSpecified = true;
+ }
+ }
+ else if ( pathInfo.length == 3 )
+ {
+ mPageLink = pathInfo[1];
+ mPage = userMgr.getPageByLink(mWebsite, pathInfo[1]);
+
+ mDate = parseDate(pathInfo[2]);
+ if ( mDate == null ) // pre-jdk1.4 --> || mDate.getYear() <= 70 )
+ {
+ // we have the /username/pagelink/anchor form of URL
+ try
+ {
+ WeblogManager weblogMgr = getRoller().getWeblogManager();
+ mWeblogEntry = weblogMgr.getWeblogEntryByAnchor(
+ mWebsite, pathInfo[2]);
+ mDate = mWeblogEntry.getPubTime();
+ mDateString = DateUtil.format8chars(mDate);
+ }
+ catch (Exception damn)
+ {
+ // doesn't really matter, we've got the Page anyway
+ mLogger.debug("Damn", damn);
+ }
+ }
+ else
+ {
+ // we have the /username/pagelink/datestring form of URL
+ mDateString = pathInfo[2];
+ mIsDateSpecified = true;
+ }
+ }
+ else if ( pathInfo.length == 4 )
+ {
+ // we have the /username/pagelink/datestring/anchor form of URL
+ mPageLink = pathInfo[1];
+ mPage = userMgr.getPageByLink(mWebsite, pathInfo[1]);
+
+ mDate = parseDate(pathInfo[2]);
+ mDateString = pathInfo[2];
+ mIsDateSpecified = true;
+
+ // we have the /username/pagelink/date/anchor form of URL
+ WeblogManager weblogMgr = getRoller().getWeblogManager();
+ mWeblogEntry = weblogMgr.getWeblogEntryByAnchor(
+ mWebsite, pathInfo[3]);
+ }
+ }
+ }
+ catch ( Exception ignored )
+ {
+ mLogger.debug("Exception parsing pathInfo",ignored);
+ }
+
+ if ( mWebsite==null || mDate==null || mPage==null )
+ {
+ String msg = "Invalid pathInfo: "+StringUtils.join(pathInfo,"|");
+ mLogger.info(msg);
+ throw new RollerException(msg);
+ }
+ }
+
+ //------------------------------------------------------------------------
+ /** Parse user, page, and entry from request params if possible */
+ private void parseRequestParams()
+ {
+ try
+ {
+ // No path info means that we need to parse request params
+
+ // First, look for user in the request params
+ UserManager userMgr = getRoller().getUserManager();
+ String userName = mRequest.getParameter(USERNAME_KEY);
+ if ( userName == null )
+ {
+ // then try remote user
+ userName = mRequest.getRemoteUser();
+ }
+
+ if ( userName != null )
+ {
+ mWebsite = userMgr.getWebsite(userName);
+ }
+
+ // Look for page ID in request params
+ String pageId = mRequest.getParameter(RollerRequest.PAGEID_KEY);
+ if ( pageId != null )
+ {
+ mPage = userMgr.retrievePage(pageId);
+
+ // We can use page to find the user, if we don't have one yet
+ if ( mWebsite == null )
+ {
+ mWebsite = mPage.getWebsite();
+ }
+ }
+ else if (mWebsite != null)
+ {
+ mPage = userMgr.retrievePage( mWebsite.getDefaultPageId() );
+ }
+
+ // Look for day in request params
+ String daystr = mRequest.getParameter(WEBLOGDAY_KEY);
+ if ( daystr != null )
+ {
+ mDate = parseDate(daystr);
+ if ( mDate != null )
+ {
+ // we have the /username/datestring form of URL
+ mDateString = daystr;
+ mIsDateSpecified = true;
+ }
+ }
+ }
+ catch ( Exception ignored )
+ {
+ mLogger.debug("Exception parsing request params",ignored);
+ }
+ }
+
+ //------------------------------------------------------------------------
+ /** Get HttpServletmRequest that is wrapped by this RollerRequest */
+ public PageContext getPageContext()
+ {
+ return mPageContext;
+ }
+
+ public void setPageContext(PageContext p)
+ {
+ mPageContext = p;
+ }
+
+ //------------------------------------------------------------------------
+ /** Get HttpServletmRequest that is wrapped by this RollerRequest */
+ public HttpServletRequest getRequest()
+ {
+ return mRequest;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Get the RollerRequest object that is stored in the request. Creates
+ * RollerRequest if one not found in mRequest.
+ */
+ public static RollerRequest getRollerRequest(
+ HttpServletRequest r, ServletContext ctx ) throws RollerException
+ {
+ RollerRequest ret= (RollerRequest)r.getAttribute(ROLLER_REQUEST);
+ if ( ret == null )
+ {
+ ret = new RollerRequest(r,ctx);
+ r.setAttribute( ROLLER_REQUEST, ret );
+ }
+ return ret;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Get the RollerRequest object that is stored in the request. Creates
+ * RollerRequest if one not found in mRequest.
+ */
+ public static RollerRequest getRollerRequest( HttpServletRequest r )
+ {
+ try
+ {
+ return getRollerRequest(r, RollerContext.getServletContext());
+ }
+ catch (Exception e)
+ {
+ mLogger.error("Unable to create a RollerRequest", e);
+ }
+ return null;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Get the RollerRequest object that is stored in the request. Creates
+ * RollerRequest if one not found in mRequest.
+ */
+ public static RollerRequest getRollerRequest( PageContext p )
+ {
+ HttpServletRequest r = (HttpServletRequest)p.getRequest();
+ RollerRequest ret = (RollerRequest)r.getAttribute(ROLLER_REQUEST);
+ if (ret == null)
+ {
+ try
+ {
+ ret = new RollerRequest( p );
+ r.setAttribute( ROLLER_REQUEST, ret );
+ }
+ catch (Exception e)
+ {
+ mLogger.error("Unable to create a RollerRequest", e);
+ }
+ }
+ else
+ {
+ ret.setPageContext( p );
+ }
+ return ret;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Get RollerRequest object for the current thread using EVIL MAGIC,
+ * do not use unless you absolutely, positively, cannot use on of the
+ * getRollerRequest() methods.
+ */
+ public static RollerRequest getRollerRequest()
+ {
+ return (RollerRequest)mRollerRequestTLS.get();
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Get the RollerRequest object that is stored in the requeset.
+ * Creates RollerRequest if one not found in mRequest.
+ */
+ public ServletContext getServletContext()
+ {
+ return mContext;
+ }
+
+ //------------------------------------------------------------------------
+ /** Get Roller instance from */
+ public Roller getRoller()
+ {
+ return RollerContext.getRoller( mRequest );
+ }
+
+ //------------------------------------------------------------------------
+ /** Is mRequest's user the admin user? */
+ public boolean isAdminUser() throws RollerException
+ {
+ RollerContext rctx = RollerContext.getRollerContext(mContext);
+
+ String userName =
+ rctx.getAuthenticator().getAuthenticatedUserName(mRequest);
+
+ String[] adminList = rctx.getRollerConfig().adminUsersArray();
+ if ( adminList != null && userName != null)
+ {
+ for (int i=0; i<adminList.length; i++)
+ {
+ if (userName.equals(adminList[i])) return true;
+ }
+ }
+ return false;
+ }
+
+ //------------------------------------------------------------------------
+ /** Is mRequest's user authorized to edit the mRequested resource */
+ public boolean isUserAuthorizedToEdit() throws RollerException
+ {
+ // Make sure authenticated user is the owner of this item
+ // Session's principal's name must match user name in mRequest
+
+ RollerContext rctx = RollerContext.getRollerContext(mContext);
+ Authenticator auth = rctx.getAuthenticator();
+
+ String userName = auth.getAuthenticatedUserName(mRequest);
+
+ UserData ud = getUser();
+ if ( userName != null
+ && ud != null
+ && userName.equals( ud.getUserName() )
+ && auth.isAuthenticatedUserInRole(mRequest,"editor"))
+ {
+ return true;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Get user by name.
+ */
+ public UserData getUser( String userName ) throws Exception
+ {
+ return getRoller().getUserManager().getUser( userName );
+ }
+
+ //------------------------------------------------------------------------
+
+ public boolean isDateSpecified()
+ {
+ return mIsDateSpecified;
+ }
+
+ //------------------------------------------------------------------------
+
+ public int getWeblogEntryCount()
+ {
+ // Get count of entries to return, or 20 if null
+ int count = 20;
+ if ( mRequest.getParameter("count") != null )
+ {
+ count= Utilities.stringToInt(mRequest.getParameter("count"));
+ if ( count==0 || count>50 )
+ {
+ count = 20;
+ }
+ }
+ return count;
+ }
+
+ //------------------------------------------------------------------------
+
+ /**
+ * Gets the date specified by the request, or null.
+ * @return Date
+ */
+ public Date getDate()
+ {
+ return getDate(false);
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the date specified by the request
+ * @param orToday If no date specified, then use today's date.
+ * @return Date
+ */
+ public Date getDate( boolean orToday )
+ {
+ Date ret = null;
+ if ( mDate != null )
+ {
+ ret = mDate;
+ }
+ else if ( orToday )
+ {
+ ret = getToday();
+ }
+ return ret;
+ }
+
+ /**
+ * Gets the current date based on Website's Locale & Timezone.
+ * @return
+ */
+ private Date getToday()
+ {
+ Calendar todayCal = Calendar.getInstance();
+ if (this.getWebsite() != null)
+ {
+ todayCal = Calendar.getInstance(
+ this.getWebsite().getTimeZoneInstance(),
+ this.getWebsite().getLocaleInstance());
+ }
+ todayCal.setTime( new Date() );
+ return todayCal.getTime();
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the YYYYMMDD date string specified by the request, or null.
+ * @return String
+ */
+ public String getDateString()
+ {
+ return getDateString(false);
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the date specified by the request
+ * @param orToday If no date specified, then use today's date.
+ * @return Date
+ */
+ public String getDateString( boolean orToday )
+ {
+ String ret = null;
+ if ( mDateString != null )
+ {
+ ret = mDateString;
+ }
+ else if ( orToday )
+ {
+ Calendar todayCal = Calendar.getInstance();
+ if (this.getWebsite() != null)
+ {
+ todayCal = Calendar.getInstance(
+ this.getWebsite().getTimeZoneInstance(),
+ this.getWebsite().getLocaleInstance());
+ }
+ todayCal.setTime( new Date() );
+ ret = mFmt.format(todayCal.getTime());
+ }
+ return ret;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the path-info specified by the request, or null.
+ * @return String
+ */
+ public String getPathInfo()
+ {
+ return mPathInfo;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the page link name specified by the request, or null.
+ * @return String
+ */
+ public String getPageLink()
+ {
+ return mPageLink;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the BookmarkData specified by the request, or null.
+ * @return BookmarkData
+ */
+ public BookmarkData getBookmark( )
+ {
+ if ( mBookmark == null )
+ {
+ String id = getFromRequest(BOOKMARKID_KEY);
+ if ( id != null )
+ {
+ try
+ {
+ mBookmark =
+ getRoller().getBookmarkManager().retrieveBookmark(id);
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("Getting bookmark from request",e);
+ }
+ }
+ }
+ return mBookmark;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the WeblogCategoryData specified by the request, or null.
+ * @return
+ */
+ public WeblogCategoryData getWeblogCategory()
+ {
+ if ( mWeblogCategory == null )
+ {
+ String id = getFromRequest(WEBLOGCATEGORYID_KEY);
+ if ( id != null )
+ {
+ try
+ {
+ mWeblogCategory =
+ getRoller().getWeblogManager().retrieveWeblogCategory(id);
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("Getting weblog category by id from request",e);
+ }
+ }
+ else if (StringUtils.isNotEmpty(id = getFromRequest(WEBLOGCATEGORYNAME_KEY)))
+ {
+ try
+ {
+ mWeblogCategory =
+ getRoller().getWeblogManager().getWeblogCategoryByPath(
+ getWebsite(), null, id);
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("Getting weblog category by name from request",e);
+ }
+ }
+ }
+ return mWeblogCategory;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the FolderData specified by the request, or null.
+ * @return FolderData
+ */
+ public FolderData getFolder( )
+ {
+ FolderData folder = null;
+ //if ( folder == null )
+ //{
+ String id = getFromRequest(FOLDERID_KEY);
+ if ( id != null )
+ {
+ try
+ {
+ folder =
+ getRoller().getBookmarkManager().retrieveFolder(id);
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("Getting folder from request",e);
+ }
+ }
+ //}
+ return folder;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the PageData specified by the request, or null.
+ * @return PageData
+ */
+ public PageData getPage()
+ {
+ if (mPage == null)
+ {
+ String id = getFromRequest(PAGEID_KEY);
+ if ( id != null )
+ {
+ try
+ {
+ mPage = getRoller().getUserManager().retrievePage(id);
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("Getting page from request",e);
+ }
+ }
+ }
+ return mPage;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Gets the Request URL specified by the request, or null.
+ * @return String
+ */
+ public String getRequestURL( )
+ {
+ return mRequest.getRequestURL().toString();
+ }
+
+ //------------------------------------------------------------------------
+
+ /**
+ * Gets the Referer URL specified by the request, or null.
+ * @return String
+ */
+ public String getRefererURL( )
+ {
+ return mRequest.getHeader("referer");
+ }
+
+ /**
+ * Gets the UserData specified by the request, or null.
+ * @return UserData
+ */
+ public UserData getUser()
+ {
+ if (mWebsite != null) return mWebsite.getUser();
+ return null;
+ }
+
+ /**
+ * Gets the WebsiteData specified by the request, or null.
+ * @return WeblogCategory
+ */
+ public WebsiteData getWebsite()
+ {
+ return mWebsite;
+ }
+
+ /**
+ * Gets the WeblogEntryData specified by the request, or null.
+ *
+ * Why is this done lazily in the parseRequestParameters() method?
+ *
+ * Because: that method is called from init(), which is called from
+ * a ServletFilter, and sometimes request parameters are not available
+ * in a ServletFiler. They ARE available when the URL points to a JSP,
+ * but they ARE NOT available when the URL points to the PageServlet.
+ * This may be a Tomcat bug, I'm not sure.
+ *
+ * @return WeblogEntryData
+ */
+ public WeblogEntryData getWeblogEntry( )
+ {
+ if ( mWeblogEntry == null )
+ {
+ // Look for anchor or entry ID that identifies a specific entry
+ String anchor = mRequest.getParameter(ANCHOR_KEY);
+ String entryid = mRequest.getParameter(WEBLOGENTRYID_KEY);
+ if (entryid == null)
+ {
+ entryid = (String)mRequest.getAttribute(WEBLOGENTRYID_KEY);
+ }
+ try
+ {
+ if ( entryid != null )
+ {
+ WeblogManager weblogMgr = getRoller().getWeblogManager();
+ mWeblogEntry = weblogMgr.retrieveWeblogEntry(entryid);
+
+ // We can use entry to find the website, if we don't have one
+ if ( mWeblogEntry != null && mWebsite == null )
+ {
+ mWebsite = mWeblogEntry.getWebsite();
+ }
+ }
+ else if ( mWebsite != null && anchor != null )
+ {
+ WeblogManager weblogMgr = getRoller().getWeblogManager();
+ mWeblogEntry = weblogMgr.getWeblogEntryByAnchor(
+ mWebsite,anchor);
+ }
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("EXCEPTION getting weblog entry",e);
+ mLogger.error("user=" + mWebsite.getUser());
+ mLogger.error("anchor=" + anchor);
+ mLogger.error("entryid=" + entryid);
+ }
+ }
+ return mWeblogEntry;
+ }
+
+ //------------------------------------------------------------------------
+
+ /** Get attribute from mRequest, and if that fails try session */
+ private String getFromRequest( String key )
+ {
+ String ret = (String)mRequest.getAttribute( key );
+ if ( ret == null )
+ {
+ ret = mRequest.getParameter( key );
+ if (ret == null && mRequest.getSession(false) != null)
+ {
+ ret = (String)mRequest.getSession().getAttribute( key );
+ }
+ }
+ return ret;
+ }
+
+ //------------------------------------------------------------------------
+
+ private Date parseDate( String dateString )
+ {
+ Date ret = null;
+ if ( dateString!=null
+ && dateString.length()==8
+ && StringUtils.isNumeric(dateString) )
+ {
+ ParsePosition pos = new ParsePosition(0);
+ ret = mFmt.parse( dateString, pos );
+
+ // make sure the requested date is not in the future
+ Date today = getToday();
+ if (ret.after(today)) ret = today;
+ }
+ return ret;
+ }
+
+ //------------------------------------------------------------------------
+
+ public String toString()
+ {
+ StringBuffer sb = new StringBuffer();
+ sb.append("[");
+ sb.append(getRequestURL());
+ sb.append(", ");
+ sb.append(getRefererURL());
+ sb.append("]");
+ return sb.toString();
+ }
+
+ //------------------------------------------------------------------------
+
+ /**
+ * @see org.roller.pojos.ParsedRequest#isLinkbackEnabled()
+ */
+ public boolean isEnableLinkback()
+ {
+ RollerContext rctx = RollerContext.getRollerContext(mRequest);
+ return rctx.getRollerConfig().getEnableLinkback().booleanValue();
+ }
+}
+
Added: incubator/roller/trunk/src/org/roller/presentation/RollerSession.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/presentation/RollerSession.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/presentation/RollerSession.java (added)
+++ incubator/roller/trunk/src/org/roller/presentation/RollerSession.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,141 @@
+package org.roller.presentation;
+
+import org.apache.commons.collections.ArrayStack;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
+import javax.servlet.http.HttpSessionActivationListener;
+import javax.servlet.http.HttpSessionEvent;
+import javax.servlet.http.HttpSessionListener;
+
+
+//////////////////////////////////////////////////////////////////////////////
+/**
+ * Roller session handles session startup and shutdown.
+ * @web.listener
+ */
+public class RollerSession
+ implements HttpSessionListener, HttpSessionActivationListener
+{
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(RollerSession.class);
+
+ public static final String BREADCRUMB = "org.roller.breadcrumb";
+ public static final String ERROR_MESSAGE = "rollererror_message";
+ public static final String STATUS_MESSAGE = "rollerstatus_message";
+
+
+ //------------------------------------------------------------------------
+ /** Create session's Roller instance */
+ public void sessionCreated(HttpSessionEvent se)
+ {
+ // put this in session too, so we can purge on passivation
+ se.getSession().setAttribute( "dummy010", this );
+
+ RollerContext rctx = RollerContext.getRollerContext(
+ se.getSession().getServletContext());
+ rctx.sessionCreated(se);
+ }
+
+ //------------------------------------------------------------------------
+ public void sessionDestroyed(HttpSessionEvent se)
+ {
+ RollerContext rctx = RollerContext.getRollerContext(
+ se.getSession().getServletContext());
+ rctx.sessionDestroyed(se);
+
+ clearSession(se);
+ }
+
+ //------------------------------------------------------------------------
+ /** Init session as if it was new */
+ public void sessionDidActivate(HttpSessionEvent se)
+ {
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Clear bread crumb trail.
+ * @param useReferer If true try to return the "referer" header.
+ */
+ public static void clearBreadCrumbTrail( HttpServletRequest req )
+ {
+ HttpSession ses = req.getSession(false);
+ if (ses != null && ses.getAttribute(BREADCRUMB) != null)
+ {
+ ArrayStack stack = (ArrayStack)ses.getAttribute(BREADCRUMB);
+ stack.clear();
+ }
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Store the url of the latest request stored in the session.
+ * @param useReferer If true try to return the "referer" header.
+ */
+ public static String getBreadCrumb(
+ HttpServletRequest req, boolean useReferer )
+ {
+ String crumb = null;
+
+ HttpSession ses = req.getSession(false);
+ if (ses != null && ses.getAttribute(BREADCRUMB) != null)
+ {
+ ArrayStack stack = (ArrayStack) ses.getAttribute(BREADCRUMB);
+ if (stack != null && !stack.empty())
+ {
+ crumb = (String)stack.peek();
+ }
+ }
+
+ if ( crumb == null && useReferer )
+ {
+ crumb = req.getHeader("referer");
+ }
+
+ return crumb;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Store the url of the latest request stored in the session.
+ * Else try to return the "referer" header.
+ */
+ public static String getBreadCrumb( HttpServletRequest req )
+ {
+ return getBreadCrumb(req,true);
+ }
+
+ //------------------------------------------------------------------------
+ /** Purge session before passivation. Because Roller currently does not
+ * support session recovery, failover, migration, or whatever you want
+ * to call it when sessions are saved and then restored at some later
+ * point in time.
+ */
+ public void sessionWillPassivate(HttpSessionEvent se)
+ {
+ clearSession(se);
+ }
+
+ //------------------------------------------------------------------------ /*
+ private void clearSession( HttpSessionEvent se )
+ {
+ HttpSession session = se.getSession();
+ try
+ {
+ session.removeAttribute( BREADCRUMB );
+ session.removeAttribute("org.roller.users");
+ }
+ catch (Throwable e)
+ {
+ if (mLogger.isDebugEnabled())
+ {
+ // ignore purge exceptions
+ mLogger.debug("EXCEPTION PURGING session attributes",e);
+ }
+ }
+ }
+}
+
Added: incubator/roller/trunk/src/org/roller/presentation/TurnoverReferersTask.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/presentation/TurnoverReferersTask.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/presentation/TurnoverReferersTask.java (added)
+++ incubator/roller/trunk/src/org/roller/presentation/TurnoverReferersTask.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,45 @@
+/*
+ * Created on Aug 16, 2003
+ */
+package org.roller.presentation;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.roller.RollerException;
+import org.roller.model.RefererManager;
+import org.roller.model.RollerFactory;
+import org.roller.util.DateUtil;
+
+import java.util.TimerTask;
+
+/**
+ * @author aim4min
+ */
+public class TurnoverReferersTask extends TimerTask {
+
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(TurnoverReferersTask.class);
+ private RefererManager refManager = null;
+
+ long period = DateUtil.millisInDay;
+
+ public TurnoverReferersTask(RefererManager refManager) {
+ this.refManager=refManager;
+ }
+
+ /* (non-Javadoc)
+ * @see java.lang.Runnable#run()
+ */
+ public void run() {
+ if (refManager!=null)
+ try {
+ RollerFactory.getRoller().begin();
+ refManager.checkForTurnover(false,null);
+ RollerFactory.getRoller().commit();
+ RollerFactory.getRoller().release();
+ } catch (RollerException e) {
+ mLogger.error("Error while checking for referer turnover",e);
+ }
+ }
+
+}
Added: incubator/roller/trunk/src/org/roller/presentation/atom/AtomAssistant.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/presentation/atom/AtomAssistant.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/presentation/atom/AtomAssistant.java (added)
+++ incubator/roller/trunk/src/org/roller/presentation/atom/AtomAssistant.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,123 @@
+/*
+ * Created on Mar 5, 2004
+ */
+package org.roller.presentation.atom;
+
+import org.osjava.atom4j.pojo.Content;
+import org.osjava.atom4j.pojo.Entry;
+import org.osjava.atom4j.pojo.Feed;
+import org.osjava.atom4j.pojo.Generator;
+import org.osjava.atom4j.pojo.Link;
+import org.osjava.atom4j.pojo.Person;
+import org.roller.pojos.UserData;
+import org.roller.pojos.WeblogEntryData;
+import org.roller.pojos.WebsiteData;
+import org.roller.presentation.RollerContext;
+import org.roller.presentation.RollerRequest;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Atom utilitities for the RollerAtomServlet.
+ * @author Lance Lavandowska
+ * @author Dave Johnson
+ */
+public abstract class AtomAssistant
+{
+ protected static String mBaseUrl = "";
+
+ /**
+ * Convert specified entries to an Atom feed, with service URIs if authorized.
+ */
+ protected static Feed convertToAtomFeed(
+ WebsiteData website, List rollerEntries, boolean authorized)
+ {
+ Feed feed = new Feed();
+
+ Generator generator = new Generator();
+ //generator.setContent("RollerWeblogger");
+ generator.setUrl("http://www.rollerweblogger.org");
+ generator.setVersion(
+ RollerContext.getRollerContext(
+ // use RollerRequest.getServletContext !!
+ RollerRequest.getRollerRequest().getServletContext()
+ ).getRollerVersion());
+ feed.setGenerator( generator );
+
+ feed.setId( website.getId() ); //TODO: better ID?
+
+ Content title = new Content();
+ title.setText(website.getName());
+ feed.setTitle(title);
+
+ Content desc = new Content();
+ desc.setText(website.getDescription());
+ feed.setTagline(desc);
+
+ List atomEntries = AtomAssistant.convertEntries(rollerEntries, authorized);
+ feed.setEntries(atomEntries);
+
+ return feed;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Convert a Roller WeblogEntryData into an Atom Entry, with service URI if authorized.
+ */
+ protected static Entry convertToAtomEntry(
+ WeblogEntryData weblogEntry, boolean authorized)
+ {
+ UserData user = weblogEntry.getWebsite().getUser();
+ Entry atomEntry = new Entry();
+ atomEntry.setId( weblogEntry.getId() );
+ atomEntry.setTitle( new Content() );
+ atomEntry.getTitle().setText(weblogEntry.getTitle());
+ atomEntry.setIssued( weblogEntry.getPubTime() );
+ atomEntry.setCreated( weblogEntry.getPubTime() );
+ atomEntry.setModified( weblogEntry.getUpdateTime() );
+
+ Link altLink = new Link();
+ altLink.setRel(Link.ALTERNATE);
+ altLink.setHref(mBaseUrl + weblogEntry.getPermaLink());
+ atomEntry.addLink(altLink);
+
+ Link editLink = new Link();
+ editLink.setRel(Link.SERVICE_EDIT);
+ editLink.setHref(mBaseUrl + "/atom/" + user.getUserName() + "/entry");
+ atomEntry.addLink(editLink);
+
+ atomEntry.setAuthor( new Person() );
+ atomEntry.getAuthor().setName( user.getFullName() );
+ atomEntry.getAuthor().setUrl( mBaseUrl + "/" + user.getUserName() );
+ atomEntry.getAuthor().setEmail( user.getEmailAddress() );
+
+ atomEntry.setContent( new Content() );
+ atomEntry.getContent().setText( weblogEntry.getText() );
+ atomEntry.getContent().setMimeType( "application/xhtml+xml" );
+ atomEntry.getContent().setLanguage( "en-us" );
+ return atomEntry;
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * Convert a List of WeblogEntryData objects to a List of Atom Entries.
+ * @param rollerEntries
+ * @return
+ */
+ protected static List convertEntries(List rollerEntries, boolean authorized)
+ {
+ // Convert Roller entries into Atom entries
+ List entries = new ArrayList(rollerEntries.size());
+ Iterator iter = rollerEntries.iterator();
+ WeblogEntryData weblogEntry = null;
+ while (iter.hasNext())
+ {
+ weblogEntry = (WeblogEntryData)iter.next();
+ entries.add( AtomAssistant.convertToAtomEntry(weblogEntry, authorized) );
+ }
+ return entries;
+ }
+
+}
Added: incubator/roller/trunk/src/org/roller/presentation/atom/AtomEntry.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/presentation/atom/AtomEntry.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/presentation/atom/AtomEntry.java (added)
+++ incubator/roller/trunk/src/org/roller/presentation/atom/AtomEntry.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,123 @@
+/*
+ * Created on Apr 2, 2004
+ */
+package org.roller.presentation.atom;
+
+import org.osjava.atom4j.Atom4J;
+import org.osjava.atom4j.pojo.Entry;
+import org.osjava.atom4j.pojo.Link;
+import org.osjava.atom4j.pojo.Person;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author lance.lavandowska
+ */
+public class AtomEntry extends Entry
+{
+ private String annotation = null;
+ private List categories = null;
+
+ /**
+ * @return Returns the annotation.
+ */
+ public String getAnnotation()
+ {
+ return this.annotation;
+ }
+
+ /**
+ * @param annotation The annotation to set.
+ */
+ public void setAnnotation(String annotation)
+ {
+ this.annotation = annotation;
+ }
+
+ /**
+ * @return Returns the categories.
+ */
+ public List getCategories()
+ {
+ return this.categories;
+ }
+
+ /**
+ * @param categories The categories to set.
+ */
+ public void setCategories(List categories)
+ {
+ this.categories = categories;
+ }
+
+ public void addCategory(String cat)
+ {
+ if (categories == null) categories = new ArrayList();
+ categories.add(cat);
+ }
+
+ /**
+ * Pretty output.
+ */
+ public String toString()
+ {
+ StringBuffer buf = new StringBuffer("<entry xmlns=\"" + Atom4J.xmlns + "\" >\n");
+
+ if (getId() != null) buf.append(" ").append(Atom4J.simpleTag(getId(), "id"));
+ if (getTitle() != null) buf.append(" ").append(getTitle().toString("title"));
+ if (getSummary() != null) buf.append(" ").append(getSummary().toString("summary"));
+
+ // generate Author and Contributor tags
+ if (getAuthor() != null)
+ {
+ buf.append(" ").append(getAuthor().toString("author"));
+ }
+ if (getContributors() != null)
+ {
+ java.util.Iterator it = getContributors().iterator();
+ while (it.hasNext())
+ {
+ Person _person = (Person)it.next();
+ buf.append(" ").append(_person.toString("contributor"));
+ }
+ }
+
+ if (getLinks() != null)
+ {
+ java.util.Iterator it = getLinks().iterator();
+ while (it.hasNext())
+ {
+ Link _link = (Link)it.next();
+ buf.append(" ").append(_link.toString());
+ }
+ }
+
+ // generate date tags
+ if (getIssued() != null)
+ buf.append(" ").append(Atom4J.dateTag(getIssued(), "issued"));
+ if (getCreated() != null)
+ buf.append(" ").append(Atom4J.dateTag(getCreated(), "created"));
+ if (getModified() != null)
+ buf.append(" ").append(Atom4J.dateTag(getModified(), "modified"));
+
+ // generate Content
+ buf.append(" ").append(getContent().toString("content"));
+
+ // custom fields
+ if (annotation != null) buf.append(" ").append(Atom4J.simpleTag(annotation, "annotation"));
+ if (categories != null)
+ {
+ java.util.Iterator it = categories.iterator();
+ while (it.hasNext())
+ {
+ buf.append(" ").append(Atom4J.simpleTag(it.next(), "subject"));
+ }
+ }
+
+ // close entry
+ buf.append("</entry>\n");
+
+ return buf.toString();
+ }
+}