[jbpm-commits] JBoss JBPM SVN: r5107 - in jbpm3/branches/jbpm-3.2-soa/modules: core/src/main/java/org/jbpm/db and 5 other directories.

do-not-reply at jboss.org do-not-reply at jboss.org
Thu Jun 25 01:31:08 EDT 2009


Author: alex.guizar at jboss.com
Date: 2009-06-25 01:31:08 -0400 (Thu, 25 Jun 2009)
New Revision: 5107

Modified:
   jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java
   jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
   jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceServiceFactory.java
   jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/Semaphore.java
   jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/perf/SimplePerformanceTest.java
   jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml
   jbpm3/branches/jbpm-3.2-soa/modules/db/scripts/antrun-jbpmschema.xml
Log:
JBPM-2115: jBPM testsuite hangs when executed with DB2 (CODING IN PROGRESS)
clear warnings in JbpmSchema, replace SchemaExport with JbpmSchema in ant task

Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/ant/JbpmSchemaTask.java	2009-06-25 05:31:08 UTC (rev 5107)
@@ -21,9 +21,9 @@
  */
 package org.jbpm.ant;
 
-import java.io.FileOutputStream;
+import java.io.FileWriter;
 import java.io.IOException;
-import java.io.PrintStream;
+import java.io.Writer;
 import java.util.Iterator;
 import java.util.List;
 
@@ -31,9 +31,9 @@
 import org.apache.tools.ant.Project;
 import org.apache.tools.ant.Task;
 import org.hibernate.cfg.Configuration;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
-import org.hibernate.tool.hbm2ddl.SchemaUpdate;
 
