Ejemplo n.º 1
0
  protected final void setupData(InputStream... dataSetStream) {
    try {
      IDataSet[] dataSets = new IDataSet[dataSetStream.length];
      for (int i = 0; i < dataSetStream.length; i++) {
        ReplacementDataSet dataSet = new ReplacementDataSet(new FlatXmlDataSet(dataSetStream[i]));
        dataSet.addReplacementObject("[null]", null);
        dataSets[i] = dataSet;
      }
      CompositeDataSet compositeDataSet = new CompositeDataSet(dataSets);

      databaseTester.setDataSet(compositeDataSet);
      connection = databaseTester.getConnection();
      connection
          .getConnection()
          .prepareStatement("set referential_integrity FALSE")
          .execute(); // HSQL DB
      DatabaseConfig config = connection.getConfig();
      config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());

      DatabaseOperation.CLEAN_INSERT.execute(connection, databaseTester.getDataSet());

      connection
          .getConnection()
          .prepareStatement("set referential_integrity TRUE")
          .execute(); // HSQL DB
    } catch (Exception e) {
      throw translateException("Could not setup DBUnit data", e);
    }
  }
Ejemplo n.º 2
0
  private void populateData() throws Exception {

    // skip db stuff of
    if (!isLocalTestEnvironment()) {
      // Once we've got the tables created populate them with data - clean insert will delete all
      // data first
      DatabaseDataSourceConnection databaseDataSourceConnection =
          new DatabaseDataSourceConnection(dataSource);

      // Set the database factory as in http://www.dbunit.org/faq.html#DefaultDataTypeFactory
      DatabaseConfig config = databaseDataSourceConnection.getConfig();

      config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
      config.setProperty(DatabaseConfig.PROPERTY_ESCAPE_PATTERN, "`?`");

      // Construct dataset
      XmlDataSet dataSet = new XmlDataSet(readFileFromClasspath("dataset.xml"));

      // Insert, cleanly (remove everything first)
      DatabaseOperation.CLEAN_INSERT.execute(databaseDataSourceConnection, dataSet);

      // Have to close the database connection
      databaseDataSourceConnection.close();
    }
  }
  /**
   * Import data into database.
   *
   * @param connection database connection
   * @throws Exception throws various exceptions
   */
  public void importData(Connection connection) throws Exception {
    InputStream inStream;
    IDataSet dataSet;

    DatabaseConnection dbconnection = new DatabaseConnection(connection);

    // initialize the data set
    DatabaseConfig config = dbconnection.getConfig();
    config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());

    inStream = this.getClass().getResourceAsStream(getDataFile());

    try {

      // put check here to ensure, finally is always executed
      if (inStream == null) {
        throw new FileNotFoundException("Datafile: " + getDataFile() + " not found");
      }

      // if no modified data set is available the test data set is loaded
      dataSet = new FlatXmlDataSet(inStream);

      DatabaseOperation.CLEAN_INSERT.execute(dbconnection, dataSet);
    } finally {
      dbconnection.close();
      connection.close();
    }
  }
