Java Code Examples for org.dbunit.operation.DatabaseOperation

The following are top voted examples for showing how to use org.dbunit.operation.DatabaseOperation. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: development   File: DatabaseTaskHandler.java   View source code 7 votes vote down vote up
/**
 * Inserts the file of the dbUnit compliant flat xml file into the database
 * used by the system.
 * 
 * @param dbSrcFileName
 *            The name of the file to be imported.
 * @throws IOException
 * @throws DataSetException
 * @throws DatabaseUnitException
 * @throws SQLException
 */
public static void insertData(String dbSourceFileLocation)
        throws IOException, DataSetException, DatabaseUnitException,
        SQLException {
    if (dbSourceFileLocation == null) {
        return;
    }
    ReplacementDataSet dataSet = new ReplacementDataSet(
            new FlatXmlDataSetBuilder()
                    .build(new File(dbSourceFileLocation)));
    dataSet.addReplacementObject("[NULL]", null);
    Date now = new Date();
    dataSet.addReplacementObject("[SYSDATE]", Long.valueOf(now.getTime()));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    dataSet.addReplacementObject("[SYSTIMESTAMP]", sdf.format(now));

    DatabaseOperation.INSERT.execute(dbConn, dataSet);
}
 
Example 2
Project: saladium   File: AbstractWorker.java   View source code 6 votes vote down vote up
/**
 * Méthode recursive.
 * @param file
 * @param hasParameters
 * @param operation
 * @throws SaladiumException
 */
private void recursive(File file, DatabaseOperation operation) throws SaladiumException {
    if (file.isDirectory()) {
        if (!".svn".equals(file.getName())) {
            for (File childFile : file.listFiles()) {
                recursive(childFile, operation);
            }
        }
    } else {
        if ("xml".equals(FilenameUtils.getExtension(file.getAbsolutePath()))) {
            dataOperation(file, operation);
        } else {
            LOGGER.info(file.getAbsolutePath() + " n'est pas un fichier valide et ne devrait pas se trouver à cet emplacement");
        }
    }
}
 
Example 3
Project: coodoo-listing   File: AbstractDbUnitTest.java   View source code 6 votes vote down vote up
/**
 * Set up memory database and insert data from test-dataset.xml
 * 
 * @throws DatabaseUnitException
 * @throws HibernateException
 * @throws SQLException
 */
@BeforeClass
public static void initEntityManager() throws HibernateException, DatabaseUnitException, SQLException {
    entityManagerFactory = Persistence.createEntityManagerFactory("listing-test-db");
    entityManager = entityManagerFactory.createEntityManager();
    connection = new DatabaseConnection(((SessionImpl) (entityManager.getDelegate())).connection());
    connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new HsqldbDataTypeFactory());

    InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(datasetXml);
    if (inputStream != null) {
        FlatXmlDataSetBuilder flatXmlDataSetBuilder = new FlatXmlDataSetBuilder();
        flatXmlDataSetBuilder.setColumnSensing(true);
        dataset = flatXmlDataSetBuilder.build(inputStream);
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataset);
    }
}
 
Example 4
Project: linkbinder   File: AbstractDaoTestCase.java   View source code 6 votes vote down vote up
@Before
public void customSetup() throws Exception {
    super.getDatabaseTester().setSchema("linkbinder_test");

    // マスタデータ
    File resource = new File(getPjUserResourceName());
    if (resource.exists()) {
        IDataSet ds = new XlsDataSet(new FileInputStream(resource));
        IDatabaseConnection connection = getConnection();
        try {
            DatabaseOperation.REFRESH.execute(connection, ds);
        } finally {
            closeConnection(connection);
        }
    }

    super.setUp();

}
 