+import org.jbpm.db.JbpmSchema;
+
 public class JbpmSchemaTask extends Task {
 
   String config = "hibernate.cfg.xml";
@@ -43,64 +43,68 @@
   String delimiter;
 
   public void execute() throws BuildException {
-    List exceptions;
-    try {
-      Configuration configuration = AntHelper.getConfiguration(config, properties);
-      if ("drop".equalsIgnoreCase(action)) {
-        SchemaExport schemaExport = getSchemaExport(configuration);
-        schemaExport.execute(false, false, true, false);
-        exceptions = schemaExport.getExceptions();
+    // Create schema tool
+    JbpmSchema jbpmSchema = getJbpmSchema();
+
+    // Generate script
+    String[] script;
+    if ("create".equalsIgnoreCase(action)) {
+      script = jbpmSchema.getCreateSql();
+    }
+    else if ("update".equalsIgnoreCase(action)) {
+      try {
+        script = jbpmSchema.getUpdateSql();
       }
-      else if ("create".equalsIgnoreCase(action)) {
-        SchemaExport schemaExport = getSchemaExport(configuration);
-        schemaExport.execute(false, false, false, true);
-        exceptions = schemaExport.getExceptions();
+      catch (RuntimeException e) {
+        e.printStackTrace();
+        throw e;
       }
-      else if ("update".equalsIgnoreCase(action)) {
-        PrintStream fileOut = null;
-        PrintStream systemOut = System.out;
-        try {
-          if (output != null) {
-            fileOut = new PrintStream(new FileOutputStream(output));
-            System.setOut(fileOut);
-          }
-          SchemaUpdate schemaUpdate = getSchemaUpdate(configuration);
-          schemaUpdate.execute(true, false);
-          exceptions = schemaUpdate.getExceptions();
-        }
-        finally {
-          if (fileOut != null) {
-            System.setOut(systemOut);
-            fileOut.close();
-          }
-        }
-      }
-      else {
-        throw new IllegalArgumentException("Unsupported action: " + action);
-      }
     }
-    catch (IOException ex) {
-      throw new BuildException(ex);
+    else if ("drop".equalsIgnoreCase(action)) {
+      script = jbpmSchema.getDropSql();
     }
+    else if ("clean".equalsIgnoreCase(action)) {
+      script = jbpmSchema.getCleanSql();
+    }
+    else {
+      throw new BuildException("Unsupported action: " + action);
+    }
 
-    // Print the exceptions if there are any
-    for (Iterator i = exceptions.iterator(); i.hasNext();) {
-      Object ex = i.next();
-      log(ex.toString(), Project.MSG_ERR);
+    // Print exceptions, if any
+    List exceptions = jbpmSchema.getExceptions();
+    if (!exceptions.isEmpty()) {
+      for (Iterator i = exceptions.iterator(); i.hasNext();) {
+        Object exception = i.next();
+        log(exception.toString(), Project.MSG_ERR);
+      }
     }
+
+    // Save script to output file
+    try {
+      saveScript(script, jbpmSchema);
+    }
+    catch (IOException e) {
+      log(e.toString(), Project.MSG_ERR);
+      throw new BuildException("Failed to write script to " + output);
+    }
   }
 
-  private SchemaExport getSchemaExport(Configuration configuration) {
-    SchemaExport schemaExport = new SchemaExport(configuration);
-    schemaExport.setFormat(false);
-    if (output != null) schemaExport.setOutputFile(output);
-    if (delimiter != null) schemaExport.setDelimiter(delimiter);
-    return schemaExport;
+  private JbpmSchema getJbpmSchema() {
+    Configuration configuration = AntHelper.getConfiguration(config, properties);
+
+    JbpmSchema jbpmSchema = new JbpmSchema(configuration);
+    jbpmSchema.setDelimiter(delimiter);
+    return jbpmSchema;
   }
 
-  private SchemaUpdate getSchemaUpdate(Configuration configuration) {
-    SchemaUpdate schemaUpdate = new SchemaUpdate(configuration);
-    return schemaUpdate;
+  private void saveScript(String[] script, JbpmSchema jbpmSchema) throws IOException {
+    Writer writer = new FileWriter(output);
+    try {
+      jbpmSchema.writeSql(writer, script);
+    }
+    finally {
+      writer.close();
+    }
   }
 
   public void setAction(String action) {

Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/db/JbpmSchema.java	2009-06-25 05:31:08 UTC (rev 5107)
@@ -23,16 +23,18 @@
 
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileOutputStream;
+import java.io.FileWriter;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.PrintStream;
+import java.io.Writer;
 import java.sql.Connection;
 import java.sql.DatabaseMetaData;
 import java.sql.ResultSet;
 import java.sql.SQLException;
+import java.sql.SQLWarning;
 import java.sql.Statement;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -41,12 +43,12 @@
 import java.util.Properties;
 import java.util.Set;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.hibernate.HibernateException;
 import org.hibernate.cfg.Configuration;
-import org.hibernate.cfg.Settings;
+import org.hibernate.cfg.Environment;
 import org.hibernate.connection.ConnectionProvider;
 import org.hibernate.connection.ConnectionProviderFactory;
+import org.hibernate.dialect.Dialect;
 import org.hibernate.mapping.Table;
 import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
 import org.hibernate.tool.hbm2ddl.TableMetadata;
@@ -60,97 +62,76 @@
 public class JbpmSchema {
 
   private final Configuration configuration;
-  private final Settings settings;
-
   private ConnectionProvider connectionProvider;
-  private Connection connection;
-
+  private String delimiter;
   private final List exceptions = new ArrayList();
 
+  private static final String[] EMPTY_STRING_ARRAY = new String[0];
+
   public JbpmSchema(Configuration configuration) {
     this.configuration = configuration;
-    settings = configuration.buildSettings();
   }
 
+  private Dialect getDialect() {
+    return Dialect.getDialect(configuration.getProperties());
+  }
+
+  private String getDefaultCatalog() {
+    return configuration.getProperty(Environment.DEFAULT_CATALOG);
+  }
+
+  private String getDefaultSchema() {
+    return configuration.getProperty(Environment.DEFAULT_SCHEMA);
+  }
+
+  private boolean getShowSql() {
+    return "true".equalsIgnoreCase(configuration.getProperty(Environment.SHOW_SQL));
+  }
+
+  public void setDelimiter(String delimiter) {
+    this.delimiter = delimiter;
+  }
+
+  public List getExceptions() {
+    return exceptions;
+  }
+
   public String[] getCreateSql() {
-    return configuration.generateSchemaCreationScript(settings.getDialect());
+    return configuration.generateSchemaCreationScript(getDialect());
   }
 
   public String[] getDropSql() {
-    return configuration.generateDropSchemaScript(settings.getDialect());
+    return configuration.generateDropSchemaScript(getDialect());
   }
 
   public String[] getCleanSql() {
     return concat(getDropSql(), getCreateSql());
   }
 
-  public Set getJbpmTables() {
-    Set jbpmTables = new HashSet();
-    for (Iterator i = configuration.getTableMappings(); i.hasNext();) {
-      Table table = (Table) i.next();
-      if (table.isPhysicalTable()) {
-        jbpmTables.add(table.getName());
-      }
-    }
-    return jbpmTables;
+  private static String[] concat(String[] array1, String[] array2) {
+    int length1 = array1.length;
+    int length2 = array2.length;
+    String[] result = new String[length1 + length2];
+    System.arraycopy(array1, 0, result, 0, length1);
+    System.arraycopy(array2, 0, result, length1, length2);
+    return result;
   }
 
-  public Set getExistingTables() {
+  public String[] getUpdateSql() {
+    Connection connection = null;
     try {
-      createConnection();
-      Set existingTables = new HashSet();
-
-      DatabaseMetaData metaData = connection.getMetaData();
-      boolean storesLowerCaseIdentifiers = metaData.storesLowerCaseIdentifiers();
-      ResultSet resultSet = metaData.getTables(settings.getDefaultCatalogName(), settings.getDefaultSchemaName(), null, new String[] { "TABLE" });
-      try {
-        while (resultSet.next()) {
-          String tableName = resultSet.getString("TABLE_NAME");
-          if (storesLowerCaseIdentifiers) {
-            tableName = tableName.toUpperCase();
-          }
-          existingTables.add(tableName);
-        }
-      }
-      finally {
-        resultSet.close();
-      }
-      return existingTables;
+      connection = createConnection();
+      return configuration.generateSchemaUpdateScript(getDialect(), getDatabaseMetadata(connection));
     }
     catch (SQLException e) {
-      throw new JbpmException("could not get available table names", e);
-    }
-    finally {
-      closeConnection();
-    }
-  }
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to generate update sql");
 
-  public Map getRowsPerTable() {
-    Map rowsPerTable = new HashMap();
-    try {
-      createConnection();
-      Statement statement = connection.createStatement();
-      for (Iterator i = getJbpmTables().iterator(); i.hasNext();) {
-        String tableName = (String) i.next();
-        String sql = "SELECT COUNT(*) FROM " + tableName;
-        ResultSet resultSet = statement.executeQuery(sql);
-        if (!resultSet.next()) throw new JbpmException("empty result set: " + sql);
-
-        long count = resultSet.getLong(1);
-        if (resultSet.wasNull()) throw new JbpmException("count was null: " + sql);
-
-        rowsPerTable.put(tableName, new Long(count));
-        resultSet.close();
-      }
-      statement.close();
+      return EMPTY_STRING_ARRAY;
     }
-    catch (SQLException e) {
-      throw new JbpmException("could not count records", e);
-    }
     finally {
-      closeConnection();
+      closeConnection(connection);
     }
-    return rowsPerTable;
   }
 
   public void dropSchema() {
@@ -158,7 +139,8 @@
       execute(getDropSql());
     }
     catch (SQLException e) {
-      throw new JbpmException("could not drop schema", e);
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to drop schema");
     }
   }
 
@@ -167,7 +149,8 @@
       execute(getCreateSql());
     }
     catch (SQLException e) {
-      throw new JbpmException("could not create schema", e);
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to create schema");
     }
   }
 
@@ -176,126 +159,279 @@
       execute(getCleanSql());
     }
     catch (SQLException e) {
-      throw new JbpmException("could not clean schema", e);
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to clean schema");
     }
   }
 
+  public void updateSchema() {
+    try {
+      execute(getUpdateSql());
+    }
+    catch (SQLException e) {
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to update schema");
+    }
+  }
+
+  private void execute(String[] script) throws SQLException {
+    Connection connection = null;
+    try {
+      connection = createConnection();
+      Statement statement = connection.createStatement();
+      try {
+        final boolean showSql = getShowSql();
+        for (int i = 0; i < script.length; i++) {
+          String sql = script[i];
+          if (showSql) System.out.println(sql);
+          execute(sql, statement);
+        }
+      }
+      finally {
+        statement.close();
+      }
+    }
+    finally {
+      closeConnection(connection);
+    }
+  }
+
+  private void execute(String sql, Statement statement) {
+    try {
+      statement.executeUpdate(sql);
+
+      SQLWarning warning = statement.getWarnings();
+      if (warning != null) {
+        JDBCExceptionReporter.logWarnings(warning);
+        statement.clearWarnings();
+      }
+    }
+    catch (SQLException e) {
+      JDBCExceptionReporter.logExceptions(e, "failed to execute update");
+      exceptions.add(e);
+    }
+  }
+
   public void saveSqlScripts(String dir, String prefix) {
+    File path = new File(dir);
+    if (!path.isDirectory()) {
+      throw new JbpmException(path + " is not a directory");
+    }
+
     try {
-      new File(dir).mkdirs();
-      saveSqlScript(dir + "/" + prefix + ".drop.sql", getDropSql());
-      saveSqlScript(dir + "/" + prefix + ".create.sql", getCreateSql());
-      saveSqlScript(dir + "/" + prefix + ".clean.sql", getCleanSql());
-      saveSqlScript(dir + "/" + prefix + ".drop.create.sql", concat(getDropSql(), getCreateSql()));
+      saveSqlScript(new File(path, prefix + ".drop.sql"), getDropSql());
+      saveSqlScript(new File(path, prefix + ".create.sql"), getCreateSql());
+      saveSqlScript(new File(path, prefix + ".clean.sql"), getCleanSql());
     }
     catch (IOException e) {
-      throw new JbpmException("couldn't generate scripts", e);
+      throw new JbpmException("failed to generate scripts", e);
     }
   }
 
-  private static String[] concat(String[] array1, String[] array2) {
-    int length1 = array1.length;
-    int length2 = array2.length;
-    String[] result = new String[length1 + length2];
-    System.arraycopy(array1, 0, result, 0, length1);
-    System.arraycopy(array2, 0, result, length1, length2);
-    return result;
+  private void saveSqlScript(File file, String[] script) throws IOException {
+    Writer writer = new FileWriter(file);
+    try {
+      writeSql(writer, script);
+    }
+    finally {
+      writer.close();
+    }
   }
 
-  public boolean tableExists(String tableName) {
-    Table table = findTableMapping(tableName);
+  public void writeSql(Writer writer, String[] script) throws IOException {
+    String lineSeparator = System.getProperty("line.separator");
+    for (int i = 0; i < script.length; i++) {
+      writer.write(script[i]);
+      if (delimiter != null) writer.write(delimiter);
+      writer.write(lineSeparator);
+    }
+  }
+
+  public Set getJbpmTables() {
+    Set jbpmTables = new HashSet();
+    for (Iterator i = configuration.getTableMappings(); i.hasNext();) {
+      Table table = (Table) i.next();
+      if (table.isPhysicalTable()) {
+        jbpmTables.add(table.getName());
+      }
+    }
+    return jbpmTables;
+  }
+
+  public Map getRowsPerTable() {
+    Connection connection = null;
     try {
-      createConnection();
-      return getTableMetadata(table) != null;
+      connection = createConnection();
+      Map rowsPerTable = new HashMap();
+
+      Statement statement = connection.createStatement();
+      try {
+        for (Iterator i = getJbpmTables().iterator(); i.hasNext();) {
+          String tableName = (String) i.next();
+          String sql = "SELECT COUNT(*) FROM " + tableName;
+
+          ResultSet resultSet = statement.executeQuery(sql);
+          if (!resultSet.next()) continue;
+
+          long count = resultSet.getLong(1);
+          if (resultSet.wasNull()) continue;
+
+          rowsPerTable.put(tableName, new Long(count));
+          resultSet.close();
+        }
+      }
+      finally {
+        statement.close();
+      }
+
+      return rowsPerTable;
     }
     catch (SQLException e) {
-      throw new JbpmException("could not tell whether table exists: " + tableName, e);
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "could not count records");
+
+      return Collections.EMPTY_MAP;
     }
     finally {
-      closeConnection();
+      closeConnection(connection);
     }
   }
 
-  public void createTable(String tableName) {
-    Table table = findTableMapping(tableName);
-    String sql = table.sqlCreateString(settings.getDialect(), configuration.buildMapping(), settings.getDefaultCatalogName(), settings.getDefaultSchemaName());
+  public Set getExistingTables() {
+    Connection connection = null;
     try {
-      execute(new String[] { sql });
+      connection = createConnection();
+      Set existingTables = new HashSet();
+
+      DatabaseMetaData metaData = connection.getMetaData();
+      boolean storesLowerCaseIdentifiers = metaData.storesLowerCaseIdentifiers();
+      ResultSet resultSet = metaData.getTables(getDefaultCatalog(), getDefaultSchema(), null,
+          new String[] { "TABLE" });
+      try {
+        while (resultSet.next()) {
+          String tableName = resultSet.getString("TABLE_NAME");
+          if (storesLowerCaseIdentifiers) tableName = tableName.toUpperCase();
+          existingTables.add(tableName);
+        }
+      }
+      finally {
+        resultSet.close();
+      }
+
+      return existingTables;
     }
     catch (SQLException e) {
-      throw new JbpmException("could not create table: " + tableName, e);
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "could not get available table names");
+
+      return Collections.EMPTY_SET;
     }
+    finally {
+      closeConnection(connection);
+    }
   }
 
+  public boolean tableExists(String tableName) {
+    Connection connection = null;
+    try {
+      connection = createConnection();
+      Table table = findTableMapping(tableName);
+      return getTableMetadata(connection, table) != null;
+    }
+    catch (SQLException e) {
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "could not determine whether table exists");
+
+      return false;
+    }
+    finally {
+      closeConnection(connection);
+    }
+  }
+
   public void updateTable(String tableName) {
-    Table table = findTableMapping(tableName);
+    Connection connection = null;
     try {
-      createConnection();
-      Iterator sqls = table.sqlAlterStrings(settings.getDialect(), configuration.buildMapping(), getTableMetadata(table), settings.getDefaultCatalogName(), settings.getDefaultSchemaName());
+      connection = createConnection();
 
+      Table table = findTableMapping(tableName);
+      Iterator script = table.sqlAlterStrings(getDialect(), configuration.buildMapping(),
+          getTableMetadata(connection, table), getDefaultCatalog(), getDefaultSchema());
+
       Statement statement = connection.createStatement();
-      while (sqls.hasNext()) {
-        String sql = (String) sqls.next();
-        statement.executeUpdate(sql);
+      try {
+        while (script.hasNext()) {
+          String sql = (String) script.next();
+          execute(sql, statement);
+        }
       }
-      statement.close();
+      finally {
+        statement.close();
+      }
     }
     catch (SQLException e) {
-      throw new JbpmException("could not update table: " + tableName, e);
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to update table");
     }
     finally {
-      closeConnection();
+      closeConnection(connection);
     }
   }
 
-  public List getExceptions() {
-    return exceptions;
-  }
-
   private Table findTableMapping(String tableName) {
     for (Iterator i = configuration.getTableMappings(); i.hasNext();) {
       Table table = (Table) i.next();
-      if (tableName.equals(table.getName())) {
-        return table;
-      }
+      if (tableName.equals(table.getName())) return table;
     }
     throw new JbpmException("no mapping found for table: " + tableName);
   }
 
-  private TableMetadata getTableMetadata(Table table) throws SQLException {
-    DatabaseMetadata databaseMetadata = new DatabaseMetadata(connection, settings.getDialect());
-    return databaseMetadata.getTableMetadata(table.getName(), table.getSchema() == null ? settings.getDefaultSchemaName()
-        : table.getSchema(), table.getCatalog() == null ? settings.getDefaultCatalogName()
-        : table.getCatalog(), table.isQuoted());
+  private DatabaseMetadata getDatabaseMetadata(Connection connection) throws SQLException {
+    return new DatabaseMetadata(connection, getDialect());
   }
 
+  private TableMetadata getTableMetadata(Connection connection, Table table) throws SQLException {
+    String tableSchema = table.getSchema();
+    String tableCatalog = table.getCatalog();
+    return getDatabaseMetadata(connection).getTableMetadata(table.getName(),
+        tableSchema != null ? tableSchema : getDefaultSchema(),
+        tableCatalog != null ? tableCatalog : getDefaultCatalog(), table.isQuoted());
+  }
+
+  public void createTable(String tableName) {
+    Table table = findTableMapping(tableName);
+    String sql = table.sqlCreateString(getDialect(), configuration.buildMapping(),
+        getDefaultCatalog(), getDefaultSchema());
+    try {
+      execute(new String[] { sql });
+    }
+    catch (SQLException e) {
+      exceptions.add(e);
+      JDBCExceptionReporter.logExceptions(e, "failed to create table");
+    }
+  }
+
   public static void main(String[] args) {
-    if (args.length == 0) syntax();
+    if (args.length > 0) {
+      String action = args[0];
 
-    if ("scripts".equalsIgnoreCase(args[0]) && args.length >= 3 && args.length <= 5) {
-      JbpmSchema jbpmSchema = new JbpmSchema(createConfiguration(args, 3));
-      jbpmSchema.saveSqlScripts(args[1], args[2]);
-    }
-    else if (args.length <= 3) {
-      if ("create".equalsIgnoreCase(args[0])) {
-        JbpmSchema jbpmSchema = new JbpmSchema(createConfiguration(args, 1));
-        jbpmSchema.createSchema();
+      if ("create".equalsIgnoreCase(action)) {
+        getJbpmSchema(args, 1).createSchema();
       }
-      else if ("drop".equalsIgnoreCase(args[0])) {
-        JbpmSchema jbpmSchema = new JbpmSchema(createConfiguration(args, 1));
-        jbpmSchema.dropSchema();
+      else if ("drop".equalsIgnoreCase(action)) {
+        getJbpmSchema(args, 1).dropSchema();
       }
-      else if ("clean".equalsIgnoreCase(args[0])) {
-        JbpmSchema jbpmSchema = new JbpmSchema(createConfiguration(args, 1));
-        jbpmSchema.cleanSchema();
+      else if ("clean".equalsIgnoreCase(action)) {
+        getJbpmSchema(args, 1).cleanSchema();
       }
-      else {
+      else if ("scripts".equalsIgnoreCase(action) && args.length > 2) {
+        getJbpmSchema(args, 3).saveSqlScripts(args[1], args[2]);
+      }
+      else
         syntax();
-      }
     }
-    else {
+    else
       syntax();
-    }
   }
 
   private static void syntax() {
@@ -307,107 +443,68 @@
     System.exit(1);
   }
 
-  static Configuration createConfiguration(String[] args, int index) {
-    String hibernateCfgXml = (args.length > index ? args[index] : "hibernate.cfg.xml");
-    String hibernateProperties = (args.length > (index + 1) ? args[index + 1] : null);
-
+  private static JbpmSchema getJbpmSchema(String[] args, int index) {
     Configuration configuration = new Configuration();
-    configuration.configure(new File(hibernateCfgXml));
-    if (hibernateProperties != null) {
-      try {
-        Properties properties = new Properties();
-        InputStream inputStream = new FileInputStream(hibernateProperties);
-        properties.load(inputStream);
-        configuration.setProperties(properties);
-      }
-      catch (IOException e) {
-        throw new JbpmException("couldn't load hibernate configuration", e);
-      }
-    }
 
-    return configuration;
-  }
+    if (index < args.length) {
+      // read configuration xml file
+      String hibernateCfgXml = args[index];
+      configuration.configure(new File(hibernateCfgXml));
 
-  void saveSqlScript(String fileName, String[] sql) throws IOException {
-    PrintStream out = new PrintStream(new FileOutputStream(fileName));
-    try {
-      for (int i = 0; i < sql.length; i++) {
-        out.println(sql[i] + getSqlDelimiter());
+      // read extra properties
+      if (index + 1 < args.length) {
+        String hibernateProperties = args[index + 1];
+        try {
+          InputStream inputStream = new FileInputStream(hibernateProperties);
+          Properties properties = new Properties();
+          properties.load(inputStream);
+          configuration.addProperties(properties);
+        }
+        catch (IOException e) {
+          throw new JbpmException("failed to load hibernate properties", e);
+        }
       }
     }
-    finally {
-      out.close();
+    else {
+      // read configuration from default resource
+      configuration.configure();
     }
+
+    return new JbpmSchema(configuration);
   }
 
-  void execute(String[] sql) throws SQLException {
-    boolean showSql = settings.isShowSqlEnabled();
-    exceptions.clear();
+  private Connection createConnection() throws SQLException {
     try {
-      createConnection();
-      Statement statement = connection.createStatement();
-      for (int i = 0; i < sql.length; i++) {
-        String line = sql[i];
-        if (showSql) System.out.println(line);
-        log.debug(line);
-        try {
-          statement.executeUpdate(line);
-        }
-        catch (SQLException e) {
-          exceptions.add(e);
-          log.debug(e.getMessage());
-        }
-      }
-      statement.close();
+      connectionProvider = ConnectionProviderFactory.newConnectionProvider(configuration.getProperties());
     }
-    finally {
-      closeConnection();
+    catch (HibernateException e) {
+      throw new SQLException(e.getMessage());
     }
-  }
-
-  void createConnection() throws SQLException {
-    connectionProvider = ConnectionProviderFactory.newConnectionProvider(configuration.getProperties());
-    connection = connectionProvider.getConnection();
+    Connection connection = connectionProvider.getConnection();
     if (connection.getAutoCommit() == false) {
       connection.commit();
       connection.setAutoCommit(true);
     }
+    return connection;
   }
 
-  void closeConnection() {
-    if (connection != null) {
+  private void closeConnection(Connection connection) {
+    if (connectionProvider != null) {
       try {
-        JDBCExceptionReporter.logAndClearWarnings(connection);
-        connectionProvider.closeConnection(connection);
+        if (connection != null) {
+          JDBCExceptionReporter.logAndClearWarnings(connection);
+          connectionProvider.closeConnection(connection);
+        }
       }
       catch (SQLException e) {
-        log.debug("could not close " + connection, e);
+        exceptions.add(e);
+        JDBCExceptionReporter.logExceptions(e);
       }
       finally {
-        connection = null;
-
         connectionProvider.close();
         connectionProvider = null;
       }
     }
   }
 
-  public Properties getProperties() {
-    return configuration.getProperties();
-  }
-
-  // sql delimiter ////////////////////////////////////////////////////////////
-
-  static String sqlDelimiter = null;
-
-  synchronized String getSqlDelimiter() {
-    if (sqlDelimiter == null) {
-      sqlDelimiter = getProperties().getProperty("jbpm.sql.delimiter", ";");
-    }
-    return sqlDelimiter;
-  }
-
-  // logger ///////////////////////////////////////////////////////////////////
-
-  private static final Log log = LogFactory.getLog(JbpmSchema.class);
 }

Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceServiceFactory.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceServiceFactory.java	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/persistence/db/DbPersistenceServiceFactory.java	2009-06-25 05:31:08 UTC (rev 5107)
@@ -73,6 +73,9 @@
     return configuration;
   }
 
+  /**
+   * @deprecated use {@link #getJbpmSchema()} instead
+   */
   public synchronized SchemaExport getSchemaExport() {
     if (schemaExport == null) {
       log.debug("creating schema export");

Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/Semaphore.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/Semaphore.java	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/main/java/org/jbpm/util/Semaphore.java	2009-06-25 05:31:08 UTC (rev 5107)
@@ -3,7 +3,12 @@
 import java.io.Serializable;
 
 /**
- * Trivial semaphore which borrows the interface of java.util.concurrent.Semaphore.
+ * A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each
+ * {@linkplain #acquire acquire} blocks if necessary until a permit is available, and then takes it.
+ * Each {@linkplain #release() release} adds a permit, potentially releasing a blocking acquirer.
+ * 
+ * @see <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Semaphore.html">
+ *      <code>java.util.concurrent.Semaphore</code></a>
  */
 public class Semaphore implements Serializable {
 
@@ -11,46 +16,114 @@
 
   private static final long serialVersionUID = 1L;
 
+  /**
+   * Creates a <tt>Semaphore</tt> with the given number of permits.
+   * 
+   * @param permits the initial number of permits available. This value may be negative, in which
+   *        case releases must occur before any acquires will be granted.
+   */
   public Semaphore(int permits) {
     this.permits = permits;
   }
 
+  /**
+   * Releases a permit, returning it to the semaphore.
+   */
   public void release() {
     release(1);
   }
 
-  public synchronized void release(int permits) {
-    this.permits += permits;
-    notifyAll();
+  /**
+   * Releases the given number of permits, returning them to the semaphore.
+   * 
+   * @param permits the number of permits to release
+   * @throws IllegalArgumentException if permits less than zero.
+   */
+  public void release(int permits) {
+    if (permits < 0) throw new IllegalArgumentException(Integer.toString(permits));
+
+    synchronized (this) {
+      this.permits += permits;
+      notifyAll();
+    }
   }
 
+  /**
+   * Acquires a permit from this semaphore, blocking until one is available, or the thread is
+   * {@link Thread#interrupt interrupted}.
+   * 
+   * @throws InterruptedException if the current thread is interrupted
+   * @see Thread#interrupt
+   */
   public void acquire() throws InterruptedException {
     acquire(1);
   }
 
-  public synchronized void acquire(int permits) throws InterruptedException {
-    while (this.permits < permits) {
-      wait();
+  /**
+   * Acquires the given number of permits from this semaphore, blocking until all are available, or
+   * the thread is {@link Thread#interrupt interrupted}.
+   * 
+   * @param permits the number of permits to acquire
+   * @throws InterruptedException if the current thread is interrupted
+   * @throws IllegalArgumentException if permits less than zero.
+   * @see Thread#interrupt
+   */
+  public void acquire(int permits) throws InterruptedException {
+    if (permits < 0) throw new IllegalArgumentException(Integer.toString(permits));
+
+    synchronized (this) {
+      while (this.permits < permits) {
+        wait();
+      }
+      this.permits -= permits;
     }
-    this.permits -= permits;
   }
 
+  /**
+   * Acquires a permit from this semaphore, if one becomes available within the given waiting time
+   * and the current thread has not been {@link Thread#interrupt interrupted}.
+   * 
+   * @param timeout the maximum time to wait for a permit
+   * @return <tt>true</tt> if a permit was acquired and <tt>false</tt> if the waiting time elapsed
+   *         before a permit was acquired.
+   * @throws InterruptedException if the current thread is interrupted
+   * @see Thread#interrupt
+   */
   public boolean tryAcquire(long timeout) throws InterruptedException {
     return tryAcquire(1, timeout);
   }
 
-  public synchronized boolean tryAcquire(int permits, long timeout) throws InterruptedException {
+  /**
+   * Acquires the given number of permits from this semaphore, if all become available within the
+   * given waiting time and the current thread has not been {@link Thread#interrupt interrupted}.
+   * 
+   * @param permits the number of permits to acquire
+   * @param timeout the maximum time to wait for the permits
+   * @return <tt>true</tt> if all permits were acquired and <tt>false</tt> if the waiting time
+   *         elapsed before all permits were acquired.
+   * @throws InterruptedException if the current thread is interrupted
+   * @throws IllegalArgumentException if permits less than zero.
+   * @see Thread#interrupt
+   */
+  public boolean tryAcquire(int permits, long timeout) throws InterruptedException {
+    if (permits < 0) throw new IllegalArgumentException(Integer.toString(permits));
+
     long startTime = System.currentTimeMillis();
-    while (this.permits < permits && System.currentTimeMillis() - startTime < timeout) {
-      wait(timeout);
-    }
-    if (this.permits >= permits) {
+    synchronized (this) {
+      while (this.permits < permits) {
+        if (System.currentTimeMillis() - startTime >= timeout) return false;
+        wait(timeout);
+      }
       this.permits -= permits;
       return true;
     }
-    return false;
   }
 
+  /**
+   * Acquire and return all permits that are immediately available.
+   * 
+   * @return the number of permits
+   */
   public synchronized int drainPermits() {
     int permits = this.permits;
     this.permits = 0;

Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/perf/SimplePerformanceTest.java
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/perf/SimplePerformanceTest.java	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/java/org/jbpm/perf/SimplePerformanceTest.java	2009-06-25 05:31:08 UTC (rev 5107)
@@ -34,7 +34,7 @@
  * @see <a href="https://jira.jboss.org/jira/browse/JBPM-2043">JBPM-2043</a>
  * @author mvecera at redhat.com
  * @author pmacik at redhat.com
- * @author thomas.diesler at jboss.com
+ * @author aguizar at redhat.com
  * @since 18-Feb-2009
  */
 public class SimplePerformanceTest extends AbstractDbTestCase {
@@ -83,15 +83,15 @@
 
     long startTime = System.currentTimeMillis();
     launchProcessInstances(MEASUREMENT_INSTANCES);
-    long duration = System.currentTimeMillis() - startTime;
+    long duration = (System.currentTimeMillis() - startTime) / 1000;
 
     System.out.println("=== Test finished processing "
         + MEASUREMENT_INSTANCES
         + " instances in "
         + duration
-        + "ms ===");
+        + " seconds ===");
     System.out.println("=== This is "
-        + Math.round(1000f * MEASUREMENT_INSTANCES / duration)
+        + (MEASUREMENT_INSTANCES / duration)
         + " instances per second ===");
   }
 

Modified: jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/core/src/test/resources/log4j.xml	2009-06-25 05:31:08 UTC (rev 5107)
@@ -36,11 +36,11 @@
     <priority value="INFO" />
   </category>
 
+  <!--
   <category name="org.hibernate.SQL">
     <priority value="DEBUG" />
   </category>
 
-  <!-- 
   <category name="org.hibernate.connection">
     <priority value="TRACE" />
   </category>

Modified: jbpm3/branches/jbpm-3.2-soa/modules/db/scripts/antrun-jbpmschema.xml
===================================================================
--- jbpm3/branches/jbpm-3.2-soa/modules/db/scripts/antrun-jbpmschema.xml	2009-06-24 18:17:43 UTC (rev 5106)
+++ jbpm3/branches/jbpm-3.2-soa/modules/db/scripts/antrun-jbpmschema.xml	2009-06-25 05:31:08 UTC (rev 5107)
@@ -40,11 +40,11 @@
   </target>
   
   <target name="update-schema" depends="setup-schema" description="Generate jBPM Database Update Scripts">
+    <jbpmschema output="${scriptsdir}/jbpm.jpdl.db2.update322.sql" config="hibernate.cfg.db2.xml" properties="db2.properties" action="update"/>
     <jbpmschema output="${scriptsdir}/jbpm.jpdl.mysql.update322.sql" config="hibernate.cfg.mysql.xml" properties="mysql.properties" action="update" delimiter=";"/>
+  	<jbpmschema output="${scriptsdir}/jbpm.jpdl.oracle.update322.sql" config="hibernate.cfg.oracle.xml" properties="oracle.properties" action="update" delimiter=";"/>
     <jbpmschema output="${scriptsdir}/jbpm.jpdl.postgresql.update322.sql" config="hibernate.cfg.postgresql.xml" properties="postgresql.properties" action="update" delimiter=";"/>
     <jbpmschema output="${scriptsdir}/jbpm.jpdl.sybase.update322.sql" config="hibernate.cfg.sybase.xml" properties="sybase.properties" action="update"/>
-  	<jbpmschema output="${scriptsdir}/jbpm.jpdl.oracle.update322.sql" config="hibernate.cfg.oracle.xml" properties="oracle.properties" action="update" delimiter=";"/>
-    <jbpmschema output="${scriptsdir}/jbpm.jpdl.db2.update322.sql" config="hibernate.cfg.db2.xml" properties="db2.properties" action="update"/>
   </target>
   
 </project>




More information about the jbpm-commits mailing list