]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
CSPACE-6520: Move additional database utility code into JDBCTools from ServiceMain.
authorAron Roberts <aron@socrates.berkeley.edu>
Fri, 5 Dec 2014 02:47:39 +0000 (18:47 -0800)
committerAron Roberts <aron@socrates.berkeley.edu>
Tue, 9 Dec 2014 21:13:01 +0000 (13:13 -0800)
services/common/src/main/java/org/collectionspace/services/common/ServiceMain.java
services/common/src/main/java/org/collectionspace/services/common/storage/JDBCTools.java

index af55175584088facf4b76cb2cae9cd06fd58575f..b38e41d3bbba3780aaae5beb86a646dc7938f7f2 100644 (file)
@@ -491,11 +491,6 @@ public class ServiceMain {
      * \r
      */\r
     private HashSet<String> createNuxeoDatabases() throws Exception {\r
-       final String DB_EXISTS_QUERY_PSQL = \r
-                       "SELECT 1 AS result FROM pg_database WHERE datname=?";\r
-       final String DB_EXISTS_QUERY_MYSQL = \r
-                       "SELECT 1 AS result FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=?";\r
-               \r
         String nuxeoUser = getBasicDataSourceUsername(JDBCTools.NUXEO_DATASOURCE_NAME);\r
        String nuxeoPW = getBasicDataSourcePassword(JDBCTools.NUXEO_DATASOURCE_NAME);\r
 \r
@@ -504,89 +499,78 @@ public class ServiceMain {
        \r
        DatabaseProductType dbType = JDBCTools.getDatabaseProductType(JDBCTools.CSADMIN_DATASOURCE_NAME,\r
                        getServiceConfig().getDbCsadminName());\r
-       String dbExistsQuery = (dbType == DatabaseProductType.POSTGRESQL) ? DB_EXISTS_QUERY_PSQL :\r
-               DB_EXISTS_QUERY_MYSQL;\r
 \r
        Hashtable<String, TenantBindingType> tenantBindings =\r
                        tenantBindingConfigReader.getTenantBindings();\r
        HashSet<String> nuxeoDBsChecked = new HashSet<String>();\r
-       PreparedStatement pstmt = null;\r
-       Statement stmt = null;\r
-               Connection conn = null;\r
-       \r
-               try {\r
-                       DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME);\r
-                       conn = csadminDataSource.getConnection();\r
-                       pstmt = conn.prepareStatement(dbExistsQuery); // create a statement\r
-                       stmt = conn.createStatement();\r
 \r
-                       // First check and create the roles as needed. (nuxeo and reader)\r
-                       for (TenantBindingType tenantBinding : tenantBindings.values()) {\r
-                               String tId = tenantBinding.getId();\r
-                               String tName = tenantBinding.getName();\r
-                               List<RepositoryDomainType> repoDomainList = tenantBinding.getRepositoryDomain();\r
-                               for (RepositoryDomainType repoDomain : repoDomainList) {\r
-                                       String repoDomainName = repoDomain.getName();\r
-                                        String repositoryName = repoDomain.getRepositoryName();\r
-                                        String cspaceInstanceId = getCspaceInstanceId();\r
-                                       String dbName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId);\r
-                                       if (nuxeoDBsChecked.contains(dbName)) {\r
-                                               if (logger.isDebugEnabled()) {\r
-                                                       logger.debug("Another user of db: " + dbName + ": Repo: " + repoDomainName\r
-                                                                       + " and tenant: " + tName + " (id:" + tId + ")");\r
-                                               }\r
-                                       } else {\r
-                                               if (logger.isDebugEnabled()) {\r
-                                                       logger.debug("Need to prepare db: " + dbName + " for Repo: " + repoDomainName\r
-                                                                       + " and tenant: " + tName + " (id:" + tId + ")");\r
-                                               }\r
-\r
-                                               pstmt.setString(1, dbName); // set dbName param\r
-                                               ResultSet rs = pstmt.executeQuery();\r
-                                               // extract data from the ResultSet\r
-                                               boolean dbExists = rs.next();\r
-                                               rs.close();\r
-                                               if (dbExists) {\r
-                                                       if (logger.isDebugEnabled()) {\r
-                                                               logger.debug("Database: " + dbName + " already exists.");\r
-                                                       }\r
-                                               } else {\r
-                                                       // Create the user as needed\r
-                                                       JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, nuxeoUser, nuxeoPW);\r
-                                                       if (readerUser != null) {\r
-                                                            JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, readerUser, readerPW);\r
-                                                       }\r
-                                                       // Create the database\r
-                                                       createDatabaseWithRights(conn, dbType, dbName, nuxeoUser, nuxeoPW, readerUser, readerPW);\r
-                                               }\r
-                                               nuxeoDBsChecked.add(dbName);\r
-                                       }\r
-                               } // Loop on repos for tenant\r
-                       } // Loop on tenants\r
-               } finally {   //close resources\r
-               try {\r
-                       if (stmt != null) {\r
-                               stmt.close();\r
-                       }\r
-                       if (conn != null) {\r
-                               conn.close();\r
-                       }\r
-               } catch(SQLException se) {\r
-                       se.printStackTrace();\r
-               }\r
-       }\r
+        // First check and create the roles as needed. (nuxeo and reader)\r
+        for (TenantBindingType tenantBinding : tenantBindings.values()) {\r
+                String tId = tenantBinding.getId();\r
+                String tName = tenantBinding.getName();\r
+                List<RepositoryDomainType> repoDomainList = tenantBinding.getRepositoryDomain();\r
+                for (RepositoryDomainType repoDomain : repoDomainList) {\r
+                        String repoDomainName = repoDomain.getName();\r
+                        String repositoryName = repoDomain.getRepositoryName();\r
+                        String cspaceInstanceId = getCspaceInstanceId();\r
+                        String dbName = JDBCTools.getDatabaseName(repositoryName, cspaceInstanceId);\r
+                        if (nuxeoDBsChecked.contains(dbName)) {\r
+                                if (logger.isDebugEnabled()) {\r
+                                        logger.debug("Another user of db: " + dbName + ": Repo: " + repoDomainName\r
+                                                        + " and tenant: " + tName + " (id:" + tId + ")");\r
+                                }\r
+                        } else {\r
+                                if (logger.isDebugEnabled()) {\r
+                                        logger.debug("Need to prepare db: " + dbName + " for Repo: " + repoDomainName\r
+                                                        + " and tenant: " + tName + " (id:" + tId + ")");\r
+                                }\r
+                                boolean dbExists = JDBCTools.hasDatabase(dbType, dbName);\r
+                                if (dbExists) {\r
+                                        if (logger.isDebugEnabled()) {\r
+                                                logger.debug("Database: " + dbName + " already exists.");\r
+                                        }\r
+                                } else {\r
+                                        // Create the user as needed\r
+                                        JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, nuxeoUser, nuxeoPW);\r
+                                        if (readerUser != null) {\r
+                                            JDBCTools.createNewDatabaseUser(JDBCTools.CSADMIN_DATASOURCE_NAME, repositoryName, cspaceInstanceId, dbType, readerUser, readerPW);\r
+                                        }\r
+                                        // Create the database\r
+                                        createDatabaseWithRights(dbType, dbName, nuxeoUser, nuxeoPW, readerUser, readerPW);\r
+                                }\r
+                                nuxeoDBsChecked.add(dbName);\r
+                        }\r
+                } // Loop on repos for tenant\r
+        } // Loop on tenants\r
                 \r
         return nuxeoDBsChecked;\r
        \r
     }\r
     \r