Example 5
Project: jpa-unit   File: CleanupStrategyProviderTest.java   View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    initialDataSet = new FlatXmlDataSetBuilder().build(new File("src/test/resources/test-data.xml"));
    connection = new DatabaseConnection(DriverManager.getConnection(CONNECTION_URL, USER_NAME, PASSWORD));

    final DatabaseOperation operation = DatabaseOperation.CLEAN_INSERT;
    operation.execute(connection, initialDataSet);

    connection.getConnection().createStatement().execute(
            "insert into XML_TABLE_1(id, version, value_1, value_2, value_3, value_4, value_5) values(10, 'Record 10 version', 'Record 10 Value 1', 'Record 10 Value 2', 'Record 10 Value 3', 'Record 10 Value 4', 'Record 10 Value 5');");
    connection.getConnection().commit();

    connection.getConnection().createStatement().execute(
            "merge into XML_TABLE_3(id, version, value_8, value_9) values(11, 'Record 11 version', 'Record 11 Value 8', 'Record 11 Value 9');");
    connection.getConnection().commit();

    assertThat(getRecordCountFromTable(connection, "XML_TABLE_1"), equalTo(4));
    assertThat(getRecordCountFromTable(connection, "XML_TABLE_2"), equalTo(1));
    assertThat(getRecordCountFromTable(connection, "XML_TABLE_3"), equalTo(1));
}
 
Example 6
Project: travel_portal   File: CleanInsertTestExecutionListener.java   View source code 6 votes vote down vote up
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
    DataSetLocation dsLocation = testContext.getTestInstance().getClass().getAnnotation(DataSetLocation.class);
    if (dsLocation != null) {
        String dataSetResourcePath = dsLocation.value();
        Resource dataSetResource = testContext.getApplicationContext().getResource(dataSetResourcePath);

        if (dataSetResource.exists()) {
            IDataSet dataSet = new FlatXmlDataSetBuilder().build(dataSetResource.getInputStream());
            IDatabaseConnection dbConn = new DatabaseDataSourceConnection(
                    testContext.getApplicationContext().getBean(DataSource.class)
            );
            DatabaseOperation.CLEAN_INSERT.execute(dbConn, dataSet);

            LOG.info("Annotated test, using data set: {}", dataSetResourcePath);
        }
    }
}
 
Example 7
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   View source code 6 votes vote down vote up
/**
 * Inserts test data in DbUnit XML format.
 *
 * @param entityManager
 *           the EntityManager
 * @param dbUnitTestdata
 *           test file stream
 */
public static void insertDbUnitTestdata(EntityManager entityManager, final InputStream dbUnitTestdata) {

   entityManager.unwrap(Session.class).doWork(new Work() {

      @Override
      public void execute(Connection connection) throws SQLException {
         // Insert Testdata
         try {
            LOGGER.debug("INSERTing testdata");
            DatabaseConnection databaseConnection = new DatabaseConnection(connection);
            databaseConnection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
               new MySqlDataTypeFactory());

            FlatXmlDataSet dataSet = new FlatXmlDataSet(
               new FlatXmlProducer(new InputSource(dbUnitTestdata), false, true));
            DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataSet);
            LOGGER.debug("INSERTing testdata ... done");
         } catch (DatabaseUnitException e) {
            throw new SQLException(e);
         }
      }

   });
}
 
Example 8
Project: testcontainers-examples   File: DockerDatabaseTestUtil.java   View source code 6 votes vote down vote up
/**
 * Inserts test data in DbUnit XML format.
 *
 * @param entityManager
 *           the EntityManager
 * @param dbUnitTestdata
 *           test file stream
 */
public static void insertDbUnitTestdata(EntityManager entityManager, final InputStream dbUnitTestdata) {

   entityManager.unwrap(Session.class).doWork(new Work() {

      @Override
      public void execute(Connection connection) throws SQLException {
         // Insert Testdata
         try {
            LOGGER.debug("INSERTing testdata");
            DatabaseConnection databaseConnection = new DatabaseConnection(connection);
            databaseConnection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY,
               new MySqlDataTypeFactory());

            FlatXmlDataSet dataSet = new FlatXmlDataSet(
               new FlatXmlProducer(new InputSource(dbUnitTestdata), false, true));
            DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, dataSet);
            LOGGER.debug("INSERTing testdata ... done");
         } catch (DatabaseUnitException e) {
            throw new SQLException(e);
         }
      }

   });
}
 
Example 9
Project: keystone4j   File: AbstractIntegratedTest.java   View source code 6 votes vote down vote up
/**
 * Will clean the dataBase before each test
 * 
 * @throws SQLException
 * @throws DatabaseUnitException
 */
