[jbpm-commits] JBoss JBPM SVN: r3692 - jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db.

do-not-reply at jboss.org do-not-reply at jboss.org
Wed Jan 21 00:10:26 EST 2009


Author: alex.guizar at jboss.com
Date: 2009-01-21 00:10:26 -0500 (Wed, 21 Jan 2009)
New Revision: 3692

Modified:
   jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java
   jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
Log:
JBPM-1975 generalize db package

Modified: jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java
===================================================================
--- jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java	2009-01-21 00:36:10 UTC (rev 3691)
+++ jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/AbstractDbTestCase.java	2009-01-21 05:10:26 UTC (rev 3692)
@@ -23,7 +23,6 @@
 
 // $Id$
 
-import java.util.Iterator;
 import java.util.Map;
 import java.util.Timer;
 import java.util.TimerTask;
@@ -46,8 +45,7 @@
 import org.jbpm.svc.Services;
 import org.jbpm.taskmgmt.exe.TaskInstance;
 
-public abstract class AbstractDbTestCase extends AbstractJbpmTestCase
-{
+public abstract class AbstractDbTestCase extends AbstractJbpmTestCase {
   private static final Log log = LogFactory.getLog(AbstractDbTestCase.class);
 
   protected JbpmConfiguration jbpmConfiguration;
@@ -64,164 +62,136 @@
 
   protected JobExecutor jobExecutor;
 
-  protected void setUp() throws Exception
-  {
+  protected void setUp() throws Exception {
     super.setUp();
     beginSessionTransaction();
   }
 
-  protected void tearDown() throws Exception
-  {
+  protected void tearDown() throws Exception {
     commitAndCloseSession();
     ensureCleanDatabase();
 
     super.tearDown();
   }
 
-  private void ensureCleanDatabase()
-  {
+  private void ensureCleanDatabase() {
     boolean hasLeftOvers = false;
 
-    DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory)getJbpmConfiguration().getServiceFactory("persistence");
+    DbPersistenceServiceFactory dbPersistenceServiceFactory = (DbPersistenceServiceFactory) getJbpmConfiguration().getServiceFactory("persistence");
     Configuration configuration = dbPersistenceServiceFactory.getConfiguration();
     JbpmSchema jbpmSchema = new JbpmSchema(configuration);
 
-    Map jbpmTablesRecordCount = jbpmSchema.getJbpmTablesRecordCount();
-    for (Iterator iter = jbpmTablesRecordCount.entrySet().iterator(); iter.hasNext();)
-    {
-      Map.Entry entry = (Map.Entry)iter.next();
-      String tableName = (String)entry.getKey();
-      Integer count = (Integer)entry.getValue();
+    Map<String, Integer> jbpmTablesRecordCount = jbpmSchema.getJbpmTablesRecordCount();
+    for (Map.Entry<String, Integer> entry : jbpmTablesRecordCount.entrySet()) {
+      // String tableName = entry.getKey();
+      Integer count = entry.getValue();
 
-      if ((count == null) || (count != 0))
-      {
+      if ((count == null) || (count != 0)) {
         hasLeftOvers = true;
         // [JBPM-1812] Fix tests that don't cleanup the database
-        // Only uncomment this if you intnde to fix it. Otherwise it just generates noise.
-        // System.err.println("FIXME: " + getClass().getName() + "." + getName() + " left " + count + " records in " + tableName);
+        // Only uncomment this if you intend to fix it. Otherwise it just generates noise.
+        // System.err.println("FIXME: " + getClass().getName() + "." + getName() + " left " + count
+        // + " records in " + tableName);
       }
     }
 
-    if (hasLeftOvers)
-    {
+    if (hasLeftOvers) {
       // TODO: JBPM-1781
       // jbpmSchema.cleanSchema();
     }
   }
 
-  protected String getHibernateDialect()
-  {
-    DbPersistenceServiceFactory factory = (DbPersistenceServiceFactory)jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
+  protected String getHibernateDialect() {
+    DbPersistenceServiceFactory factory = (DbPersistenceServiceFactory) jbpmContext.getServiceFactory(Services.SERVICENAME_PERSISTENCE);
     return factory.getConfiguration().getProperty(Environment.DIALECT);
   }
 
-  protected void beginSessionTransaction()
-  {
+  protected void beginSessionTransaction() {
     createJbpmContext();
     initializeMembers();
   }
 
-  protected void commitAndCloseSession()
-  {
+  protected void commitAndCloseSession() {
     closeJbpmContext();
     resetMembers();
   }
 
-  protected void newTransaction()
-  {
+  protected void newTransaction() {
     commitAndCloseSession();
     beginSessionTransaction();
   }
 
-  protected ProcessInstance saveAndReload(ProcessInstance pi)
-  {
+  protected ProcessInstance saveAndReload(ProcessInstance pi) {
     jbpmContext.save(pi);
     newTransaction();
     return graphSession.loadProcessInstance(pi.getId());
   }
 
-  protected TaskInstance saveAndReload(TaskInstance taskInstance)
-  {
+  protected TaskInstance saveAndReload(TaskInstance taskInstance) {
     jbpmContext.save(taskInstance);
     newTransaction();
-    return (TaskInstance)session.load(TaskInstance.class, new Long(taskInstance.getId()));
+    return (TaskInstance) session.load(TaskInstance.class, new Long(taskInstance.getId()));
   }
 
-  protected ProcessDefinition saveAndReload(ProcessDefinition pd)
-  {
+  protected ProcessDefinition saveAndReload(ProcessDefinition pd) {
     graphSession.saveProcessDefinition(pd);
     newTransaction();
     return graphSession.loadProcessDefinition(pd.getId());
   }
 
-  protected ProcessLog saveAndReload(ProcessLog processLog)
-  {
+  protected ProcessLog saveAndReload(ProcessLog processLog) {
     loggingSession.saveProcessLog(processLog);
     newTransaction();
     return loggingSession.loadProcessLog(processLog.getId());
   }
 
-  protected void createSchema()
-  {
+  protected void createSchema() {
     getJbpmConfiguration().createSchema();
   }
 
-  protected void cleanSchema()
-  {
+  protected void cleanSchema() {
     getJbpmConfiguration().cleanSchema();
   }
 
-  protected void dropSchema()
-  {
+  protected void dropSchema() {
     getJbpmConfiguration().dropSchema();
   }
 
-  protected String getJbpmTestConfig()
-  {
+  protected String getJbpmTestConfig() {
     return "org/jbpm/db/jbpm.db.test.cfg.xml";
   }
 
-  protected JbpmConfiguration getJbpmConfiguration()
-  {
-    if (jbpmConfiguration == null)
-    {
+  protected JbpmConfiguration getJbpmConfiguration() {
+    if (jbpmConfiguration == null) {
       String jbpmTestConfiguration = getJbpmTestConfig();
       jbpmConfiguration = JbpmConfiguration.getInstance(jbpmTestConfiguration);
     }
     return jbpmConfiguration;
   }
 
-  protected void createJbpmContext()
-  {
+  protected void createJbpmContext() {
     jbpmContext = getJbpmConfiguration().createJbpmContext();
   }
 
-  protected void closeJbpmContext()
-  {
-    if (jbpmContext != null)
-    {
+  protected void closeJbpmContext() {
+    if (jbpmContext != null) {
       jbpmContext.close();
       jbpmContext = null;
     }
   }
 
-  protected void startJobExecutor()
-  {
+  protected void startJobExecutor() {
     jobExecutor = getJbpmConfiguration().getJobExecutor();
     jobExecutor.start();
   }
 
-  protected void waitForJobs(long timeout)
-  {
+  protected void waitForJobs(long timeout) {
     // install a timer that will interrupt if it takes too long
-    // if that happens, it will lead to an interrupted exception and the test
-    // will fail
-    TimerTask interruptTask = new TimerTask()
-    {
+    // if that happens, it will lead to an interrupted exception and the test will fail
+    TimerTask interruptTask = new TimerTask() {
       Thread testThread = Thread.currentThread();
 
-      public void run()
-      {
+      public void run() {
         log.debug("test " + getName() + " took too long. going to interrupt...");
         testThread.interrupt();
       }
@@ -229,100 +199,81 @@
     Timer timer = new Timer();
     timer.schedule(interruptTask, timeout);
 
-    try
-    {
-      while (getNbrOfJobsAvailable() > 0)
-      {
+    try {
+      while (getNbrOfJobsAvailable() > 0) {
         log.debug("going to sleep for 200 millis, waiting for the job executor to process more jobs");
         Thread.sleep(200);
       }
     }
-    catch (InterruptedException e)
-    {
+    catch (InterruptedException e) {
       fail("test execution exceeded treshold of " + timeout + " milliseconds");
     }
-    finally
-    {
+    finally {
       timer.cancel();
     }
   }
 
-  protected int getNbrOfJobsAvailable()
-  {
-    if (session != null)
-    {
+  protected int getNbrOfJobsAvailable() {
+    if (session != null) {
       return getNbrOfJobsAvailable(session);
     }
-    else
-    {
+    else {
       beginSessionTransaction();
-      try
-      {
+      try {
         return getNbrOfJobsAvailable(session);
       }
-      finally
-      {
+      finally {
         commitAndCloseSession();
       }
     }
   }
 
-  private int getNbrOfJobsAvailable(Session session)
-  {
+  private int getNbrOfJobsAvailable(Session session) {
     int nbrOfJobsAvailable = 0;
-    Number jobs = (Number)session.createQuery("select count(*) from org.jbpm.job.Job").uniqueResult();
+    Number jobs = (Number) session.createQuery("select count(*) from org.jbpm.job.Job")
+        .uniqueResult();
     log.debug("there are " + jobs + " jobs in the database");
-    if (jobs != null)
-    {
+    if (jobs != null) {
       nbrOfJobsAvailable = jobs.intValue();
     }
     return nbrOfJobsAvailable;
   }
 
-  protected int getTimerCount()
-  {
-    Number timerCount = (Number)session.createQuery("select count(*) from org.jbpm.job.Timer").uniqueResult();
+  protected int getTimerCount() {
+    Number timerCount = (Number) session.createQuery("select count(*) from org.jbpm.job.Timer")
+        .uniqueResult();
     log.debug("there are " + timerCount + " timers in the database");
     return timerCount.intValue();
   }
 
-  protected Job getJob()
-  {
-    return (Job)session.createQuery("from org.jbpm.job.Job").uniqueResult();
+  protected Job getJob() {
+    return (Job) session.createQuery("from org.jbpm.job.Job").uniqueResult();
   }
 
-  protected void processJobs(long maxWait)
-  {
+  protected void processJobs(long maxWait) {
     commitAndCloseSession();
     startJobExecutor();
-    try
-    {
+    try {
       waitForJobs(maxWait);
     }
-    finally
-    {
+    finally {
       stopJobExecutor();
       beginSessionTransaction();
     }
   }
 
-  protected void stopJobExecutor()
-  {
-    if (jobExecutor != null)
-    {
-      try
-      {
+  protected void stopJobExecutor() {
+    if (jobExecutor != null) {
+      try {
         jobExecutor.stopAndJoin();
       }
-      catch (InterruptedException e)
-      {
+      catch (InterruptedException e) {
         throw new RuntimeException("waiting for job executor to stop and join got interrupted", e);
       }
     }
   }
 
-  protected void initializeMembers()
-  {
+  protected void initializeMembers() {
     session = jbpmContext.getSession();
     graphSession = jbpmContext.getGraphSession();
     taskMgmtSession = jbpmContext.getTaskMgmtSession();
@@ -331,8 +282,7 @@
     contextSession = jbpmContext.getContextSession();
   }
 
-  protected void resetMembers()
-  {
+  protected void resetMembers() {
     session = null;
     graphSession = null;
     taskMgmtSession = null;

Modified: jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
===================================================================
--- jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java	2009-01-21 00:36:10 UTC (rev 3691)
+++ jbpm3/branches/aguizar/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java	2009-01-21 05:10:26 UTC (rev 3692)
@@ -23,7 +23,6 @@
 
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
@@ -67,8 +66,9 @@
 
   ConnectionProvider connectionProvider = null;
   Connection connection = null;
-  Statement statement = null;
 
+  private Statement statement;
+
   public JbpmSchema(Configuration configuration) {
     this.configuration = configuration;
     this.settings = configuration.buildSettings();
@@ -96,15 +96,16 @@
       Mapping mapping = configuration.buildMapping();
 
       // loop over all foreign key constraints
-      List dropForeignKeysSql = new ArrayList();
-      List createForeignKeysSql = new ArrayList();
-      List deleteSql = new ArrayList();
+      List<String> dropForeignKeysSql = new ArrayList<String>();
+      List<String> createForeignKeysSql = new ArrayList<String>();
+      List<String> deleteSql = new ArrayList<String>();
 
-      Iterator iter = configuration.getTableMappings();
+      Iterator<?> iter = configuration.getTableMappings();
       while (iter.hasNext()) {
         Table table = (Table) iter.next();
+
         if (table.isPhysicalTable()) {
-          Iterator subIter = table.getForeignKeyIterator();
+          Iterator<?> subIter = table.getForeignKeyIterator();
           while (subIter.hasNext()) {
             ForeignKey fk = (ForeignKey) subIter.next();
 
@@ -118,7 +119,7 @@
               createForeignKeysSql.add(sqlCreateString);
             }
           }
-          deleteSql.add("delete from " + table.getName());
+          deleteSql.add("DELETE FROM " + table.getName());
         }
       }
 
@@ -132,16 +133,16 @@
     return cleanSql;
   }
 
-  private static String[] concat(List<String>... lists) {
+  private static String[] concat(List<?>... lists) {
     int length = 0;
-    for (List<String> list : lists) {
+    for (List<?> list : lists) {
       length += list.size();
     }
     String[] array = new String[length];
-    int i = 0;
-    for (List<String> list : lists) {
-      for (String element : list) {
-        array[i++] = element;
+    int index = 0;
+    for (List<?> list : lists) {
+      for (Object element : list) {
+        array[index++] = (String) element;
       }
     }
     return array;
@@ -151,12 +152,13 @@
     return (getJbpmTables().size() > 0);
   }
 
-  public List getJbpmTables() {
+  public List<String> getJbpmTables() {
     // delete all the data in the jbpm tables
-    List jbpmTableNames = new ArrayList();
-    Iterator iter = configuration.getTableMappings();
+    List<String> jbpmTableNames = new ArrayList<String>();
+    Iterator<?> iter = configuration.getTableMappings();
     while (iter.hasNext()) {
       Table table = (Table) iter.next();
+
       if (table.isPhysicalTable()) {
         jbpmTableNames.add(table.getName());
       }
@@ -164,34 +166,31 @@
     return jbpmTableNames;
   }
 
-  public Map getJbpmTablesRecordCount() {
-    Map recordCounts = new HashMap();
-
-    String sql = null;
-
+  public Map<String, Integer> getJbpmTablesRecordCount() {
+    Map<String, Integer> recordCounts = new HashMap<String, Integer>();
     try {
-      Iterator iter = getJbpmTables().iterator();
-
       createConnection();
-      while (iter.hasNext()) {
-        statement = connection.createStatement();
-        String tableName = (String) iter.next();
-        sql = "SELECT COUNT(*) FROM " + tableName;
-        ResultSet resultSet = statement.executeQuery(sql);
-        resultSet.next();
-        int count = resultSet.getInt(1);
-        resultSet.close();
-        statement.close();
-        recordCounts.put(tableName, count);
+
+      statement = connection.createStatement();
+      for (String tableName : getJbpmTables()) {
+        String sql = "SELECT COUNT(*) FROM " + tableName;
+        try {
+          ResultSet resultSet = statement.executeQuery(sql);
+          resultSet.next();
+          recordCounts.put(tableName, resultSet.getInt(1));
+          resultSet.close();
+        }
+        catch (SQLException e) {
+          throw new JbpmException("could not execute sql '" + sql + "'", e);
+        }
       }
     }
     catch (SQLException e) {
-      throw new JbpmException("couldn't execute sql '" + sql + "'", e);
+      throw new JbpmException("database connection failed", e);
     }
     finally {
       closeConnection();
     }
-
     return recordCounts;
   }
 
@@ -204,7 +203,7 @@
   }
 
   public void cleanSchema() {
-    if (getJbpmTables().size() > 0)
+    if (!getJbpmTables().isEmpty())
       execute(getCleanSql());
   }
 
@@ -260,8 +259,7 @@
     System.err.println("JbpmSchema create [<hibernate.cfg.xml> [<hibernate.properties>]]");
     System.err.println("JbpmSchema drop [<hibernate.cfg.xml> [<hibernate.properties>]]");
     System.err.println("JbpmSchema clean [<hibernate.cfg.xml> [<hibernate.properties>]]");
-    System.err
-        .println("JbpmSchema scripts <dir> <prefix> [<hibernate.cfg.xml> [<hibernate.properties>]]");
+    System.err.println("JbpmSchema scripts <dir> <prefix> [<hibernate.cfg.xml> [<hibernate.properties>]]");
   }
 
   static Configuration createConfiguration(String[] args, int index) {
@@ -285,43 +283,37 @@
     return configuration;
   }
 
-  void saveSqlScript(String fileName, String[] sql) throws FileNotFoundException {
-    FileOutputStream fileOutputStream = new FileOutputStream(fileName);
+  void saveSqlScript(String fileName, String[] sql) throws IOException {
+    PrintStream out = new PrintStream(new FileOutputStream(fileName));
     try {
-      PrintStream printStream = new PrintStream(fileOutputStream);
-      for (int i = 0; i < sql.length; i++) {
-        printStream.println(sql[i] + getSqlDelimiter());
+      for (String line : sql) {
+        out.println(line + getSqlDelimiter());
       }
     }
     finally {
-      try {
-        fileOutputStream.close();
-      }
-      catch (IOException e) {
-        log.debug("failed to close file", e);
-      }
+      out.close();
     }
   }
 
   void execute(String[] sqls) {
-    String sql = null;
     boolean showSql = settings.isShowSqlEnabled();
-
     try {
       createConnection();
-      statement = connection.createStatement();
 
-      for (int i = 0; i < sqls.length; i++) {
-        sql = sqls[i];
-
+      statement = connection.createStatement();
+      for (String sql : sqls) {
         if (showSql)
           log.debug(sql);
-        statement.executeUpdate(sql);
+        try {
+          statement.executeUpdate(sql);
+        }
+        catch (SQLException e) {
+          throw new JbpmException("could not execute '" + sql + "'", e);
+        }
       }
-
     }
     catch (SQLException e) {
-      throw new JbpmException("couldn't execute sql '" + sql + "'", e);
+      throw new JbpmException("database connection failed", e);
     }
     finally {
       closeConnection();
@@ -334,19 +326,20 @@
         statement.close();
       }
       catch (SQLException e) {
-        log.debug("could not close jdbc statement", e);
+        log.debug("could not close " + statement, e);
       }
     }
     if (connection != null) {
       try {
-        JDBCExceptionReporter.logWarnings(connection.getWarnings());
-        connection.clearWarnings();
+        JDBCExceptionReporter.logAndClearWarnings(connection);
         connectionProvider.closeConnection(connection);
-        connectionProvider.close();
       }
       catch (SQLException e) {
-        log.debug("could not close jdbc connection", e);
+        log.debug("could not close " + connection, e);
       }
+      finally {
+        connectionProvider.close();
+      }
     }
   }
 




More information about the jbpm-commits mailing list