org.dbunit.dataset.xml.FlatXmlDataSet Java Examples

The following examples show how to use org.dbunit.dataset.xml.FlatXmlDataSet. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BasePaymentModuleDBTestCase.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
protected void dumpDataBase(final String prefix, final String ... tables) {

        if (!enabled) {
            return; // no dumps
        }

        if (tables != null && tables.length > 0) {
            final File dump = new File("target" + File.separator + prefix + "_dataset.xml");
            try {
                QueryDataSet queryDataSet = new QueryDataSet(dbTester.getConnection());
                for (String tableName : tables) {
                    queryDataSet.addTable(tableName);
                }
                FlatXmlDataSet.write(queryDataSet, new FileOutputStream(dump));
                System.out.println("DUMP: " + dump.getAbsoluteFile());
            } catch (Exception exp) {
                System.out.println("Unable to create dump file: " + dump.getAbsoluteFile());
                exp.printStackTrace();
            }
        }
    }
 
Example #2
Source File: DbUnitUtil.java    From Leo with Apache License 2.0 6 votes vote down vote up
/**
 * 把数据集写入到文件中
 * @param dataSet
 * @param destFilePath
 */
public static void writeToFileFromDataSet(IDataSet dataSet,String destFilePath) {
	File destFile = new File(destFilePath);
	try {
			String destFileName = destFile.getName();
			//转换为excel格式
			if(destFileName.endsWith(".xls")){
				XlsDataSet.write(dataSet, new FileOutputStream(destFile));
			}else if(destFileName.endsWith(".xml")){
				FlatXmlDataSet.write(dataSet, new FileOutputStream(destFile));
			}else{
				log.error("文件格式不是xls或者xml,不支持");
				return;
			}
			log.info("写入数据到文件 : "+destFile.getAbsolutePath());
	} catch (Exception e) {
			log.error("写入数据到文件失败");
			log.error(e.getMessage());
	}
}
 
Example #3
Source File: AbstractTestDAO.java    From yes-cart with Apache License 2.0 6 votes vote down vote up
protected void dumpDataBase(final String prefix, final String ... tables) {

        if (!enabled) {
            return; // no dumps
        }

        if (tables != null && tables.length > 0) {
            final File dump = new File("target" + File.separator + prefix + "_dataset.xml");
            try {
                QueryDataSet queryDataSet = new QueryDataSet(dbTester.getConnection());
                for (String tableName : tables) {
                    queryDataSet.addTable(tableName);
                }
                FlatXmlDataSet.write(queryDataSet, new FileOutputStream(dump));
                System.out.println("DUMP: " + dump.getAbsoluteFile());
            } catch (Exception exp) {
                System.out.println("Unable to create dump file: " + dump.getAbsoluteFile());
                exp.printStackTrace();
            }
        }

    }
 
Example #4
Source File: DataSetBuilderTest.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGeneratFlatXmlDataSetWithEmptyUserTableWithColumnValuesSyntax() throws DataSetException, IOException {
    DataSetBuilder builder = new DataSetBuilder();
    builder
            .table("USER")
            .table("TWEET")
                .columns("ID","CONTENT","DATE")
                .values("abcdef12345", "dbunit rules!", "[DAY,NOW]")
            .table("FOLLOWER")
                .columns("ID", "USER_ID","FOLLOWER_ID")
                .values(1 , 1 , 2)
            .build();

    IDataSet dataSet = builder.build();

    File datasetFile = Files.createTempFile("rider-dataset", ".xml").toFile();
    FileOutputStream fos = new FileOutputStream(datasetFile);
    FlatXmlDataSet.write(dataSet, fos);
    assertThat(contentOf(datasetFile)).
            contains("<?xml version='1.0' encoding='UTF-8'?>"+NEW_LINE +
                    "<dataset>"+NEW_LINE +
                    "  <USER/>"+NEW_LINE +
                    "  <TWEET ID=\"abcdef12345\" CONTENT=\"dbunit rules!\" DATE=\"[DAY,NOW]\"/>"+NEW_LINE +
                    "  <FOLLOWER ID=\"1\" USER_ID=\"1\" FOLLOWER_ID=\"2\"/>"+NEW_LINE +
                    "</dataset>");
}
 