Ejemplo n.º 4
0
  @Override
  protected DbUnitDatabaseConnection createDbUnitConnection(String schemaName) {
    Assert.notNull(schemaName, "数据集的模式名不能为空,且必须规范。");
    // 获取数据连接
    DbUnitDatabaseConnection connection = super.createDbUnitConnection(schemaName);

    // 没有根据数据库类型使用特订数据源的MetadataHandler,以下代码防止取不到表的元数据信息
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    boolean isMySQL = false;
    try {
      String databaseProductName =
          connection.getConnection().getMetaData().getDatabaseProductName();
      if ("MySQL".equals(databaseProductName)) {
        isMySQL = true;
        logger.info(
            "Database product name = "
                + databaseProductName
                + ", set DatabaseConfig.PROPERTY_METADATA_HANDLER to new MySqlMetadataHandler()");
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    // if database is MySQL, reset PROPERTY_METADATA_HANDLER to use MySQL specific Handler
    if (isMySQL) {
      DatabaseConfig config = connection.getConfig();
      config.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    return connection;
  }
Ejemplo n.º 5
0
  private String[] getPrimaryKeyNames() throws SQLException {
    logger.debug("getPrimaryKeyNames() - start");

    String schemaName = _qualifiedTableNameSupport.getSchema();
    String tableName = _qualifiedTableNameSupport.getTable();

    Connection connection = _connection.getConnection();
    DatabaseMetaData databaseMetaData = connection.getMetaData();

    DatabaseConfig config = _connection.getConfig();
    IMetadataHandler metadataHandler =
        (IMetadataHandler) config.getProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER);

    ResultSet resultSet = metadataHandler.getPrimaryKeys(databaseMetaData, schemaName, tableName);

    List list = new ArrayList();
    try {
      while (resultSet.next()) {
        String name = resultSet.getString(4);
        int sequence = resultSet.getInt(5);
        list.add(new PrimaryKeyData(name, sequence));
      }
    } finally {
      resultSet.close();
    }

    Collections.sort(list);
    String[] keys = new String[list.size()];
    for (int i = 0; i < keys.length; i++) {
      PrimaryKeyData data = (PrimaryKeyData) list.get(i);
      keys[i] = data.getName();
    }

    return keys;
  }
Ejemplo n.º 6
0
  /**
   * Creates a new database table metadata
   *
   * @param tableName The name of the table - can be fully qualified
   * @param connection The database connection
   * @param validate Whether or not to validate the given input data. It is not recommended to set
   *     the validation to <code>false</code> because it is then possible to create an instance of
   *     this object for a db table that does not exist.
   * @param caseSensitiveMetaData Whether or not the metadata looked up in a case sensitive way
   * @throws DataSetException
   * @since 2.4.1
   */
  DatabaseTableMetaData(
      final String tableName,
      IDatabaseConnection connection,
      boolean validate,
      boolean caseSensitiveMetaData)
      throws DataSetException {
    if (tableName == null) {
      throw new NullPointerException("The parameter 'tableName' must not be null");
    }
    if (connection == null) {
      throw new NullPointerException("The parameter 'connection' must not be null");
    }

    _connection = connection;
    _caseSensitiveMetaData = caseSensitiveMetaData;

    try {
      Connection jdbcConnection = connection.getConnection();
      if (!caseSensitiveMetaData) {
        _originalTableName = SQLHelper.correctCase(tableName, jdbcConnection);
        SQLHelper.logDebugIfValueChanged(
            tableName, _originalTableName, "Corrected table name:", DatabaseTableMetaData.class);
      } else {
        _originalTableName = tableName;
      }

      // qualified names support - table name and schema is stored here
      _qualifiedTableNameSupport =
          new QualifiedTableName(_originalTableName, _connection.getSchema());

      if (validate) {
        String schemaName = _qualifiedTableNameSupport.getSchema();
        String plainTableName = _qualifiedTableNameSupport.getTable();
        logger.debug(
            "Validating if table '{}' exists in schema '{}' ...", plainTableName, schemaName);
        try {
          DatabaseConfig config = connection.getConfig();
          IMetadataHandler metadataHandler =
              (IMetadataHandler) config.getProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER);
          DatabaseMetaData databaseMetaData = jdbcConnection.getMetaData();
          if (!metadataHandler.tableExists(databaseMetaData, schemaName, plainTableName)) {
            throw new NoSuchTableException(
                "Did not find table '" + plainTableName + "' in schema '" + schemaName + "'");
          }
        } catch (SQLException e) {
          throw new DataSetException(
              "Exception while validation existence of table '" + plainTableName + "'", e);
        }
      } else {
        logger.debug("Validation switched off. Will not check if table exists.");
      }
    } catch (SQLException e) {
      throw new DataSetException(
          "Exception while retrieving JDBC connection from dbunit connection '" + connection + "'",
          e);
    }
  }
Ejemplo n.º 7
0
 /**
  * Print the contents of the given tableName to system.out<br>
  * <br>
  * Call this from any {@link BaseContextSensitiveTest} child by:
  * TestUtil.printOutTableContents(getConnection(), "encounter");
  *
  * @param sqlConnection the connection to use
  * @param tableNames the name(s) of the table(s) to print out
  * @throws Exception
  */
 public static void printOutTableContents(Connection sqlConnection, String... tableNames)
     throws Exception {
   for (String tableName : tableNames) {
     System.out.println("The contents of table: " + tableName);
     IDatabaseConnection connection = new DatabaseConnection(sqlConnection);
     DatabaseConfig config = connection.getConfig();
     config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());
     QueryDataSet outputSet = new QueryDataSet(connection);
     outputSet.addTable(tableName);
     FlatXmlDataSet.write(outputSet, System.out);
   }
 }
