Author: snoopdave
Date: Thu May 24 08:39:58 2007
New Revision: 541329

URL: http://svn.apache.org/viewvc?view=rev&rev=541329
Log:
Planet now uses DatabaseProvider properties based config just like Roller does

Added:
    
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/DatabaseProvider.java
    
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernateConnectionProvider.java
Modified:
    
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePersistenceStrategy.java
    
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePlanetImpl.java
    roller/trunk/apps/planet/web/WEB-INF/classes/hibernate.cfg.xml
    roller/trunk/apps/planet/web/WEB-INF/classes/planet.properties

Added: 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/DatabaseProvider.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/DatabaseProvider.java?view=auto&rev=541329
==============================================================================
--- 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/DatabaseProvider.java
 (added)
+++ 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/DatabaseProvider.java
 Thu May 24 08:39:58 2007
@@ -0,0 +1,121 @@
+package org.apache.roller.planet.business;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+import javax.sql.DataSource;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.roller.RollerException;
+import org.apache.roller.planet.config.PlanetConfig;
+
+/**
+ * Encapsulates Roller database configuration via JDBC properties or JNDI.
+ *
+ * <p>Reads configuration properties from PlanetConfig:</p>
+ * <pre>
+ * # Specify database configuration type of 'jndi' or 'jdbc'
+ * database.configurationType=jndi
+ * 
+ * # For database configuration type 'jndi',this will be used
+ * database.jndi.name=jdbc/rollerdb
+ * 
+ * # For database configuration type of 'jdbc', you MUST override these
+ * database.jdbc.driverClass=
+ * database.jdbc.connectionURL=
+ * database.jdbc.username=
+ * database.jdbc.password=
+ * </pre>
+ */
+public class DatabaseProvider  {
+    private static Log log = LogFactory.getLog(DatabaseProvider.class);
+    private enum ConfigurationType {JNDI_NAME, JDBC_PROPERTIES;}
+    
+    private static DatabaseProvider singletonInstance = null;
+    
+    private DataSource dataSource = null;
+    
+    private ConfigurationType type = ConfigurationType.JNDI_NAME; 
+    
+    private String jndiName = null; 
+    
+    private String jdbcDriverClass = null;
+    private String jdbcConnectionURL = null;
+    private String jdbcPassword = null;
+    private String jdbcUsername = null;
+    private Properties props = null;
+   
+    /**
+     * Reads configuraiton, loads driver or locates data-source and attempts
+     * to get test connecton so that we can fail early.
+     */ 
+    private DatabaseProvider() throws RollerException {
+        String connectionTypeString = 
+                PlanetConfig.getProperty("database.configurationType"); 
+        if ("jdbc".equals(connectionTypeString)) {
+            type = ConfigurationType.JDBC_PROPERTIES;
+        }
+        jndiName =          PlanetConfig.getProperty("database.jndi.name");
+        jdbcDriverClass =   
PlanetConfig.getProperty("database.jdbc.driverClass");
+        jdbcConnectionURL = 
PlanetConfig.getProperty("database.jdbc.connectionURL");
+        jdbcUsername =      PlanetConfig.getProperty("database.jdbc.username");
+        jdbcPassword =      PlanetConfig.getProperty("database.jdbc.password");
+        
+        // init now so we fail early
+        if (type == ConfigurationType.JDBC_PROPERTIES) {
+            log.info("Using 'jdbc' properties based configuration");
+            try {
+                Class.forName(jdbcDriverClass);
+            } catch (ClassNotFoundException ex) {
+                throw new RollerException(
+                   "Cannot load specified JDBC driver class [" 
+jdbcDriverClass+ "]", ex);
+            }
+            if (jdbcUsername != null || jdbcPassword != null) {
+                props = new Properties();
+                if (jdbcUsername != null) props.put("user", jdbcUsername);
+                if (jdbcPassword != null) props.put("password", jdbcPassword);
+            }
+        } else {
+            log.info("Using 'jndi' based configuration");
+            String name = "java:comp/env/" + jndiName;
+            try {
+                InitialContext ic = new InitialContext();
+                dataSource = (DataSource)ic.lookup(name);
+            } catch (NamingException ex) {
+                throw new RollerException(
+                    "ERROR looking up data-source with JNDI name: " + name, 
ex);
+            }            
+        }
+        try { 
+            Connection testcon = getConnection();
+            testcon.close();
+        } catch (Throwable t) {
+            throw new RollerException("ERROR unable to obtain connection", t);
+        }
+    }
+    
+    /**
+     * Get global database provider singlton, instantiating if necessary.
+     */
+    public static DatabaseProvider getDatabaseProvider() throws 
RollerException {
+        if (singletonInstance == null) {
+            singletonInstance = new DatabaseProvider();
+        }
+        return singletonInstance;
+    }
+    
+    /**
+     * Get database connection from data-source or driver manager, depending 
+     * on which is configured.
+     */
+    public Connection getConnection() throws SQLException {
+        if (type == ConfigurationType.JDBC_PROPERTIES) {
+            return DriverManager.getConnection(jdbcConnectionURL, props);
+        } else {
+            return dataSource.getConnection();
+        }
+    } 
+}