Example #5
Source File: DataSetBuilderTest.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAddEmptyTable() throws IOException, DataSetException {
    DataSetBuilder builder = new DataSetBuilder();
    IDataSet dataSet = builder.
            table("USER")
            .build();

    File datasetFile = Files.createTempFile("rider-empty-dataset", ".xml").toFile();
    FileOutputStream fos = new FileOutputStream(datasetFile);
    FlatXmlDataSet.write(dataSet, fos);
    assertThat(contentOf(datasetFile)).
            contains("<?xml version='1.0' encoding='UTF-8'?>"+NEW_LINE +
                    "<dataset>"+NEW_LINE +
                    "  <USER/>"+NEW_LINE +
                    "</dataset>");

}
 
Example #6
Source File: DataSetExecutorImpl.java    From database-rider with Apache License 2.0 5 votes vote down vote up
private void logDataSet(IDataSet resultingDataSet, Exception e) {
    try {
        File datasetFile = Files.createTempFile("dataset-log", ".xml").toFile();
        log.info("Saving current dataset to " + datasetFile.getAbsolutePath());
        try (FileOutputStream fos = new FileOutputStream(datasetFile)) {
            FlatXmlDataSet.write(resultingDataSet, fos);
        }
    } catch (Exception e1) {
        log.error("Could not log created dataset.", e);
    }
}
 
Example #7
Source File: DataSetBuilderTest.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGeneratFlatXmlDataSetWithEmptyUserTable() throws DataSetException, IOException {
    DataSetBuilder builder = new DataSetBuilder();
    ColumnSpec id = ColumnSpec.of("ID");
    builder.table("USER")
            .table("TWEET")
            .row()
                .column("ID", "abcdef12345")
                .column("CONTENT", "dbunit rules!")
                .column("DATE", "[DAY,NOW]")
            .table("FOLLOWER")
            .row()
                .column(id, 1)
                .column("USER_ID", 1)
                .column("FOLLOWER_ID", 2)
            .build();

    IDataSet dataSet = builder.build();

    File datasetFile = Files.createTempFile("rider-dataset", ".xml").toFile();
    FileOutputStream fos = new FileOutputStream(datasetFile);
    FlatXmlDataSet.write(dataSet, fos);
    assertThat(contentOf(datasetFile)).
            contains("<?xml version='1.0' encoding='UTF-8'?>"+NEW_LINE +
                    "<dataset>"+NEW_LINE +
                    "  <USER/>"+NEW_LINE +
                    "  <TWEET ID=\"abcdef12345\" CONTENT=\"dbunit rules!\" DATE=\"[DAY,NOW]\"/>"+NEW_LINE +
                    "  <FOLLOWER ID=\"1\" USER_ID=\"1\" FOLLOWER_ID=\"2\"/>"+NEW_LINE +
                    "</dataset>");
}
 
Example #8
Source File: DBUnitDataExtractor.java    From gazpachoquest with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Performs the extraction. If no tables or queries are specified, data from
 * entire database will be extracted.
 * Otherwise, a partial extraction will be performed.
 * 
 * @throws Exception
 */