-       private void createDatabaseWithRights(Connection conn, DatabaseProductType dbType, String dbName, String ownerName,\r
+        /**\r
+         * Creates a Nuxeo-managed database, sets up an owner for that\r
+         * database, and adds (at least) connection privileges to a reader\r
+         * of that database.\r
+         * \r
+         * @param conn\r
+         * @param dbType\r
+         * @param dbName\r
+         * @param ownerName\r
+         * @param ownerPW\r
+         * @param readerName\r
+         * @param readerPW\r
+         * @throws Exception \r
+         */\r
+       private void createDatabaseWithRights(DatabaseProductType dbType, String dbName, String ownerName,\r
                        String ownerPW, String readerName, String readerPW) throws Exception {\r
+                Connection conn = null;\r
                Statement stmt = null;\r
                try {\r
+                       DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME);\r
+                       conn = csadminDataSource.getConnection();\r
                        stmt = conn.createStatement();\r
                        if (dbType == DatabaseProductType.POSTGRESQL) {\r
-                               // Postgres does not need passwords.\r
+                               // PostgreSQL does not need passwords in grant statements.\r
                                String sql = "CREATE DATABASE " + dbName + " ENCODING 'UTF8' OWNER " + ownerName;\r
                                stmt.executeUpdate(sql);\r
                                if (logger.isDebugEnabled()) {\r
@@ -629,6 +613,9 @@ public class ServiceMain {
                                if (stmt != null) {\r
                                        stmt.close();\r
                                }\r
+                                if (conn != null) {\r
+                                        conn.close();\r
+                                }\r
                        } catch (SQLException se) {\r
                                se.printStackTrace();\r
                        }\r
index 55b27395dc4ea018861c4a89123b2d8e53b0b66f..a647b07571e1b4c09988e7cef5008dd0d7e92c41 100644 (file)
@@ -627,7 +627,54 @@ public class JDBCTools {
     }\r
     \r
     /**\r
-     * Identify whether a database user already exists.\r
+     * Identify whether a database exists.\r
+     * \r
+     * @param dbType a database product type.\r
+     * @param dbName a database product name.\r
+     * @return true if a database with that name exists, false if that database does not exit.\r
+     * @throws Exception\r
+     */\r
+    public static boolean hasDatabase(DatabaseProductType dbType, String dbName) throws Exception {\r
+        PreparedStatement pstmt = null;\r
+        Connection conn = null;\r
+        String dbExistsQuery = "";\r
+        if (dbType == DatabaseProductType.POSTGRESQL) {\r
+           dbExistsQuery = "SELECT 1 AS result FROM pg_database WHERE datname=?";\r
+        } else if (dbType == DatabaseProductType.MYSQL) {\r
+           dbExistsQuery = "SELECT 1 AS result FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME=?";\r
+        } else {\r
+            throw new UnsupportedOperationException("hasDatabase encountered unknown database product type");\r
+        }\r
+        try {\r
+            DataSource csadminDataSource = JDBCTools.getDataSource(JDBCTools.CSADMIN_DATASOURCE_NAME);\r
+            conn = csadminDataSource.getConnection();\r
+            pstmt = conn.prepareStatement(dbExistsQuery); // create a statement\r
+            pstmt.setString(1, dbName); // set dbName param\r
+            ResultSet rs = pstmt.executeQuery();\r
+            // extract data from the ResultSet\r
+            boolean dbExists = rs.next();  // Will return a value of 1 if database exists\r
+            rs.close();\r
+            return dbExists;\r
+        } catch (Exception e) {\r
+            logger.error("hasDatabase failed on exception: " + e.getLocalizedMessage());\r
+            throw e;\r
+        } finally {\r
+            try {\r
+                if (pstmt != null) {\r
+                    pstmt.close();\r
+                }\r
+                if (conn != null) {\r
+                    conn.close();\r
+                }\r
+            } catch (SQLException sqle) {\r
+                // nothing we can do here except log\r
+                logger.warn("SQL Exception when closing statement/connection: " + sqle.getLocalizedMessage());\r
+           }\r
+        }\r
+    }\r
+    \r
+    /**\r
+     * Identify whether a database user exists.\r
      * \r
      * @param dataSourceName a JDBC datasource name.\r
      * @param repositoryName a repository (e.g. RDBMS database) name.\r
@@ -635,6 +682,8 @@ public class JDBCTools {
      * @param dbType a database product type.\r
      * @param username the name of the database user to create.\r
      * @param userPW the initial password for that database user.\r
+     * @return true if a database user with that name exists, false if that user does not exist.\r
+     * @throws Exception\r
      */\r
     public static boolean hasDatabaseUser(String dataSourceName, String repositoryName,\r
              String cspaceInstanceId, DatabaseProductType dbType, String username) throws Exception {\r