@Before
public void cleanDB() throws DatabaseUnitException, SQLException {
	// DatabaseOperation.TRUNCATE_TABLE.execute(connection, dataset);
	DatabaseOperation.CLEAN_INSERT.execute(connection, dataset);
	// try {
	// EntityManagerHelper.beginTransaction();
	// } catch (RuntimeException e) {
	// e.printStackTrace();
	// if (EntityManagerHelper.getEntityManager() != null &&
	// EntityManagerHelper.getEntityManager().isOpen()) {
	// EntityManagerHelper.rollback();
	// }
	// EntityManagerHelper.closeEntityManager();
	// throw e;
	// }
}
 
Example 10
Project: keystone4j   File: AbstractDbUnitJpaTest.java   View source code 6 votes vote down vote up
/**
 * Will clean the dataBase before each test
 * 
 * @throws SQLException
 * @throws DatabaseUnitException
 */
@Before
public void cleanDB() throws DatabaseUnitException, SQLException {
	// DatabaseOperation.TRUNCATE_TABLE.execute(connection, dataset);
	DatabaseOperation.CLEAN_INSERT.execute(connection, dataset);
	try {
		EntityManagerHelper.beginTransaction();
	} catch (RuntimeException e) {
		e.printStackTrace();
		if (EntityManagerHelper.getEntityManager() != null && EntityManagerHelper.getEntityManager().isOpen()) {
			EntityManagerHelper.rollback();
		}
		EntityManagerHelper.closeEntityManager();
		throw e;
	}
}
 
Example 11
Project: greenpepper   File: AbstractDBUnitHibernateMemoryTest.java   View source code 6 votes vote down vote up
/**
 * This composite operation performs a  deleteAllFromDatabase operation
 * followed by an insertIntoDatabase operation. This is the safest approach
 * to ensure that the database is in a known state. This is appropriate for
 * tests that require the database to only contain a specific set of data.
 *
 * @param dataSet
 * @throws Exception
 */
protected void cleanInsertIntoDatabase( IDataSet dataSet )
        throws Exception
{
    IDatabaseConnection connection = null;

    try
    {
        connection = getConnection();
        DatabaseOperation.CLEAN_INSERT.execute( connection, dataSet );
    }
    finally
    {
        closeConnection( connection );
    }
}
 
