You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@roller.apache.org by ag...@apache.org on 2007/06/20 17:27:17 UTC

svn commit: r549132 [2/2] - in /roller/trunk/apps/weblogger: src/java/org/apache/roller/weblogger/business/ src/java/org/apache/roller/weblogger/business/hibernate/ src/java/org/apache/roller/weblogger/business/jpa/ src/java/org/apache/roller/weblogger...

Added: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseInstaller.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseInstaller.java?view=auto&rev=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseInstaller.java (added)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseInstaller.java Wed Jun 20 08:27:15 2007
@@ -0,0 +1,1081 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  The ASF licenses this file to You
+ * under the Apache License, Version 2.0 (the "License"); you may not
+ * use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.  For additional information regarding
+ * copyright in this work, please see the NOTICE file in the top level
+ * directory of this distribution.
+ */
+
+package org.apache.roller.weblogger.business.utils;
+
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Properties;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.roller.weblogger.business.DatabaseProvider;
+import org.apache.roller.weblogger.business.startup.StartupException;
+import org.apache.roller.weblogger.pojos.WeblogPermission;
+
+
+/**
+ * Handles the install/upgrade of the Roller Weblogger database when the user
+ * has configured their installation type to 'auto'.
+ */
+public class DatabaseInstaller {
+    
+    private static Log log = LogFactory.getLog(DatabaseInstaller.class);
+    
+    private final DatabaseProvider db;
+    private final DatabaseScriptProvider scripts;
+    private final String version;
+    private List<String> messages = new ArrayList<String>();
+    
+    // the name of the property which holds the dbversion value
+    private static final String DBVERSION_PROP = "roller.database.version";
+    
+    
+    public DatabaseInstaller(DatabaseProvider dbProvider, DatabaseScriptProvider scriptProvider) {
+        db = dbProvider;
+        scripts = scriptProvider;
+        
+        Properties props = new Properties();
+        try {
+            props.load(getClass().getResourceAsStream("/version.properties"));
+        } catch (IOException e) {
+            log.error("version.properties not found", e);
+        }
+        
+        version = props.getProperty("ro.version", "UNKNOWN");
+    }
+    
+    
+    /** 
+     * Determine if database schema needs to be upgraded.
+     */
+    public boolean isCreationRequired() {
+        Connection con = null;
+        try {            
+            con = db.getConnection();
+            
+            // just check for a couple key Roller tables
+            if (tableExists(con, "rolleruser") && tableExists(con, "userrole")) {
+                return false;
+            }
+            
+        } catch (Throwable t) {
+            throw new RuntimeException("Error checking for tables", t);            
+        } finally {
+            try { if (con != null) con.close(); } catch (Exception ignored) {}
+        }
+        
+        return true;
+    }
+    
+    
+    /** 
+     * Determine if database schema needs to be upgraded.
+     */
+    public boolean isUpgradeRequired() {        
+        int desiredVersion = parseVersionString(version);
+        int databaseVersion;
+        try {
+            databaseVersion = getDatabaseVersion();
+        } catch (StartupException ex) {
+            throw new RuntimeException(ex);
+        }
+        return databaseVersion < desiredVersion;
+    }
+    
+    
+    public List<String> getMessages() {
+        return messages;
+    }
+    
+    
+    private void errorMessage(String msg) {
+        messages.add(msg);
+        log.error(msg);
+    }    
+    
+    
+    private void errorMessage(String msg, Throwable t) {
+        messages.add(msg);
+        log.error(msg, t);
+    }
+    
+    
+    private void successMessage(String msg) {
+        messages.add(msg);
+        log.trace(msg);
+    }
+    
+    
+    /**
+     * Create datatabase tables.
+     */
+    public void createDatabase() throws StartupException {
+        
+        log.debug("Attempting to create database");
+        
+        Connection con = null;
+        SQLScriptRunner create = null;
+        try {
+            con = db.getConnection();
+            String handle = getDatabaseHandle(con);
+            create = new SQLScriptRunner(scripts.getDatabaseScript(handle + "/createdb.sql"));
+            create.runScript(con, true);
+            messages.addAll(create.getMessages());
+            
+            setDatabaseVersion(con, version);
+            
+        } catch (SQLException sqle) {
+            errorMessage("ERROR running SQL in database creation script");
+            throw new StartupException("Error running sql script", sqle);           
+        } catch (Exception ioe) {
+            if (create != null) messages.addAll(create.getMessages());
+            errorMessage("ERROR reading/parsing database creation script");
+            throw new StartupException("Error running sql script", ioe);           
+        } finally {
+            try { if (con != null) con.close(); } catch (Exception ignored) {}
+        }
+    }
+    
+    
+    /**
+     * Upgrade database if dbVersion is older than desiredVersion.
+     */
+    public void upgradeDatabase(boolean runScripts) throws StartupException {
+        
+        int myVersion = parseVersionString(version);
+        int dbversion = getDatabaseVersion();
+        
+        log.debug("Database version = "+dbversion);
+        log.debug("Desired version = "+myVersion);
+       
+        Connection con = null;
+        try {
+            con = db.getConnection();
+            if(dbversion < 0) {
+                String msg = "Cannot upgrade database tables, Roller database version cannot be determined";
+                errorMessage(msg);
+                throw new StartupException(msg);
+            } else if(dbversion >= myVersion) {
+                log.info("Database is current, no upgrade needed");
+                return;
+            }
+
+            log.info("Database is old, beginning upgrade to version "+myVersion);
+
+            // iterate through each upgrade as needed
+            // to add to the upgrade sequence simply add a new "if" statement
+            // for whatever version needed and then define a new method upgradeXXX()
+            if(dbversion < 130) {
+                upgradeTo130(con, runScripts);
+                dbversion = 130;
+            }
+            if (dbversion < 200) {
+                upgradeTo200(con, runScripts);
+                dbversion = 200;
+            }
+            if(dbversion < 210) {
+                upgradeTo210(con, runScripts);
+                dbversion = 210;
+            }
+            if(dbversion < 230) {
+                upgradeTo230(con, runScripts);
+                dbversion = 230;
+            }
+            if(dbversion < 240) {
+                upgradeTo240(con, runScripts);
+                dbversion = 240;
+            }
+            if(dbversion < 300) {
+                upgradeTo300(con, runScripts);
+                dbversion = 300;
+            }
+            if(dbversion < 310) {
+                upgradeTo310(con, runScripts);
+                dbversion = 310;
+            }
+            if(dbversion < 320) {
+                upgradeTo320(con, runScripts);
+                dbversion = 320;
+            }
+            if(dbversion < 400) {
+                upgradeTo400(con, runScripts);
+                dbversion = 400;
+            }
+
+            // make sure the database version is the exact version
+            // we are upgrading too.
+            updateDatabaseVersion(con, myVersion);
+        
+        } catch (SQLException e) {
+            throw new StartupException("ERROR obtaining connection");
+        } finally {
+            try { if (con != null) con.close(); } catch (Exception ignored) {}
+        }
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 1.3.0
+     */
+    private void upgradeTo130(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/120-to-130-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+            
+            /*
+             * The new theme management code is going into place and it uses
+             * the old website.themeEditor attribute to store a users theme.
+             *
+             * In pre-1.3 Roller *all* websites are considered to be using a
+             * custom theme, so we need to make sure this is properly defined
+             * by setting the theme on all websites to custom.
+             *
+             * NOTE: If we don't do this then nothing would break, but some users
+             * would be suprised that their template customizations are no longer
+             * in effect because they are using a shared theme instead.
+             */
+            
+            successMessage("Doing upgrade to 130 ...");
+            successMessage("Ensuring that all website themes are set to custom");
+            
+            PreparedStatement setCustomThemeStmt = con.prepareStatement(
+                    "update website set editortheme = ?");
+            
+            setCustomThemeStmt.setString(1, org.apache.roller.weblogger.pojos.WeblogTheme.CUSTOM);
+            setCustomThemeStmt.executeUpdate();
+            
+            if (!con.getAutoCommit()) con.commit();
+            
+            successMessage("Upgrade to 130 complete.");
+            
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 130", e);  
+            throw new StartupException("Problem upgrading database to version 130", e);
+        }
+        
+        updateDatabaseVersion(con, 130);
+    }
+    
+    /**
+     * Upgrade database for Roller 2.0.0
+     */
+    private void upgradeTo200(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/130-to-200-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+            
+            successMessage("Doing upgrade to 200 ...");
+            successMessage("Populating roller_user_permissions table");
+            
+            PreparedStatement websitesQuery = con.prepareStatement(
+                    "select w.id as wid, u.id as uid, u.username as uname from "
+                    + "website as w, rolleruser as u where u.id=w.userid");
+            PreparedStatement websiteUpdate = con.prepareStatement(
+                    "update website set handle=? where id=?");
+            PreparedStatement entryUpdate = con.prepareStatement(
+                    "update weblogentry set userid=?, status=?, "
+                    + "pubtime=pubtime, updatetime=updatetime "
+                    + "where publishentry=? and websiteid=?");
+            PreparedStatement permsInsert = con.prepareStatement(
+                    "insert into roller_user_permissions "
+                    + "(id, website_id, user_id, permission_mask, pending) "
+                    + "values (?,?,?,?,?)");
+            
+            // loop through websites, each has a user
+            ResultSet websiteSet = websitesQuery.executeQuery();
+            while (websiteSet.next()) {
+                String websiteid = websiteSet.getString("wid");
+                String userid = websiteSet.getString("uid");
+                String handle = websiteSet.getString("uname");
+                successMessage("Processing website: " + handle);
+                
+                // use website user's username as website handle
+                websiteUpdate.clearParameters();
+                websiteUpdate.setString(1, handle);
+                websiteUpdate.setString(2, websiteid);
+                websiteUpdate.executeUpdate();
+                
+                // update all of pubished entries to include userid and status
+                entryUpdate.clearParameters();
+                entryUpdate.setString( 1, userid);
+                entryUpdate.setString( 2, "PUBLISHED");
+                entryUpdate.setBoolean(3, true);
+                entryUpdate.setString( 4, websiteid);
+                entryUpdate.executeUpdate();
+                
+                // update all of draft entries to include userid and status
+                entryUpdate.clearParameters();
+                entryUpdate.setString( 1, userid);
+                entryUpdate.setString( 2, "DRAFT");
+                entryUpdate.setBoolean(3, false);
+                entryUpdate.setString( 4, websiteid);
+                entryUpdate.executeUpdate();
+                
+                // add  permission for user in website
+                permsInsert.clearParameters();
+                permsInsert.setString( 1, websiteid+"p");
+                permsInsert.setString( 2, websiteid);
+                permsInsert.setString( 3, userid);
+                permsInsert.setShort(    4,WeblogPermission.ADMIN);
+                permsInsert.setBoolean(5, false);
+                permsInsert.executeUpdate();
+            }
+            
+            if (!con.getAutoCommit()) con.commit();
+            
+            successMessage("Upgrade to 200 complete.");
+            
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 200", e);
+            throw new StartupException("Problem upgrading database to version 200", e);
+        }
+        
+        updateDatabaseVersion(con, 200);
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 2.1.0
+     */
+    private void upgradeTo210(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/200-to-210-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+            
+            /*
+             * For Roller 2.1.0 we are going to standardize some of the
+             * weblog templates and make them less editable.  To do this
+             * we need to do a little surgery.
+             *
+             * The goal for this upgrade is to ensure that ALL weblogs now have
+             * the required "Weblog" template as their default template.
+             */
+            
+            successMessage("Doing upgrade to 210 ...");
+            successMessage("Ensuring that all weblogs use the 'Weblog' template as their default page");
+            
+            // this query will give us all websites that have modified their
+            // default page to link to something other than "Weblog"
+            PreparedStatement selectUpdateWeblogs = con.prepareStatement(
+                    "select website.id,template,website.handle from website,webpage "+
+                    "where webpage.id = website.defaultpageid "+
+                    "and webpage.link != 'Weblog'");
+            
+            PreparedStatement selectWeblogTemplate = con.prepareStatement(
+                    "select id from webpage where websiteid = ? and link = 'Weblog'");
+            
+            PreparedStatement updateWeblogTemplate = con.prepareStatement(
+                    "update webpage set template = ? where id = ?");
+            
+            // insert a new template for a website
+            PreparedStatement insertWeblogTemplate = con.prepareStatement(
+                    "insert into webpage"+
+                    "(id, name, description, link, websiteid, template, updatetime) "+
+                    "values(?,?,?,?,?,?,?)");
+            
+            // update the default page for a website
+            PreparedStatement updateDefaultPage = con.prepareStatement(
+                    "update website set defaultpageid = ? "+
+                    "where id = ?");
+            
+            String description = "This template is used to render the main "+
+                    "page of your weblog.";
+            ResultSet websiteSet = selectUpdateWeblogs.executeQuery();
+            Date now = new Date();
+            while (websiteSet.next()) {
+                String websiteid = websiteSet.getString(1);
+                String template = websiteSet.getString(2);
+                String handle = websiteSet.getString(3);
+                successMessage("Processing website: " + handle);
+                
+                String defaultpageid = null;
+                
+                // it's possible that this weblog has a "Weblog" template, but just
+                // isn't using it as their default.  if so we need to fix that.
+                selectWeblogTemplate.clearParameters();
+                selectWeblogTemplate.setString(1, websiteid);
+                ResultSet weblogPageSet = selectWeblogTemplate.executeQuery();
+                if(weblogPageSet.next()) {
+                    // this person already has a "Weblog" template, so update it
+                    String id = weblogPageSet.getString(1);
+                    
+                    updateWeblogTemplate.clearParameters();
+                    updateWeblogTemplate.setString(1, template);
+                    updateWeblogTemplate.setString(2, id);
+                    updateWeblogTemplate.executeUpdate();
+                    
+                    // make sure and adjust what default page id we want to use
+                    defaultpageid = id;
+                } else {
+                    // no "Weblog" template, so insert a new one
+                    insertWeblogTemplate.clearParameters();
+                    insertWeblogTemplate.setString( 1, websiteid+"q");
+                    insertWeblogTemplate.setString( 2, "Weblog");
+                    insertWeblogTemplate.setString( 3, description);
+                    insertWeblogTemplate.setString( 4, "Weblog");
+                    insertWeblogTemplate.setString( 5, websiteid);
+                    insertWeblogTemplate.setString( 6, template);
+                    insertWeblogTemplate.setDate(   7, new java.sql.Date(now.getTime()));
+                    insertWeblogTemplate.executeUpdate();
+                    
+                    // set the new default page id
+                    defaultpageid = websiteid+"q";
+                }
+                
+                // update defaultpageid value
+                updateDefaultPage.clearParameters();
+                updateDefaultPage.setString( 1, defaultpageid);
+                updateDefaultPage.setString( 2, websiteid);
+                updateDefaultPage.executeUpdate();
+            }
+            
+            
+            if (!con.getAutoCommit()) con.commit();
+            
+            successMessage("Upgrade to 210 complete.");
+            
+        } catch (Exception e) {
+            log.error("Problem upgrading database to version 210", e);
+            throw new StartupException("Problem upgrading database to version 210", e);
+        }
+        
+        updateDatabaseVersion(con, 210);
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 2.3.0
+     */
+    private void upgradeTo230(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/210-to-230-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 230", e);
+            throw new StartupException("Problem upgrading database to version 230", e);
+        }
+        
+        updateDatabaseVersion(con, 230);
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 2.4.0
+     */
+    private void upgradeTo240(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/230-to-240-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 240", e);
+            throw new StartupException("Problem upgrading database to version 240", e);
+        }
+        
+        updateDatabaseVersion(con, 240);
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 3.0.0
+     */
+    private void upgradeTo300(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/240-to-300-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+            
+            /*
+             * For Roller 3.0.0 we are allowing each weblogentry to track a
+             * locale now so that we can support multi-lingual blogs.  As part
+             * of the upgrade process we want to do 2 things ..
+             *
+             * 1. make sure all weblogs have a locale
+             * 2. set the locale on all entries to the locale for the weblog
+             */
+            
+            successMessage("Doing upgrade to 300 ...");
+            
+            // get system default language
+            String locale = java.util.Locale.getDefault().getLanguage();
+            
+            successMessage("Setting website locale to "+locale+" for websites with no locale");
+            
+            // update all weblogs where locale is "null"
+            PreparedStatement updateNullWeblogLocale = con.prepareStatement(
+                    "update website set locale = ? where locale is NULL");
+            // update all weblogs where locale is empty string ""
+            PreparedStatement updateEmptyWeblogLocale = con.prepareStatement(
+                    "update website set locale = ? where locale = ''");
+            updateNullWeblogLocale.setString( 1, locale);
+            updateEmptyWeblogLocale.setString( 1, locale);
+            updateNullWeblogLocale.executeUpdate();
+            updateEmptyWeblogLocale.executeUpdate();
+
+            
+            successMessage("Setting weblogentry locales to website locale");
+            
+            // get all entries and the locale of its website
+            PreparedStatement selectWeblogsLocale = con.prepareStatement(
+                    "select weblogentry.id,website.locale "+
+                    "from weblogentry,website "+
+                    "where weblogentry.websiteid = website.id");
+            
+            // set the locale for an entry
+            PreparedStatement updateWeblogLocale = con.prepareStatement(
+                    "update weblogentry set locale = ? where id = ?");
+            
+            ResultSet websiteSet = selectWeblogsLocale.executeQuery();
+            while (websiteSet.next()) {
+                String entryid = websiteSet.getString(1);
+                String entrylocale = websiteSet.getString(2);
+                
+                // update entry locale
+                updateWeblogLocale.clearParameters();
+                updateWeblogLocale.setString( 1, entrylocale);
+                updateWeblogLocale.setString( 2, entryid);
+                updateWeblogLocale.executeUpdate();
+            }
+            
+            
+            if (!con.getAutoCommit()) con.commit();
+            
+            successMessage("Upgrade to 300 complete.");
+            
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 300", e);
+            throw new StartupException("Problem upgrading database to version 300", e);
+        }
+        
+        updateDatabaseVersion(con, 300);
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 3.1.0
+     */
+    private void upgradeTo310(Connection con, boolean runScripts) throws StartupException {
+        try {
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/300-to-310-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 310", e);
+            throw new StartupException("Problem upgrading database to version 310", e);
+        }
+        
+        updateDatabaseVersion(con, 310);
+    }
+
+    
+    /**
+     * Upgrade database for Roller 3.2.0
+     */
+    private void upgradeTo320(Connection con, boolean runScripts) throws StartupException {
+        
+        successMessage("Doing upgrade to 320 ...");
+        
+        try {    
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/310-to-320-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+            
+            successMessage("Populating parentid columns for weblogcategory and folder tables");
+            
+            // Populate parentid in weblogcategory and folder tables.
+            //
+            // We'd like to do something like the below, but few databases 
+            // support multiple table udpates, which are part of SQL-99
+            //
+            // update weblogcategory, weblogcategoryassoc 
+            //   set weblogcategory.parentid = weblogcategoryassoc.ancestorid 
+            //   where 
+            //      weblogcategory.id = weblogcategoryassoc.categoryid 
+            //      and weblogcategoryassoc.relation = 'PARENT';
+            //
+            // update folder,folderassoc 
+            //   set folder.parentid = folderassoc.ancestorid 
+            //   where 
+            //      folder.id = folderassoc.folderid 
+            //      and folderassoc.relation = 'PARENT';
+            
+            PreparedStatement selectParents = con.prepareStatement(
+                "select categoryid, ancestorid from weblogcategoryassoc where relation='PARENT'");
+            PreparedStatement updateParent = con.prepareStatement(
+                "update weblogcategory set parentid=? where id=?");            
+            ResultSet parentSet = selectParents.executeQuery();
+            while (parentSet.next()) {
+                String categoryid = parentSet.getString(1);
+                String parentid = parentSet.getString(2);                
+                updateParent.clearParameters();
+                updateParent.setString( 1, parentid);
+                updateParent.setString( 2, categoryid);
+                updateParent.executeUpdate();
+            }
+            
+            selectParents = con.prepareStatement(
+                "select folderid, ancestorid from folderassoc where relation='PARENT'");
+            updateParent = con.prepareStatement(
+                "update folder set parentid=? where id=?");            
+            parentSet = selectParents.executeQuery();
+            while (parentSet.next()) {
+                String folderid = parentSet.getString(1);
+                String parentid = parentSet.getString(2);                
+                updateParent.clearParameters();
+                updateParent.setString( 1, parentid);
+                updateParent.setString( 2, folderid);
+                updateParent.executeUpdate();
+            }
+            
+            if (!con.getAutoCommit()) con.commit();
+           
+            successMessage("Done populating parentid columns.");
+            
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 320", e);
+            throw new StartupException("Problem upgrading database to version 320", e);
+        }
+        
+        
+        try {
+            successMessage("Populating path columns for weblogcategory and folder tables.");
+                        
+            // Populate path in weblogcategory and folder tables.
+            //
+            // It would be nice if there was a simple sql solution for doing
+            // this, but sadly the only real way to do it is through brute
+            // force walking the hierarchical trees.  Luckily, it seems that
+            // most people don't create multi-level hierarchies, so hopefully
+            // this won't be too bad
+            
+            // set path to '/' for nodes with no parents (aka root nodes)
+            PreparedStatement setRootPaths = con.prepareStatement(
+                "update weblogcategory set path = '/' where parentid is NULL");
+            setRootPaths.clearParameters();
+            setRootPaths.executeUpdate();
+            
+            // select all nodes whose parent has no parent (aka 1st level nodes)
+            PreparedStatement selectL1Children = con.prepareStatement(
+                "select f.id, f.name from weblogcategory f, weblogcategory p "+
+                    "where f.parentid = p.id and p.parentid is NULL");
+            // update L1 nodes with their path (/<name>)
+            PreparedStatement updateL1Children = con.prepareStatement(
+                "update weblogcategory set path=? where id=?");
+            ResultSet L1Set = selectL1Children.executeQuery();
+            while (L1Set.next()) {
+                String id = L1Set.getString(1);
+                String name = L1Set.getString(2);                
+                updateL1Children.clearParameters();
+                updateL1Children.setString( 1, "/"+name);
+                updateL1Children.setString( 2, id);
+                updateL1Children.executeUpdate();
+            }
+            
+            // now for the complicated part =(
+            // we need to keep iterating over L2, L3, etc nodes and setting
+            // their path until all nodes have been updated.
+            
+            // select all nodes whose parent path has been set, excluding L1 nodes
+            PreparedStatement selectLxChildren = con.prepareStatement(
+                "select f.id, f.name, p.path from weblogcategory f, weblogcategory p "+
+                    "where f.parentid = p.id and p.path <> '/' "+
+                    "and p.path is not NULL and f.path is NULL");
+            // update Lx nodes with their path (<parentPath>/<name>)
+            PreparedStatement updateLxChildren = con.prepareStatement(
+                "update weblogcategory set path=? where id=?");
+            
+            // this loop allows us to run this part of the upgrade process as
+            // long as is necessary based on the depth of the hierarchy, and
+            // we use the do/while construct to ensure it's run at least once
+            int catNumCounted = 0;
+            do {
+                log.debug("Doing pass over Lx children for categories");
+                
+                // reset count for each iteration of outer loop
+                catNumCounted = 0;
+                
+                ResultSet LxSet = selectLxChildren.executeQuery();
+                while (LxSet.next()) {
+                    String id = LxSet.getString(1);
+                    String name = LxSet.getString(2);
+                    String parentPath = LxSet.getString(3);
+                    updateLxChildren.clearParameters();
+                    updateLxChildren.setString( 1, parentPath+"/"+name);
+                    updateLxChildren.setString( 2, id);
+                    updateLxChildren.executeUpdate();
+                    
+                    // count the updated rows
+                    catNumCounted++;
+                }
+                
+                log.debug("Updated "+catNumCounted+" Lx category paths");
+            } while(catNumCounted > 0);
+            
+            
+            
+            // set path to '/' for nodes with no parents (aka root nodes)
+            setRootPaths = con.prepareStatement(
+                "update folder set path = '/' where parentid is NULL");
+            setRootPaths.clearParameters();
+            setRootPaths.executeUpdate();
+            
+            // select all nodes whose parent has no parent (aka 1st level nodes)
+            selectL1Children = con.prepareStatement(
+                "select f.id, f.name from folder f, folder p "+
+                    "where f.parentid = p.id and p.parentid is NULL");
+            // update L1 nodes with their path (/<name>)
+            updateL1Children = con.prepareStatement(
+                "update folder set path=? where id=?");
+            L1Set = selectL1Children.executeQuery();
+            while (L1Set.next()) {
+                String id = L1Set.getString(1);
+                String name = L1Set.getString(2);                
+                updateL1Children.clearParameters();
+                updateL1Children.setString( 1, "/"+name);
+                updateL1Children.setString( 2, id);
+                updateL1Children.executeUpdate();
+            }
+            
+            // now for the complicated part =(
+            // we need to keep iterating over L2, L3, etc nodes and setting
+            // their path until all nodes have been updated.
+            
+            // select all nodes whose parent path has been set, excluding L1 nodes
+            selectLxChildren = con.prepareStatement(
+                "select f.id, f.name, p.path from folder f, folder p "+
+                    "where f.parentid = p.id and p.path <> '/' "+
+                    "and p.path is not NULL and f.path is NULL");
+            // update Lx nodes with their path (/<name>)
+            updateLxChildren = con.prepareStatement(
+                "update folder set path=? where id=?");
+            
+            // this loop allows us to run this part of the upgrade process as
+            // long as is necessary based on the depth of the hierarchy, and
+            // we use the do/while construct to ensure it's run at least once
+            int folderNumUpdated = 0;
+            do {
+                log.debug("Doing pass over Lx children for folders");
+                
+                // reset count for each iteration of outer loop
+                folderNumUpdated = 0;
+                
+                ResultSet LxSet = selectLxChildren.executeQuery();
+                while (LxSet.next()) {
+                    String id = LxSet.getString(1);
+                    String name = LxSet.getString(2);
+                    String parentPath = LxSet.getString(3);
+                    updateLxChildren.clearParameters();
+                    updateLxChildren.setString( 1, parentPath+"/"+name);
+                    updateLxChildren.setString( 2, id);
+                    updateLxChildren.executeUpdate();
+                    
+                    // count the updated rows
+                    folderNumUpdated++;
+                }
+                
+                log.debug("Updated "+folderNumUpdated+" Lx folder paths");
+            } while(folderNumUpdated > 0);
+            
+            if (!con.getAutoCommit()) con.commit();
+           
+            successMessage("Done populating path columns.");
+            
+        } catch (SQLException e) {
+            log.error("Problem upgrading database to version 320", e);
+            throw new StartupException("Problem upgrading database to version 320", e);
+        }
+        
+        // finally, upgrade db version string to 320
+        updateDatabaseVersion(con, 320);
+    }
+    
+    
+    /**
+     * Upgrade database for Roller 4.0.0
+     */
+    private void upgradeTo400(Connection con, boolean runScripts) throws StartupException {
+        
+        successMessage("Doing upgrade to 400 ...");
+        
+        try {    
+            if (runScripts) {
+                String handle = getDatabaseHandle(con);
+                String scriptPath = handle + "/320-to-400-migration.sql";
+                successMessage("Running database upgrade script: "+scriptPath);                
+                SQLScriptRunner runner = new SQLScriptRunner(scripts.getDatabaseScript(scriptPath));
+                runner.runScript(con, true);
+                messages.addAll(runner.getMessages());
+            }
+            
+            successMessage("Merging planet groups 'all' and 'external'");
+            
+            // Move all subscriptions in the planet group 'external' to group 'all'
+            
+            String allGroupId = null;
+            PreparedStatement selectAllGroupId = con.prepareStatement(
+                "select id from rag_group where handle = 'all'");
+            ResultSet rs = selectAllGroupId.executeQuery();
+            if (rs.next()) {
+                allGroupId = rs.getString(1);
+            }
+            
+            String externalGroupId = null;
+            PreparedStatement selectExternalGroupId = con.prepareStatement(
+                "select id from rag_group where handle = 'external'");            
+            rs = selectExternalGroupId.executeQuery();
+            if (rs.next()) {
+                externalGroupId = rs.getString(1);
+            }
+            
+            // we only need to merge if both of those groups already existed
+            if(allGroupId != null && externalGroupId != null) {
+                PreparedStatement updateGroupSubs = con.prepareStatement(
+                        "update rag_group_subscription set group_id = ? where group_id = ?");
+                updateGroupSubs.clearParameters();
+                updateGroupSubs.setString( 1, allGroupId);
+                updateGroupSubs.setString( 2, externalGroupId);
+                updateGroupSubs.executeUpdate();
+                
+                // we no longer need the group 'external'
+                PreparedStatement deleteExternalGroup = con.prepareStatement(
+                        "delete from rag_group where handle = 'external'");
+                deleteExternalGroup.executeUpdate();
+                
+            // if we only have group 'external' then just rename it to 'all'
+            } else if(allGroupId == null && externalGroupId != null) {
+                
+                // rename 'external' to 'all'
+                PreparedStatement renameExternalGroup = con.prepareStatement(
+                        "update rag_group set handle = 'all' where handle = 'external'");
+                renameExternalGroup.executeUpdate();
+            }
+            
+            if (!con.getAutoCommit()) con.commit();
+           
+            successMessage("Planet group 'external' merged into group 'all'.");
+            
+        } catch (Exception e) {
+            errorMessage("Problem upgrading database to version 400", e);
+            throw new StartupException("Problem upgrading database to version 400", e);
+        }
+        
+        // finally, upgrade db version string to 400
+        updateDatabaseVersion(con, 400);
+    }
+    
+    
+    /**
+     * Use database product name to get the database script directory name.
+     */
+    public String getDatabaseHandle(Connection con) throws SQLException {
+        
+        String productName = con.getMetaData().getDatabaseProductName();
+        String handle = "mysql";
+        if (       productName.toLowerCase().indexOf("mysql") != -1) {
+            handle =  "mysql";
+        } else if (productName.toLowerCase().indexOf("derby") != -1) {
+            handle =  "derby";
+        } else if (productName.toLowerCase().indexOf("hsql") != -1) {
+            handle =  "hsqldb";
+        } else if (productName.toLowerCase().indexOf("postgres") != -1) {
+            handle =  "postgresql";
+        } else if (productName.toLowerCase().indexOf("oracle") != -1) {
+            handle =  "oracle";
+        } else if (productName.toLowerCase().indexOf("microsoft") != -1) {
+            handle =  "mssql";
+        } else if (productName.toLowerCase().indexOf("db2") != -1) {   
+            handle =  "db2";
+        }
+        
+        return handle;
+    }
+
+    
+    /**
+     * Return true if named table exists in database.
+     */
+    private boolean tableExists(Connection con, String tableName) throws SQLException {
+        String[] types = {"TABLE"};
+        ResultSet rs = con.getMetaData().getTables(null, null, "%", null);
+        while (rs.next()) {
+            if (tableName.toLowerCase().equals(rs.getString("TABLE_NAME").toLowerCase())) {
+                return true;
+            }
+        }
+        return false;
+    }
+    
+    
+    private int getDatabaseVersion() throws StartupException {
+        int dbversion = -1;
+        
+        // get the current db version
+        Connection con = null;
+        try {
+            con = db.getConnection();
+            Statement stmt = con.createStatement();
+            
+            // just check in the roller_properties table
+            ResultSet rs = stmt.executeQuery(
+                    "select value from roller_properties where name = '"+DBVERSION_PROP+"'");
+            
+            if(rs.next()) {
+                dbversion = Integer.parseInt(rs.getString(1));
+                
+            } else {
+                // tough to know if this is an upgrade with no db version :/
+                // however, if roller_properties is not empty then we at least
+                // we have someone upgrading from 1.2.x
+                rs = stmt.executeQuery("select count(*) from roller_properties");
+                if(rs.next()) {
+                    if(rs.getInt(1) > 0)
+                        dbversion = 120;
+                }
+            }
+            
+        } catch(Exception e) {
+            // that's strange ... hopefully we didn't need to upgrade
+            log.error("Couldn't lookup current database version", e);           
+        } finally {
+            try { if (con != null) con.close(); } catch (Exception ignored) {}
+        }       
+        return dbversion;
+    }
+    
+    
+    private int parseVersionString(String vstring) {        
+        int myversion = 0;
+        
+        // NOTE: this assumes a maximum of 3 digits for the version number
+        // so if we get to 10.0 then we'll need to upgrade this
+        
+        // strip out non-digits
+        vstring = vstring.replaceAll("\\Q.\\E", "");
+        vstring = vstring.replaceAll("\\D", "");
+        if(vstring.length() > 3)
+            vstring = vstring.substring(0, 3);
+        
+        // parse to an int
+        try {
+            int parsed = Integer.parseInt(vstring);            
+            if(parsed < 100) myversion = parsed * 10;
+            else myversion = parsed;
+        } catch(Exception e) {}  
+        
+        return myversion;
+    }
+    
+
+    /**
+     * Insert a new database.version property.
+     * This should only be called once for new installations
+     */
+    private void setDatabaseVersion(Connection con, String version) 
+            throws StartupException {
+        setDatabaseVersion(con, parseVersionString(version));
+    }
+
+    /**
+     * Insert a new database.version property.
+     * This should only be called once for new installations
+     */
+    private void setDatabaseVersion(Connection con, int version)
+            throws StartupException {
+        
+        try {
+            Statement stmt = con.createStatement();
+            stmt.executeUpdate("insert into roller_properties "+
+                    "values('"+DBVERSION_PROP+"', '"+version+"')");
+            
+            log.debug("Set database verstion to "+version);
+        } catch(SQLException se) {
+            throw new StartupException("Error setting database version.", se);
+        }
+    }
+    
+    
+    /**
+     * Update the existing database.version property
+     */
+    private void updateDatabaseVersion(Connection con, int version)
+            throws StartupException {
+        
+        try {
+            Statement stmt = con.createStatement();
+            stmt.executeUpdate("update roller_properties "+
+                    "set value = '"+version+"'"+
+                    "where name = '"+DBVERSION_PROP+"'");
+            
+            log.debug("Updated database verstion to "+version);
+        } catch(SQLException se) {
+            throw new StartupException("Error setting database version.", se);
+        } 
+    }
+    
+}

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseScriptProvider.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseScriptProvider.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseScriptProvider.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/DatabaseScriptProvider.java Wed Jun 20 08:27:15 2007
@@ -15,15 +15,20 @@
  * copyright in this work, please see the NOTICE file in the top level
  * directory of this distribution.
  */
