db-ojb-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From to...@apache.org
Subject cvs commit: db-ojb/lib commons-betwixt-20030211.133854.jar commons-sql-1.0-dev.jar commons-digester-1.5.jar
Date Sun, 04 Jul 2004 21:45:51 GMT
tomdz       2004/07/04 14:45:51

  Modified:    .        .classpath
  Added:       src/java/org/apache/ojb/broker/util/dbhandling
                        DatabaseHandlingException.java
                        CommonsSqlDatabaseHandling.java
                        DatabaseHandling.java DatabaseHandlingTask.java
                        TorqueDatabaseHandling.java
               lib      commons-betwixt-20030211.133854.jar
                        commons-sql-1.0-dev.jar commons-digester-1.5.jar
  Removed:     src/java/org/apache/ojb/broker/util/dbhandling
                        TorqueDBHandling.java DBHandling.java
                        DBHandlingTask.java
  Log:
  First version of database handling via commons-sql; needs testing and modifications for specific databases (creation url)
  
  Revision  Changes    Path
  1.36      +3 -0      db-ojb/.classpath
  
  Index: .classpath
  ===================================================================
  RCS file: /home/cvs/db-ojb/.classpath,v
  retrieving revision 1.35
  retrieving revision 1.36
  diff -u -r1.35 -r1.36
  --- .classpath	22 Jun 2004 20:46:48 -0000	1.35
  +++ .classpath	4 Jul 2004 21:45:50 -0000	1.36
  @@ -35,5 +35,8 @@
   	<classpathentry kind="lib" path="lib/ant-1.6.0.jar"/>
   	<classpathentry kind="lib" path="lib/ant-junit.jar"/>
   	<classpathentry kind="lib" path="lib/ant-launcher.jar"/>
  +	<classpathentry kind="lib" path="lib/commons-sql-1.0-dev.jar"/>
  +	<classpathentry kind="lib" path="lib/commons-betwixt-20030211.133854.jar"/>
  +	<classpathentry kind="lib" path="lib/commons-digester-1.5.jar"/>
   	<classpathentry kind="output" path="target/classes"/>
   </classpath>
  
  
  
  1.1                  db-ojb/src/java/org/apache/ojb/broker/util/dbhandling/DatabaseHandlingException.java
  
  Index: DatabaseHandlingException.java
  ===================================================================
  package org.apache.ojb.broker.util.dbhandling;
  
  /* Copyright 2002-2004 The Apache Software Foundation
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import org.apache.ojb.broker.OJBException;
  
  public class DatabaseHandlingException extends OJBException
  {
      public DatabaseHandlingException()
      {
          super();
      }
  
      public DatabaseHandlingException(String message)
      {
          super(message);
      }
  
      public DatabaseHandlingException(Throwable cause)
      {
          super(cause);
      }
  
      public DatabaseHandlingException(String message, Throwable cause)
      {
          super(message, cause);
      }
  }
  
  
  
  1.1                  db-ojb/src/java/org/apache/ojb/broker/util/dbhandling/CommonsSqlDatabaseHandling.java
  
  Index: CommonsSqlDatabaseHandling.java
  ===================================================================
  package org.apache.ojb.broker.util.dbhandling;
  
  /* Copyright 2004-2004 The Apache Software Foundation
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.*;
  import java.sql.Connection;
  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.StringTokenizer;
  
  import org.apache.commons.sql.builder.SqlBuilder;
  import org.apache.commons.sql.builder.SqlBuilderFactory;
  import org.apache.commons.sql.io.DatabaseReader;
  import org.apache.commons.sql.io.DatabaseWriter;
  import org.apache.commons.sql.io.JdbcModelReader;
  import org.apache.commons.sql.model.Database;
  import org.apache.commons.sql.util.DDLExecutor;
  import org.apache.commons.sql.util.DataSourceWrapper;
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  
  /**
   * Provides database handling via commons-sql.
   * 
   * @author Thomas Dudziak
   */
  public class CommonsSqlDatabaseHandling implements DatabaseHandling
  {
      /** Maps jcd platforms to commons-sql database types */
      private static HashMap _platformToDatabaseType = new HashMap();
  
      static
      {
          _platformToDatabaseType.put("Db2",         "db2");
          _platformToDatabaseType.put("Firebird",    null);
          _platformToDatabaseType.put("Hsqldb",      "hsqldb");
          _platformToDatabaseType.put("Informix",    null);
          _platformToDatabaseType.put("MaxDB",       null);
          _platformToDatabaseType.put("MsAccess",    null);
          _platformToDatabaseType.put("MsSQLServer", "mssql");
          _platformToDatabaseType.put("MySQL",       "mysql");
          _platformToDatabaseType.put("Oracle",      "oracle");
          _platformToDatabaseType.put("Oracle9i",    "oracle");
          _platformToDatabaseType.put("WLOracle9i",  "oracle");
          _platformToDatabaseType.put("PostgreSQL",  "postgresql");
          _platformToDatabaseType.put("Sapdb",       null);
          _platformToDatabaseType.put("Sybase",      "sybase");
          _platformToDatabaseType.put("SybaseASA",   "sysbase");
          _platformToDatabaseType.put("SybaseASE",   "sybase");
      }
  
      /** The database connection descriptor */
      private JdbcConnectionDescriptor _jcd;
      /** The datasource for commons-sql */
      private DataSourceWrapper _dataSource;
      /** The database sql builder */
      private SqlBuilder _builder;
      /** The database schemas */
      private ArrayList _schemas = new ArrayList();
      /** Performs SQL statements */
      private DDLExecutor _ddlExecutor;
  
      /**
       * Returns the database type as used by commons-sql.
       * 
       * @return The database type
       * @throws DatabaseHandlingException If the database specified in the JCD is not supported by commons-sql
       */
      private String getDatabaseType() throws DatabaseHandlingException
      {
          String dbType = (String)_platformToDatabaseType.get(_jcd.getDbms());
  
          if (dbType == null)
          {
              throw new DatabaseHandlingException("Database "+_jcd.getDbms()+" is currently not supported by commons-sql");
          }
          return dbType;
      }
      
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DBHandling#setWorkDir(java.lang.String)
       */
      public void setWorkDir(String dir) throws IOException
      {
          // Not necessary for commons-sql
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DBHandling#setConnection(org.apache.ojb.broker.metadata.JdbcConnectionDescriptor)
       */
      public void setConnection(JdbcConnectionDescriptor jcd) throws DatabaseHandlingException
      {
          _jcd = jcd;
  
          _dataSource = new DataSourceWrapper();
  
          try
          {
              _dataSource.setDriverClassName(jcd.getDriver());
          }
          catch (ClassNotFoundException ex)
          {
              throw new DatabaseHandlingException(ex);
          }
          _dataSource.setJdbcURL(jcd.getProtocol() + ":" + jcd.getSubProtocol() + ":" + jcd.getDbAlias());
          _dataSource.setUserName(jcd.getUserName());
          _dataSource.setPassword(jcd.getPassWord());
  
          try
          {
              _builder = SqlBuilderFactory.newSqlBuilder(getDatabaseType());
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
  
          _ddlExecutor = new DDLExecutor(_dataSource, _builder);
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DBHandling#getConnection()
       */
      public JdbcConnectionDescriptor getConnection()
      {
          return _jcd;
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DBHandling#addSchemaFiles(java.lang.String, java.lang.String)
       */
      public void addSchemaFiles(String srcDir, String listOfFilenames) throws IOException, DatabaseHandlingException
      {
          StringTokenizer tokenizer = new StringTokenizer(listOfFilenames, ",");
          String          baseDir   = ((srcDir != null) && (srcDir.length() > 0) ? srcDir : ".") + "/";
          String          token;
  
          try
          {
              DatabaseReader dbReader = new DatabaseReader();
  
              dbReader.setValidating(false);
              while (tokenizer.hasMoreTokens())
              {
                  token = tokenizer.nextToken();
                  if (token.length() > 0)
                  {
                      _schemas.add(dbReader.parse(baseDir + token));
                  }
              }
          }
          catch (Exception ex)
          {
              if (ex instanceof IOException)
              {
                  throw (IOException)ex;
              }
              else
              {
                  throw new DatabaseHandlingException(ex);
              }
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DBHandling#addSchemaFile(java.io.Reader)
       */
      public void addSchemaFile(Reader reader) throws IOException, DatabaseHandlingException
      {
          try
          {
              _schemas.add(new DatabaseReader().parse(reader));
          }
          catch (Exception ex)
          {
              if (ex instanceof IOException)
              {
                  throw (IOException)ex;
              }
              else
              {
                  throw new DatabaseHandlingException(ex);
              }
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DBHandling#createDatabase()
       */
      public void createDatabase() throws DatabaseHandlingException
      {
          try
          {
              for (Iterator it = _schemas.iterator(); it.hasNext();)
              {
                  _ddlExecutor.createDatabase((Database)it.next(), true);
              }
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#alterDatabase()
       */
      public void alterDatabase() throws DatabaseHandlingException
      {
          StringWriter writer = new StringWriter();
  
          try
          {
              getAlterationSql(writer);
              _ddlExecutor.evaluateBatch(writer.getBuffer().toString());
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#dropDatabase()
       */
      public void dropDatabase() throws DatabaseHandlingException
      {
          try
          {
              JdbcModelReader modelReader = new JdbcModelReader(_dataSource.getConnection());
  
              _ddlExecutor.dropDatabase(modelReader.getDatabase());
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#dumpDatabaseSchema(java.io.Writer)
       */
      public void dumpDatabaseSchema(Writer writer) throws DatabaseHandlingException
      {
          try
          {
              JdbcModelReader modelReader = new JdbcModelReader(_dataSource.getConnection());
  
              new DatabaseWriter(writer).write(modelReader.getDatabase());
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#getDropSql(java.io.Writer)
       */
      public void getDropSql(Writer writer) throws DatabaseHandlingException
      {
          _builder.setWriter(writer);
          try
          {
              JdbcModelReader modelReader = new JdbcModelReader(_dataSource.getConnection());
  
              _builder.dropDatabase(modelReader.getDatabase());
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#getAlterationSql(java.io.Writer)
       */
      public void getAlterationSql(Writer writer) throws DatabaseHandlingException
      {
          _builder.setWriter(writer);
          try
          {
              Connection conn = _dataSource.getConnection();
  
              // TODO: Does this work ?
              for (Iterator it = _schemas.iterator(); it.hasNext();)
              {
                  _builder.alterDatabase((Database)it.next(), conn, true, true);
              }
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#getCreationSql(java.io.Writer)
       */
      public void getCreationSql(Writer writer) throws DatabaseHandlingException
      {
          _builder.setWriter(writer);
          try
          {
              // TODO: Does this work ?
              for (Iterator it = _schemas.iterator(); it.hasNext();)
              {
                  _builder.createDatabase((Database)it.next(), true);
              }
          }
          catch (Exception ex)
          {
              throw new DatabaseHandlingException(ex);
          }
      }
  }
  
  
  
  1.1                  db-ojb/src/java/org/apache/ojb/broker/util/dbhandling/DatabaseHandling.java
  
  Index: DatabaseHandling.java
  ===================================================================
  package org.apache.ojb.broker.util.dbhandling;
  
  /* Copyright 2004-2004 The Apache Software Foundation
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.*;
  
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  
  /**
   * Interface for classes providing basic database handling (drop, create, init).
   * 
   * @author Thomas Dudziak
   */
  public interface DatabaseHandling
  {
      /**
       * Sets the working directory.
       * 
       * @param dir The directory
       * @throws IOException If the directory does not exist or cannot be written/read
       */
      public void setWorkDir(String dir) throws IOException;
  
      /**
       * Sets the jdbc connection to use.
       * 
       * @param jcd The connection to use
       * @throws DatabaseHandlingException If the target database cannot be handled
       */
      public void setConnection(JdbcConnectionDescriptor jcd) throws DatabaseHandlingException;
  
      /**
       * Returns the connection descriptor used by this handling object.
       * 
       * @return The connection descriptor
       */
      public JdbcConnectionDescriptor getConnection();
  
      /**
       * Adds db definition files to use.
       * 
       * @param srcDir          The directory containing the files
       * @param listOfFilenames The filenames in a comma-separated list
       */
      public void addSchemaFiles(String srcDir, String listOfFilenames) throws IOException, DatabaseHandlingException;
  
      /**
       * Adds an input stream containg part of the db definition to use.
       * 
       * @param reader A reader returning the schema
       */
      public void addSchemaFile(Reader reader) throws IOException, DatabaseHandlingException;
  
      /**
       * Creates the database with all tables as defined in the schema(s).
       * If it already exists, then it will be cleared.
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void createDatabase() throws DatabaseHandlingException;
  
      /**
       * Generates SQL for dropping the database, and writes the SQL to the given
       * output stream. Note that this does not modify the database.
       * 
       * @param writer The writer to write the schema to
       * @throws DatabaseHandlingException If some error occurred
       */
      public void getDropSql(Writer writer) throws DatabaseHandlingException;
      
      /**
       * Generates SQL for creating a new database according to the schema, and
       * writes the SQL to the given output stream. Note that this does not
       * access the database in any way.
       * 
       * @param writer The writer to write the schema to
       * @throws DatabaseHandlingException If some error occurred
       */
      public void getCreationSql(Writer writer) throws DatabaseHandlingException;
  
      /**
       * Generates SQL for altering a new database according to the schema, and
       * writes the SQL to the given output stream. Note that this method reads
       * the database but does not change it.
       * 
       * @param writer The writer to write the schema to
       * @throws DatabaseHandlingException If some error occurred
       */
      public void getAlterationSql(Writer writer) throws DatabaseHandlingException;
  
      /**
       * Alters an existing database. If it already does not exist yet, then it's
       * created, else the data in it is maintained as much as possible (depending
       * on the structural changes).
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void alterDatabase() throws DatabaseHandlingException;
  
      /**
       * Drops the database.
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void dropDatabase() throws DatabaseHandlingException;
  
      /**
       * Dumps the database schema to the given stream.
       * 
       * @param writer The writer to write the schema to
       * @throws DatabaseHandlingException If some error occurred
       */
      public void dumpDatabaseSchema(Writer writer) throws DatabaseHandlingException;
  }
  
  
  
  1.1                  db-ojb/src/java/org/apache/ojb/broker/util/dbhandling/DatabaseHandlingTask.java
  
  Index: DatabaseHandlingTask.java
  ===================================================================
  package org.apache.ojb.broker.util.dbhandling;
  
  /* Copyright 2004-2004 The Apache Software Foundation
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.*;
  import java.util.ArrayList;
  import java.util.Iterator;
  
  import org.apache.ojb.broker.PBKey;
  import org.apache.ojb.broker.PersistenceBrokerFactory;
  import org.apache.ojb.broker.metadata.ConnectionRepository;
  import org.apache.ojb.broker.metadata.MetadataManager;
  import org.apache.tools.ant.*;
  import org.apache.tools.ant.types.FileSet;
  
  /**
   * Ant task for performing basic db setup functions.
   * 
   * @author Thomas Dudziak
   */
  public class DatabaseHandlingTask extends Task
  {
      /** The name of the default database handler */
      private final String DEFAULT_HANDLER = CommonsSqlDatabaseHandling.class.getName();
  
      /**
       * Declares a database action.
       */
      public interface DatabaseAction
      {
          /**
           * Performs the action.
           * 
           * @param handler The database handler to use 
           */
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException;
      }
      
      /**
       * Database creation action.
       */
      public class CreateAction implements DatabaseAction
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              handler.createDatabase();
          }
      }
  
      /**
       * Database alteration action.
       */
      public class AlterAction implements DatabaseAction
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              handler.alterDatabase();
          }
      }
  
      /**
       * Database drop action.
       */
      public class DropAction implements DatabaseAction
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              handler.dropDatabase();
          }
      }
  
      /**
       * Base class for sql creation actions.
       */
      public abstract class GenerateSqlActionBase implements DatabaseAction
      {
          /** The file to write the schema to */
          private File _destFile;
  
          /**
           * Sets the file to which the schema will be written to.
           * 
           * @param destFile The destination file
           */
          public void setDestFile(File destFile)
          {
              _destFile = destFile;
          }
  
          /**
           * Returns the file to which the schema will be written to.
           *  
           * @return The destination file
           */
          public File getDestFile()
          {
              return _destFile;
          }
  
          /**
           * Returns a writer for the destination file.
           * 
           * @return The writer
           * @throws DatabaseHandlingException If no writer could be created
           */
          protected Writer getWriter() throws DatabaseHandlingException
          {
              try
              {
                  if (_destFile != null)
                  {
                      return new FileWriter(_destFile);
                  }
                  else
                  {
                      return new OutputStreamWriter(System.out);
                  }
              }
              catch (IOException ex)
              {
                  throw new DatabaseHandlingException(ex);
              }
          }
      }
  
      /**
       * Database drop action.
       */
      public class DumpAction extends GenerateSqlActionBase
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              try
              {
                  Writer writer = getWriter();
      
                  handler.dumpDatabaseSchema(writer);
                  writer.close();
              }
              catch (IOException ex)
              {
                  throw new BuildException(ex);
              }
          }
      }
  
      /**
       * Action for writing the creation sql to a file.
       */
      public class GenerateCreationSqlAction extends GenerateSqlActionBase
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              try
              {
                  Writer writer = getWriter();
      
                  handler.getCreationSql(writer);
                  writer.close();
              }
              catch (IOException ex)
              {
                  throw new BuildException(ex);
              }
          }
      }
  
      /**
       * Action for writing the alteration sql to a file.
       */
      public class GenerateAlterationSqlAction extends GenerateSqlActionBase
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              try
              {
                  Writer writer = getWriter();
      
                  handler.getAlterationSql(writer);
                  writer.close();
              }
              catch (IOException ex)
              {
                  throw new BuildException(ex);
              }
          }
      }
  
      /**
       * Action for writing the drop sql to a file.
       */
      public class GenerateDropSqlAction extends GenerateSqlActionBase
      {
          public void execute(DatabaseHandling handler) throws DatabaseHandlingException
          {
              try
              {
                  Writer writer = getWriter();
      
                  handler.getDropSql(writer);
                  writer.close();
              }
              catch (IOException ex)
              {
                  throw new BuildException(ex);
              }
          }
      }
  
      /** The qualified class name of the db handling to use */
      private String _handlerClassName = DEFAULT_HANDLER;
      /** The alias of the jdbc connection to use (empty = default connection) */
      private String _jcdAlias;
      /** The working directory */
      private String _workDir;
      /** The input files */
      private ArrayList _fileSets = new ArrayList();
      /** The actions to perform */
      private ArrayList _actions = new ArrayList();
      
      /**
       * Sets the name of the handling to use.
       * 
       * @param qualifiedClassName The qualified class name of the handler
       */
      public void setHandler(String qualifiedClassName)
      {
          _handlerClassName = (qualifiedClassName == null ? DEFAULT_HANDLER : qualifiedClassName);
      }
  
      /**
       * Returns the name of the handler that is used.
       * 
       * @return The qualified class name of the handler
       */
      public String getHandler()
      {
          return _handlerClassName;
      }
  
      /**
       * Sets the alias of the jdbc connection to use.
       * 
       * @param alias The alias of the connection
       */
      public void setJcdAlias(String alias)
      {
          _jcdAlias = alias;
      }
  
      /**
       * Returns the alias of the jdbc connection.
       * 
       * @return The alias
       */
      public String getJcdAlias()
      {
          return _jcdAlias;
      }
  
      /**
       * Sets the working directory. If none is given, then the system's temporary directory is used.
       * 
       * @param dir The working directory
       */
      public void setWorkDir(String dir)
      {
          _workDir = dir;
      }
  
      /**
       * Returns the working directory.
       * 
       * @return The working directory
       */
      public String getWorkDir()
      {
          return _workDir;
      }
  
      /**
       * Adds a fileset.
       * 
       * @param fileset The additional input files
       */
      public void addFileset(FileSet fileset)
      {
          _fileSets.add(fileset);
      }
  
      /**
       * Creates a new create action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createCreate()
      {
          DatabaseAction action = new CreateAction();
  
          _actions.add(action);
          return action;
      }
  
      /**
       * Creates a new alter action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createAlter()
      {
          DatabaseAction action = new AlterAction();
  
          _actions.add(action);
          return action;
      }
  
      /**
       * Creates a new drop action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createDrop()
      {
          DatabaseAction action = new DropAction();
  
          _actions.add(action);
          return action;
      }
  
      /**
       * Creates a new dump action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createDump()
      {
          DatabaseAction action = new DumpAction();
  
          _actions.add(action);
          return action;
      }
  
      /**
       * Creates a new createSql action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createCreateSql()
      {
          DatabaseAction action = new GenerateCreationSqlAction();
  
          _actions.add(action);
          return action;
      }
  
      /**
       * Creates a new alterSql action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createAlterSql()
      {
          DatabaseAction action = new GenerateAlterationSqlAction();
  
          _actions.add(action);
          return action;
      }
  
      /**
       * Creates a new dropSql action object for Ant.
       * 
       * @return The action object
       */
      public DatabaseAction createDropSql()
      {
          DatabaseAction action = new GenerateDropSqlAction();
  
          _actions.add(action);
          return action;
      }
  
      /* (non-Javadoc)
       * @see org.apache.tools.ant.Task#execute()
       */
      public void execute() throws BuildException
      {
          if (_actions.isEmpty())
          {
              return;
          }
  
          DatabaseHandling handling = createDatabaseHandler();
  
          try
          {
              if ((_workDir != null) && (_workDir.length() > 0))
              {
                  File   workDir = new File(_workDir); 
                  String absPath = workDir.getAbsolutePath();
  
                  handling.setWorkDir(absPath);
                  System.setProperty("user.dir", absPath);
              }
              for (Iterator it = _fileSets.iterator(); it.hasNext();)
              {
                  addIncludes(handling, (FileSet)it.next());
              }
  
              ConnectionRepository connRep = MetadataManager.getInstance().connectionRepository();
              PBKey                pbKey   = null;
  
              if ((_jcdAlias == null) || (_jcdAlias.length() == 0))
              {
                  pbKey = PersistenceBrokerFactory.getDefaultKey();
              }
              else
              {
                  pbKey = connRep.getStandardPBKeyForJcdAlias(_jcdAlias);
                  if (pbKey == null)
                  {
                      throw new BuildException("Undefined jcdAlias "+_jcdAlias);
                  }
              }
              handling.setConnection(connRep.getDescriptor(pbKey));
  
              for (Iterator it = _actions.iterator(); it.hasNext();)
              {
                  ((DatabaseAction)it.next()).execute(handling);
              }
          }
          catch (Exception ex)
          {
              if (ex instanceof BuildException)
              {
                  throw (BuildException)ex;
              }
              else
              {
                  throw new BuildException(ex);
              }
          }
      }
  
      /**
       * Creates a db handler object.
       * 
       * @return The db handler object
       * @throws BuildException If the handler is invalid
       */
      private DatabaseHandling createDatabaseHandler() throws BuildException
      {
          try
          {
              Class handlerClass = Class.forName(_handlerClassName);
  
              return (DatabaseHandling)handlerClass.newInstance();
          }
          catch (Exception ex)
          {
              throw new BuildException("Invalid database handling '"+_handlerClassName+"' specified");
          }
      }
  
      /**
       * Adds the includes of the fileset to the handling.
       * 
       * @param handling The handling
       * @param fileSet  The fileset
       */
      private void addIncludes(DatabaseHandling handling, FileSet fileSet) throws BuildException
      {
          DirectoryScanner scanner  = fileSet.getDirectoryScanner(getProject());
          String[]         files    = scanner.getIncludedFiles();
          StringBuffer     includes = new StringBuffer();
  
          for (int idx = 0; idx < files.length; idx++)
          {
              if (idx > 0)
              {
                  includes.append(",");
              }
              includes.append(files[idx]);
          }
          try
          {
              handling.addSchemaFiles(fileSet.getDir(getProject()).getAbsolutePath(), includes.toString());
          }
          catch (Exception ex)
          {
              throw new BuildException(ex);
          }
      }
  }
  
  
  
  1.1                  db-ojb/src/java/org/apache/ojb/broker/util/dbhandling/TorqueDatabaseHandling.java
  
  Index: TorqueDatabaseHandling.java
  ===================================================================
  package org.apache.ojb.broker.util.dbhandling;
  
  /* Copyright 2004-2004 The Apache Software Foundation
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *     http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  
  import java.io.*;
  import java.util.HashMap;
  import java.util.Iterator;
  import java.util.StringTokenizer;
  import java.util.zip.GZIPInputStream;
  import java.util.zip.GZIPOutputStream;
  
  import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
  import org.apache.ojb.broker.util.logging.LoggerFactory;
  import org.apache.tools.ant.Project;
  import org.apache.tools.ant.taskdefs.SQLExec;
  import org.apache.tools.ant.types.FileSet;
  import org.apache.torque.task.TorqueDataModelTask;
  import org.apache.torque.task.TorqueSQLExec;
  import org.apache.torque.task.TorqueSQLTask;
  
  /**
   * Provides basic database handling (drop, create, init) via torque.
   * 
   * @author Thomas Dudziak
   */
  public class TorqueDatabaseHandling implements DatabaseHandling
  {
      /** Torque db platforms */
      protected static final String TORQUE_PLATFORM_DB2        = "db2";
      protected static final String TORQUE_PLATFORM_HYPERSONIC = "hypersonic";
      protected static final String TORQUE_PLATFORM_INTERBASE  = "interbase";
      protected static final String TORQUE_PLATFORM_MSSQL      = "mssql";
      protected static final String TORQUE_PLATFORM_MYSQL      = "mysql";
      protected static final String TORQUE_PLATFORM_ORACLE     = "oracle";
      protected static final String TORQUE_PLATFORM_POSTGRESQL = "postgresql";
      protected static final String TORQUE_PLATFORM_SAPDB      = "sapdb";
      protected static final String TORQUE_PLATFORM_SYBASE     = "sybase";
  
      /** The name of the db-creation script */
      private static final String CREATION_SCRIPT_NAME = "create-db.sql";
      /** The name of the torque database mapping file */
      private static final String SQL_DB_MAP_NAME      = "sqldb.map";
  
      /** Mapping from ojb dbms to torque database setting */
      private static HashMap _dbmsToTorqueDb = new HashMap();
      
      static
      {
          _dbmsToTorqueDb.put("db2",         TORQUE_PLATFORM_DB2);
          _dbmsToTorqueDb.put("hsqldb",      TORQUE_PLATFORM_HYPERSONIC);
          _dbmsToTorqueDb.put("firebird",    TORQUE_PLATFORM_INTERBASE);
          _dbmsToTorqueDb.put("mssqlserver", TORQUE_PLATFORM_MSSQL);
          _dbmsToTorqueDb.put("mysql",       TORQUE_PLATFORM_MYSQL);
          _dbmsToTorqueDb.put("oracle",      TORQUE_PLATFORM_ORACLE);
          _dbmsToTorqueDb.put("oracle9i",    TORQUE_PLATFORM_ORACLE);
          _dbmsToTorqueDb.put("postgresql",  TORQUE_PLATFORM_POSTGRESQL);
          _dbmsToTorqueDb.put("sapdb",       TORQUE_PLATFORM_SAPDB);
          _dbmsToTorqueDb.put("sybaseasa",   TORQUE_PLATFORM_SYBASE);
          _dbmsToTorqueDb.put("sybasease",   TORQUE_PLATFORM_SYBASE);
          _dbmsToTorqueDb.put("sybase",      TORQUE_PLATFORM_SYBASE);
      }
      
      /** The jdbc connection for communicating with the db */
      private JdbcConnectionDescriptor _jcd;
      /** The target database */
      private String _targetDatabase;
      /** The directory where we work in */
      private File _workDir;
      /** The compressed contents of the torque schemata */
      private HashMap _torqueSchemata = new HashMap();
      /** The compressed content of the creation script */
      private byte[] _creationScript;
      /** The compressed contents of the db initialization scripts */
      private HashMap _initScripts = new HashMap();
  
      /**
       * Creates a new handling object.
       */
      public TorqueDatabaseHandling()
      {}
  
      /**
       * Sets the jdbc connection to use.
       * 
       * @param jcd The connection to use
       * @throws DatabaseHandlingException If the target database cannot be handled with torque
       */
      public void setConnection(JdbcConnectionDescriptor jcd) throws DatabaseHandlingException
      {
          _jcd = jcd;
  
          String targetDatabase = (String)_dbmsToTorqueDb.get(_jcd.getDbms().toLowerCase());
  
          if (targetDatabase == null)
          {
              throw new DatabaseHandlingException("Database "+_jcd.getDbms()+" is not supported by torque");
          }
          if (!targetDatabase.equals(_targetDatabase))
          {
              _targetDatabase = targetDatabase;
              _creationScript = null;
              _initScripts.clear();
          }
      }
  
      /**
       * Returns the connection descriptor used by this handling object.
       * 
       * @return The connection descriptor
       */
      public JdbcConnectionDescriptor getConnection()
      {
          return _jcd;
      }
  
      /**
       * Returns the torque database platform used.
       * 
       * @return The target db platform
       */
      public String getTargetTorquePlatform()
      {
          return _targetDatabase;
      }
  
      /**
       * Adds the input files (in our case torque schema files) to use.
       * 
       * @param srcDir          The directory containing the files
       * @param listOfFilenames The filenames in a comma-separated list
       */
      public void addSchemaFiles(String srcDir, String listOfFilenames) throws IOException
      {
          StringTokenizer tokenizer = new StringTokenizer(listOfFilenames, ",");
          File            dir       = new File(srcDir);
          String          filename;
          
          while (tokenizer.hasMoreTokens())
          {
              filename = tokenizer.nextToken().trim();
              if (filename.length() > 0)
              {    
                   _torqueSchemata.put("schema"+_torqueSchemata.size()+".xml",
                                       readTextCompressed(new File(dir, filename)));
              }
          }
      }
  
      /**
       * Adds an input stream of a db definition (in our case of a torque schema file).
       * 
       * @param reader The input
       */
      public void addSchemaFile(Reader reader) throws IOException
      {
          _torqueSchemata.put("schema"+_torqueSchemata.size()+".xml",
                              readStreamCompressed(reader));
      }
  
      /**
       * Writes the torque schemata to files in the given directory and returns
       * a comma-separated list of the filenames.
       * 
       * @param dir The directory to write the files to
       * @return The list of filenames
       * @throws IOException If an error occurred
       */
      private String writeSchemata(File dir) throws IOException
      {
          writeCompressedTexts(dir, _torqueSchemata);
  
          StringBuffer includes = new StringBuffer();
  
          for (Iterator it = _torqueSchemata.keySet().iterator(); it.hasNext();)
          {
              includes.append((String)it.next());
              if (it.hasNext())
              {
                  includes.append(",");
              }
          }
          return includes.toString();
      }
      
      /**
       * Creates the db-creation sql script (but does not perform it).
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void createCreationScript() throws DatabaseHandlingException
      {
          Project             project    = new Project();
          TorqueDataModelTask modelTask  = new TorqueDataModelTask();
          File                tmpDir     = null;
          File                scriptFile = null;
          
          _creationScript = null;
          try
          {
              tmpDir = new File(getWorkDir(), "schemas");
              tmpDir.mkdir();
  
              String includes = writeSchemata(tmpDir);
              
              scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);
  
              project.setBasedir(tmpDir.getAbsolutePath());
  
              // populating with defaults
              modelTask.setProject(project);
              modelTask.setUseClasspath(true);
              modelTask.setControlTemplate("sql/db-init/Control.vm");
              modelTask.setOutputDirectory(tmpDir);
              modelTask.setOutputFile(CREATION_SCRIPT_NAME);
              modelTask.setTargetDatabase(_targetDatabase);
  
              FileSet files = new FileSet();
  
              files.setDir(tmpDir);
              files.setIncludes(includes);
              modelTask.addFileset(files);
              modelTask.execute();
  
              _creationScript = readTextCompressed(scriptFile);
  
              deleteDir(tmpDir);
          }
          catch (Exception ex)
          {
              // clean-up
              if ((tmpDir != null) && tmpDir.exists())
              {
                  deleteDir(tmpDir);
              }
              throw new DatabaseHandlingException(ex);
          }
      }
      
      /**
       * Creates the database.
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void createDatabase() throws DatabaseHandlingException
      {
          if (_creationScript == null)
          {
              createCreationScript();
          }
  
          Project             project    = new Project();
          TorqueDataModelTask modelTask  = new TorqueDataModelTask();
          File                tmpDir     = null;
          File                scriptFile = null;
          
          try
          {
              tmpDir = new File(getWorkDir(), "schemas");
              tmpDir.mkdir();
  
              scriptFile = new File(tmpDir, CREATION_SCRIPT_NAME);
  
              writeCompressedText(scriptFile, _creationScript);
  
              project.setBasedir(tmpDir.getAbsolutePath());
  
              // we use the ant task 'sql' to perform the creation script
  	        SQLExec         sqlTask = new SQLExec();
  	        SQLExec.OnError onError = new SQLExec.OnError();
  	
  	        onError.setValue("continue");
  	        sqlTask.setProject(project);
  	        sqlTask.setAutocommit(true);
  	        sqlTask.setDriver(_jcd.getDriver());
  	        sqlTask.setOnerror(onError);
  	        sqlTask.setUserid(_jcd.getUserName());
  	        sqlTask.setPassword(_jcd.getPassWord() == null ? "" : _jcd.getPassWord());
  	        sqlTask.setUrl(getDBCreationUrl());
  	        sqlTask.setSrc(scriptFile);
  	        sqlTask.execute();
  
  	        deleteDir(tmpDir);
          }
          catch (Exception ex)
          {
              // clean-up
              if ((tmpDir != null) && tmpDir.exists())
              {
                  try
                  {
                      scriptFile.delete();
                  }
                  catch (NullPointerException e) 
                  {
                      LoggerFactory.getLogger(this.getClass()).error("NPE While deleting scriptFile [" + scriptFile.getName() + "]", e);
                  }
              }
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /**
       * Creates the initialization scripts (creation of tables etc.) but does
       * not perform them.
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void createInitScripts() throws DatabaseHandlingException
      {
          Project       project   = new Project();
          TorqueSQLTask sqlTask   = new TorqueSQLTask(); 
          File          schemaDir = null;
          File          sqlDir    = null;
          
          _initScripts.clear();
          try
          {
              File tmpDir = getWorkDir();
  
              schemaDir = new File(tmpDir, "schemas");
              sqlDir    = new File(tmpDir, "sql");
              schemaDir.mkdir();
              sqlDir.mkdir();
  
              String includes     = writeSchemata(schemaDir);
              File   sqlDbMapFile = new File(sqlDir, SQL_DB_MAP_NAME);
  
              sqlDbMapFile.createNewFile();
              project.setBasedir(sqlDir.getAbsolutePath());
              
              // populating with defaults
              sqlTask.setProject(project);
              sqlTask.setUseClasspath(true);
              sqlTask.setBasePathToDbProps("sql/base/");
              sqlTask.setControlTemplate("sql/base/Control.vm");
              sqlTask.setOutputDirectory(sqlDir);
              // we put the report in the parent directory as we don't want
              // to read it in later on
              sqlTask.setOutputFile("../report.sql.generation");
              sqlTask.setSqlDbMap(SQL_DB_MAP_NAME);
              sqlTask.setTargetDatabase(_targetDatabase);
  
              FileSet files = new FileSet();
              
              files.setDir(schemaDir);
              files.setIncludes(includes);
              sqlTask.addFileset(files);
              sqlTask.execute();
  
              readTextsCompressed(sqlDir, _initScripts);
              deleteDir(schemaDir);
              deleteDir(sqlDir);
          }
          catch (Exception ex)
          {
              // clean-up
              if ((schemaDir != null) && schemaDir.exists())
              {
                  deleteDir(schemaDir);
              }
              if ((sqlDir != null) && sqlDir.exists())
              {
                  deleteDir(sqlDir);
              }
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /**
       * Creates the tables according to the schema files.
       * 
       * @throws DatabaseHandlingException If some error occurred
       */
      public void initDatabase() throws DatabaseHandlingException
      {
          if (_initScripts.isEmpty())
          {
              createInitScripts();
          }
  
          Project       project   = new Project();
          TorqueSQLTask sqlTask   = new TorqueSQLTask(); 
          File          outputDir = null;
          
          try
          {
              outputDir = new File(getWorkDir(), "sql");
  
              outputDir.mkdir();
              writeCompressedTexts(outputDir, _initScripts);
  
              project.setBasedir(outputDir.getAbsolutePath());
  
              // executing the generated sql, but this time with a torque task 
              TorqueSQLExec         sqlExec = new TorqueSQLExec();
              TorqueSQLExec.OnError onError = new TorqueSQLExec.OnError();
  
              sqlExec.setProject(project);
              onError.setValue("continue");
              sqlExec.setAutocommit(true);
              sqlExec.setDriver(_jcd.getDriver());
              sqlExec.setOnerror(onError);
              sqlExec.setUserid(_jcd.getUserName());
              sqlExec.setPassword(_jcd.getPassWord() == null ? "" : _jcd.getPassWord());
              sqlExec.setUrl(getDBManipulationUrl());
              sqlExec.setSrcDir(outputDir.getAbsolutePath());
              sqlExec.setSqlDbMap(SQL_DB_MAP_NAME);
              sqlExec.execute();
              
              deleteDir(outputDir);
          }
          catch (Exception ex)
          {
              // clean-up
              if (outputDir != null)
              {
                  deleteDir(outputDir);
              }
              throw new DatabaseHandlingException(ex);
          }
      }
  
      /**
       * Template-and-Hook method for generating the url required by the jdbc driver
       * to allow for creating a database (as opposed to accessing an already-existing
       * database).
       *
       */
      protected String getDBCreationUrl()
      {
          JdbcConnectionDescriptor jcd = getConnection();
  
          // currently I only know about specifics for mysql
          if (TORQUE_PLATFORM_MYSQL.equals(getTargetTorquePlatform()))
          {
              // we have to remove the db name as the jdbc driver would try to connect to
              // a non-existing db
              // the db-alias has this form: [host&port]/[dbname]?[options]
              String dbAliasPrefix = jcd.getDbAlias();
              String dbAliasSuffix = "";
              int    questionPos   = dbAliasPrefix.indexOf('?');
  
              if (questionPos > 0)
              {
                  dbAliasSuffix = dbAliasPrefix.substring(questionPos);
                  dbAliasPrefix = dbAliasPrefix.substring(0, questionPos);
              }
  
              int slashPos = dbAliasPrefix.lastIndexOf('/');
  
              if (slashPos > 0)
              {
                  // it is important that the slash at the end is present
                  dbAliasPrefix = dbAliasPrefix.substring(0, slashPos + 1);
              }
              return jcd.getProtocol()+":"+jcd.getSubProtocol()+":"+dbAliasPrefix+dbAliasSuffix;
          }
          else if (TORQUE_PLATFORM_POSTGRESQL.equals(getTargetTorquePlatform()))
          {
              // we have to replace the db name with 'template1'
              // the db-alias has this form: [host&port]/[dbname]?[options]
              String dbAliasPrefix = jcd.getDbAlias();
              String dbAliasSuffix = "";
              int    questionPos   = dbAliasPrefix.indexOf('?');
  
              if (questionPos > 0)
              {
                  dbAliasSuffix = dbAliasPrefix.substring(questionPos);
                  dbAliasPrefix = dbAliasPrefix.substring(0, questionPos);
              }
  
              int slashPos = dbAliasPrefix.lastIndexOf('/');
  
              if (slashPos > 0)
              {
                  // it is important that the slash at the end is present
                  dbAliasPrefix = dbAliasPrefix.substring(0, slashPos + 1);
              }
              else
              {
                  dbAliasPrefix += "/";
              }
              dbAliasPrefix += "template1";
              if (dbAliasSuffix.length() > 0)
              {
                  dbAliasPrefix += "/";
              }
              return jcd.getProtocol()+":"+jcd.getSubProtocol()+":"+dbAliasPrefix+dbAliasSuffix;
              
          }
          else
          {
              return jcd.getProtocol()+":"+jcd.getSubProtocol()+":"+jcd.getDbAlias();
          }
      }
  
      /**
       * Template-and-Hook method for generating the url required by the jdbc driver
       * to allow for modifying an existing database.
       *
       */
      protected String getDBManipulationUrl()
      {
          JdbcConnectionDescriptor jcd = getConnection();
  
          return jcd.getProtocol()+":"+jcd.getSubProtocol()+":"+jcd.getDbAlias();
      }
  
      /**
       * Reads the given text file and compressed its content.
       * 
       * @param file The file
       * @return A byte array containing the GZIP-compressed content of the file
       * @throws IOException If an error ocurred
       */
      private byte[] readTextCompressed(File file) throws IOException
      {
          return readStreamCompressed(new FileReader(file));
      }
  
      /**
       * Reads the given text stream and compressed its content.
       * 
       * @param reader The input
       * @return A byte array containing the GZIP-compressed content of the stream
       * @throws IOException If an error ocurred
       */
      private byte[] readStreamCompressed(Reader reader) throws IOException
      {
          ByteArrayOutputStream bao    = new ByteArrayOutputStream();
          GZIPOutputStream      gos    = new GZIPOutputStream(bao);
          OutputStreamWriter    output = new OutputStreamWriter(gos);
          BufferedReader        input  = new BufferedReader(reader);
          String                line;
  
          while ((line = input.readLine()) != null)
          {
              output.write(line);
              output.write('\n');
          }
          input.close();
          reader.close();
          output.close();
          gos.close();
          bao.close();
          return bao.toByteArray();
      }
  
      /**
       * Reads the text files in the given directory and puts their content
       * in the given map after compressing it. Note that this method does not
       * traverse recursivly into sub-directories.
       * 
       * @param dir     The directory to process
       * @param results Map that will receive the contents (indexed by the relative filenames)
       * @throws IOException If an error ocurred
       */
      private void readTextsCompressed(File dir, HashMap results) throws IOException
      {
          if (dir.exists() && dir.isDirectory())
          {
              File[] files = dir.listFiles();
  
              for (int idx = 0; idx < files.length; idx++)
              {
                  if (files[idx].isDirectory())
                  {
                      continue;
                  }
                  results.put(files[idx].getName(), readTextCompressed(files[idx]));
              }
          }
      }
  
      /**
       * Uncompresses the given textual content and writes it to the given file.
       * 
       * @param file              The file to write to
       * @param compressedContent The content
       * @throws IOException If an error occurred
       */
      private void writeCompressedText(File file, byte[] compressedContent) throws IOException
      {
          ByteArrayInputStream bais   = new ByteArrayInputStream(compressedContent);
          GZIPInputStream      gis    = new GZIPInputStream(bais);
          BufferedReader       input  = new BufferedReader(new InputStreamReader(gis));
          BufferedWriter       output = new BufferedWriter(new FileWriter(file));
          String               line;
  
          while ((line = input.readLine()) != null)
          {
              output.write(line);
              output.write('\n');
          }
          input.close();
          gis.close();
          bais.close();
          output.close();
      }
      
      /**
       * Uncompresses the textual contents in the given map and and writes them to the files
       * denoted by the keys of the map.
       * 
       * @param dir      The base directory into which the files will be written 
       * @param contents The map containing the contents indexed by the filename
       * @throws IOException If an error occurred
       */
      private void writeCompressedTexts(File dir, HashMap contents) throws IOException
      {
          String filename;
  
          for (Iterator nameIt = contents.keySet().iterator(); nameIt.hasNext();)
          {
              filename = (String)nameIt.next();
              writeCompressedText(new File(dir, filename), (byte[])contents.get(filename));
          }
      }
      
      /**
       * Sets the working directory.
       * 
       * @param dir The directory
       * @throws IOException If the directory does not exist or cannot be written/read
       */
      public void setWorkDir(String dir) throws IOException
      {
          File workDir = new File(dir);
  
          if (!workDir.exists() || !workDir.canWrite() || !workDir.canRead())
          {
              throw new IOException("Cannot access directory "+dir);
          }
          _workDir = workDir;
      }
  
      /**
       * Returns the temporary directory used by java.
       * 
       * @return The temporary directory
       * @throws IOException If an io error occurred
       */
      private File getWorkDir() throws IOException
      {
          if (_workDir == null)
          {    
              File   dummy   = File.createTempFile("dummy", ".log");
              String workDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar));
      
              if ((workDir == null) || (workDir.length() == 0))
              {
                  workDir = ".";
              }
              dummy.delete();
              _workDir = new File(workDir);
          }
          return _workDir;
      }
  
      /**
       * Little helper function that recursivly deletes a directory.
       * 
       * @param dir The directory
       */
      private void deleteDir(File dir)
      {
          if (dir.exists() && dir.isDirectory())
          {
              File[] files = dir.listFiles();
  
              for (int idx = 0; idx < files.length; idx++)
              {
                  if (!files[idx].exists())
                  {
                      continue;
                  }
                  if (files[idx].isDirectory())
                  {
                      deleteDir(files[idx]);
                  }
                  else
                  {
                      files[idx].delete();
                  }
              }
              dir.delete();
          }
      }
  
      public void alterDatabase() throws DatabaseHandlingException
      {
          throw new UnsupportedOperationException("Not yet implemented");
      }
  
      public void dropDatabase() throws DatabaseHandlingException
      {
          throw new UnsupportedOperationException("Not yet implemented");
      }
  
      public void dumpDatabaseSchema(Writer writer)
              throws DatabaseHandlingException
      {
          throw new UnsupportedOperationException("Not yet implemented");
      }
  
      public void getAlterationSql(Writer writer)
              throws DatabaseHandlingException
      {
          throw new UnsupportedOperationException("Not yet implemented");
      }
  
      public void getCreationSql(Writer writer)
              throws DatabaseHandlingException
      {
          throw new UnsupportedOperationException("Not yet implemented");
      }
  
      /* (non-Javadoc)
       * @see org.apache.ojb.broker.util.dbhandling.DatabaseHandling#getDropSql(java.io.Writer)
       */
      public void getDropSql(Writer writer) throws DatabaseHandlingException
      {
          throw new UnsupportedOperationException("Not yet implemented");
      }
  }
  
  
  
  1.1                  db-ojb/lib/commons-betwixt-20030211.133854.jar
  
  	<<Binary file>>
  
  
  1.1                  db-ojb/lib/commons-sql-1.0-dev.jar
  
  	<<Binary file>>
  
  
  1.1                  db-ojb/lib/commons-digester-1.5.jar
  
  	<<Binary file>>
  
  

---------------------------------------------------------------------
To unsubscribe, e-mail: ojb-dev-unsubscribe@db.apache.org
For additional commands, e-mail: ojb-dev-help@db.apache.org


Mime
View raw message