Example 12
Project: SpringCloud   File: TestUserDao.java   View source code 6 votes vote down vote up
@Test
public void testFindByArgs() throws DatabaseUnitException, SQLException {
    IDataSet ds = createDateSet("t_user");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    SystemContext.setOrder("desc");
    SystemContext.setSort("id");
    SystemContext.setPageSize(3);
    SystemContext.setPageOffset(0);
    Pager<User> expected = userDao.find("from User where id>=? and id<=?", new Object[] { 1, 10 });
    List<User> actuals = Arrays.asList(new User(10, "admin10"), new User(9, "admin9"), new User(8, "admin8"));
    assertNotNull(expected);
    assertTrue(expected.getTotal() == 10);
    assertTrue(expected.getOffset() == 0);
    assertTrue(expected.getSize() == 3);
    EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 13
Project: SpringCloud   File: TestUserDao.java   View source code 6 votes vote down vote up
@Test
public void testFindByArgsAndAlias() throws DatabaseUnitException, SQLException {
    IDataSet ds = createDateSet("t_user");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    SystemContext.removeOrder();
    SystemContext.removeSort();
    SystemContext.setPageSize(3);
    SystemContext.setPageOffset(0);
    Map<String, Object> alias = new HashMap<String, Object>();
    alias.put("ids", Arrays.asList(1, 2, 4, 5, 6, 7, 8, 10));
    Pager<User> expected = userDao.find("from User where id>=? and id<=? and id in (:ids)", new Object[] { 1, 10 },
            alias);
    List<User> actuals = Arrays.asList(new User(1, "admin1"), new User(2, "admin2"), new User(4, "admin4"));
    assertNotNull(expected);
    assertTrue(expected.getTotal() == 8);
    assertTrue(expected.getOffset() == 0);
    assertTrue(expected.getSize() == 3);
    EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 14
Project: SpringCloud   File: TestUserDao.java   View source code 6 votes vote down vote up
@Test
public void testFindSQLByArgs() throws DatabaseUnitException, SQLException {
    IDataSet ds = createDateSet("t_user");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    SystemContext.setOrder("desc");
    SystemContext.setSort("id");
    SystemContext.setPageSize(3);
    SystemContext.setPageOffset(0);
    Pager<User> expected = userDao.findUserBySql("select * from t_user where id>=? and id<=?",
            new Object[] { 1, 10 }, User.class, true);
    List<User> actuals = Arrays.asList(new User(10, "admin10"), new User(9, "admin9"), new User(8, "admin8"));
    assertNotNull(expected);
    assertTrue(expected.getTotal() == 10);
    assertTrue(expected.getOffset() == 0);
    assertTrue(expected.getSize() == 3);
    EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 15
Project: SpringCloud   File: TestUserDao.java   View source code 6 votes vote down vote up
@Test
public void testFindSQLByArgsAndAlias() throws DatabaseUnitException, SQLException {
    IDataSet ds = createDateSet("t_user");
    DatabaseOperation.CLEAN_INSERT.execute(dbunitCon, ds);
    SystemContext.removeOrder();
    SystemContext.removeSort();
    SystemContext.setPageSize(3);
    SystemContext.setPageOffset(0);
    Map<String, Object> alias = new HashMap<String, Object>();
    alias.put("ids", Arrays.asList(1, 2, 4, 5, 6, 7, 8, 10));
    Pager<User> expected = userDao.findUserBySql("select * from t_user where id>=? and id<=? and id in (:ids)",
            new Object[] { 1, 10 }, alias, User.class, true);
    List<User> actuals = Arrays.asList(new User(1, "admin1"), new User(2, "admin2"), new User(4, "admin4"));
    assertNotNull(expected);
    assertTrue(expected.getTotal() == 8);
    assertTrue(expected.getOffset() == 0);
    assertTrue(expected.getSize() == 3);
    EntitiesHelper.assertUsers(expected.getDatas(), actuals);
}
 
Example 16
Project: message-server   File: AppTest.java   View source code 6 votes vote down vote up
@BeforeClass
public static void setupDB() throws Exception {
  ds = UnitTestDSProvider.getDataSource();
  //clean any existing records and load some records into the database.
  FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
  builder.setColumnSensing(true);
  Connection setup = ds.getConnection();
  IDatabaseConnection con = new DatabaseConnection(setup);
  {
    InputStream xmlInput = DeviceDAOImplTest.class.getResourceAsStream("/data/app-data-1.xml");
    IDataSet dataSet = builder.build(xmlInput);
    DatabaseOperation.CLEAN_INSERT.execute(con, dataSet);
  }
  // load test encryptor class
  Class.forName(EncryptorForTest.class.getName());
}
 
Example 17
Project: greenpepper3   File: AbstractDBUnitHibernateMemoryTest.java   View source code 6 votes vote down vote up
/**
 * This composite operation performs a  deleteAllFromDatabase operation
 * followed by an insertIntoDatabase operation. This is the safest approach
 * to ensure that the database is in a known state. This is appropriate for
 * tests that require the database to only contain a specific set of data.
 *
 * @param dataSet
 * @throws Exception
 */
protected void cleanInsertIntoDatabase( IDataSet dataSet )
        throws Exception
{
    IDatabaseConnection connection = null;

    try
    {
        connection = getConnection();
        DatabaseOperation.CLEAN_INSERT.execute( connection, dataSet );
    }
    finally
    {
        closeConnection( connection );
    }
}
 
Example 18
Project: easycukes   File: DBUnitManager.java   View source code 6 votes vote down vote up
/**
 * Gets the Database operation
 *
 * @param operation
 * @return
 * @throws Exception
 */
private static DatabaseOperation getDBOperation(@NonNull String operation)
        throws Exception {

    switch (operation) {
        case "INSERT":
            return DatabaseOperation.INSERT;
        case "CLEAN_INSERT":
            return DatabaseOperation.CLEAN_INSERT;
        case "UPDATE":
            return DatabaseOperation.UPDATE;
        case "REFRESH":
            return DatabaseOperation.REFRESH;
        case "DELETE":
            return DatabaseOperation.DELETE;
        case "DELETE_ALL":
            return DatabaseOperation.DELETE_ALL;
        case "TRUNCATE_TABLE":
            return DatabaseOperation.TRUNCATE_TABLE;
        case "NONE":
            return DatabaseOperation.NONE;
        default:
            log.error("Unknown DB operation : " + operation);
            throw new Exception("Unknown DB operation : " + operation);
    }
}
 
Example 19
Project: automation-test-engine   File: TestDatabaseInitializer.java   View source code 6 votes vote down vote up
/**
 * Initialize.
 *
 * @param context
 *            the context
 * @param dataSource
 *            the data source
 * @throws DatabaseUnitException
 *             the database unit exception
 * @throws SQLException
 *             the SQL exception
 * @throws MalformedURLException
 *             the malformed url exception
 */
public void initializeGlobalDataFile(ApplicationContext context)
		throws DatabaseUnitException, SQLException, MalformedURLException {
	DataSource datas = GlobalUtils.findDataSourceBean(context);
	IDatabaseConnection con = new DatabaseConnection(datas.getConnection()); // Create
																				// DBUnit
																				// Database
																				// connection
	FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
	builder.setColumnSensing(true);

	datasets = new IDataSet[] { builder.build(singleInitXmlFile) };
	DatabaseOperation.REFRESH.execute(con, new CompositeDataSet(datasets)); // Import
																			// your
																			// data

	// TODO handle the empty data file case.
	con.close();

}
 
Example 20
Project: opennmszh   File: DbUnit.java   View source code 6 votes vote down vote up
public void cleanDb() {
    try {

        try {
            DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
        } finally {
            // connection.close();
        }
    } catch (Throwable e) {
        /* do we care?
        System.err.print("An error occurred deleting dataset: ");
        e.printStackTrace();
        */
    }

    ++operation;

}
 
Example 21
Project: test-suites   File: PerformanceTestContext.java   View source code 6 votes vote down vote up
@AfterClass
public static void tearDownDB() {
    System.out.println("Tearing down DB");
    try (ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("context.xml")) {
        IDatabaseConnection connection = new DatabaseDataSourceConnection(
                (DataSource) applicationContext.getBean("dataSource"));

        try {
            DatabaseOperation.DELETE_ALL.execute(connection,
                    new FlatXmlDataSetBuilder().build(
                            applicationContext.getResource("/database_tear_down.xml").getInputStream()));
        } finally {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 22
Project: test-suites   File: TestDataCreation.java   View source code 6 votes vote down vote up
public static void setupDb() {
    try (ConfigurableApplicationContext applicationContext = new ClassPathXmlApplicationContext("context.xml")) {
        IDatabaseConnection connection = new DatabaseDataSourceConnection(
                (DataSource) applicationContext.getBean("dataSource"));

        try {
            DatabaseOperation.CLEAN_INSERT.execute(connection,
                    new FlatXmlDataSetBuilder().build(
                            applicationContext.getResource("/database_seed_minimal.xml").getInputStream()));
        } finally {
            connection.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 23
Project: base-framework   File: Fixtures.java   View source code 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 24
Project: repository-parent   File: AbstractRepositoryTest.java   View source code 6 votes vote down vote up
private void refreshDatabase() throws Exception {
    
    // Get the database connection.
    IDatabaseConnection databaseConnection = this.getDatabaseConnection();
    
    // Refresh the dataset in the database.
    DatabaseOperation.CLEAN_INSERT.execute(databaseConnection, getDataSet());

    // Get the maximum ID from the address table.
    Statement statement = databaseConnection.getConnection().createStatement();
    ResultSet resultSet = statement.executeQuery("SELECT MAX(id) as max_id FROM address");
    resultSet.next();
    int max = resultSet.getInt("max_id");
    resultSet.close();
    statement.close();
    
    // Set the address table next generated Id value to the maximum ID plus 1.
    statement =  databaseConnection.getConnection().createStatement();
    statement.executeUpdate("ALTER TABLE address ALTER COLUMN id RESTART WITH " + (max + 1));
    statement.close();
}
 
Example 25
Project: OpenNMS   File: DbUnit.java   View source code 6 votes vote down vote up
public void cleanDb() {
    try {

        try {
            DatabaseOperation.DELETE_ALL.execute(getConnection(), getDataSet());
        } finally {
            // connection.close();
        }
    } catch (Throwable e) {
        /* do we care?
        System.err.print("An error occurred deleting dataset: ");
        e.printStackTrace();
        */
    }

    ++operation;

}
 
Example 26
Project: drinkwater-java   File: DatabaseInject.java   View source code 5 votes vote down vote up
private static void cleanlyInsert(DataSource datasource, IDataSet dataSet) throws Exception {
    //FIXME this assumes we always use postgres
    PostgresDataSourceTester databaseTester = new PostgresDataSourceTester(datasource);
    databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
    databaseTester.setDataSet(dataSet);
    databaseTester.onSetup();
}
 
Example 27
Project: saladium   File: AbstractWorker.java   View source code 5 votes vote down vote up
@Override
public void insert(String chemin) throws SaladiumException {
    this.toogleContrainte(false);
    LOGGER.info("Insertion des données de " + chemin);
    this.load(chemin, DatabaseOperation.INSERT);
    this.toogleContrainte(true);
}
 
Example 28
Project: saladium   File: AbstractWorker.java   View source code 5 votes vote down vote up
@Override
public void delete(String chemin) throws SaladiumException {
    this.toogleContrainte(false);
    LOGGER.info("Suppression des données de " + chemin);
    this.load(chemin, DatabaseOperation.DELETE);
    this.toogleContrainte(true);
}
 
Example 29
Project: saladium   File: AbstractWorker.java   View source code 5 votes vote down vote up
@Override
public void load(File file, DatabaseOperation operation) throws SaladiumException {
    if (file.exists()) {
        recursive(file, operation);
    } else {
        String chemin = "";
        try {
            chemin = file.getCanonicalPath();
        } catch (IOException e) {
            throw new SaladiumException(String.format(
                "Le chemin \"%s\" n'existe pas! impossible de traiter les données!", chemin));
        }
    }
}
 
Example 30
Project: saladium   File: AbstractWorker.java   View source code 5 votes vote down vote up
@Override
public void restore() throws SaladiumException {
    LOGGER.debug("Restauration " + avecSauvegarde);
    if (avecSauvegarde) {
        try {
            LOGGER.debug("Autocommit false ");
            databaseConnect.getConnection().setAutoCommit(false);
            this.toogleContrainte(false);

            Set<TableBDD> tables = getAllTablesTypeTable();
            cleaner.setTables(tables);
            cleaner.execution();

            LOGGER.info("Insertion des données de la base sauvegardée");
            load(xmlDirectorySave, DatabaseOperation.INSERT);

            this.majSequence();

            this.toogleContrainte(true);

            LOGGER.debug("commit");
            databaseConnect.getConnection().commit();

            LOGGER.debug("Autocommit true ");
            databaseConnect.getConnection().setAutoCommit(true);
        } catch (Exception e1) {
            try {
                databaseConnect.getConnection().rollback();
            } catch (SQLException | NullPointerException e) {
                throw new SaladiumException("Erreur lors du rollback de la base de donnée pendant le stop avec sauvegarde.");
            }
            throw new SaladiumException(e1);
        }
    }
}
 
Example 31
Project: oscm   File: TestDatabase.java   View source code 5 votes vote down vote up
public void insertData(URL dataSetUrl) throws Exception {
    System.out.println("Insert test data.");
    final IDataSet dataSet = loadDataSet(dataSetUrl);
    final DatabaseConnection connection = new DatabaseConnection(
            getDBconnection());
    DatabaseOperation.INSERT.execute(connection, dataSet);
}
 
Example 32
Project: oscm   File: TestDatabase.java   View source code 5 votes vote down vote up
public void insertData(URL dataSetUrl) throws Exception {
    System.out.println("Insert test data.");
    final IDataSet dataSet = loadDataSet(dataSetUrl);
    final DatabaseConnection connection = new DatabaseConnection(
            getDBconnection());
    DatabaseOperation.INSERT.execute(connection, dataSet);
}
 
Example 33
Project: oscm   File: DatabaseTaskHandler.java   View source code 5 votes vote down vote up
public static void cleanDatabase() throws IOException, DataSetException,
        DatabaseUnitException, SQLException {
    String filePath = ROOT_PATH + "javares/devscripts/deleteDbContent.xml";
    String tableList = DatabaseTaskHandler.class.getResource(".").getFile()
            + filePath;
    IDataSet dataToDelete = new FlatXmlDataSetBuilder().build(new File(
            tableList));
    DatabaseOperation.DELETE_ALL.execute(dbConn, dataToDelete);
}
 
Example 34
Project: oscm   File: DatabaseTaskHandler.java   View source code 5 votes vote down vote up
/**
 * Inserts the file of the dbUnit compliant flat xml file into the database
 * used by the system.
 * 
 * @param dbSrcFileName
 *            The name of the file to be imported.
 * @throws IOException
 * @throws DataSetException
 * @throws DatabaseUnitException
 * @throws SQLException
 */
public static void insertData(String dbSourceFileLocation)
        throws IOException, DataSetException, DatabaseUnitException,
        SQLException {
    if (dbSourceFileLocation == null) {
        return;
    }
    ReplacementDataSet dataSet = new ReplacementDataSet(
            new FlatXmlDataSetBuilder()
                    .build(new File(dbSourceFileLocation)));
    dataSet.addReplacementObject("[NULL]", null);
    Date now = new Date();
    dataSet.addReplacementObject("[SYSDATE]", Long.valueOf(now.getTime()));
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
    dataSet.addReplacementObject("[SYSTIMESTAMP]", sdf.format(now));

    DatabaseOperation.INSERT.execute(dbConn, dataSet);
}
 
Example 35
Project: lams   File: FlatXmlDataSetMigrationTask.java   View source code 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 36
Project: OperatieBRP   File: AbstractDBUnitUtil.java   View source code 5 votes vote down vote up
/**
 * Truncate tables specified in the datafile
 * @param connection database connection
 * @param clazz class from which the datafile resource is retrieved
 * @param datafile datafile specifying tables to be truncated
 * @throws DatabaseUnitException on error
 */
public void truncate(final IDatabaseConnection connection, final Class<?> clazz, final String datafile) throws DatabaseUnitException {
    try {
        DatabaseOperation.TRUNCATE_TABLE.execute(connection, new CachedDataSet(new FlatXmlProducer(new InputSource(getResource(clazz, datafile)))));
    } catch (final SQLException e) {
        throw new DatabaseUnitException(e);
    }
}
 
Example 37
Project: drinkwater-java   File: DatabaseInject.java   View source code 5 votes vote down vote up
private static void cleanlyInsert(DataSource datasource, IDataSet dataSet) throws Exception {
    //FIXME this assumes we always use postgres
    PostgresDataSourceTester databaseTester = new PostgresDataSourceTester(datasource);
    databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
    databaseTester.setDataSet(dataSet);
    databaseTester.onSetup();
}
 
Example 38
Project: linkbinder   File: TableDataOperator.java   View source code 5 votes vote down vote up
/**
 * 指定されたExcelファイルのデータをデータベースのテーブルにINSERTする. 同一キーのレコードがある場合は上書きせず、処理が失敗する.
 * @param con
 *            データベース接続オブジェクト
 * @param fileName
 *            データファイル名
 * @throws Exception
 *             例外
 */
public void insert(IDatabaseConnection con, String fileName) throws Exception {

    InputStream in = new FileInputStream(new File(fileName));
    try {
        XlsDataSet ds = new XlsDataSet(in);
        DatabaseOperation.INSERT.execute(con, ds);
    } finally {
        in.close();
    }
}
 
Example 39
Project: linkbinder   File: TableDataOperator.java   View source code 5 votes vote down vote up
/**
 * 指定されたExcelファイルのデータをデータベースのテーブルにINSERTする. 同一キーのレコードがある場合はUPDATEする.
 * @param con
 *            データベース接続オブジェクト
 * @param fileName
 *            データファイル名
 * @throws Exception
 *             例外
 */
public void insertUpdate(IDatabaseConnection con, String fileName) throws Exception {

    InputStream in = new FileInputStream(new File(fileName));
    try {
        XlsDataSet ds = new XlsDataSet(in);
        DatabaseOperation.REFRESH.execute(con, ds);
    } finally {
        in.close();
    }
}
 
Example 40
Project: linkbinder   File: TableDataOperator.java   View source code 5 votes vote down vote up
/**
 * 指定されたExcelファイルのデータをデータベースのテーブルにINSERTする. テーブルに存在するレコードはすべて削除される.
 * @param con
 *            データベース接続オブジェクト
 * @param fileName
 *            データファイル名
 * @throws Exception
 *             例外
 */
public void deleteInsert(IDatabaseConnection con, String fileName) throws Exception {

    InputStream in = new FileInputStream(new File(fileName));
    try {
        XlsDataSet ds = new XlsDataSet(in);
        DatabaseOperation.CLEAN_INSERT.execute(con, ds);
    } finally {
        in.close();
    }
}