Added: 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernateConnectionProvider.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernateConnectionProvider.java?view=auto&rev=541329
==============================================================================
--- 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernateConnectionProvider.java
 (added)
+++ 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernateConnectionProvider.java
 Thu May 24 08:39:58 2007
@@ -0,0 +1,54 @@
+package org.apache.roller.planet.business.hibernate;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Properties;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.roller.RollerException;
+import org.apache.roller.planet.business.DatabaseProvider;
+import org.hibernate.HibernateException;
+import org.hibernate.connection.ConnectionProvider;
+
+/**
+ * Allows use to provide Hibernate with database connections via Roller's
+ * DatabaseProvider class. By default HibernatePersistenceStrategy adds this 
+ * class to Hibernate's configuration. If you'd like to provide your own
+ * ConnctionProvider implementation you can do so by overriding Roller's 
+ * 'hibernate.connectionProvider' property with the classname of your impl.
+ */
+public class HibernateConnectionProvider implements ConnectionProvider {
+    private static Log log = 
LogFactory.getLog(HibernateConnectionProvider.class);
+    
+    /** No-op: we get our configuration from Roller's DatabaseProvider */
+    public void configure(Properties properties) throws HibernateException {
+        // no-op
+    }
+
+    /** Get connecetion from Roller's Database provider */
+    public Connection getConnection() throws SQLException {
+        try {
+            return DatabaseProvider.getDatabaseProvider().getConnection();
+        } catch (RollerException ex) {
+            // The DatabaseProvider should have been constructed long before 
+            // we get to this point, so this should never ever happen
+            throw new RuntimeException("ERROR getting database provider", ex);
+        }
+    }
+
+    /** Close connection by calling connection.close() */
+    public void closeConnection(Connection connection) throws SQLException {
+        connection.close();
+    }
+
+    /** No-op: no need to close Roller's DatabaseProvider */
+    public void close() throws HibernateException {
+        // no-op
+    }
+
+    /** Returns false, we don't support aggressive release */
+    public boolean supportsAggressiveRelease() {
+        return false;
+    }
+    
+}

Modified: 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePersistenceStrategy.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePersistenceStrategy.java?view=diff&rev=541329&r1=541328&r2=541329
==============================================================================
--- 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePersistenceStrategy.java
 (original)
+++ 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePersistenceStrategy.java
 Thu May 24 08:39:58 2007
@@ -19,9 +19,7 @@
 package org.apache.roller.planet.business.hibernate;
 
 import java.io.StringBufferInputStream;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
+import java.util.Properties;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.hibernate.HibernateException;
@@ -30,11 +28,7 @@
 import org.hibernate.Transaction;
 import org.hibernate.cfg.Configuration;
 import org.apache.roller.RollerException;
-import org.jdom.Attribute;
-import org.jdom.Document;
-import org.jdom.Element;
-import org.jdom.input.SAXBuilder;
-import org.jdom.output.DOMOutputter;
+import org.hibernate.cfg.Environment;
 import org.xml.sax.EntityResolver;
 import org.xml.sax.InputSource;
 
@@ -45,7 +39,6 @@
  * This class serves as a helper/util class for all of the Hibernate
  * manager implementations by providing a set of basic persistence methods
  * that can be easily reused.
- *
  */
 public class HibernatePersistenceStrategy {
     
@@ -62,133 +55,25 @@
         }
     };
     