public void extract() throws Exception {
    Connection conn = null;
    try {
        conn = dataSource.getConnection();
        logger.info("Beginning extraction from '" + conn.toString() + "'.");
        IDatabaseConnection connection = new DatabaseConnection(conn, schema);
        configConnection((DatabaseConnection) connection);
        if (tableList != null || queryList != null) {
            // partial database export
            QueryDataSet partialDataSet = new QueryDataSet(connection);
            addTables(partialDataSet);
            addQueries(partialDataSet);
            FlatXmlDataSet.write(partialDataSet, new FileOutputStream(dataSetName));
        } else {
            // full database export
            IDataSet fullDataSet = connection.createDataSet();
            FlatXmlDataSet.write(fullDataSet, new FileOutputStream(dataSetName));

            // dependent tables database export: export table X and all
            // tables that
            // have a PK which is a FK on X, in the right order for
            // insertion
            String[] depTableNames = TablesDependencyHelper.getAllDependentTables(connection, "research");
            IDataSet depDataset = connection.createDataSet(depTableNames);

            FlatXmlWriter datasetWriter = new FlatXmlWriter(new FileOutputStream("target/dependents.xml"));
            datasetWriter.write(depDataset);

        }
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
    logger.info("Completed extraction to '" + dataSetName + "'.");
}
 
Example #9
Source File: DatabaseCapable.java    From jadira with Apache License 2.0 5 votes vote down vote up
protected void writeExpectedFile(IDatabaseConnection dbunitConnection,
		File outputFile, String tableName) throws IOException,
		DataSetException {

	QueryDataSet partialDataSet = new QueryDataSet(dbunitConnection);
	partialDataSet.addTable(tableName);

	FlatXmlDataSet.write(partialDataSet, new FileOutputStream(outputFile));
}
 
Example #10
Source File: AbstractDbUnitTestCase.java    From SpringCloud with Apache License 2.0 5 votes vote down vote up
/**
 * 根据配置文件的名称创建DateSet
 * @param tname配置文件的名称
 * @return
 * @throws DataSetException
 */
protected IDataSet createDateSet(String tname) throws DataSetException {
	//配置文件在classes的根目录下
	InputStream is = AbstractDbUnitTestCase
				.class
				.getClassLoader().getResourceAsStream(tname+".xml");
	Assert.assertNotNull("dbunit的基本数据文件不存在",is);
	//创建DataSet
	return new FlatXmlDataSet(new FlatXmlProducer(new InputSource(is)));
}
 
Example #11
Source File: DbUnitSupport.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
public IDataSet loadFlatXmlDataStream(Class<?> c, String resource, boolean resetDtdSchema) throws Exception {
        FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
        builder.setMetaDataSetFromDtd(getDtdSchema(resetDtdSchema));
//        builder.setMetaDataSet(getConnection().createDataSet());
        FlatXmlDataSet fds = builder.build(getResourceStream(c, resource));
        return fds;
    }
 
Example #12
Source File: AbstractDaoTestCase.java    From Asqatasun with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Charge le jeu de données à partir d'un fichier XML d'import
 */
@Override
protected IDataSet getDataSet() throws Exception {
    FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder();
    FlatXmlDataSet loadedDataSet = flatXmlDataSetBuilder.build(new FileInputStream(
            getInputDataFileName()));
    return loadedDataSet;

}
 
Example #13
Source File: DataSetBuilderTest.java    From database-rider with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldGenerateFlatXmlDataSet() throws DataSetException, IOException {
    DataSetBuilder builder = new DataSetBuilder();
    ColumnSpec id = ColumnSpec.of("ID");
    builder.table("USER")
            .row()
                .column("ID", 1)
                .column("NAME", "@realpestano")
            .table("USER")
            .row().column(id, 2)
                .column("NAME", "@dbunit")
            .table("TWEET")
            .row()
                .column("ID", "abcdef12345")
                .column("CONTENT", "dbunit rules!")
                .column("DATE", "[DAY,NOW]")
            .table("FOLLOWER")
            .row()
                .column(id, 1)
                .column("USER_ID", 1)
                .column("FOLLOWER_ID", 2)
            .build();

    IDataSet dataSet = builder.build();

    File datasetFile = Files.createTempFile("rider-dataset", ".xml").toFile();
    FileOutputStream fos = new FileOutputStream(datasetFile);
    FlatXmlDataSet.write(dataSet, fos);
    assertThat(contentOf(datasetFile)).
            contains("<?xml version='1.0' encoding='UTF-8'?>"+NEW_LINE  +
                    "<dataset>"+NEW_LINE  +
                    "  <USER ID=\"1\" NAME=\"@realpestano\"/>"+NEW_LINE  +
                    "  <USER ID=\"2\" NAME=\"@dbunit\"/>"+NEW_LINE  +
                    "  <TWEET ID=\"abcdef12345\" CONTENT=\"dbunit rules!\" DATE=\"[DAY,NOW]\"/>"+NEW_LINE  +
                    "  <FOLLOWER ID=\"1\" USER_ID=\"1\" FOLLOWER_ID=\"2\"/>"+NEW_LINE  +
                    "</dataset>");

}
 
Example #14
Source File: AbstractTestDAO.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
protected IDataSet createDataSet() throws Exception {
    final FlatXmlDataSet dataSet = new FlatXmlDataSetBuilder()
            //.setColumnSensing(true) // This enables auto discovery of columns but breaks the tests, possibly our data needs clean up
            .build(getClass().getClassLoader().getResourceAsStream(createDataSetFile()));
    final ReplacementDataSet rDataSet = new ReplacementDataSet(dataSet);
    rDataSet.addReplacementObject("[NULL]", null);
    return rDataSet;
}
 
Example #15
Source File: FlatXmlDataSetMigrationTask.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Run the migration using the given context.
 *
 * @param context the context to run under
 * @throws MigrationException if an unexpected error occurs
 */
public void migrate(MigrationContext context) throws MigrationException
{
    log.debug("Executing patch " + getLevel());
    // down casting, technically not safe, but everyone else is doing it.
    JdbcMigrationContext jdbcContext = (JdbcMigrationContext) context;
    // used to close connection in finally block
    Connection contextConnection = null;
    try
    {
        FlatXmlDataSet xmlDataSet = new FlatXmlDataSet(getXmlAsStream());
        // Set contextConnection so it can be accessed in the finally block.
        contextConnection = jdbcContext.getConnection();

        // run the data load
        IDatabaseConnection connection = new DatabaseConnection(contextConnection);
        DatabaseOperation.INSERT.execute(connection, xmlDataSet);
        context.commit();

        // Closing here instead of in finally block to keep the signature of this from throwing
        // a SqlException.  Exceptional condition handled in finally block to make sure
        // we don't leak a connection.
        connection.close();
    }
    catch (Exception e)
    {
        log.debug("Unable to patch due to " + e.getMessage());
        context.rollback();
        throw new MigrationException("Unable to patch", e);
    }
    finally
    {
        // Might already be closed if everything worked fine and connection.close was called 
        // above, in that case, calling close again shouldn't do any harm.  However, if an 
        // exception occurred the DBUnit based connection wrapper didn't get closed, so we 
        // catch that case here.
        SqlUtil.close(contextConnection, null, null);
    }
}
 
Example #16
Source File: BasePaymentModuleDBTestCase.java    From yes-cart with Apache License 2.0 5 votes vote down vote up
protected IDataSet createDataSet() throws Exception {
    final FlatXmlDataSet dataSet = new FlatXmlDataSetBuilder()
            //.setColumnSensing(true) // This enables auto discovery of columns but breaks the tests, possibly our data needs clean up
            .build(getClass().getClassLoader().getResourceAsStream(createDataSetFile()));
    final ReplacementDataSet rDataSet = new ReplacementDataSet(dataSet);
    rDataSet.addReplacementObject("[NULL]", null);
    return rDataSet;
}
 
Example #17
Source File: AbstractDbUnitTestCase.java    From wetech-cms with MIT License 5 votes vote down vote up
/**
 * 根据配置文件的名称创建DateSet
 * @param tname配置文件的名称
 * @return
 * @throws DataSetException
 */
protected IDataSet createDateSet(String tname) throws DataSetException {
	//配置文件在classes的根目录下
	InputStream is = AbstractDbUnitTestCase
				.class
				.getClassLoader().getResourceAsStream(tname+".xml");
	Assert.assertNotNull("dbunit的基本数据文件不存在",is);
	//创建DataSet
	return new FlatXmlDataSet(new FlatXmlProducer(new InputSource(is)));
}
 
Example #18
Source File: AbstractDbUnitTestCase.java    From wetech-cms with MIT License 5 votes vote down vote up
private void writeBackupFile(IDataSet ds) throws IOException, DataSetException {
	tempFile = File.createTempFile("back", "xml");
	dtdFile = File.createTempFile("back","dtd");
	//写dtd
	FlatDtdDataSet.write(ds, new FileWriter(dtdFile));
	//写数据表中的文件
	FlatXmlDataSet.write(ds, new FileWriter(tempFile));
}
 
Example #19
Source File: AbstractDbUnitTestCase.java    From wetech-cms with MIT License 5 votes vote down vote up
protected IDataSet createDateSet(String tname) throws DataSetException, FileNotFoundException, IOException {
	InputStream is = AbstractDbUnitTestCase
				.class
				.getClassLoader().getResourceAsStream(tname+".xml");
	Assert.assertNotNull("dbunit的基本数据文件不存在",is);
	//通过dtd和传入的文件创建测试的IDataSet
	return new FlatXmlDataSet(new FlatXmlProducer(new InputSource(is),new FlatDtdDataSet(new FileReader(dtdFile))));
}
 
Example #20
Source File: AbstractDbUnitTestCase.java    From wetech-cms with MIT License 4 votes vote down vote up
protected void resumeTable() throws FileNotFoundException, DatabaseUnitException, SQLException {
	IDataSet ds = new FlatXmlDataSet(new FlatXmlProducer(new InputSource(new FileInputStream(tempFile))));
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
}
 
Example #21
Source File: AbstractDbUnitTestCase.java    From wetech-cms with MIT License 4 votes vote down vote up
private void writeBackupFile(IDataSet ds) throws IOException, DataSetException {
	tempFile = File.createTempFile("back","xml");
	FlatXmlDataSet.write(ds, new FileWriter(tempFile));
}
 
Example #22
Source File: AbstractDbUnitTestCase.java    From SpringCloud with Apache License 2.0 4 votes vote down vote up
private void writeBackupFile(IDataSet ds) throws IOException, DataSetException {
	tempFile = File.createTempFile("back","xml");
	FlatXmlDataSet.write(ds, new FileWriter(tempFile));
}
 
Example #23
Source File: AbstractDbUnitTestCase.java    From SpringCloud with Apache License 2.0 4 votes vote down vote up
protected void resumeTable() throws FileNotFoundException, DatabaseUnitException, SQLException {
	IDataSet ds = new FlatXmlDataSet(new FlatXmlProducer(new InputSource(new FileInputStream(tempFile))));
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
}
 
Example #24
Source File: AbstractDbUnitTestCase.java    From wetech-cms with MIT License 4 votes vote down vote up
protected void resumeTable() throws DatabaseUnitException, SQLException, IOException {
	//创建ds的时候引入相应的dtd
	IDataSet ds = new FlatXmlDataSet(new FlatXmlProducer(
				new InputSource(new FileInputStream(tempFile)),new FlatDtdDataSet(new FileReader(dtdFile))));
	DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
}
 
Example #25
Source File: DBUnitTestExecutionListener.java    From flyway-test-extensions with Apache License 2.0 4 votes vote down vote up
/**
 * Only annotation with saveIt will be executed
 */
public void afterTestMethod(final TestContext testContext) throws Exception {
	// no we check for the DBResetForClass
	final Method testMethod = testContext.getTestMethod();

	final Annotation annotation = testMethod
			.getAnnotation(DBUnitSupport.class);

	if (annotation != null) {
		final DBUnitSupport dbUnitAnnotaton = (DBUnitSupport) annotation;
		final String saveIt = dbUnitAnnotaton.saveFileAfterRun();
		final String[] tables = dbUnitAnnotaton.saveTableAfterRun();

		if (saveIt != null && saveIt.trim().length() > 0) {
			String executionInfo = "";
			if (logger.isDebugEnabled()) {
				executionInfo = ExecutionListenerHelper
						.getExecutionInformation(testContext);
				logger.debug("******** Start save information '"
						+ executionInfo + "' info file '" + saveIt + "'.");
			}
			final DataSource ds = getSaveDataSource(testContext);

			final IDatabaseConnection con = getConnection(ds, testContext);
               // Issue 16 fix leaking database connection - will look better with Java 7 Closable
               try {
                   final IDataSet dataSet = getDataSetToExport(tables, con);
                   final File fileToExport = getFileToExport(saveIt);

                   final FileWriter fileWriter = new FileWriter(fileToExport);
                   FlatXmlDataSet.write(dataSet, fileWriter);
               } finally {
                   if (logger.isDebugEnabled()) {
                       logger.debug("******** Close database connection " + con);
                   }
                   con.close();
               }
               if (logger.isDebugEnabled()) {
                   logger.debug("******** Finished save information '"
                           + executionInfo + "' info file '" + saveIt + "'.");
               }
           }
	}
}
 
Example #26
Source File: DBUnitTestExecutionListener.java    From flyway-test-extensions with Apache License 2.0 4 votes vote down vote up
private FlatXmlDataSet getFileDataSet(final InputStream is)
		throws Exception {

	final FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
	return builder.build(is);
}