Java Code Examples for org.dbunit.database.IDatabaseConnection#close()

The following examples show how to use org.dbunit.database.IDatabaseConnection#close() . 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: ITKylinQueryTest.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidQuery() throws Exception {

    logger.info("-------------------- Test Invalid Query --------------------");
    String queryFolder = getQueryFolderPrefix() + "src/test/resources/query/sql_invalid";
    List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
    for (File sqlFile : sqlFiles) {
        String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
        logger.info("Testing Query " + queryName);
        String sql = getTextFromFile(sqlFile);
        IDatabaseConnection cubeConn = new DatabaseConnection(cubeConnection);
        try {
            cubeConn.createQueryTable(queryName, sql);
        } catch (Throwable t) {
            continue;
        } finally {
            cubeConn.close();
        }
        throw new IllegalStateException(queryName + " should be error!");
    }
}
 
Example 2
Source File: ITKylinQueryTest.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidQuery() throws Exception {

    logger.info("-------------------- Test Invalid Query --------------------");
    String queryFolder = getQueryFolderPrefix() + "src/test/resources/query/sql_invalid";
    List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
    for (File sqlFile : sqlFiles) {
        String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
        logger.info("Testing Query " + queryName);
        String sql = getTextFromFile(sqlFile);
        IDatabaseConnection cubeConn = new DatabaseConnection(cubeConnection);
        try {
            cubeConn.createQueryTable(queryName, sql);
        } catch (Throwable t) {
            continue;
        } finally {
            cubeConn.close();
        }
        throw new IllegalStateException(queryName + " should be error!");
    }
}
 
Example 3
Source File: KylinQueryTest.java    From Kylin with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidQuery() throws Exception {

    printInfo("-------------------- Test Invalid Query --------------------");
    String queryFolder = "src/test/resources/query/sql_invalid";
    List<File> sqlFiles = getFilesFromFolder(new File(queryFolder), ".sql");
    for (File sqlFile : sqlFiles) {
        String queryName = StringUtils.split(sqlFile.getName(), '.')[0];
        printInfo("Testing Query " + queryName);
        String sql = getTextFromFile(sqlFile);
        IDatabaseConnection cubeConn = new DatabaseConnection(cubeConnection);
        try {
            cubeConn.createQueryTable(queryName, sql);
        } catch (Throwable t) {
            continue;
        } finally {
            cubeConn.close();
        }
        throw new IllegalStateException(queryName + " should be error!");
    }
}
 
Example 4
Source File: Fixtures.java    From base-framework with Apache License 2.0 6 votes vote down vote up
/**
 * 对XML文件中的数据在H2数据库中执行Operation.
 * 
 * @param xmlFilePaths 符合Spring Resource路径格式的文件列表.
 */
private static void execute(DatabaseOperation operation, DataSource dataSource, String... xmlFilePaths)
		throws DatabaseUnitException, SQLException {
	//注意这里HardCode了使用H2的Connetion
	IDatabaseConnection connection = new H2Connection(dataSource.getConnection(), null);

	for (String xmlPath : xmlFilePaths) {
		try {
			InputStream input = resourceLoader.getResource(xmlPath).getInputStream();
			IDataSet dataSet = new FlatXmlDataSetBuilder().setColumnSensing(true).build(input);
			operation.execute(connection, dataSet);
		} catch (IOException e) {
			logger.warn(xmlPath + " file not found", e);
		}finally{
			connection.close();
		}
	}
}
 
Example 5
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 6
Source File: DbUnitDatabaseConnectionDecorator.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Override
public void afterAll(final TestInvocation invocation) throws Exception {
    final ExecutionContext context = invocation.getContext();
    final IDatabaseConnection connection = (IDatabaseConnection) context.getData(Constants.KEY_CONNECTION);
    context.storeData(Constants.KEY_CONNECTION, null);

    connection.close();
}
 
Example 7
Source File: ProarcDatabaseTest.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void testUpgrade() throws Exception {
    ProarcDatabaseV1 v1 = new ProarcDatabaseV1();
    ProarcDatabaseV2 v2 = new ProarcDatabaseV2();
    ProarcDatabaseV3 v3 = new ProarcDatabaseV3();
    ProarcDatabaseV4 v4 = new ProarcDatabaseV4();
    final IDatabaseConnection con = support.getConnection();
    try {
        // clear DB
        dropSchema(schema);
        dropSchema(v4);
        dropSchema(v3);
        dropSchema(v2);
        dropSchema(v1);
        v1.init(emireCfg);
        assertEquals(1, ProarcDatabase.schemaExists(schema, con.getConnection()));

        IDataSet db = support.loadFlatXmlDataStream(getClass(), "proarc_v1.xml", true);
        try {
            DatabaseOperation.INSERT.execute(con, db);
            con.getConnection().commit();
        } finally {
            support.clearDtdSchema();
        }
        schema.init(emireCfg);
        assertEquals(ProarcDatabase.VERSION, ProarcDatabase.schemaExists(schema, con.getConnection()));
    } finally {
        con.close();
        dropSchema(schema);
        dropSchema(v1);
    }
}
 