Ejemplo n.º 8
0
  public void test() throws Exception {
    Connection jdbcConnection = null;
    IDatabaseConnection connection = new DatabaseConnection(jdbcConnection, "");
    DatabaseConfig config = connection.getConfig();

    // Use the ForwardOnlyResultSetTableFactory to export very large dataset.
    config.setProperty(
        DatabaseConfig.PROPERTY_RESULTSET_TABLE_FACTORY, new ForwardOnlyResultSetTableFactory());

    // Use the StreamingDataSet to import very large dataset.
    IDataSetProducer producer = new FlatXmlProducer(new InputSource("dataset.xml"));
    IDataSet dataSet = new StreamingDataSet(producer);
  }
Ejemplo n.º 9
0
 @Override
 protected IDatabaseConnection getConnection() throws Exception {
   Connection conn = dataSource.getConnection();
   IDatabaseConnection connection =
       new DatabaseConnection(
           conn,
           dbType.equalsIgnoreCase("oracle") ? testProperties.getProperty("db.username") : null);
   DatabaseConfig config = connection.getConfig();
   if (containsProperty(testProperties, DATATYPE_FACTORY)) {
     Class clazz = Class.forName(testProperties.getProperty(DATATYPE_FACTORY));
     config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, BeanUtils.getInstance(clazz));
   }
   return connection;
 }
  @Override
  public void configure(IDatabaseConnection connection) {
    DatabaseConfig config = connection.getConfig();

    config.setProperty(DBUnit.DATATYPE_FACTORY, new MySqlDataTypeFactory());

    config.setProperty(DBUnit.ESCAPE_PATTERN, "`?`");

    config.setProperty(
        DBUnit.METADATA_HANDLER, //
        new MySqlMetadataHandler());

    config.setProperty(DBUnit.QUALIFIED_TABLE_NAMES, true);
  }
  private synchronized IDatabaseConnection initialiseDbUnitConnection(
      ApplicationContext applicationContext) {
    if (dbUnitCon == null) {
      try {
        DataSource dataSource = applicationContext.getBean(DataSource.class);
        Preconditions.checkNotNull("dataSource not found", dataSource);
        dbUnitCon = new DatabaseDataSourceConnection(dataSource);
        DatabaseConfig config = dbUnitCon.getConfig();
        config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new H2DataTypeFactory());
        checkDataBase(dbUnitCon.getConnection().getMetaData());
      } catch (SQLException e) {

        log.error("error initialiseDbUnitConnection ", e);
      }
    }
    return dbUnitCon;
  }
Ejemplo n.º 12
0
  /**
   * @return
   * @throws Exception
   */
  protected IDatabaseConnection getConnection() throws Exception {
    logger.entry();

    DatabaseConnection connection = null;

    Connection con = datasource.getConnection();
    connection = new DatabaseConnection(con);
    DatabaseConfig config = connection.getConfig();
    config.setProperty(
        "http://www.dbunit.org/properties/datatypeFactory", new MsSqlDataTypeFactory());

    // Disable foreign key constraint checking
    con.prepareStatement(
            "EXEC sp_MSforeachtable @command1=\"ALTER TABLE ? NOCHECK CONSTRAINT ALL\"")
        .execute();

    logger.exit();

    return connection;
  }