+
 package org.apache.roller.weblogger.business.utils;
 
 import java.io.InputStream;
 
+
 /**
  * Interface for retrieving database script.
  */
 public interface DatabaseScriptProvider {
     
-    /** Get database script, path is relative to dbscripts dir */
+    /** 
+     * Get an InputStream to a database script at the given path.
+     */
     public InputStream getDatabaseScript(String path) throws Exception;
+    
 }

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/SQLScriptRunner.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/SQLScriptRunner.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/SQLScriptRunner.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/business/utils/SQLScriptRunner.java Wed Jun 20 08:27:15 2007
@@ -50,12 +50,16 @@
     
     /** Creates a new instance of SQLScriptRunner */
     public SQLScriptRunner(InputStream is) throws IOException {
+        
+        log.debug("instantiated");
+        
         this.scriptPath = scriptPath;
         BufferedReader in = new BufferedReader(new InputStreamReader(is));
         String command = ""; 
         String line;
         while ((line = in.readLine()) != null) {
             line = line.trim();
+            log.debug(line);
             
             if (!line.startsWith("--")) { // ignore lines starting with "--"    
                 

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetImpl.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetImpl.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetImpl.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/planet/business/jpa/JPARollerPlanetImpl.java Wed Jun 20 08:27:15 2007
@@ -30,6 +30,7 @@
 import org.apache.roller.planet.business.Planet;
 import org.apache.roller.planet.business.jpa.JPAPlanetImpl;
 import org.apache.roller.planet.config.PlanetConfig;
+import org.apache.roller.weblogger.business.startup.WebloggerStartup;
 
 
 /**
@@ -56,12 +57,7 @@
             }
         }
         
-        DatabaseProvider dbProvider;
-        try {
-            dbProvider = DatabaseProvider.getDatabaseProvider();
-        } catch (WebloggerException ex) {
-            throw new PlanetException(ex);
-        }
+        DatabaseProvider dbProvider = WebloggerStartup.getDatabaseProvider();
         
         if (dbProvider.getType() == DatabaseProvider.ConfigurationType.JNDI_NAME) {
             return new JPAPersistenceStrategy(

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/RollerContext.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/RollerContext.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/RollerContext.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/RollerContext.java Wed Jun 20 08:27:15 2007
@@ -33,15 +33,16 @@
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.roller.weblogger.WebloggerException;
-import org.apache.roller.weblogger.business.utils.DatabaseUpgrader;
+import org.apache.roller.weblogger.business.BootstrapException;
+import org.apache.roller.weblogger.business.startup.StartupException;
 import org.apache.roller.weblogger.config.RollerConfig;
 import org.apache.roller.weblogger.business.RollerFactory;
 import org.apache.roller.planet.business.Planet;
 import org.apache.roller.planet.business.PlanetFactory;
+import org.apache.roller.weblogger.business.startup.WebloggerStartup;
 import org.apache.roller.weblogger.ui.core.plugins.UIPluginManager;
 import org.apache.roller.weblogger.ui.core.plugins.UIPluginManagerImpl;
 import org.apache.roller.weblogger.ui.core.security.AutoProvision;
-import org.apache.roller.weblogger.ui.struts2.core.ServletContextDatabaseScriptProvider;
 import org.apache.roller.weblogger.util.cache.CacheManager;
 import org.apache.velocity.runtime.RuntimeSingleton;
 import org.springframework.context.ApplicationContext;
@@ -70,89 +71,102 @@
      */
     public void contextInitialized(ServletContextEvent sce) {
         
-        log.info("Apache Roller Weblogger Initializing ...");
-            
+        // First, initialize everything that requires no database
+        
+        // Keep a reverence to ServletContext object
+        this.servletContext = sce.getServletContext();
+        
+        // Call Spring's context ContextLoaderListener to initialize all the
+        // context files specified in web.xml. This is necessary because
+        // listeners don't initialize in the order specified in 2.3 containers
+        super.contextInitialized(sce);
+        
+        // get the *real* path to <context>/resources
+        String ctxPath = servletContext.getRealPath("/");
+        if(!ctxPath.endsWith(File.separator))
+            ctxPath += File.separator + "resources";
+        else
+            ctxPath += "resources";
+        
+        // try setting the uploads path to <context>/resources
+        // NOTE: this should go away at some point
+        // we leave it here for now to allow users to keep writing
+        // uploads into their webapp context, but this is a bad idea
+        //
+        // also, the RollerConfig.setUploadsDir() method is smart
+        // enough to disregard this call unless the uploads.path
+        // is set to ${webapp.context}
+        RollerConfig.setUploadsDir(ctxPath);
+        
+        // try setting the themes path to <context>/themes
+        // NOTE: this should go away at some point
+        // we leave it here for now to allow users to keep using
+        // themes in their webapp context, but this is a bad idea
+        //
+        // also, the RollerConfig.setThemesDir() method is smart
+        // enough to disregard this call unless the themes.dir
+        // is set to ${webapp.context}
+        RollerConfig.setThemesDir(servletContext.getRealPath("/")+File.separator+"themes");
+        
+        
+        // Now prepare the core services of the app so we can bootstrap
         try {
+            WebloggerStartup.prepare();
+        } catch (StartupException ex) {
+            log.fatal("Roller Weblogger startup failed during app preparation", ex);
+            return;
+        }
+        
+        
+        // if preparation failed or is incomplete then we are done,
+        // otherwise try to bootstrap the business tier
+        if (!WebloggerStartup.isPrepared()) {
+            log.info("Roller Weblogger startup requires interaction from user to continue");
+        } else {
+            try {
+                // trigger bootstrapping process
+                RollerFactory.bootstrap();
+                
+                // trigger initialization process
+                RollerFactory.initialize();
+                
+                // flush any changes made during initialization
+                RollerFactory.getRoller().flush();
+                
+            } catch (BootstrapException ex) {
+                log.fatal("Roller Weblogger bootstrap failed", ex);
+            } catch (WebloggerException ex) {
+                log.fatal("Roller Weblogger initialization failed", ex);
+            }
             
-            // First, initialize everything that requires no database 
-
-            // Keep a reverence to ServletContext object
-            this.servletContext = sce.getServletContext();
-
-            // Call Spring's context ContextLoaderListener to initialize all the 
-            // context files specified in web.xml. This is necessary because 
-            // listeners don't initialize in the order specified in 2.3 containers
-            super.contextInitialized(sce);
-
-            // get the *real* path to <context>/resources
-            String ctxPath = servletContext.getRealPath("/");
-            if(!ctxPath.endsWith(File.separator))
-                ctxPath += File.separator + "resources";
-            else
-                ctxPath += "resources";
-
-            // try setting the uploads path to <context>/resources
-            // NOTE: this should go away at some point
-            // we leave it here for now to allow users to keep writing
-            // uploads into their webapp context, but this is a bad idea
-            //
-            // also, the RollerConfig.setUploadsDir() method is smart
-            // enough to disregard this call unless the uploads.path
-            // is set to ${webapp.context}
-            RollerConfig.setUploadsDir(ctxPath);
-
-            // try setting the themes path to <context>/themes
-            // NOTE: this should go away at some point
-            // we leave it here for now to allow users to keep using
-            // themes in their webapp context, but this is a bad idea
-            //
-            // also, the RollerConfig.setThemesDir() method is smart
-            // enough to disregard this call unless the themes.dir
-            // is set to ${webapp.context}
-            RollerConfig.setThemesDir(servletContext.getRealPath("/")+File.separator+"themes");
+            // Initialize Planet if necessary
+            if (RollerFactory.isBootstrapped()) {
+                if (RollerConfig.getBooleanProperty("planet.aggregator.enabled")) {
+                    try {
+                        Planet planet = PlanetFactory.getPlanet();
+                        PlanetFactory.getPlanet().getPropertiesManager();
+                        planet.flush();
+                        planet.release();
+                        
+                    } catch (Throwable t) {
+                        log.fatal("Roller Planet initialization failed", t);
+                    }
+                }
+            }
+        }
         
+        
+        // do a small amount of work to initialize the web tier
+        try {
             // Initialize Acegi based on Roller configuration
             initializeSecurityFeatures(servletContext);
             
             // Setup Velocity template engine
             setupVelocity();
-           
-
-            // Now, the database dependent part...
-
-            // If installation type is manual, then don't run migraton scripts
-            if ("manual".equals(RollerConfig.getProperty("installation.type"))) {
-                if (DatabaseUpgrader.isUpgradeRequired()) {
-                    DatabaseUpgrader upgrader = new DatabaseUpgrader(
-                            new ServletContextDatabaseScriptProvider());  
-                    upgrader.upgradeDatabase(false);
-                }
-            }
-            
-            // trigger bootstrapping process
-            RollerFactory.bootstrap();
-            
-            // flush any changes made during bootstrapping
-            RollerFactory.getRoller().flush();
-            
-        } catch (Throwable t) {
-            log.fatal("Roller Weblogger initialization failed", t);
-        }
-        
-        // Initialize Planet if necessary
-        if (RollerConfig.getBooleanProperty("planet.aggregator.enabled")) {
-            try {
-                Planet planet = PlanetFactory.getPlanet();                
-                PlanetFactory.getPlanet().getPropertiesManager();                
-                planet.flush();
-                planet.release();
-                
-            } catch (Throwable t) {
-                log.fatal("Roller Planet initialization failed", t);
-            }
+        } catch (WebloggerException ex) {
+            log.fatal("Error initializing Roller Weblogger web tier", ex);
         }
         
-        log.info("Apache Roller Weblogger Initialization Complete");
     }
     
     
@@ -169,7 +183,7 @@
     /**
      * Initialize the Velocity rendering engine.
      */
-    private void setupVelocity() throws Exception {        
+    private void setupVelocity() throws WebloggerException {        
         log.info("Initializing Velocity");
         
         // initialize the Velocity engine
@@ -203,7 +217,7 @@
     /**
      * Setup Acegi security features.
      */
-    protected void initializeSecurityFeatures(ServletContext context) throws WebloggerException { 
+    protected void initializeSecurityFeatures(ServletContext context) { 
 
         ApplicationContext ctx =
                 WebApplicationContextUtils.getRequiredWebApplicationContext(context);

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/BootstrapFilter.java Wed Jun 20 08:27:15 2007
@@ -23,7 +23,6 @@
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
 import javax.servlet.RequestDispatcher;
-import javax.servlet.ServletContext;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
@@ -31,25 +30,19 @@
 import javax.servlet.http.HttpServletResponse;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.roller.RollerException;
-import org.apache.roller.weblogger.business.DatabaseProvider;
 import org.apache.roller.weblogger.business.RollerFactory;
 import org.apache.roller.weblogger.config.RollerConfig;
-import org.apache.roller.weblogger.business.utils.DatabaseCreator;
-import org.apache.roller.weblogger.business.utils.DatabaseUpgrader;
 
 
 /**
- * Checks database setup, forwards to appropriate error or setup page.
+ * Redirects clients to install page when app is not bootstrapped and install
+ * type is "auto", otherwise does nothing.
  */
 public class BootstrapFilter implements Filter {
-    private ServletContext context = null;
+    
     private static Log log = LogFactory.getLog(BootstrapFilter.class);
     
     
-    /**
-     * Release Roller persistence session at end of request processing.
-     */
     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
             throws IOException, ServletException {
         
@@ -58,37 +51,29 @@
         
         log.debug("Entered "+request.getRequestURI());
         
-        if ("auto".equals(RollerConfig.getProperty("installation.type"))) {            
-            // an auto-install is in progress, do some checks and if necessary
-            // redirect to error, db create or db upgrade page
-
-            // only do this if Roller is configured for auto-install and 
-            // only if request is NOT for install page or a style/script file            
-            String requestURI = request.getRequestURI();
-            if (     requestURI != null 
-                 &&  requestURI.indexOf("/roller-ui/install") < 0 
-                 && !requestURI.endsWith(".js")
-                 && !requestURI.endsWith(".css")) {
-                
-                if (!RollerFactory.isBootstrapped()) {
-                    // we doing an install, so forward to installer
-                    RequestDispatcher rd = context.getRequestDispatcher(
-                            "/roller-ui/install/install.rol");
-                    rd.forward(req, res);
-                    return;
-                }
-            }
+        if (!RollerFactory.isBootstrapped() &&
+                "auto".equals(RollerConfig.getProperty("installation.type")) &&
+                !isInstallUrl(request.getServletPath())) {
+            
+            // just redirect to install action
+            response.sendRedirect("/roller-ui/install/install.rol");
+            
+        } else {
+            chain.doFilter(request, response);
         }
-        chain.doFilter(request, response);                    
+        
         log.debug("Exiting "+request.getRequestURI());
     }
     
     
-    public void init(FilterConfig filterConfig) throws ServletException {
-        context = filterConfig.getServletContext();
+    private boolean isInstallUrl(String uri) {
+        return (uri != null && (uri.startsWith("/roller-ui/install") ||
+                uri.endsWith(".js") || uri.endsWith(".css")));
     }
     
+    
+    public void init(FilterConfig filterConfig) throws ServletException {}
+    
     public void destroy() {}
     
 }
-

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/core/filters/PersistenceSessionFilter.java Wed Jun 20 08:27:15 2007
@@ -59,17 +59,20 @@
         try {
             chain.doFilter(request, response);
         } finally {
-            log.debug("Releasing Roller Session");
-            if (RollerFactory.getRoller() != null) {
+            if (RollerFactory.isBootstrapped()) {
+                log.debug("Releasing Roller Session");
                 RollerFactory.getRoller().release();
-            }
-            
-            // if planet is enabled then release planet backend as well
-            if (RollerConfig.getBooleanProperty("planet.aggregator.enabled")) {
-                if (PlanetFactory.getPlanet() != null) {
-                    PlanetFactory.getPlanet().release();
+                
+                // if planet is enabled then release planet backend as well
+                if (RollerConfig.getBooleanProperty("planet.aggregator.enabled")) {
+                    // TODO: once planet uses same lifecycle options as weblogger
+                    // then this should be updated to if(PlanetFactory.isBootstrapped())
+                    if (PlanetFactory.getPlanet() != null) {
+                        PlanetFactory.getPlanet().release();
+                    }
                 }
             }
+            
         }
         
         log.debug("Exiting "+request.getRequestURI());

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/struts2/core/Install.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/struts2/core/Install.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/struts2/core/Install.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/ui/struts2/core/Install.java Wed Jun 20 08:27:15 2007
@@ -20,69 +20,154 @@
 
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.sql.Connection;
+import java.util.List;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.apache.roller.RollerException;
-import org.apache.roller.weblogger.business.DatabaseProvider;
+import org.apache.roller.weblogger.WebloggerException;
 import org.apache.roller.weblogger.business.RollerFactory;
-import org.apache.roller.weblogger.business.utils.DatabaseCreator;
-import org.apache.roller.weblogger.business.utils.DatabaseUpgrader;
+import org.apache.roller.weblogger.business.startup.StartupException;
+import org.apache.roller.weblogger.business.startup.WebloggerStartup;
+import org.apache.roller.weblogger.config.RollerConfig;
 import org.apache.roller.weblogger.ui.struts2.util.UIAction;
+import org.springframework.beans.factory.access.BootstrapException;
+
 
 /**
  * Walk user through install process.
  */
-public class Install extends UIAction { 
+public class Install extends UIAction {
+    
     private static Log log = LogFactory.getLog(Install.class);
+    
     private static final String DATABASE_ERROR = "database_error";
     private static final String CREATE_DATABASE = "create_database";
     private static final String UPGRADE_DATABASE = "upgrade_database";
-    private static final String UNKNOWN_ERROR = "unknown_error";
+    private static final String BOOTSTRAP = "bootstrap";
+    
     private Throwable rootCauseException = null;
-       
+    private boolean error = false;
+    private boolean success = false;
+    private List<String> messages = null;
+    private String databaseName = "Unknown";
+    
+    
+    public boolean isUserRequired() {
+        return false;
+    }
+    
+    public boolean isWeblogRequired() {
+        return false;
+    }
+    
+    
     public String execute() {
 
-        try {
-            DatabaseProvider dp = DatabaseProvider.getDatabaseProvider();             
-        } catch (RollerException e) {
+        if(WebloggerStartup.getDatabaseProviderException() != null) {
+            StartupException se = WebloggerStartup.getDatabaseProviderException();
+            if (se.getRootCause() != null) {
+                rootCauseException = se.getRootCause();
+            } else {
+                rootCauseException = se;
+            }
+            messages = se.getStartupLog();
+            
+            log.debug("Forwarding to database error page");
             return DATABASE_ERROR;
         }   
         
-        try {               
-            if (DatabaseCreator.isCreationRequired()) {  
-                log.info("Forwarding to database table creation page");
-                return CREATE_DATABASE;
-            } 
-            if (DatabaseUpgrader.isUpgradeRequired()) {
-                log.info("Forwarding to database table upgrade page");
-                return UPGRADE_DATABASE;
-            }
-        } catch (Throwable t) {
-            rootCauseException = t;
-            log.error("ERROR checking database status", t);
-            return UNKNOWN_ERROR;
-        } 
+        if (WebloggerStartup.isDatabaseCreationRequired()) {
+            log.debug("Forwarding to database table creation page");
+            return CREATE_DATABASE;
+        }
+        if (WebloggerStartup.isDatabaseUpgradeRequired()) {
+            log.debug("Forwarding to database table upgrade page");
+            return UPGRADE_DATABASE;
+        }
+        
+        return BOOTSTRAP;
+    }
+    
+    
+    public String create() {
+        
+        try {
+            messages = WebloggerStartup.createDatabase();
+            
+            success = true;
+        } catch (StartupException se) {
+            error = true;
+            messages = se.getStartupLog();
+        }
+        
+        return CREATE_DATABASE;
+    }
+    
+    
+    public String upgrade() {
+        
+        try {
+            messages = WebloggerStartup.upgradeDatabase(true);
+            
+            success = true;
+        } catch (StartupException se) {
+            error = true;
+            messages = se.getStartupLog();
+        }
+        
+        return UPGRADE_DATABASE;
+    }
+    
+    
+    public String bootstrap() {
         
         try {
-            log.info("Attempting to bootstrap Roller");
+            // trigger bootstrapping process
             RollerFactory.bootstrap();
-        } catch (Throwable t) {
-            rootCauseException = t;
-            log.error("ERROR bootstrapping Roller", t);
-            return UNKNOWN_ERROR;
+            
+            // trigger initialization process
+            RollerFactory.initialize();
+            
+            // flush any changes made during initialization
+            RollerFactory.getRoller().flush();
+            
+            return SUCCESS;
+            
+        } catch (BootstrapException ex) {
+            rootCauseException = ex;
+        } catch (WebloggerException ex) {
+            rootCauseException = ex;
         }
         
-        return SUCCESS;
+        return BOOTSTRAP;
     }
-
-    public boolean isUserRequired() {
-        return false;
+    
+    
+    public String getDatabaseProductName() {
+        String name = "unknown";
+        
+        Connection con = null;
+        try {
+            con = WebloggerStartup.getDatabaseProvider().getConnection();
+            name = con.getMetaData().getDatabaseProductName();
+        } catch (Exception intentionallyIgnored) {
+            // ignored
+        } finally {
+            if(con != null) try {
+                con.close();
+            } catch(Exception ex) {}
+        }
+        
+        return name;
     }
     
-    public boolean isWeblogRequired() {
-        return false;
+    public String getProp(String key) {
+        // Static config only, we don't have database yet
+        String value = RollerConfig.getProperty(key);
+        return (value == null) ? key : value;
     }
     
+    
     public Throwable getRootCauseException() {
         return rootCauseException;
     }
@@ -96,5 +181,21 @@
         }
         return stackTrace;
     }
-}
 
+    public boolean isError() {
+        return error;
+    }
+
+    public List<String> getMessages() {
+        return messages;
+    }
+
+    public String getDatabaseName() {
+        return databaseName;
+    }
+
+    public boolean isSuccess() {
+        return success;
+    }
+    
+}

Modified: roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/util/MailUtil.java
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/util/MailUtil.java?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/util/MailUtil.java (original)
+++ roller/trunk/apps/weblogger/src/java/org/apache/roller/weblogger/util/MailUtil.java Wed Jun 20 08:27:15 2007
@@ -42,6 +42,7 @@
 import org.apache.roller.weblogger.business.MailProvider;
 import org.apache.roller.weblogger.business.RollerFactory;
 import org.apache.roller.weblogger.business.UserManager;
+import org.apache.roller.weblogger.business.startup.WebloggerStartup;
 import org.apache.roller.weblogger.config.RollerConfig;
 import org.apache.roller.weblogger.config.RollerRuntimeConfig;
 import org.apache.roller.weblogger.pojos.WeblogPermission;
@@ -68,7 +69,7 @@
      * startup, no need to complain on every attempt to send.
      */
     public static boolean isMailConfigured() {
-        return MailProvider.isMailConfigured(); 
+        return WebloggerStartup.getMailProvider() != null; 
     }
     
     /**
@@ -77,7 +78,7 @@
     public static void sendPendingEntryNotice(WeblogEntry entry) 
             throws WebloggerException {
         
-        Session mailSession = MailProvider.getMailProvider().getSession();
+        Session mailSession = WebloggerStartup.getMailProvider().getSession();
         if(mailSession == null) {
             throw new WebloggerException("Couldn't get mail Session");
         }
@@ -147,7 +148,7 @@
                                             User user)
             throws WebloggerException {
         
-        Session mailSession = MailProvider.getMailProvider().getSession();
+        Session mailSession = WebloggerStartup.getMailProvider().getSession();
         if(mailSession == null) {
             throw new WebloggerException("ERROR: Notification email(s) not sent, "
                     + "Roller's mail session not properly configured");
@@ -204,7 +205,7 @@
     public static void sendUserActivationEmail(User user)
             throws WebloggerException {
         
-        Session mailSession = MailProvider.getMailProvider().getSession();
+        Session mailSession = WebloggerStartup.getMailProvider().getSession();
         if(mailSession == null) {
             throw new WebloggerException("ERROR: Notification email(s) not sent, "
                     + "Roller's mail session not properly configured");
@@ -568,16 +569,12 @@
             )
             throws MessagingException {
         
-        MailProvider mailProvider = null;
-        Session session = null;
-        try {
-            mailProvider = MailProvider.getMailProvider(); 
-        } catch (WebloggerException ex) {
-            // The MailProvider should have been constructed long before 
-            // we get to this point, so this should never ever happen
-            throw new RuntimeException("ERROR getting mail provider", ex);
+        MailProvider mailProvider = WebloggerStartup.getMailProvider();
+        if(mailProvider == null) {
+            return;
         }
-        session = mailProvider.getSession();
+        
+        Session session = mailProvider.getSession();
         Message message = new MimeMessage(session);
         
         // n.b. any default from address is expected to be determined by caller.

Modified: roller/trunk/apps/weblogger/web/WEB-INF/classes/struts.xml
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/web/WEB-INF/classes/struts.xml?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/web/WEB-INF/classes/struts.xml (original)
+++ roller/trunk/apps/weblogger/web/WEB-INF/classes/struts.xml Wed Jun 20 08:27:15 2007
@@ -124,34 +124,14 @@
     
     <!-- Weblogger install/bootstrap actions -->
     <package name="weblogger-install" namespace="/roller-ui/install" extends="weblogger">
-        
-        <action name="databaseError"
-                class="org.apache.roller.weblogger.ui.struts2.core.DatabaseError">
-            <result name="success" type="tiles">.DatabaseError</result>
-        </action>
-            
-        <action name="unknownError"
-                class="org.apache.roller.weblogger.ui.struts2.core.UpgradeDatabase">
-            <result name="success" type="tiles">.UnknownError</result>
-        </action>
-    
-        <action name="createDatabase!*" method="{1}"
-                class="org.apache.roller.weblogger.ui.struts2.core.CreateDatabase">
-            <result name="success" type="tiles">.CreateDatabase</result>
-        </action>
-            
-        <action name="upgradeDatabase!*" method="{1}"
-                class="org.apache.roller.weblogger.ui.struts2.core.UpgradeDatabase">
-            <result name="success" type="tiles">.UpgradeDatabase</result>
-        </action>
     
         <action name="install"
                 class="org.apache.roller.weblogger.ui.struts2.core.Install">
-            <result name="database_error"   type="chain">databaseError</result>
-            <result name="create_database"  type="chain">createDatabase</result>
-            <result name="upgrade_database" type="chain">upgradeDatabase</result>
-            <result name="unknown_error"    type="tiles">.UnknownError</result>
-            <result name="success"          type="chain">home</result>
+            <result name="database_error" type="tiles">.DatabaseError</result>
+            <result name="create_database" type="tiles">.CreateDatabase</result>
+            <result name="upgrade_database" type="tiles">.UpgradeDatabase</result>
+            <result name="bootstrap" type="tiles">.Bootstrap</result>
+            <result name="success" type="chain">home</result>
         </action>
             
     </package>

Modified: roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/CreateDatabase.jsp
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/CreateDatabase.jsp?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/CreateDatabase.jsp (original)
+++ roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/CreateDatabase.jsp Wed Jun 20 08:27:15 2007
@@ -26,36 +26,36 @@
 </pre>
     
 </s:if>
-<s:elseif test="creationRequired">
+<s:elseif test="success">
 
-    <h2><s:text name="installer.noDatabaseTablesFound" /></h2>
-
-    <p>
-        <s:text name="installer.noDatabaseTablesExplanation">
-            <s:param value="databaseProductName" />
-        </s:text>
-    </p>
-    <p><s:text name="installer.createTables" /></p>
-
-    <s:form action="createDatabase!create">
-        <s:submit key="installer.yesCreateTables" />
-    </s:form>
-
-</s:elseif>
-<s:else>
-    
     <h2><s:text name="installer.tablesCreated" /></h2>
     
     <p><s:text name="installer.tablesCreatedExplanation" /></p>
     <p>
         <s:text name="installer.tryBootstrapping">
-            <s:param><s:url value="/"/></s:param>
+            <s:param><s:url action="install!bootstrap"/></s:param>
         </s:text>
     </p>
     
 <pre>
 <s:iterator value="messages"><s:property/><br /></s:iterator>
 </pre>
+
+</s:elseif>
+<s:else>
+    
+    <h2><s:text name="installer.noDatabaseTablesFound" /></h2>
+
+    <p>
+        <s:text name="installer.noDatabaseTablesExplanation">
+            <s:param value="databaseProductName" />
+        </s:text>
+    </p>
+    <p><s:text name="installer.createTables" /></p>
+
+    <s:form action="install!create">
+        <s:submit key="installer.yesCreateTables" />
+    </s:form>
     
 </s:else>
 

Modified: roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/DatabaseError.jsp
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/DatabaseError.jsp?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/DatabaseError.jsp (original)
+++ roller/trunk/apps/weblogger/web/WEB-INF/jsps/core/DatabaseError.jsp Wed Jun 20 08:27:15 2007
@@ -23,7 +23,7 @@
 
 <p><s:text name="installer.whatHappenedDatabaseConnectionError" /></p>
 <ul>
-   <s:iterator value="startupLog">
+   <s:iterator value="messages">
       <li><s:property/></li>
    </s:iterator>
 </ul>

Modified: roller/trunk/apps/weblogger/web/WEB-INF/tiles.xml
URL: http://svn.apache.org/viewvc/roller/trunk/apps/weblogger/web/WEB-INF/tiles.xml?view=diff&rev=549132&r1=549131&r2=549132
==============================================================================
--- roller/trunk/apps/weblogger/web/WEB-INF/tiles.xml (original)
+++ roller/trunk/apps/weblogger/web/WEB-INF/tiles.xml Wed Jun 20 08:27:15 2007
@@ -122,7 +122,7 @@
         <put name="banner" value="/WEB-INF/jsps/tiles/bannerInstallation.jsp" />
     </definition>
     
-    <definition name=".UnknownError" extends=".tiles-errorpage" >
+    <definition name=".Bootstrap" extends=".tiles-errorpage" >
         <put name="content" value="/WEB-INF/jsps/core/UnknownError.jsp" />
         <put name="footer" value="/WEB-INF/jsps/tiles/empty.jsp" />
         <put name="banner" value="/WEB-INF/jsps/tiles/bannerInstallation.jsp" />