Example 8
Source File: FosstrakInteropTestCase.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 5 votes vote down vote up
protected void setUp() throws Exception {
    IDatabaseConnection connection = getConnection();
    IDataSet dataSet = getDataSet();
    String op = getSetUpOperation().getClass().getSimpleName();

    // reset the database
    try {
        long t1 = System.currentTimeMillis();
        getSetUpOperation().execute(connection, dataSet);
        long t2 = System.currentTimeMillis();
        System.out.println("database reset (" + op + ") successful in " + (t2 - t1) + "ms");
    } finally {
        connection.close();
    }
}
 
Example 9
Source File: DatabaseConfigurationTestHelper.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the internal data source. This method also initializes the
 * database.
 *
 * @return the data source
 * @throws Exception if an error occurs
 */
private DataSource setUpDataSource() throws Exception
{
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(DATABASE_DRIVER);
    ds.setUrl(DATABASE_URL);
    ds.setUsername(DATABASE_USERNAME);
    ds.setPassword(DATABASE_PASSWORD);
    ds.setDefaultAutoCommit(!isAutoCommit());

    // prepare the database
    final Connection conn = ds.getConnection();
    final IDatabaseConnection connection = new DatabaseConnection(conn);
    final IDataSet dataSet = new XmlDataSet(new FileInputStream(
            ConfigurationAssert.getTestFile("dataset.xml")));

    try
    {
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
    }
    finally
    {
        if (!isAutoCommit())
        {
            conn.commit();
        }
        connection.close();
    }

    return ds;
}
 
Example 10
Source File: AbstractDBUnitHibernateMemoryTest.java    From livingdoc-confluence with GNU General Public License v3.0 4 votes vote down vote up
private void closeConnection(IDatabaseConnection connection) throws SQLException {
    if (null != connection) {
        connection.close();
    }
}
 
Example 11
Source File: WorkflowManagerTest.java    From proarc with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void testAddJob() throws Exception {
    IDataSet db = database(
            support.loadFlatXmlDataStream(EmpireWorkflowJobDaoTest.class, "user.xml"),
            emptyBatchSet(schema)
            );
    final IDatabaseConnection dbcon = support.getConnection();
    support.cleanInsert(dbcon, db);
    dbcon.getConnection().commit();
    dbcon.close();

    WorkflowManager wm = initWorkflowManager("WorkflowManagerAddProfile.xml");
    WorkflowDefinition workflow = wp.getProfiles();
    assertNotNull(workflow);
    JobDefinition jobProfile = workflow.getJobs().get(0);
    assertNotNull(jobProfile);
    CatalogConfiguration c = new CatalogConfiguration("testCatalogId", "", new BaseConfiguration() {{
        addProperty(CatalogConfiguration.PROPERTY_URL, "tcp://localhost:9991");
        addProperty(CatalogConfiguration.PROPERTY_NAME, "test");
        addProperty(CatalogConfiguration.PROPERTY_TYPE, Z3950Catalog.TYPE);
    }});
    String mods = IOUtils.toString(WorkflowManagerTest.class.getResource("rdczmods.xml"));
    Job job = wm.addJob(jobProfile, mods, c, null, null, null);
    assertNotNull(job);

    Job getJob = wm.getJob(job.getId());
    assertNotNull(getJob);

    JobFilter filter = new JobFilter();
    filter.setId(job.getId());
    Locale locale = new Locale("cs");
    filter.setLocale(locale);

    List<JobView> findJob = wm.findJob(filter);
    assertEquals(1, findJob.size());
    assertEquals("csTitle", findJob.get(0).getProfileLabel());

    TaskFilter taskFilter = new TaskFilter();
    taskFilter.setLocale(locale);
    taskFilter.setJobId(job.getId());
    List<TaskView> findTask = wm.tasks().findTask(taskFilter, workflow);
    assertEquals(2, findTask.size());
    assertEquals(job.getId(), findTask.get(0).getJobId());

    MaterialFilter materialFilter = new MaterialFilter();
    materialFilter.setJobId(job.getId());
    materialFilter.setLocale(locale);
    List<MaterialView> findMaterial = wm.findMaterial(materialFilter);
    assertEquals(2, findMaterial.size());

    TaskParameterFilter paramFilter = new TaskParameterFilter();
    paramFilter.setLocale(locale);
    paramFilter.setProfileName("param.id1");
    List<TaskParameterView> findParameter = wm.findParameter(paramFilter);
    assertEquals(2, findParameter.size());
    assertEquals("param.id1", findParameter.get(0).getParamRef());
    assertEquals("param.id1.value", findParameter.get(0).getValue());
    assertEquals(job.getId(), findParameter.get(0).getJobId());
    assertEquals("Param1", findParameter.get(0).getProfileLabel());
    // param.id2 comes just from the profile not db!
    assertEquals("param.id2", findParameter.get(1).getParamRef());
    assertNull(findParameter.get(1).getValue());
    assertEquals(job.getId(), findParameter.get(1).getJobId());
    assertEquals("param.id2", findParameter.get(1).getProfileLabel());
    assertEquals(findParameter.get(0).getTaskId(), findParameter.get(1).getTaskId());
    assertEquals("task.id1", findParameter.get(1).getTaskProfileName());
    assertEquals("proarc.devices", findParameter.get(1).getValueMapId());
    assertEquals(ValueMapSource.PROARC, findParameter.get(1).getValueMapType());
    assertEquals(Boolean.TRUE, findParameter.get(1).getRequired());
    assertEquals(ValueType.STRING, findParameter.get(1).getValueType());
}
 
Example 12
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 + "'.");
               }
           }
	}
}