-    
-    public HibernatePersistenceStrategy() {
-    }   
-
-    /** 
-     * Construct self using Hibernate config resource and optional dialect.
-     * @param configResouce Classpath-based path to Hibernate config file 
(e.g. "/hibernate.cgf.xml")
-     * @parma dialect Classname of Hibernate dialect to be used (overriding 
any specified in the configResource)
+    /**
+     * Persistence strategy configures itself by using Roller properties:
+     * 'hibernate.configResource' - the resource name of Roller's Hibernate 
XML configuration file, 
+     * 'hibernate.dialect' - the classname of the Hibernate dialect to be used,
+     * 'hibernate.connectionProvider - the classname of Roller's connnection 
provider impl.
      */
-    public HibernatePersistenceStrategy(
-            String configResource,
-            String dialect) throws Exception {
-
-        log.info("configResource: " + configResource);
-        log.info("dialect:        " + dialect);
-        
-        // read configResource into DOM form
-        SAXBuilder builder = new SAXBuilder();
-        builder.setEntityResolver(noOpEntityResolver); 
-        Document configDoc = builder.build(
-            getClass().getResourceAsStream(configResource));
-        Element root = configDoc.getRootElement();
-        Element sessionFactoryElem = root.getChild("session-factory");
-        
-        // remove any existing connection.datasource and dialect properties
-        List propertyElems = sessionFactoryElem.getChildren("property");
-        List removeList = new ArrayList();
-        for (Iterator it = propertyElems.iterator(); it.hasNext();) {
-            Element elem = (Element) it.next();
-            if (elem.getAttribute("name") != null 
-                && elem.getAttribute("name").getValue().equals("dialect")) {
-                removeList.add(elem);           
-            }
-        }
-        for (Iterator it = removeList.iterator(); it.hasNext();) {
-            Element elem = (Element) it.next();
-            sessionFactoryElem.removeContent(elem); 
-        }
-        
-        // add Roller dialect property      
-        Element prop = new Element("property").setAttribute(
-            new Attribute("name","dialect"));
-        prop.addContent(dialect);
-        sessionFactoryElem.addContent(prop);
+    public HibernatePersistenceStrategy(String configResource, String dialect, 
String connectionProvider) {
         
+        // Read Hibernate config file specified by Roller config
         Configuration config = new Configuration();
-        DOMOutputter outputter = new DOMOutputter();
-        config.configure(outputter.output(configDoc));
-        this.sessionFactory = config.buildSessionFactory(); 
-    }
-    
-    /** 
-     * Construct self using Hibernate config resource and optional dialect.
-     * @param configResouce Classpath-based path to Hibernate config file 
(e.g. "/hibernate.cgf.xml")
-     * @parma dialect Classname of Hibernate dialect to be used (or null to 
use one specified in configResource)
-     */
-    public HibernatePersistenceStrategy(
-            String configResource,
-            String dialect,
-            String driverClass,
-            String connectionURL,
-            String username,
-            String password) throws Exception {
-        
-        log.info("configResource: " + configResource);
-        log.info("dialect:        " + dialect);
-        log.info("driverClass:    " + driverClass);
-        log.info("connectionURL:  " + connectionURL);
-        log.info("username:       " + username);
-
-        // read configResource into DOM form
-        SAXBuilder builder = new SAXBuilder();
-        builder.setEntityResolver(noOpEntityResolver); 
-        Document configDoc = builder.build(
-            getClass().getResourceAsStream(configResource));
-        Element root = configDoc.getRootElement();
-        Element sessionFactoryElem = root.getChild("session-factory");
-        
-        // remove any existing connection.datasource and dialect properties
-        List propertyElems = sessionFactoryElem.getChildren("property");
-        List removeList = new ArrayList();
-        for (Iterator it = propertyElems.iterator(); it.hasNext();) {
-            Element elem = (Element) it.next();
-            if (elem.getAttribute("name") != null 
-                && 
elem.getAttribute("name").getValue().equals("connection.datasource")) {
-                removeList.add(elem);
-            }
-            if (elem.getAttribute("name") != null 
-                && elem.getAttribute("name").getValue().equals("dialect")) {
-                removeList.add(elem);
-            }
-        }
-        for (Iterator it = removeList.iterator(); it.hasNext();) {
-            Element elem = (Element) it.next();
-            sessionFactoryElem.removeContent(elem); 
-        }
-                                       
-        // add JDBC connection params instead
-        Element prop = new Element("property").setAttribute(
-            new Attribute("name","hibernate.connection.driver_class"));
-        prop.addContent(driverClass);
-        sessionFactoryElem.addContent(prop);
+        config.configure(configResource);
 
-        prop = new Element("property").setAttribute(
-            new Attribute("name","hibernate.connection.url"));
-        prop.addContent(connectionURL);
-        sessionFactoryElem.addContent(prop);
+        // Add dialect specified by Roller config and our connection provider
+        Properties props = new Properties();
+        props.put(Environment.DIALECT, dialect);
+        props.put(Environment.CONNECTION_PROVIDER, connectionProvider);
+        config.mergeProperties(props);
         
-        prop = new Element("property").setAttribute(
-            new Attribute("name","hibernate.connection.username"));
-        prop.addContent(username);
-        sessionFactoryElem.addContent(prop);
-        
-        prop = new Element("property").setAttribute(
-            new Attribute("name","hibernate.connection.password"));
-        prop.addContent(password);
-        sessionFactoryElem.addContent(prop);
-        
-        prop = new Element("property").setAttribute(
-            new Attribute("name","dialect"));
-        prop.addContent(dialect);
-        sessionFactoryElem.addContent(prop);
-        
-        Configuration config = new Configuration();
-        DOMOutputter outputter = new DOMOutputter();
-        config.configure(outputter.output(configDoc));
-        this.sessionFactory = config.buildSessionFactory();
+        this.sessionFactory = config.buildSessionFactory(); 
     }
     
     

Modified: 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePlanetImpl.java
URL: 
http://svn.apache.org/viewvc/roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePlanetImpl.java?view=diff&rev=541329&r1=541328&r2=541329
==============================================================================
--- 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePlanetImpl.java
 (original)
+++ 
roller/trunk/apps/planet/src/java/org/apache/roller/planet/business/hibernate/HibernatePlanetImpl.java
 Thu May 24 08:39:58 2007
@@ -18,7 +18,6 @@
 
 package org.apache.roller.planet.business.hibernate;
 
-import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.roller.RollerException;
@@ -38,7 +37,7 @@
     private static Log log = LogFactory.getLog(HibernatePlanetImpl.class);
     
     // our singleton instance
-    private static HibernatePlanetImpl me = null;
+    protected static HibernatePlanetImpl me = null;
     
     // a persistence utility class
     protected HibernatePersistenceStrategy strategy = null;
@@ -59,28 +58,8 @@
      * file plus JDBC overrides from planet-custom.properties.
      */
     protected HibernatePlanetImpl() throws RollerException {
-        try {
-            if 
(StringUtils.isNotEmpty(PlanetConfig.getProperty("jdbc.driverClass"))) {
-                // create and configure for JDBC access
-                strategy = new HibernatePersistenceStrategy(
-                    PlanetConfig.getProperty("hibernate.configResource"),
-                    PlanetConfig.getProperty("hibernate.dialect"),
-                    PlanetConfig.getProperty("jdbc.driverClass"),
-                    PlanetConfig.getProperty("jdbc.connectionURL"),
-                    PlanetConfig.getProperty("jdbc.username"),
-                    PlanetConfig.getProperty("jdbc.password"));
-            } else {
-                // create an configure via config resource only
-                strategy = new HibernatePersistenceStrategy(
-                    PlanetConfig.getProperty("hibernate.configResource"),
-                    PlanetConfig.getProperty("hibernate.dialect")); 
-            }
-
-        } catch(Throwable t) {
-            // if this happens then we are screwed
-            log.fatal("Error initializing Hibernate", t);
-            throw new RollerException(t);
-        }
+        
+        strategy = getStrategy();
         
         try {
             String feedFetchClass = 
PlanetConfig.getProperty("feedfetcher.classname");
@@ -97,6 +76,22 @@
         } catch (Exception e) {
             throw new RollerException("Error initializing feed fetcher", e);
         }
+    }
+    
+    protected HibernatePersistenceStrategy getStrategy() throws 
RollerException {
+        try {
+            String dialect =  
+                PlanetConfig.getProperty("hibernate.dialect");
+            String connectionProvider = 
+                PlanetConfig.getProperty("hibernate.connectionProvider");
+            return new HibernatePersistenceStrategy(
+                "/hibernate.cfg.xml", dialect, connectionProvider);
+
+        } catch(Throwable t) {
+            // if this happens then we are screwed
+            log.fatal("Error initializing Hibernate", t);
+            throw new RollerException(t);
+        }        
     }
     
     

Modified: roller/trunk/apps/planet/web/WEB-INF/classes/hibernate.cfg.xml
URL: 
http://svn.apache.org/viewvc/roller/trunk/apps/planet/web/WEB-INF/classes/hibernate.cfg.xml?view=diff&rev=541329&r1=541328&r2=541329
==============================================================================
--- roller/trunk/apps/planet/web/WEB-INF/classes/hibernate.cfg.xml (original)
+++ roller/trunk/apps/planet/web/WEB-INF/classes/hibernate.cfg.xml Thu May 24 
08:39:58 2007
@@ -22,11 +22,10 @@
 <hibernate-configuration>
     <session-factory>
     
-        <!-- you can override with JDBC connection via 
planet-custom.properties -->
-        <property 
name="connection.datasource">java:comp/env/jdbc/rollerdb</property>
-                        
-        <!-- you can override the dialect via planet-custom.properties -->
-        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
+        <!-- 
+            Specify your Planet database configuration parameters
+            in your planet-custom.properties override file, not here.
+         -->
         
         <property name="show_sql">false</property>
         

Modified: roller/trunk/apps/planet/web/WEB-INF/classes/planet.properties
URL: 
http://svn.apache.org/viewvc/roller/trunk/apps/planet/web/WEB-INF/classes/planet.properties?view=diff&rev=541329&r1=541328&r2=541329
==============================================================================
--- roller/trunk/apps/planet/web/WEB-INF/classes/planet.properties (original)
+++ roller/trunk/apps/planet/web/WEB-INF/classes/planet.properties Thu May 24 
08:39:58 2007
@@ -40,18 +40,47 @@
 # properties in this file are accessed like this ...
 #    PlanetConfig.getProperty("propname");
 
-# You MUST override and set these three properties correctly:
+
+#----------------------------------------------------
+# Manditory properties
+# You MUST ensure that these properies are set correctly.
+# If not, you MUST override them in your planet-custom.properties file.
+
 cache.dir=/var/planet/cache
 output.dir=/usr/local/planet/webapp
 template.dir=/usr/local/planet/webapp/WEB-INF/templates
 
+# Specify database configuration type of 'jndi' or 'jdbc'
+database.configurationType=jndi
+
+# For database configuration type 'jndi',this will be used
+database.jndi.name=jdbc/rollerdb
+
+# For database configuration type of 'jdbc', you MUST override these
+database.jdbc.driverClass=
+database.jdbc.connectionURL=
+database.jdbc.username=
+database.jdbc.password=
+
+# Hibernate dialect: You must override this to use a database other than MySQL4
+hibernate.dialect=org.hibernate.dialect.MySQLDialect
+
+
+#----------------------------------------------------
+# Optional properties
+
+
 # Number of Technorati queries allowed per day
 planet.aggregator.technorati.limit=500
 
-# Business layer implementation to be used
+# Business layer implementation to be used - don't touch unless you are 
customizing Planet
 persistence.planet.classname=\
 org.apache.roller.planet.business.hibernate.HibernatePlanetImpl
 
+# Connection provider to be used - don't touch unless you are customizing 
Planet
+hibernate.connectionProvider=\
+org.apache.roller.planet.business.hibernate.HibernateConnectionProvider
+
 # choose a url strategy
 urlstrategy.classname=\
 org.apache.roller.planet.business.MultiPlanetURLStrategy
@@ -101,20 +130,3 @@
 org.apache.roller.planet.ui.rendering.model.PlanetGroupModel,\
 org.apache.roller.planet.ui.rendering.model.PlanetURLModel,\
 org.apache.roller.planet.ui.rendering.model.UtilitiesModel
-
-# Hibernate dialect: You must override this to use a database other than MySQL4
-hibernate.dialect=org.hibernate.dialect.MySQLDialect
-
-# Hibernate config resource (a classpath-based path)
-# No need to override this unless you are doing 
-hibernate.configResource=/hibernate.cfg.xml
-
-# JDBC configuration. Don't override these in the planet-custom.properties file
-# you use with the Planet webapp, but for the standalone tasks (e.g. refresh 
-# entries) you'll need to override these properties. Do it in a separate 
-# planet-custom.properties file.
-jdbc.driverClass=
-jdbc.connectionURL=
-jdbc.username=
-jdbc.password=
-


Reply via email to