Ejemplo n.º 13
0
  public Column[] getPrimaryKeys() throws DataSetException {
    logger.debug("getPrimaryKeys() - start");
    DatabaseConfig config = _connection.getConfig();
    IColumnFilter primaryKeysFilter =
        (IColumnFilter) config.getProperty(DatabaseConfig.PROPERTY_PRIMARY_KEY_FILTER);

    if (_primaryKeys == null || primaryKeyFilterChanged(primaryKeysFilter)) {
      try {
        lastKeyFilter = primaryKeysFilter;
        if (primaryKeysFilter != null) {
          _primaryKeys = Columns.getColumns(getTableName(), getColumns(), primaryKeysFilter);
        } else {
          String[] pkNames = getPrimaryKeyNames();
          _primaryKeys = Columns.getColumns(pkNames, getColumns());
        }
      } catch (SQLException e) {
        throw new DataSetException(e);
      }
    }
    return _primaryKeys;
  }
Ejemplo n.º 14
0
  /**
   * Creates a new instance of dbUnit's <code>IDatabaseConnection</code>
   *
   * @param schemaName The schema name, not null
   * @return A new instance of dbUnit's <code>IDatabaseConnection</code>
   */
  protected DbUnitDatabaseConnection createDbUnitConnection(String schemaName) {
    // A DbSupport instance is fetched in order to get the schema name in correct case
    DataSource dataSource = getDatabaseModule().getDataSourceAndActivateTransactionIfNeeded();
    SQLHandler sqlHandler = new DefaultSQLHandler(dataSource);
    DbSupport dbSupport = getDbSupport(configuration, sqlHandler, schemaName);

    // Create connection
    DbUnitDatabaseConnection connection =
        new DbUnitDatabaseConnection(dataSource, dbSupport.getSchemaName());
    DatabaseConfig config = connection.getConfig();
    if (dbSupport.getDatabaseDialect().toLowerCase().equals("mysql")) {
      config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
      config.setProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER, new MySqlMetadataHandler());
    }

    // Make sure that dbunit's correct IDataTypeFactory, that handles dbms specific data type
    // issues, is used
    IDataTypeFactory dataTypeFactory =
        getInstanceOf(IDataTypeFactory.class, configuration, dbSupport.getDatabaseDialect());
    config.setProperty(PROPERTY_DATATYPE_FACTORY, dataTypeFactory);
    // Make sure that table and column names are escaped using the dbms-specific identifier quote
    // string
    config.setProperty(
        PROPERTY_ESCAPE_PATTERN,
        dbSupport.getIdentifierQuoteString() + '?' + dbSupport.getIdentifierQuoteString());
    // Make sure that batched statements are used to insert the data into the database
    config.setProperty(FEATURE_BATCHED_STATEMENTS, "true");
    // Make sure that Oracle's recycled tables (BIN$) are ignored (value is used to ensure
    // dbunit-2.2 compliancy)
    config.setProperty("http://www.dbunit.org/features/skipOracleRecycleBinTables", "true");

    return connection;
  }
Ejemplo n.º 15
0
  /**
   * Sets the given properties on the {@link DatabaseConfig} instance using the given String values.
   * This is useful to set properties configured as strings by a build tool like ant or maven. If
   * the required property type is an object it uses reflection to create an instance of the class
   * specified as string.
   *
   * @param stringProperties The properties as strings. The key of the properties can be either the
   *     long or the short name.
   * @throws DatabaseUnitException
   */
  public void setPropertiesByString(Properties stringProperties) throws DatabaseUnitException {
    for (Iterator iterator = stringProperties.entrySet().iterator(); iterator.hasNext(); ) {
      Map.Entry entry = (Map.Entry) iterator.next();

      String propKey = (String) entry.getKey();
      String propValue = (String) entry.getValue();

      ConfigProperty dbunitProp = DatabaseConfig.findByName(propKey);
      if (dbunitProp == null) {
        logger.debug("Did not find long name property {} - trying short name...", entry);
        dbunitProp = DatabaseConfig.findByShortName(propKey);
      }

      if (dbunitProp == null) {
        logger.info(
            "Could not set property '" + entry + "' - not found in the list of known properties.");
      } else {
        String fullPropName = dbunitProp.getProperty();
        Object obj = createObjectFromString(dbunitProp, propValue);
        this.setProperty(fullPropName, obj);
      }
    }
  }
