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 [9/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/business/RefererManagerImpl.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/business/RefererManagerImpl.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/business/RefererManagerImpl.java (added)
+++ incubator/roller/trunk/src/org/roller/business/RefererManagerImpl.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,523 @@
+package org.roller.business;
+
+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.RefererManager;
+import org.roller.model.Roller;
+import org.roller.pojos.RefererData;
+import org.roller.pojos.WeblogEntryData;
+import org.roller.pojos.WebsiteData;
+import org.roller.util.DateUtil;
+import org.roller.util.LinkbackExtractor;
+import org.roller.util.ThreadManager;
+import org.roller.util.Utilities;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+
+/**
+ * Abstract base implementation using PersistenceStrategy.
+ * @author Dave Johnson
+ * @author Lance Lavandowska
+ */
+public abstract class RefererManagerImpl implements RefererManager
+{
+ static Log mLogger =
+ LogFactory.getFactory().getInstance(RefererManagerImpl.class);
+
+ protected static final String DAYHITS = "dayHits";
+ protected static final String TOTALHITS = "totalHits";
+
+ protected PersistenceStrategy mStrategy;
+ protected Roller mRoller = null;
+ protected ThreadManager mThreadManager;
+ protected Date mRefDate = new Date();
+ protected SimpleDateFormat mDateFormat = DateUtil.get8charDateFormat();
+
+ protected abstract List getReferersWithSameTitle(
+ WebsiteData website,
+ String requestUrl,
+ String title,
+ String excerpt)
+ throws RollerException;
+
+ protected abstract List getExistingReferers(
+ WebsiteData website,
+ String dateString,
+ String permalink) throws RollerException;
+
+ protected abstract List getReferersToWebsite(
+ WebsiteData website,
+ String refererUrl) throws RollerException;
+
+ protected abstract List getMatchingReferers(
+ WebsiteData website,
+ String requestUrl,
+ String refererUrl) throws RollerException;
+
+ //-----------------------------------------------------------------------
+
+ public RefererManagerImpl(Roller roller)
+ {
+ mRoller = roller;
+ }
+
+ //-----------------------------------------------------------------------
+
+ protected abstract int getHits(WebsiteData website, String type)
+ throws RollerException;
+
+ //-----------------------------------------------------------------------
+
+ //------------------------------------------------------------------------
+
+ public void release()
+ {
+ }
+
+ //-----------------------------------------------------------------------
+ public synchronized void forceTurnover(String websiteId) throws RollerException
+ {
+ mLogger.debug("forceTurnover");
+ checkForTurnover(true, websiteId);
+ }
+
+ //--------------------------------------------------------- Get hit counts
+
+ public int getDayHits(WebsiteData website) throws RollerException
+ {
+ return getHits(website, DAYHITS);
+ }
+
+ //-----------------------------------------------------------------------
+
+ public int getTotalHits(WebsiteData website) throws RollerException
+ {
+ return getHits(website, TOTALHITS);
+ }
+
+
+ //------------------------------------------------------- Referer Storage
+
+ /**
+ * @see org.roller.pojos.RefererManager#removeReferer(java.lang.String)
+ */
+ public void removeReferer(String id) throws RollerException
+ {
+ mStrategy.remove(id, RefererData.class);
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * @see org.roller.pojos.RefererManager#retrieveReferer(java.lang.String)
+ */
+ public RefererData retrieveReferer(String id) throws RollerException
+ {
+ return (RefererData)mStrategy.load(id,RefererData.class);
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * @see org.roller.pojos.RefererManager#storeReferer(
+ * org.roller.pojos.RefererData)
+ */
+ public void storeReferer(RefererData data) throws RollerException
+ {
+ mStrategy.store(data);
+ }
+
+ //-----------------------------------------------------------------------
+ public List getEntryReferers(String entryId, boolean authorized)
+ throws RollerException
+ {
+ //TODO: Redesign this so this is performed using the DB query, and
+ // not in java code for perf/memory reasons
+ List authorizedvisible = new ArrayList();
+ List referers = getReferersToEntry(entryId);
+ for (Iterator rItr = referers.iterator(); rItr.hasNext();)
+ {
+ RefererData referer = (RefererData) rItr.next();
+ if ( referer.getVisible().booleanValue() || authorized )
+ {
+ authorizedvisible.add( referer );
+ }
+ }
+
+ return authorizedvisible;
+ }
+
+ //------------------------------------------------------------------------
+
+ /**
+ * Process incoming request for referer information.
+ *
+ * <p>If there is no referer, treat it as a direct request.</p>
+ *
+ * <p>If there is a referer and there is no record for that referer, then
+ * parse the refering page for title and excerpt surround the refering link.
+ * If the excerpt cannot be found, then ignore the referer because it is
+ * fake - probably a referer spam.
+ * </p>
+ *
+ * @see org.roller.pojos.RefererManager#processReferer(
+ * java.lang.String, java.lang.String)
+ */
+ public void processRequest( ParsedRequest request )
+ {
+ String msg = "processRequest";
+ if ( request.getWebsite()==null ) return;
+
+ try
+ {
+ List matchRef = null;
+
+ String requestUrl = request.getRequestURL();
+ String refererUrl = request.getRefererURL();
+ WebsiteData website = request.getWebsite();
+ WeblogEntryData entry = request.getWeblogEntry();
+ String selfSiteFragment = "/page/" + website.getUser().getUserName();
+
+ String dateString = null;
+ if ( request.getDateString()!=null && request.isDateSpecified())
+ {
+ dateString = request.getDateString();
+ }
+
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug( msg+": refurl="+refererUrl );
+ }
+
+ if ( refererUrl != null )
+ {
+ // If referer URL contains ignoreWords then don't log it.
+ String[] ignoreWords = new String[0];
+ if ( website.getIgnoreWords() != null )
+ {
+ ignoreWords = Utilities.stringToStringArray(
+ website.getIgnoreWords(),",");
+ }
+ for (int i = 0; i < ignoreWords.length; i++)
+ {
+ if (refererUrl.indexOf(ignoreWords[i].trim()) != -1)
+ {
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("Ignoring due to :"+ignoreWords[i]);
+ }
+ refererUrl = null;
+ return;
+ }
+ }
+
+ // treat own URL as direct
+ if (refererUrl != null && refererUrl.indexOf(selfSiteFragment) != -1)
+ {
+ refererUrl = null;
+ }
+ }
+
+ if (refererUrl == null || refererUrl.trim().length() < 8)
+ {
+ refererUrl = "direct";
+
+ // Get referer specified by referer URL of direct
+ matchRef = getReferersToWebsite(website, refererUrl);
+ }
+ else
+ {
+ refererUrl = Utilities.stripJsessionId(refererUrl);
+
+ // Query for referer with same referer and request URLs
+ matchRef = getMatchingReferers(website, requestUrl, refererUrl);
+
+ // If referer was not found, try adding or leaving off 'www'
+ if ( matchRef.size() == 0 )
+ {
+ String secondTryUrl = null;
+ if ( refererUrl.startsWith("http://www") )
+ {
+ secondTryUrl = "http://"+refererUrl.substring(11);
+ }
+ else
+ {
+ secondTryUrl = "http://www"+refererUrl.substring(7);
+ }
+
+ matchRef = getMatchingReferers(
+ website, requestUrl, secondTryUrl);
+ if ( matchRef.size() == 1 )
+ {
+ refererUrl = secondTryUrl;
+ }
+ }
+ }
+
+ if (matchRef.size() == 1)
+ {
+ // Referer was found in database, so bump up hit count
+ RefererData ref = (RefererData)matchRef.get(0);
+
+ ref.setDayHits(
+ new Integer(ref.getDayHits().intValue() + 1));
+ ref.setTotalHits(
+ new Integer(ref.getTotalHits().intValue() + 1));
+
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug(
+ "Incrementing hit count on existing referer: "+refererUrl);
+ }
+
+ storeReferer(ref);
+ mStrategy.commit();
+ }
+ else if (matchRef.size() == 0)
+ {
+ // Referer was not found in database, so new Referer object
+ Integer one = new Integer(1);
+ RefererData ref =
+ new RefererData(
+ null,
+ website,
+ entry,
+ dateString,
+ refererUrl,
+ null,
+ requestUrl,
+ null,
+ null,
+ Boolean.FALSE,
+ Boolean.FALSE,
+ one,
+ one);
+
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("newReferer="+ref.getRefererUrl());
+ }
+
+ String refurl = ref.getRefererUrl();
+
+ // If not a direct or search engine then search for linkback
+ if ( request.isEnableLinkback()
+ && request.isDateSpecified()
+ && !refurl.equals("direct")
+ && !refurl.startsWith("http://google")
+ && !refurl.startsWith("http://www.google")
+ && !refurl.startsWith("http://search.netscape")
+ && !refurl.startsWith("http://www.blinkpro")
+ && !refurl.startsWith("http://auto.search.msn")
+ && !refurl.startsWith("http://search.yahoo")
+ && !refurl.startsWith("http://uk.search.yahoo")
+ && !refurl.startsWith("http://www.javablogs.com")
+ && !refurl.startsWith("http://www.teoma")
+ )
+ {
+ // Launch thread to extract referer linkback
+
+ try
+ {
+ if (mThreadManager!=null)
+ {
+ mThreadManager.executeInBackground( new LinkbackExtractorRunnable(ref) );
+ }
+ else
+ {
+ mLogger.warn("No thread manager found.");
+ }
+ } catch (InterruptedException e) {
+ mLogger.warn("Interrupted during linkback extraction",e);
+ }
+ }
+ else
+ {
+ storeReferer(ref);
+ mStrategy.commit();
+ }
+ }
+ }
+ catch (RollerException pe)
+ {
+ mLogger.error(msg, pe);
+ }
+ catch (NullPointerException npe)
+ {
+ mLogger.error(msg, npe);
+ }
+
+ }
+
+ /**
+ * Use LinkbackExtractor to parse title and excerpt from referer
+ */
+ class LinkbackExtractorRunnable implements Runnable
+ {
+
+ private RefererData mReferer = null;
+
+ public LinkbackExtractorRunnable( RefererData referer)
+ {
+ mReferer = referer;
+ }
+
+ public void run()
+ {
+
+ try
+ {
+ LinkbackExtractor lb = new LinkbackExtractor(
+ mReferer.getRefererUrl(),mReferer.getRequestUrl());
+
+ if ( lb.getTitle()!=null && lb.getExcerpt()!=null )
+ {
+ mReferer.setTitle(lb.getTitle());
+ mReferer.setExcerpt(lb.getExcerpt());
+
+
+ if ( lb.getPermalink() != null )
+ {
+ // The presence of a permalink indicates that this
+ // linkback was parsed out of an RSS feed and is
+ // presumed to be a good linkback.
+
+ mReferer.setRefererPermalink(lb.getPermalink());
+
+ // See if this request/permalink is in the DB
+ List matchRef = getExistingReferers(
+ mReferer.getWebsite(),
+ mReferer.getDateString(),
+ mReferer.getRefererPermalink());
+
+ // If it is the first, then set it to be visible
+ if ( matchRef.size() == 0 )
+ {
+ mReferer.setVisible(Boolean.TRUE);
+ }
+ else
+ {
+ // We can't throw away duplicates or we will
+ // end up reparsing them everytime a hit comes
+ // in from one of them, but we can mark them
+ // as duplicates.
+ mReferer.setDuplicate(Boolean.TRUE);
+ }
+
+ storeReferer(mReferer);
+ }
+
+ else
+ {
+ // Store the new referer
+ storeReferer(mReferer);
+
+ // Hacky Referer URL weighting kludge:
+ //
+ // If there are multple referers to a request URL,
+ // then we want to pick the best one. The others
+ // are marked as duplicates. To do this we use a
+ // weight. The weight formula is:
+ //
+ // w = URL length + (100 if URL contains anchor)
+
+ // LOOP: find the referer with the highest weight
+ Boolean visible = Boolean.FALSE;
+ List refs= getReferersWithSameTitle(
+ mReferer.getWebsite(),
+ mReferer.getRequestUrl(),
+ lb.getTitle(),
+ lb.getExcerpt());
+ RefererData chosen = null;
+ int maxweight = 0;
+ for (Iterator rdItr = refs.iterator();rdItr.hasNext();)
+ {
+ RefererData referer = (RefererData) rdItr.next();
+
+ int weight = referer.getRefererUrl().length();
+ if (referer.getRefererUrl().indexOf('#') != -1)
+ {
+ weight += 100;
+ }
+
+ if ( weight > maxweight )
+ {
+ chosen = referer;
+ maxweight = weight;
+ }
+
+ if (referer.getVisible().booleanValue())
+ {
+ // If any are visible then chosen
+ // replacement must be visible as well.
+ visible = Boolean.TRUE;
+ }
+
+ }
+
+ // LOOP: to mark all of the lower weight ones
+ // as duplicates
+ for (Iterator rdItr = refs.iterator();rdItr.hasNext();) {
+ RefererData referer = (RefererData) rdItr.next();
+
+ if (referer != chosen)
+ {
+ referer.setDuplicate(Boolean.TRUE);
+ }
+ else
+ {
+ referer.setDuplicate(Boolean.FALSE);
+ referer.setVisible(visible);
+ }
+ storeReferer(referer);
+ }
+
+
+ }
+ }
+ else
+ {
+ // It is not a linkback, but store it anyway
+ storeReferer(mReferer);
+
+ mLogger.info("No excerpt found at refering URL "
+ + mReferer.getRefererUrl());
+ }
+ }
+ catch (Exception e)
+ {
+ mLogger.error("Processing linkback",e);
+ }
+ finally
+ {
+ try {
+ mStrategy.release();
+ }
+ catch (RollerException e) {
+ mLogger.error(
+ "Exception logged by ManagerSupport.releaseDatabase()");
+ }
+ }
+
+ }
+
+ }
+
+ /**
+ * @see org.roller.model.RefererManager#setThreadManager(org.roller.ThreadManager)
+ */
+ public void setThreadManager(ThreadManager threadManager)
+ {
+ mThreadManager = threadManager;
+ }
+
+}
+
+
Added: incubator/roller/trunk/src/org/roller/business/UserManagerImpl.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/business/UserManagerImpl.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/business/UserManagerImpl.java (added)
+++ incubator/roller/trunk/src/org/roller/business/UserManagerImpl.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,397 @@
+/*
+ * Created on Aug 13, 2003
+ */
+package org.roller.business;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.roller.RollerException;
+import org.roller.model.BookmarkManager;
+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.RoleData;
+import org.roller.pojos.UserCookie;
+import org.roller.pojos.UserData;
+import org.roller.pojos.WeblogCategoryData;
+import org.roller.pojos.WebsiteData;
+import org.roller.util.RandomGUID;
+import org.roller.util.Utilities;
+
+import java.io.IOException;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Abstract base implementation using PersistenceStrategy.
+ * @author Dave Johnson
+ * @author Lance Lavandowska
+ */
+public abstract class UserManagerImpl implements UserManager
+{
+ protected PersistenceStrategy mStrategy;
+ protected Roller mRoller;
+
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(UserManagerImpl.class);
+
+ public UserManagerImpl(PersistenceStrategy strategy, Roller roller)
+ {
+ mStrategy = strategy;
+ mRoller = roller;
+ }
+
+ public void release()
+ {
+ }
+
+ //--------------------------------------------------------------- Website
+
+ public WebsiteData retrieveWebsite(String id) throws RollerException
+ {
+ return (WebsiteData)mStrategy.load(id,WebsiteData.class);
+ }
+
+ /**
+ * @see org.roller.model.UserManager#storeWebsite(org.roller.pojos.WebsiteData)
+ */
+ public void storeWebsite(WebsiteData data) throws RollerException
+ {
+ mStrategy.store(data);
+ }
+
+ public void removeWebsite(String id) throws RollerException
+ {
+ mStrategy.remove(id,WebsiteData.class);
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ /**
+ * This method is a hotspot, it is called on every page request.
+ */
+ public WebsiteData getWebsite(String userName) throws RollerException
+ {
+ return getWebsite(userName, true);
+ }
+
+ //------------------------------------------------------------------- User
+
+ public UserData retrieveUser(String id) throws RollerException
+ {
+ return (UserData)mStrategy.load(id,UserData.class);
+ }
+
+ public void storeUser(UserData data) throws RollerException
+ {
+ mStrategy.store(data);
+ }
+
+ public void removeUser(String id) throws RollerException
+ {
+ mStrategy.remove(id,UserData.class);
+ }
+
+ //-----------------------------------------------------------------------
+
+ public UserData getUser(String userName) throws RollerException
+ {
+ return getUser(userName, true);
+ }
+
+ // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+ public UserData getUser(String userName, boolean enabledOnly) throws RollerException
+ {
+ if (userName==null )
+ throw new RollerException("userName is null");
+
+ WebsiteData website = getWebsite(userName, enabledOnly);
+ if (website != null)
+ {
+ return website.getUser();
+ }
+ return null;
+ }
+
+ //-----------------------------------------------------------------------
+
+ public List getUsers() throws RollerException
+ {
+ return getUsers(true);
+ }
+
+ //------------------------------------------------------------------------
+ /**
+ * @see org.roller.model.UserManager#retrievePage(java.lang.String)
+ */
+ public PageData retrievePageReadOnly(String id) throws RollerException
+ {
+ // Don't hit database for templates stored on disk
+ if (id != null && id.endsWith(".vm")) return null;
+
+ // Hibernate has a read-only flag: LockMode.READ
+ return (PageData)mStrategy.load(id,PageData.class);
+ }
+
+ //------------------------------------------------------------------- Role
+
+ public RoleData retrieveRole(String id) throws RollerException
+ {
+ return (RoleData)mStrategy.load(id,RoleData.class);
+ }
+
+ public void storeRole(RoleData data) throws RollerException
+ {
+ mStrategy.store(data);
+ }
+
+ public void removeRole(String id) throws RollerException
+ {
+ mStrategy.remove(id,RoleData.class);
+ }
+
+ //------------------------------------------------------------------- Page
+
+ public PageData retrievePage(String id) throws RollerException
+ {
+ // Don't hit database for templates stored on disk
+ if (id != null && id.endsWith(".vm")) return null;
+
+ return (PageData)mStrategy.load(id,PageData.class);
+ }
+
+ public void removePage(String id) throws RollerException
+ {
+ mStrategy.remove(id,PageData.class);
+ }
+
+ /**
+ * @see org.roller.model.UserManager#storePage(org.roller.pojos.PageData)
+ */
+ public void storePage(PageData data) throws RollerException
+ {
+ mStrategy.store(data);
+ }
+
+ public String fixPageLink(PageData data) throws RollerException
+ {
+ String link = Utilities.removeHTML(data.getName());
+ link = Utilities.removeNonAlphanumeric(link);
+
+ data.setLink(link);
+ mStrategy.store( data );
+
+ return link;
+ }
+
+ /**
+ * Add a new Roller user. Store new User, Role, Website, Category, and a
+ * "first post" WeblogEntry in the database. Reads in files from a theme
+ * directory and adds them as Pages for the User's new Website.
+ *
+ * @param ud User object representing the new user.
+ * @param themeDir Directory containing the theme for this user
+ */
+ public void addUser(UserData ud, Map pages, String theme,
+ String locale, String timezone)
+ throws RollerException
+ {
+ UserManager umgr = mRoller.getUserManager();
+ WeblogManager wmgr = mRoller.getWeblogManager();
+ if ( umgr.getUser(ud.getUserName()) != null
+ || umgr.getUser(ud.getUserName().toLowerCase()) != null)
+ {
+ throw new RollerException("error.add.user.userNameInUse");
+ }
+
+ mStrategy.store(ud);
+
+ RoleData rd = new RoleData(
+ null,ud.getUserName(),ud.getId(),"editor");
+ mStrategy.store(rd);
+
+ //
+ // CREATE WEBSITE AND CATEGORIES FOR USER
+ //
+
+ WebsiteData website = new WebsiteData(null,
+ ud.getFullName()+"'s Weblog", // name
+ ud.getFullName()+"'s Weblog", // description
+ ud, // userId
+ "dummy", // defaultPageId
+ "dummy", // weblogDayPageId
+ Boolean.TRUE, // enableBloggerApi
+ null, // bloggerCategory
+ null, // defaultCategory
+ "editor-text.jsp", // editorPage
+ "", // ignoreWords
+ Boolean.TRUE, // allowComments
+ Boolean.FALSE, // emailComments
+ "", // emailFromAddress
+ Boolean.TRUE); // isEnabled
+ website.setEditorTheme(theme);
+ website.setLocale(locale);
+ website.setTimezone(timezone);
+ website.save();
+
+ WeblogCategoryData rootCat = wmgr.createWeblogCategory(
+ website, // websiteId
+ null, // parent
+ "root", // name
+ "root", // description
+ null ); // image
+ rootCat.save();
+
+ WeblogCategoryData generalCat = wmgr.createWeblogCategory(
+ website, // websiteId
+ rootCat,
+ "General", // name
+ "General", // description
+ null ); // image
+ generalCat.save();
+
+ WeblogCategoryData javaCat = wmgr.createWeblogCategory(
+ website, // websiteId
+ rootCat,
+ "Java", // name
+ "Java", // description
+ null ); // image
+ javaCat.save();
+
+ WeblogCategoryData musicCat = wmgr.createWeblogCategory(
+ website, // websiteId
+ rootCat,
+ "Music", // name
+ "Music", // description
+ null ); // image
+ musicCat.save();
+
+ website.setBloggerCategory(rootCat);
+ website.setDefaultCategory(rootCat);
+
+ Integer zero = new Integer(0);
+
+ BookmarkManager bmgr = mRoller.getBookmarkManager();
+
+ FolderData root = bmgr.createFolder(
+ null, "root", "root", website);
+ root.save();
+
+ FolderData blogroll = bmgr.createFolder(
+ root, "Blogroll", "Blogroll", website);
+ blogroll.save();
+
+ BookmarkData b1 = bmgr.createBookmark(
+ blogroll, "Dave Johnson", "",
+ "http://rollerweblogger.org/page/roller",
+ "http://rollerweblogger.org/rss/roller",
+ zero, zero, null);
+ b1.save();
+
+ BookmarkData b2 = bmgr.createBookmark(
+ blogroll, "Matt Raible", "",
+ "http://raibledesigns.com/page/rd",
+ "http://raibledesigns.com/rss/rd",
+ zero, zero, null);
+ b2.save();
+
+ BookmarkData b3 = bmgr.createBookmark(
+ blogroll, "Lance Lavandowska", "",
+ "http://brainopolis.dnsalias.com/roller/page/lance/",
+ "http://brainopolis.dnsalias.com/roller/rss/lance/",
+ zero, zero, null);
+ b3.save();
+
+
+ FolderData news = bmgr.createFolder(
+ root, "News", "News", website);
+ news.save();
+
+ BookmarkData b5 = bmgr.createBookmark(
+ news, "CNN", "",
+ "http://www.cnn.com",
+ "",
+ zero, zero, null);
+ b5.save();
+
+ BookmarkData b6 = bmgr.createBookmark(
+ news, "NY Times", "",
+ "http://nytimes.com",
+ "",
+ zero, zero, null);
+ b6.save();
+
+
+ //
+ // READ THEME FILES AND CREATE PAGES FOR USER
+ //
+ Iterator iter = pages.keySet().iterator();
+ while ( iter.hasNext() )
+ {
+ String pageName = (String) iter.next();
+ String sb = (String)pages.get( pageName );
+
+ // Store each Velocity template as a page
+ PageData pd = new PageData( null,
+ website, // website
+ pageName, // name
+ pageName, // description
+ pageName, // link
+ sb, // template
+ new Date() // updateTime
+ );
+ mStrategy.store(pd);
+
+ if ( pd.getName().equals("Weblog") )
+ {
+ website.setDefaultPageId(pd.getId());
+ }
+ else if ( pd.getName().equals("_day") )
+ {
+ website.setWeblogDayPageId(pd.getId());
+ }
+ }
+
+ // Save website with blogger cat id, defauld page id and day id
+ mStrategy.store(website);
+ }
+
+ /**
+ * @see org.roller.model.UserManager#createLoginCookie(java.lang.String)
+ */
+ public String createLoginCookie(String username) throws RollerException
+ {
+ UserCookie cookie = new UserCookie();
+ cookie.setUsername(username);
+
+ return saveLoginCookie(cookie);
+ }
+
+ /**
+ * Convenience method to set a unique cookie id and save to database
+ *
+ * @param cookie
+ * @return
+ * @throws Exception
+ */
+ protected String saveLoginCookie(UserCookie cookie) throws RollerException
+ {
+ cookie.setCookieId(new RandomGUID().toString());
+ cookie.save();
+
+ String cookieString = null;
+ try {
+ cookieString = Utilities.encodeString(cookie.getUsername() + "|" +
+ cookie.getCookieId());
+ } catch (IOException io) {
+ mLogger.warn("Failed to encode rememberMe cookieString");
+ mLogger.warn(io.getMessage());
+ cookieString = cookie.getUsername() + "|" + cookie.getCookieId();
+ }
+ return cookieString;
+ }
+}
Added: incubator/roller/trunk/src/org/roller/business/WeblogManagerImpl.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/business/WeblogManagerImpl.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/business/WeblogManagerImpl.java (added)
+++ incubator/roller/trunk/src/org/roller/business/WeblogManagerImpl.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,444 @@
+/*
+ * Created on Feb 24, 2003
+ */
+package org.roller.business;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.roller.RollerException;
+import org.roller.model.Roller;
+import org.roller.model.WeblogManager;
+import org.roller.pojos.CommentData;
+import org.roller.pojos.UserData;
+import org.roller.pojos.WeblogCategoryAssoc;
+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.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Comparator;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Abstract base implementation using PersistenceStrategy.
+ * @author Dave Johnson
+ * @author Lance Lavandowska
+ */
+public abstract class WeblogManagerImpl implements WeblogManager
+{
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(WeblogManagerImpl.class);
+
+ protected Roller mRoller;
+ protected PersistenceStrategy mStrategy;
+ private Comparator reverseComparator = new ReverseComparator();
+ private SimpleDateFormat formatter = DateUtil.get8charDateFormat();
+
+ public abstract List getWeblogEntries(
+ WebsiteData website,
+ Date startDate,
+ Date endDate,
+ String catName,
+ String status,
+ Integer maxEntries,
+ Boolean pinned) throws RollerException;
+
+ public abstract WeblogEntryData getNextPrevEntry(
+ WeblogEntryData current,
+ String catName,
+ boolean next) throws RollerException;
+
+ public WeblogManagerImpl(PersistenceStrategy strategy, Roller roller)
+ {
+ mStrategy = strategy;
+ mRoller = roller;
+ }
+
+ class ReverseComparator implements Comparator
+ {
+ public int compare(Object o1, Object o2)
+ {
+ return -1 * ((Date) o1).compareTo((Date)o2);
+ }
+ public boolean equals(Object obj)
+ {
+ return false;
+ }
+ }
+
+ public void release()
+ {
+ }
+
+ //------------------------------------------------ WeblogCategoryData CRUD
+
+ /**
+ * @see org.roller.model.WeblogManager#createWeblogCategory()
+ */
+ public WeblogCategoryData createWeblogCategory()
+ {
+ return new WeblogCategoryData();
+ }
+
+ /**
+ * @see org.roller.model.WeblogManager#createWeblogCategory(
+ * org.roller.pojos.WebsiteData, org.roller.pojos.WeblogCategoryData,
+ * java.lang.String, java.lang.String, java.lang.String)
+ */
+ public WeblogCategoryData createWeblogCategory(
+ WebsiteData website,
+ WeblogCategoryData parent,
+ String name,
+ String description,
+ String image) throws RollerException
+ {
+ return new WeblogCategoryData(
+ null, website, parent, name, description, image);
+ }
+
+ public WeblogCategoryData retrieveWeblogCategory(String id)
+ throws RollerException
+ {
+ return (WeblogCategoryData) mStrategy.load(
+ id,
+ WeblogCategoryData.class);
+ }
+
+ //--------------------------------------------- WeblogCategoryData Queries
+
+ public WeblogCategoryData getWeblogCategoryByPath(
+ WebsiteData website, String categoryPath) throws RollerException
+ {
+ return getWeblogCategoryByPath(website, null, categoryPath);
+ }
+
+ public String getPath(WeblogCategoryData category) throws RollerException
+ {
+ if (null == category.getParent())
+ {
+ return new String("/");
+ }
+ else
+ {
+ String parentPath = getPath(category.getParent());
+ parentPath = "/".equals(parentPath) ? "" : parentPath;
+ return parentPath + "/" + category.getName();
+ }
+ }
+
+ public WeblogCategoryData getWeblogCategoryByPath(
+ WebsiteData website, WeblogCategoryData category, String path)
+ throws RollerException
+ {
+ final Iterator cats;
+ final String[] pathArray = Utilities.stringToStringArray(path, "/");
+
+ if (category == null && (null == path || "".equals(path.trim())))
+ {
+ throw new RollerException("Bad arguments.");
+ }
+
+ if (path.trim().equals("/"))
+ {
+ return getRootWeblogCategory(website);
+ }
+ else if (category == null || path.trim().startsWith("/"))
+ {
+ cats = getRootWeblogCategory(website).getWeblogCategories().iterator();
+ }
+ else
+ {
+ cats = category.getWeblogCategories().iterator();
+ }
+
+ while (cats.hasNext())
+ {
+ WeblogCategoryData possibleMatch = (WeblogCategoryData)cats.next();
+ if (possibleMatch.getName().equals(pathArray[0]))
+ {
+ if (pathArray.length == 1)
+ {
+ return possibleMatch;
+ }
+ else
+ {
+ String[] subpath = new String[pathArray.length - 1];
+ System.arraycopy(pathArray, 1, subpath, 0, subpath.length);
+
+ String pathString= Utilities.stringArrayToString(subpath,"/");
+ return getWeblogCategoryByPath(website, possibleMatch, pathString);
+ }
+ }
+ }
+
+ // The category did not match and neither did any sub-categories
+ return null;
+ }
+
+ //----------------------------------------------- WeblogCategoryAssoc CRUD
+
+ public WeblogCategoryAssoc createWeblogCategoryAssoc()
+ {
+ return new WeblogCategoryAssoc();
+ }
+
+ public WeblogCategoryAssoc createWeblogCategoryAssoc(
+ WeblogCategoryData category,
+ WeblogCategoryData ancestor,
+ String relation) throws RollerException
+ {
+ return new WeblogCategoryAssoc(null, category, ancestor, relation);
+ }
+
+ public WeblogCategoryAssoc retrieveWeblogCategoryAssoc(String id) throws RollerException
+ {
+ return (WeblogCategoryAssoc)mStrategy.load(id, WeblogCategoryAssoc.class);
+ }
+
+ //------------------------------------------------------- CommentData CRUD
+
+ public void removeComment(String id) throws RollerException
+ {
+ mStrategy.remove(id, CommentData.class);
+ }
+
+ public void removeComments(String[] ids) throws RollerException
+ {
+ for (int i = 0; i < ids.length; i++)
+ {
+ removeComment(ids[i]);
+ }
+ }
+
+ public void removeCommentsForEntry(String entryId) throws RollerException
+ {
+ List comments = getComments(entryId, false); // get all Comments
+ Iterator it = comments.iterator();
+ while (it.hasNext())
+ {
+ removeComment( ((CommentData)it.next()).getId() );
+ }
+ }
+
+ //---------------------------------------------------- CommentData Queries
+
+ public CommentData retrieveComment(String id) throws RollerException
+ {
+ return (CommentData) mStrategy.load(id, CommentData.class);
+ }
+
+ public List getComments(String entryId) throws RollerException
+ {
+ return getComments(entryId, true);
+ }
+
+ //--------------------------------------------------- WeblogEntryData CRUD
+
+ public WeblogEntryData retrieveWeblogEntry(String id)
+ throws RollerException
+ {
+ return (WeblogEntryData) mStrategy.load(
+ id, WeblogEntryData.class);
+ }
+
+ public void removeWeblogEntry(String id) throws RollerException
+ {
+ mRoller.getRefererManager().removeReferersForEntry(id);
+ removeCommentsForEntry( id );
+ mStrategy.remove(id, WeblogEntryData.class);
+ }
+
+ //------------------------------------------------ WeblogEntryData Queries
+
+ /**
+ * Gets the Date of the latest Entry publish time, before the end of today,
+ * for all WeblogEntries
+ *
+ * @param userName
+ * @return Date
+ * @throws RollerException
+ */
+ public Date getWeblogLastPublishTime(String userName)
+ throws RollerException
+ {
+ return getWeblogLastPublishTime(userName, null);
+ }
+
+ //--------------------------------------------------------- Implementation
+
+ /**
+ * @see org.roller.model.WeblogManager#getWeblogEntries(
+ * java.lang.String,
+ * java.util.Date,
+ * java.util.Date,
+ * java.lang.String,
+ * java.lang.String,
+ * java.lang.Integer)
+ */
+ public List getWeblogEntries(
+ WebsiteData website,
+ Date startDate,
+ Date endDate,
+ String catName,
+ String status,
+ Integer maxEntries) throws RollerException
+ {
+ return getWeblogEntries(
+ website,
+ startDate,
+ endDate,
+ catName,
+ status,
+ maxEntries,
+ null);
+ }
+
+ /**
+ * @see org.roller.model.WeblogManager#getWeblogEntryDayMap(
+ * java.lang.String,
+ * java.util.Date,
+ * java.util.Date,
+ * java.lang.String,
+ * java.lang.String,
+ * java.lang.Integer)
+ */
+ public Map getWeblogEntryObjectMap(
+ WebsiteData website,
+ Date startDate,
+ Date endDate,
+ String catName,
+ String status,
+ Integer maxEntries) throws RollerException
+ {
+ return getWeblogEntryMap(
+ website,
+ startDate,
+ endDate,
+ catName,
+ status,
+ maxEntries,
+ false);
+ }
+
+ /**
+ * @see org.roller.model.WeblogManager#getWeblogEntryDayMap(
+ * java.lang.String,
+ * java.util.Date,
+ * java.util.Date,
+ * java.lang.String,
+ * java.lang.String,
+ * java.lang.Integer)
+ */
+ public Map getWeblogEntryStringMap(
+ WebsiteData website,
+ Date startDate,
+ Date endDate,
+ String catName,
+ String status,
+ Integer maxEntries) throws RollerException
+ {
+ return getWeblogEntryMap(
+ website,
+ startDate,
+ endDate,
+ catName,
+ status,
+ maxEntries,
+ true);
+ }
+
+ private Map getWeblogEntryMap(
+ WebsiteData website,
+ Date startDate,
+ Date endDate,
+ String catName,
+ String status,
+ Integer maxEntries,
+ boolean stringsOnly) throws RollerException
+ {
+ TreeMap map = new TreeMap(reverseComparator);
+
+ List entries = getWeblogEntries(
+ website,
+ startDate,
+ endDate,
+ catName,
+ status,
+ maxEntries);
+
+ Calendar cal = Calendar.getInstance();
+ if (website != null)
+ {
+ cal.setTimeZone(website.getTimeZoneInstance());
+ }
+
+ for (Iterator wbItr = entries.iterator(); wbItr.hasNext();)
+ {
+ WeblogEntryData entry = (WeblogEntryData) wbItr.next();
+ Date sDate = DateUtil.getNoonOfDay(entry.getPubTime(), cal);
+ if (stringsOnly)
+ {
+ if (map.get(sDate) == null)
+ map.put(sDate, formatter.format(sDate));
+ }
+ else
+ {
+ List dayEntries = (List) map.get(sDate);
+ if (dayEntries == null)
+ {
+ dayEntries = new ArrayList();
+ map.put(sDate, dayEntries);
+ }
+ dayEntries.add(entry);
+ }
+ }
+ return map;
+ }
+
+ /*
+ * @see org.roller.model.WeblogManager#getNextEntry(org.roller.pojos.WeblogEntryData)
+ */
+ public WeblogEntryData getNextEntry(WeblogEntryData current, String catName)
+ throws RollerException
+ {
+ return getNextPrevEntry(current, catName, true);
+ }
+
+ /*
+ * @see org.roller.model.WeblogManager#getPreviousEntry(org.roller.pojos.WeblogEntryData)
+ */
+ public WeblogEntryData getPreviousEntry(WeblogEntryData current, String catName)
+ throws RollerException
+ {
+ return getNextPrevEntry(current, catName, false);
+ }
+
+ /**
+ * @see org.roller.model.WeblogManager#getWeblogEntriesPinnedToMain(int)
+ */
+ public List getWeblogEntriesPinnedToMain(Integer max) throws RollerException
+ {
+ return getWeblogEntries(
+ null, null, new Date(), null, null, max, Boolean.TRUE);
+ }
+
+ /**
+ * Get absolute URL to this website.
+ * @return Absolute URL to this website.
+ */
+ public String getUrl(UserData user, String contextUrl)
+ {
+ String url =
+ Utilities.escapeHTML(contextUrl + "/page/" + user.getUserName());
+ return url;
+ }
+
+}
Added: incubator/roller/trunk/src/org/roller/business/hibernate/HibernateBookmarkManagerImpl.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/business/hibernate/HibernateBookmarkManagerImpl.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/business/hibernate/HibernateBookmarkManagerImpl.java (added)
+++ incubator/roller/trunk/src/org/roller/business/hibernate/HibernateBookmarkManagerImpl.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,263 @@
+/*
+ * Created on Jun 18, 2004
+ */
+package org.roller.business.hibernate;
+import net.sf.hibernate.Criteria;
+import net.sf.hibernate.HibernateException;
+import net.sf.hibernate.Session;
+import net.sf.hibernate.expression.Expression;
+import org.roller.RollerException;
+import org.roller.business.BookmarkManagerImpl;
+import org.roller.business.PersistenceStrategy;
+import org.roller.model.Roller;
+import org.roller.pojos.Assoc;
+import org.roller.pojos.BookmarkData;
+import org.roller.pojos.FolderAssoc;
+import org.roller.pojos.FolderData;
+import org.roller.pojos.WebsiteData;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+/**
+ * Hibernate queries.
+ *
+ * @author David M Johnson
+ */
+public class HibernateBookmarkManagerImpl extends BookmarkManagerImpl
+{
+ /**
+ * @param pstrategy
+ * @param roller
+ */
+ public HibernateBookmarkManagerImpl(PersistenceStrategy pstrategy, Roller roller)
+ {
+ super(pstrategy, roller);
+ }
+
+ /**
+ * @see org.roller.model.WeblogManager#retrieveWeblogEntries(
+ * org.roller.pojos.FolderData, boolean)
+ */
+ public List retrieveBookmarks(FolderData folder, boolean subfolders)
+ throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy) mStrategy).getSession();
+ List bookmarks = new LinkedList();
+ if (subfolders)
+ {
+ // get bookmarks in subfolders
+ Criteria assocsQuery = session
+ .createCriteria(FolderAssoc.class);
+ assocsQuery.add(Expression.eq("ancestorFolder", folder));
+ Iterator assocs = assocsQuery.list().iterator();
+ while (assocs.hasNext())
+ {
+ FolderAssoc assoc = (FolderAssoc) assocs.next();
+ Criteria bookmarksQuery = session
+ .createCriteria(BookmarkData.class);
+ bookmarksQuery.add(Expression.eq("folder", assoc
+ .getFolder()));
+ Iterator bookmarkIter = bookmarksQuery.list().iterator();
+ while (bookmarkIter.hasNext())
+ {
+ BookmarkData entry = (BookmarkData) bookmarkIter.next();
+ bookmarks.add(entry);
+ }
+ }
+ }
+ // get bookmarks in folder
+ Criteria bookmarksQuery = session
+ .createCriteria(BookmarkData.class);
+ bookmarksQuery.add(Expression.eq("folder", folder));
+ Iterator bookmarkIter = bookmarksQuery.list().iterator();
+ while (bookmarkIter.hasNext())
+ {
+ BookmarkData bookmark = (BookmarkData) bookmarkIter.next();
+ bookmarks.add(bookmark);
+ }
+ return bookmarks;
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ public FolderData getRootFolder(WebsiteData website) throws RollerException
+ {
+ if (website == null)
+ throw new RollerException("website is null");
+ try
+ {
+ Session session = ((HibernateStrategy) mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderAssoc.class);
+ criteria.createAlias("folder", "f");
+ criteria.add(Expression.eq("f.website", website));
+ criteria.add(Expression.isNull("ancestorFolder"));
+ criteria.add(Expression.eq("relation", FolderAssoc.PARENT));
+ List results = criteria.list();
+ if (results.size() > 1)
+ {
+ // Should not have more than one root
+ throw new RollerException(
+ "More than one root folder found for website "
+ + website.getId());
+ }
+ else if (results.size() == 1)
+ {
+ // Return root
+ return ((FolderAssoc) results.get(0)).getFolder();
+ }
+ return null;
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ public List getAllFolders(WebsiteData website) throws RollerException
+ {
+ if (website == null)
+ throw new RollerException("Website is null");
+
+ try
+ {
+ Session session = ((HibernateStrategy) mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderData.class);
+ criteria.add(Expression.eq("website", website));
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+
+ }
+
+ /**
+ * @see org.roller.model.BookmarkManager#isFolderInUser(org.roller.pojos.FolderData)
+ */
+ public boolean isDuplicateFolderName(FolderData folder) throws RollerException
+ {
+ // ensure that no sibling folders share the same name
+ FolderData parent =
+ null == folder.getId() ? (FolderData)folder.getNewParent() : folder.getParent();
+
+ if (null != parent)
+ {
+ List sameNames;
+ try
+ {
+ Session session = ((HibernateStrategy) mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderAssoc.class);
+ criteria.createAlias("folder", "f");
+ criteria.add(Expression.eq("f.name", folder.getName()));
+ criteria.add(Expression.eq("ancestorFolder", parent));
+ criteria.add(Expression.eq("relation", Assoc.PARENT));
+ sameNames = criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ if (sameNames.size() > 0)
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @see org.roller.model.BookmarkManager#getFolderParentAssoc(
+ * org.roller.pojos.FolderData)
+ */
+ public Assoc getFolderParentAssoc(FolderData folder) throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderAssoc.class);
+ criteria.add(Expression.eq("folder", folder));
+ criteria.add(Expression.eq("relation", Assoc.PARENT));
+ List parents = criteria.list();
+ if (parents.size() > 1)
+ {
+ throw new RollerException("ERROR: more than one parent");
+ }
+ else if (parents.size() == 1)
+ {
+ return (Assoc) parents.get(0);
+ }
+ else
+ {
+ return null;
+ }
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ /**
+ * @see org.roller.model.BookmarkManager#getFolderChildAssocs(
+ * org.roller.pojos.FolderData)
+ */
+ public List getFolderChildAssocs(FolderData folder) throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderAssoc.class);
+ criteria.add(Expression.eq("ancestorFolder", folder));
+ criteria.add(Expression.eq("relation", Assoc.PARENT));
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ /**
+ * @see org.roller.model.BookmarkManager#getAllFolderDecscendentAssocs(
+ * org.roller.pojos.FolderData)
+ */
+ public List getAllFolderDecscendentAssocs(FolderData folder) throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderAssoc.class);
+ criteria.add(Expression.eq("ancestorFolder", folder));
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ /**
+ * @see org.roller.model.BookmarkManager#getFolderAncestorAssocs(
+ * org.roller.pojos.FolderData)
+ */
+ public List getFolderAncestorAssocs(FolderData folder) throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(FolderAssoc.class);
+ criteria.add(Expression.eq("folder", folder));
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+}
Added: incubator/roller/trunk/src/org/roller/business/hibernate/HibernateConfigManagerImpl.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/business/hibernate/HibernateConfigManagerImpl.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/business/hibernate/HibernateConfigManagerImpl.java (added)
+++ incubator/roller/trunk/src/org/roller/business/hibernate/HibernateConfigManagerImpl.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,53 @@
+/*
+ * Created on Jun 18, 2004
+ */
+package org.roller.business.hibernate;
+
+import net.sf.hibernate.Criteria;
+import net.sf.hibernate.HibernateException;
+import net.sf.hibernate.Session;
+
+import org.roller.RollerException;
+import org.roller.business.ConfigManagerImpl;
+import org.roller.business.PersistenceStrategy;
+import org.roller.model.Roller;
+import org.roller.pojos.RollerConfig;
+
+import java.util.List;
+
+/**
+ * @author David M Johnson
+ */
+public class HibernateConfigManagerImpl extends ConfigManagerImpl
+{
+ /**
+ * @param strategy
+ * @param roller
+ */
+ public HibernateConfigManagerImpl(PersistenceStrategy strategy, Roller roller)
+ {
+ super(strategy, roller);
+ }
+
+ /**
+ * Fetch all RollerConfigs and return the first one, if any.
+ * Note: there should only be one!
+ * @see org.roller.model.ConfigManager#getRollerConfig()
+ */
+ public RollerConfig getRollerConfig() throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RollerConfig.class);
+ criteria.setMaxResults(1);
+ List list = criteria.list();
+ return list.size()!=0 ? (RollerConfig)list.get(0) : null;
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+}
Added: incubator/roller/trunk/src/org/roller/business/hibernate/HibernateRefererManagerImpl.java
URL: http://svn.apache.org/viewcvs/incubator/roller/trunk/src/org/roller/business/hibernate/HibernateRefererManagerImpl.java?rev=189602&view=auto
==============================================================================
--- incubator/roller/trunk/src/org/roller/business/hibernate/HibernateRefererManagerImpl.java (added)
+++ incubator/roller/trunk/src/org/roller/business/hibernate/HibernateRefererManagerImpl.java Wed Jun 8 09:06:16 2005
@@ -0,0 +1,511 @@
+/*
+ * Created on Feb 23, 2003
+ */
+package org.roller.business.hibernate;
+
+import java.io.Serializable;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import net.sf.hibernate.Criteria;
+import net.sf.hibernate.Hibernate;
+import net.sf.hibernate.HibernateException;
+import net.sf.hibernate.Session;
+import net.sf.hibernate.expression.Expression;
+import net.sf.hibernate.expression.Junction;
+import net.sf.hibernate.expression.Order;
+import net.sf.hibernate.type.Type;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.roller.RollerException;
+import org.roller.business.PersistenceStrategy;
+import org.roller.business.RefererManagerImpl;
+import org.roller.model.RefererManager;
+import org.roller.model.Roller;
+import org.roller.pojos.RefererData;
+import org.roller.pojos.WebsiteData;
+import org.roller.pojos.WebsiteDisplayData;
+
+
+/**
+ * Hibernate queries.
+ * @author David M Johnson
+ */
+public class HibernateRefererManagerImpl extends RefererManagerImpl
+ implements RefererManager, Serializable
+{
+ private static Log mLogger =
+ LogFactory.getFactory().getInstance(HibernateRefererManagerImpl.class);
+
+ //-------------------------------------------------- Startup and Shutdown
+ public HibernateRefererManagerImpl(Roller roller, PersistenceStrategy support)
+ throws RollerException
+ {
+ super(roller);
+ mStrategy = (HibernateStrategy)support;
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Use Hibernate directly because Roller's Query API does too much allocation.
+ */
+ protected List getExistingReferers(WebsiteData website, String dateString,
+ String permalink) throws RollerException
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.conjunction()
+ .add(Expression.eq("website",website))
+ .add(Expression.eq("dateString",dateString))
+ .add(Expression.eq("refererPermalink",permalink)));
+ try
+ {
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Use Hibernate directly because Roller's Query API does too much allocation.
+ */
+ protected List getMatchingReferers(WebsiteData website, String requestUrl,
+ String refererUrl) throws RollerException
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.conjunction()
+ .add(Expression.eq("website",website))
+ .add(Expression.eq("requestUrl",requestUrl))
+ .add(Expression.eq("refererUrl",refererUrl)));
+ try
+ {
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Use raw SQL because Hibernate can't handle sorting by sum.
+ */
+ public List getDaysPopularWebsites(int max) throws RollerException
+ {
+ // TODO Hibernate version of getDaysPopularWebsites
+ // TODO Move to full use of mSupport
+ String msg = "Getting popular websites";
+ Session ses = null; // the session will eventually be release by RequestFilter
+ Connection con = null;
+ try
+ {
+ List list = new ArrayList();
+
+ ses = ((HibernateStrategy)mStrategy).getSession();
+ con = ses.connection();
+
+ final PreparedStatement stmt;
+ if (con.getMetaData().getDriverName().startsWith("HSQL"))
+ {
+ // special handling for HSQLDB
+ stmt = con.prepareStatement(
+ "select top ? u.username,w.name,w.name,sum(r.dayhits) as s "+
+ "from rolleruser as u, website as w, referer as r "+
+ "where r.websiteid=w.id and w.userid=u.id and w.isenabled=? " +
+ "group by u.username,w.name,w.id order by s desc");
+ stmt.setInt(1, max);
+ stmt.setBoolean(2, true);
+ }
+ else
+ {
+ stmt = con.prepareStatement(
+ "select u.username,w.name,w.name,sum(r.dayhits) as s "+
+ "from rolleruser as u, website as w, referer as r "+
+ "where r.websiteid=w.id and w.userid=u.id and w.isenabled= ? " +
+ // Ben Walding (a Postgres SQL user): Basically, you have
+ // to have all non-aggregated columns that exist in your
+ // 'SELECT' section, in the 'GROUP BY' section as well:
+ "group by u.username,w.name,w.id order by s desc limit ?");
+ // and not this: "group by w.id order by s desc");
+ stmt.setBoolean(1, true);
+ stmt.setInt(2, max);
+ }
+ ResultSet rs = stmt.executeQuery();
+ if ( rs.next() )
+ {
+ do
+ {
+ String userName = rs.getString(1);
+ String name = rs.getString(2);
+ String websiteName = rs.getString(3);
+ Integer hits = new Integer(rs.getInt(4));
+ list.add(new WebsiteDisplayData(
+ name,
+ userName,
+ websiteName,
+ hits));
+ }
+ while ( rs.next() );
+ }
+ return list;
+ }
+ catch (Throwable pe)
+ {
+ mLogger.error(msg, pe);
+ throw new RollerException(msg, pe);
+ }
+
+// Don't close connection, Hibernate is holding it
+// finally
+// {
+// try
+// {
+// if (con != null) con.close();
+// }
+// catch (Throwable t)
+// {
+// mLogger.error("Closing connection",t);
+// }
+// }
+
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Use raw SQL because Hibernate can't handle the query.
+ */
+ protected int getHits(WebsiteData website, String type)
+ throws RollerException
+ {
+ int hits = 0;
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("getHits: " + website.getName());
+ }
+
+ //Question: why not use website.id instead to reduce joins?
+ Object[] args = { Boolean.TRUE, website.getUser().getUserName() };
+ Type[] types = { Hibernate.BOOLEAN, Hibernate.STRING };
+
+ // For a query like this, Hibernate returns a list of lists
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ List results;
+ try
+ {
+ results = session.find(
+ "select sum(h.dayHits),sum(h.totalHits) from h in class " +
+ "org.roller.pojos.RefererData " +
+ "where h.website.isEnabled=? and h.website.user.userName=? ",
+ args, types);
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ Object[] resultsArray = (Object[]) results.get(0);
+
+ if (resultsArray.length > 0 && type.equals(DAYHITS))
+ {
+ if ( resultsArray[0] != null )
+ {
+ hits = ((Integer) resultsArray[0]).intValue();
+ }
+ }
+ else if ( resultsArray.length > 0 )
+ {
+ if ( resultsArray[0] != null )
+ {
+ hits = ((Integer) resultsArray[1]).intValue();
+ }
+ }
+ else
+ {
+ hits = 0;
+ }
+
+ return hits;
+ }
+
+ /**
+ * @see org.roller.pojos.RefererManager#getReferers(java.lang.String)
+ */
+ public List getReferers(WebsiteData website) throws RollerException
+ {
+ if (website==null )
+ throw new RollerException("website is null");
+
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.eq("website",website));
+ criteria.addOrder(Order.desc("totalHits"));
+ try
+ {
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * @see org.roller.pojos.RefererManager#getTodaysReferers(String)
+ */
+ public List getTodaysReferers(WebsiteData website)
+ throws RollerException
+ {
+ if (website==null )
+ throw new RollerException("website is null");
+
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.eq("website", website));
+ criteria.add(Expression.gt("dayHits", new Integer(0)));
+ criteria.addOrder(Order.desc("dayHits"));
+ try
+ {
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Returns referers for a specified day. Duplicate enties are not
+ * included in this list so the hit counts may not be accurate.
+ * @see org.roller.pojos.RefererManager#getReferersToDate(
+ * org.roller.pojos.WebsiteData, java.lang.String)
+ */
+ public List getReferersToDate(WebsiteData website, String date)
+ throws RollerException
+ {
+ if (website==null )
+ throw new RollerException("website is null");
+
+ if (date==null )
+ throw new RollerException("Date is null");
+
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.eq("website", website));
+ criteria.add(Expression.eq("dateString", date));
+ criteria.add(Expression.eq("duplicate", Boolean.FALSE));
+ criteria.addOrder(Order.desc("totalHits"));
+ try
+ {
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * @see org.roller.pojos.RefererManager#getReferersToEntry(
+ * java.lang.String, java.lang.String)
+ */
+ public List getReferersToEntry(String entryid) throws RollerException
+ {
+ if (null == entryid)
+ throw new RollerException("entryid is null");
+
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.createAlias("weblogEntry","e");
+
+ criteria.add(Expression.eq("e.id", entryid));
+ criteria.add(Expression.isNotNull("title"));
+ criteria.add(Expression.isNotNull("excerpt"));
+
+ criteria.addOrder(Order.desc("totalHits"));
+
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * @see org.roller.pojos.RefererManager#getReferersToEntry(
+ * java.lang.String, java.lang.String)
+ */
+ public void removeReferersForEntry(String entryid) throws RollerException
+ {
+ if (null == entryid)
+ throw new RollerException("entryid is null");
+
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.createAlias("weblogEntry","e");
+ criteria.add(Expression.eq("e.id", entryid));
+
+ Iterator referers = criteria.list().iterator();
+ while (referers.hasNext())
+ {
+ removeReferer( ((RefererData)referers.next()).getId() );
+ }
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Query for collection of referers.
+ */
+ protected List getReferersToWebsite(WebsiteData website, String refererUrl)
+ throws RollerException
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.eq("website", website));
+ criteria.add(Expression.eq("refererUrl", refererUrl));
+ try
+ {
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ //-----------------------------------------------------------------------
+
+ /**
+ * Query for collection of referers.
+ */
+ protected List getReferersWithSameTitle(
+ WebsiteData website,
+ String requestUrl,
+ String title,
+ String excerpt)
+ throws RollerException
+ {
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+
+ Junction conjunction = Expression.conjunction();
+ conjunction.add(Expression.eq("website", website));
+ conjunction.add(Expression.eq("requestUrl", requestUrl));
+
+ Junction disjunction = Expression.conjunction();
+ disjunction.add(Expression.eq("title", title));
+ disjunction.add(Expression.eq("excerpt", excerpt));
+
+ criteria.add(conjunction);
+ criteria.add(disjunction);
+
+ return criteria.list();
+ }
+ catch (HibernateException e)
+ {
+ throw new RollerException(e);
+ }
+ }
+
+ /**
+ * Purge referers at midnight. Zero out all dayHits and remove all
+ * referers that do not have excerpts.
+ */
+ public void checkForTurnover( boolean forceTurnover, String websiteId )
+ throws RollerException
+ {
+ // Note, this method doesn't need to be synchronized anymore since
+ // it's called from the timer task now, and will never be executed
+ // by two threads simultaneously.
+ if (mLogger.isDebugEnabled())
+ {
+ mLogger.debug("checkForTurnover");
+ }
+
+ Date now = new Date();
+
+ if (forceTurnover ||
+ !mDateFormat.format(now).equals(mDateFormat.format(mRefDate)))
+ {
+ try
+ {
+ if (websiteId == null) mRefDate = now;
+
+ List refs;
+ try
+ {
+ Session session = ((HibernateStrategy)mStrategy).getSession();
+ Criteria criteria = session.createCriteria(RefererData.class);
+ criteria.add(Expression.gt("dayHits", new Integer(0)));
+ if (websiteId != null)
+ {
+ criteria.add(Expression.eq("website.id", websiteId));
+ }
+ refs = criteria.list();
+ }
+ catch (HibernateException e1)
+ {
+ throw new RollerException(e1);
+ }
+
+ Integer zero = new Integer(0);
+ for (Iterator rdItr = refs.iterator(); rdItr.hasNext();) {
+ RefererData referer = (RefererData) rdItr.next();
+
+ if ( (referer.getExcerpt() != null) &&
+ (referer.getExcerpt().trim().length() > 0))
+ {
+ // Zero out dayHits of referers with excerpts
+ referer.setDayHits(zero);
+ storeReferer(referer);
+ }
+ else
+ {
+ // Throw away referers without excerpts
+ removeReferer(referer.getId());
+ }
+ }
+ }
+ catch (RollerException e)
+ {
+ mLogger.error("EXCEPTION resetting referers",e);
+ }
+ }
+ }
+
+
+}