Ejemplo n.º 16
0
 /**
  * Override this method if you require DBUnit configuration features or additional properties.
  *
  * <p>Called after a connection has been obtaind and before the connection is used. Can be a NOOP
  * method if no additional settings are necessary for your DBUnit/DBMS setup.
  *
  * @param config A DBUnit <tt>DatabaseConfig</tt> object for setting properties and features
  */
 protected void editConfig(DatabaseConfig config) {
   if (database.equals(Database.hsql)) {
     // DBUnit/HSQL bugfix
     // http://www.carbonfive.com/community/archives/2005/07/dbunit_hsql_and.html
     config.setProperty(
         DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
         new DefaultDataTypeFactory() {
           public DataType createDataType(int sqlType, String sqlTypeName)
               throws DataTypeException {
             if (sqlType == Types.BOOLEAN) {
               return DataType.BOOLEAN;
             }
             return super.createDataType(sqlType, sqlTypeName);
           }
         });
   }
 }
Ejemplo n.º 17
0
 /**
  * Configures the given statement so that it has the properties that are configured in this
  * {@link DatabaseConfig}.
  *
  * @param stmt The statement to be configured.
  * @throws SQLException
  * @since 2.4.4
  */
 void configureStatement(Statement stmt) throws SQLException {
   logger.trace("configureStatement(stmt={}) - start", stmt);
   Integer fetchSize = (Integer) config.getProperty(DatabaseConfig.PROPERTY_FETCH_SIZE);
   stmt.setFetchSize(fetchSize.intValue());
   logger.debug("Statement fetch size set to {}", fetchSize);
 }
Ejemplo n.º 18
0
 protected void applyConfigProperties(final DatabaseConfig config) {
   for (final String key : this.configProperties.keySet()) {
     final Object value = this.configProperties.get(key);
     config.setProperty(key, value);
   }
 }
Ejemplo n.º 19
0
  public Column[] getColumns() throws DataSetException {
    logger.debug("getColumns() - start");

    if (_columns == null) {
      try {
        // qualified names support
        String schemaName = _qualifiedTableNameSupport.getSchema();
        String tableName = _qualifiedTableNameSupport.getTable();

        Connection jdbcConnection = _connection.getConnection();
        DatabaseMetaData databaseMetaData = jdbcConnection.getMetaData();

        DatabaseConfig config = _connection.getConfig();

        IMetadataHandler metadataHandler =
            (IMetadataHandler) config.getProperty(DatabaseConfig.PROPERTY_METADATA_HANDLER);
        ResultSet resultSet = metadataHandler.getColumns(databaseMetaData, schemaName, tableName);

        try {
          IDataTypeFactory dataTypeFactory = super.getDataTypeFactory(_connection);
          boolean datatypeWarning = config.getFeature(DatabaseConfig.FEATURE_DATATYPE_WARNING);

          List columnList = new ArrayList();
          while (resultSet.next()) {
            // Check for exact table/schema name match because
            // databaseMetaData.getColumns() uses patterns for the lookup
            boolean match =
                metadataHandler.matches(resultSet, schemaName, tableName, _caseSensitiveMetaData);
            if (match) {
              Column column = SQLHelper.createColumn(resultSet, dataTypeFactory, datatypeWarning);
              if (column != null) {
                columnList.add(column);
              }
            } else {
              logger.debug(
                  "Skipping <schema.table> '"
                      + resultSet.getString(2)
                      + "."
                      + resultSet.getString(3)
                      + "' because names do not exactly match.");
            }
          }

          if (columnList.size() == 0) {
            logger.warn(
                "No columns found for table '"
                    + tableName
                    + "' that are supported by dbunit. "
                    + "Will return an empty column list");
          }

          _columns = (Column[]) columnList.toArray(new Column[0]);
        } finally {
          resultSet.close();
        }
      } catch (SQLException e) {
        throw new DataSetException(e);
      }
    }
    return _columns;
  }
 /** Override method to set custom properties/features {@inheritDoc} */
 @Override
 protected void setUpDatabaseConfig(DatabaseConfig config) {
   super.setUpDatabaseConfig(config);
   config.setProperty(DatabaseConfig.PROPERTY_BATCH_SIZE, new Integer(97));
 }