org.springframework.jdbc.datasource.SingleConnectionDataSource Java Examples

The following examples show how to use org.springframework.jdbc.datasource.SingleConnectionDataSource. 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: V20190406_1__MigrateBugRelation.java    From mycollab with GNU Affero General Public License v3.0 6 votes vote down vote up
public void migrate(Context context) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
    SimpleJdbcInsert insertOp = new SimpleJdbcInsert(jdbcTemplate).withTableName("m_prj_ticket_relation");

    List<Map<String, Object>> rows = jdbcTemplate.queryForList("SELECT * FROM m_tracker_related_bug");
    rows.forEach(row -> {
        Map<String, Object> parameters = new HashMap<>(6);
        parameters.put("ticketId", row.get("bugid"));
        parameters.put("ticketType", "Project-Bug");
        parameters.put("type", "Project-Bug");
        parameters.put("typeId", row.get("relatedid"));
        parameters.put("rel", row.get("relatetype"));
        parameters.put("comment", row.get("comment"));
        insertOp.execute(parameters);
    });
    jdbcTemplate.execute("DROP TABLE `m_tracker_related_bug`;");
}
 
Example #2
Source File: Sql2oIntegrationTest.java    From SimpleFlatMapper with MIT License 6 votes vote down vote up
@Test
public void testSql2O() throws SQLException, ParseException {
    Connection connection = DbHelper.objectDb();
    try {
        SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
        Sql2o sql2o = new Sql2o(scds);

        Query query = sql2o.open().createQuery(DbHelper.TEST_DB_OBJECT_QUERY);
        query.setAutoDeriveColumnNames(true);
        query.setResultSetHandlerFactoryBuilder(new SfmResultSetHandlerFactoryBuilder());

        List<DbObject> dbObjects = query.executeAndFetch(DbObject.class);

        assertEquals(1, dbObjects.size());
        DbHelper.assertDbObjectMapping(dbObjects.get(0));

    } finally {
        connection.close();
    }
}
 
Example #3
Source File: PostgreSqlRule.java    From booties with Apache License 2.0 6 votes vote down vote up
private void applyScripts(String url) throws SQLException, IOException {
    log.info("Apply Scripts ...");
    Connection connection = getConnection(url);
    DataSource ds = new SingleConnectionDataSource(connection, false);
    FileSystemScanner scanner = new FileSystemScanner();
    for (String location : builder.locations) {
        File directory = new File(location);
        if (directory.exists() && directory.isDirectory()) {
            Resource[] resources = scanner.scanForResources(location, "", ".sql");
            ResourceDatabasePopulator populator = new ResourceDatabasePopulator(resources);
            populator.setSeparator(builder.separator);
            populator.execute(ds);
        } else {
            // log not existing directory
        }
    }
    log.info("Scripts applied!");
}
 
Example #4
Source File: TestDataSourceProvider.java    From multiapps with Apache License 2.0 6 votes vote down vote up
public static DataSource getDataSource(String liquibaseChangelogLocation) throws Exception {
    // create a hsql in memory connection
    Connection connection = createH2InMemory();

    // Create the schema for unit testing
    Database liquibaseDb = DatabaseFactory.getInstance()
                                          .findCorrectDatabaseImplementation(new JdbcConnection(connection));
    Liquibase lq = new Liquibase(liquibaseChangelogLocation, new ClassLoaderResourceAccessor(), liquibaseDb);
    try {
        lq.update("");
    } catch (MigrationFailedException e) {
        // catch the exception because in PopulateConfigurationRegistrySpaceIdColumnChange liquibase change there is rest call
        if (e.getCause()
             .getClass() != UnexpectedLiquibaseException.class) {
            throw e;
        }
    }

    // Initialize the fileService to use our in-memory connection through a pool emulation (so
    // that close releases rather than close)
    return new SingleConnectionDataSource(connection, true);
}
 
Example #5
Source File: SimpleHiloIdentifierGenerator.java    From score with Apache License 2.0 6 votes vote down vote up
private void updateCurrentChunk() {
    if (logger.isDebugEnabled()) {
        logger.debug("Updating HILO chunk...");
    }

    long t = System.currentTimeMillis();
    try (Connection conn = dataSource.getConnection()) {
        conn.setAutoCommit(false);
        JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(conn, true));

        jdbcTemplate.update(SQL_LOCK);
        currentChunk = jdbcTemplate.queryForObject(SQL_SELECT, Integer.class);
        if (logger.isDebugEnabled())
            logger.debug("Current chunk: " + currentChunk);
        jdbcTemplate.execute(SQL_UPDATE);
        jdbcTemplate.execute("commit");

        if (logger.isDebugEnabled()) {
            logger.debug("Updating HILO chunk done in " + (System.currentTimeMillis() - t) + " ms");
        }
        currentId = 0;
    } catch (SQLException e) {
        logger.error("Unable to update current chunk", e);
        throw new IllegalStateException("Unable to update current chunk");
    }
}
 
Example #6
Source File: JdbcNonceVerifierTest.java    From openid4java with Apache License 2.0 6 votes vote down vote up
@Override
public NonceVerifier createVerifier(int maxAge) {
	DataSource dataSource = new SingleConnectionDataSource(
			"org.hsqldb.jdbcDriver",
			"jdbc:hsqldb:mem:saasstore_security_client", "sa", "", true);
	SimpleJdbcTemplate jdbcTemplate = new SimpleJdbcTemplate(dataSource);
	jdbcTemplate.getJdbcOperations().execute(
			"DROP TABLE IF EXISTS openid_nonce;");
	jdbcTemplate
			.getJdbcOperations()
			.execute(
					"CREATE TABLE openid_nonce (  "
							+ "opurl varchar(255) NOT NULL,  nonce varchar(25) NOT NULL,  "
							+ "date datetime DEFAULT NULL,  PRIMARY KEY (opurl,nonce))");

	JdbcNonceVerifier jdbcNonceVerifier = new JdbcNonceVerifier(maxAge,
			"openid_nonce");
	jdbcNonceVerifier.setDataSource(dataSource);
	return jdbcNonceVerifier;
}
 
Example #7
Source File: EntityManagerFactoryServiceImpl.java    From multitenant with Apache License 2.0 6 votes vote down vote up
@Override
public EntityManagerFactory createTempEntityManagerFactory(
		Organization organization) {
	SingleConnectionDataSource dataSource = dataSourceService.createSingleConnectionDataSource(organization);
	if (dataSource != null) {
		Map<String, Object> vendorProperties = getVendorProperties(dataSource);
		customizeVendorProperties(vendorProperties);
	    Builder builder = getEntityManagerFactoryBuilder(dataSource).dataSource(dataSource).packages(mergePackagesToScan())
				.properties(vendorProperties).jta(isJta());
		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = builder.build();
		entityManagerFactoryBean.setBeanClassLoader(classLoader);
		entityManagerFactoryBean.setBeanFactory(beanFactory);
		entityManagerFactoryBean.setBeanName(beanName);
		entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
		entityManagerFactoryBean.setResourceLoader(resourceLoader);
		entityManagerFactoryBean.afterPropertiesSet();
		return entityManagerFactoryBean.getObject();
	}
	return null;
}
 
Example #8
Source File: EntityManagerFactoryServiceImpl.java    From multitenant with Apache License 2.0 6 votes vote down vote up
@Override
public void generateTables(Organization organization) {
	SingleConnectionDataSource dataSource = dataSourceService.createSingleConnectionDataSource(organization);
	if (dataSource != null) {
		Map<String, Object> vendorProperties = getVendorProperties(dataSource);
		customizeVendorProperties(vendorProperties);
		Builder builder = getEntityManagerFactoryBuilder(dataSource).dataSource(dataSource).packages(packagesToScan.split(","))
				.properties(vendorProperties).jta(isJta());
		LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = builder.build();

	    publishEvent(organization, builder);

		entityManagerFactoryBean.setBeanClassLoader(classLoader);
		entityManagerFactoryBean.setBeanFactory(beanFactory);
		entityManagerFactoryBean.setBeanName(beanName);
		entityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
		entityManagerFactoryBean.setResourceLoader(resourceLoader);
		entityManagerFactoryBean.afterPropertiesSet();
		entityManagerFactoryBean.destroy();
		dataSource.destroy();
	}
}
 
Example #9
Source File: DatabaseResourceAllocator.java    From multitenant with Apache License 2.0 6 votes vote down vote up
@Override
public void allocate(Organization organization) {
	SingleConnectionDataSource dataSource = dataSourceService.createSingleConnectionDataSource(organization);
	try {
		scriptService.runScripts(organization.getId(), dataSource, resourceScript, "database");
	} finally {
		if (dataSource != null) {
			try {
				dataSource.destroy();
			} catch (Throwable ex) {
				logger.debug("Could not destroy DataSource", ex);
			}
		}
	}
	entityManagerFactoryService.getOrCreateEntityManagerFactory(organization);
}
 
Example #10
Source File: JdbcTemplateTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example #11
Source File: R__Hibernate_Sequence.java    From spring-cloud-skipper with Apache License 2.0 6 votes vote down vote up
@Override
public void migrate(Context context) throws Exception {
	logger.info("About to check if mssql hibernate_sequence needs fix from table to a sequence");
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
		// in case we have old wrongly created table, this command should succeed
		jdbcTemplate.execute("select 1 from hibernate_sequence");
		fixHibernateSequence = true;
		logger.info("Looks like we have hibernate_sequence table, initiate fix");
	}
	catch (Exception e) {
		logger.debug("Unable to query hibernate_sequence table, looks like we have a proper sequence", e);
	}
	// will result call to get commands from this class and then we choose which ones to run
	super.migrate(context);
}
 
Example #12
Source File: R__Hibernate_Sequence.java    From spring-cloud-dataflow with Apache License 2.0 6 votes vote down vote up
@Override
public void migrate(Context context) throws Exception {
	logger.info("About to check if mssql hibernate_sequence needs fix from table to a sequence");
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
		// in case we have old wrongly created table, this command should succeed
		jdbcTemplate.execute("select 1 from hibernate_sequence");
		fixHibernateSequence = true;
		logger.info("Looks like we have hibernate_sequence table, initiate fix");
	}
	catch (Exception e) {
		logger.debug("Unable to query hibernate_sequence table, looks like we have a proper sequence", e);
	}
	// will result call to get commands from this class and then we choose which ones to run
	super.migrate(context);
}
 
Example #13
Source File: JdbcTemplateTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example #14
Source File: JdbcTemplateTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example #15
Source File: ComRecipientDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
private <T> T selectRecipients(@VelocityCheck int companyID, ResultSetExtractor<T> extractor, String sqlStatement, Object... sqlParameters) throws SQLException {
	// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371
	final boolean useUnsharpRecipientQuery = configService.useUnsharpRecipientQuery(companyID);

	try (Connection connection = getDataSource().getConnection()) {
		try {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, true);
			}

			final SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
			final JdbcTemplate template = new JdbcTemplate(scds);

			return template.query(sqlStatement, extractor, sqlParameters);
		} finally {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, false);
			}
		}
	}
}
 
Example #16
Source File: ComRecipientDaoImpl.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
protected List<Recipient> getRecipientList(int companyID, String statement, Object[] parameters, boolean useUnsharpRecipientQuery) throws SQLException {
	try (Connection connection = getDataSource().getConnection()) {
		try {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, true);
			}
			
			final SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
			final JdbcTemplate template = new JdbcTemplate(scds);
			RecipientRowMapper rowMapper = new RecipientRowMapper(recipientFactory, companyID);
			
			return template.query(statement, parameters, rowMapper);
			
		} finally {
			// TODO: IGNORE_BOUNCELOAD_COMPANY_ID is a bad hack for CONRAD-371!!!
			if (useUnsharpRecipientQuery) {
				setRuleOptimizerMode(connection, false);
			}
		}
	}
}
 
Example #17
Source File: RowMapperTests.java    From effectivejava with Apache License 2.0 6 votes vote down vote up
@Override
@Before
public void setUp() throws SQLException {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	preparedStatement = mock(PreparedStatement.class);
	resultSet = mock(ResultSet.class);
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);
	template = new JdbcTemplate();
	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example #18
Source File: JdbcTemplateTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
	String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";

	given(this.resultSet.next()).willReturn(false);
	given(this.connection.isClosed()).willReturn(false);
	given(this.connection.createStatement()).willReturn(this.preparedStatement);
	// if close is called entire test will fail
	willThrow(new RuntimeException()).given(this.connection).close();

	SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
	this.template = new JdbcTemplate(scf, false);
	RowCountCallbackHandler rcch = new RowCountCallbackHandler();
	this.template.query(sql, rcch);

	verify(this.resultSet).close();
	verify(this.preparedStatement).close();
}
 
Example #19
Source File: AbstractBaselineCallback.java    From spring-cloud-dataflow with Apache License 2.0 5 votes vote down vote up
@Override
public List<SqlCommand> getCommands(Event event, Context context) {
	List<SqlCommand> commands = new ArrayList<>();
	List<SqlCommand> defaultCommands = super.getCommands(event, context);
	if (defaultCommands != null) {
		commands.addAll(defaultCommands);
	}

	boolean migrateToInitial = true;
	try {
		JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
		jdbcTemplate.execute("select 1 from APP_REGISTRATION");
		migrateToInitial = false;
	} catch (Exception e) {
	}

	if (migrateToInitial) {
		logger.info("Did not detect prior Data Flow schema, doing baseline.");
		commands.addAll(initialSetupMigration.getCommands());
	}
	else {
		logger.info("Detected old Data Flow schema, doing baseline.");
		commands.addAll(dropIndexes());
		commands.addAll(changeAppRegistrationTable());
		commands.addAll(changeUriRegistryTable());
		commands.addAll(changeStreamDefinitionsTable());
		commands.addAll(changeTaskDefinitionsTable());
		commands.addAll(changeAuditRecordsTable());
		commands.addAll(createTaskLockTable());
		commands.addAll(createTaskDeploymentTable());
		commands.addAll(createIndexes());
	}

	return commands;
}
 
Example #20
Source File: ManagementNodeManagerImpl.java    From zstack with Apache License 2.0 5 votes vote down vote up
HeartBeatDBSource() {
    try {
        connectionTimeoutExecutor = Executors.newFixedThreadPool(3);
        conn = dbf.getExtraDataSource().getConnection();
        conn.setNetworkTimeout(connectionTimeoutExecutor, (int) TimeUnit.SECONDS.toMillis(PortalGlobalProperty.HEART_BEAT_QUERY_TIMEOUT));
        source = new SingleConnectionDataSource(conn, true);
        jdbc = new JdbcTemplate(source);
    } catch (SQLException e) {
        throw new CloudRuntimeException(e);
    }
}
 
Example #21
Source File: RowMapperTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}
 
Example #22
Source File: Sql2oIntegrationTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Test
public void testDiscriminator608() throws SQLException {
    Connection connection = DbHelper.getDbConnection(DbHelper.TargetDB.POSTGRESQL);
    if ( connection == null) return;
    try {
        SingleConnectionDataSource scds = new SingleConnectionDataSource(connection, true);
        Sql2o sql2o = new Sql2o(scds);

        Query query = sql2o.open().createQuery("with t(id, type, name) as (values(1, 's', 'solar'), (2, 'e', 'electric')) select * from t" +
                "");
        query.setAutoDeriveColumnNames(true);

        JdbcMapperFactory jdbcMapperFactory = JdbcMapperFactory
                .newInstance()
                .discriminator(Device.class,
                        "type",
                        ResultSet::getString,
                        b ->
                                b.when("e", ElectricDevice.class)
                                        .when("s", SolarDevice.class));

        query.setResultSetHandlerFactoryBuilder(new SfmResultSetHandlerFactoryBuilder(jdbcMapperFactory));


        List<Device> devices = query.executeAndFetch(Device.class);


        assertEquals(2, devices.size());

        assertEquals(new SolarDevice(1, "s", "solar"), devices.get(0));
        assertEquals(new ElectricDevice(2, "e", "electric"), devices.get(1));



    } finally {
        connection.close();
    }
}
 
Example #23
Source File: JdbcTemplateCrudTest.java    From SimpleFlatMapper with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	Connection dbConnection;

	try {
		dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.MYSQL);
		dbConnection.createStatement().executeQuery("SELECT 1");
	} catch(Exception e) {
		dbConnection = DbHelper.getDbConnection(DbHelper.TargetDB.HSQLDB);
	}

	template = new JdbcTemplate(new SingleConnectionDataSource(dbConnection, true));
}
 
Example #24
Source File: SqliteDbService.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
    try {
        if (!closed) ((SingleConnectionDataSource) getJdbcTemplate().getDataSource()).destroy();
    } catch (Throwable t) {
        log.warn("could not close data source", t);
    }
    closed = true;
    super.close();
}
 
Example #25
Source File: SqliteDbService.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
@Override
protected JdbcTemplate createJdbcTemplate() {
    SingleConnectionDataSource ds = new SingleConnectionDataSource();
    ds.setUrl(JDBC_URL_BASE + getDbFile());
    ds.setSuppressClose(true);
    return new JdbcTemplate(ds);
}
 
Example #26
Source File: AbstractRowMapperTests.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
public Mock(MockType type)
		throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO ? true : false);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example #27
Source File: V22_1_14_8__MigrateMailchimp.java    From alf.io with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void migrate(Context context) throws Exception {
    var jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));
    Integer enabledCount = jdbcTemplate.queryForObject("select count(*) from plugin_configuration where plugin_id = 'alfio.mailchimp' and conf_name = 'enabled' and conf_value = 'true'", Integer.class);
    if (enabledCount == null || enabledCount == 0) {
        return;
    }

    DataSource dataSource = Objects.requireNonNull(jdbcTemplate.getDataSource());
    ExtensionRepository extensionRepository = QueryFactory.from(ExtensionRepository.class, "PGSQL", dataSource);
    ExtensionLogRepository extensionLogRepository = QueryFactory.from(ExtensionLogRepository.class, "PGSQL", dataSource);
    PluginRepository pluginRepository = QueryFactory.from(PluginRepository.class, "PGSQL", dataSource);
    ExtensionService extensionService = new ExtensionService(new ScriptingExecutionService(HttpClient.newHttpClient(), () -> Executors.newSingleThreadExecutor()), extensionRepository, extensionLogRepository, new DataSourceTransactionManager(dataSource), new ExternalConfiguration());

    extensionService.createOrUpdate(null, null, new Extension("-", "mailchimp", getMailChimpScript(), true));

    int extensionId = extensionRepository.getExtensionIdFor("-", "mailchimp");
    int apiKeyId = pluginRepository.getConfigurationMetadataIdFor(extensionId, "apiKey", "EVENT");
    int listIdId = pluginRepository.getConfigurationMetadataIdFor(extensionId, "listId", "EVENT");


    List<ConfValue> confValues = pluginRepository.findAllMailChimpConfigurationValues();

    for (ConfValue cv : confValues) {
        if(cv.value != null) {
            optionally(() ->jdbcTemplate.queryForObject("select org_id from event where id = "+cv.eventId, Integer.class))
                .ifPresent(orgId -> extensionRepository.insertSettingValue("apiKey".equals(cv.name) ? apiKeyId : listIdId, "-" + orgId + "-" + cv.eventId, cv.value));

        }
    }
}
 
Example #28
Source File: V2__InsertRandomUsers.java    From code-examples with MIT License 5 votes vote down vote up
public void migrate(Context context) {

    final JdbcTemplate jdbcTemplate = new JdbcTemplate(new SingleConnectionDataSource(context.getConnection(), true));

    // Create 10 random users
    for (int i = 1; i <= 10; i++) {
      jdbcTemplate.execute(String.format("insert into test_user(username, first_name, last_name) "
                                             + "values('%[email protected]', 'Elvis_%d', 'Presley_%d')", i, i, i));
    }
  }
 
Example #29
Source File: AbstractRowMapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public Mock(MockType type) throws Exception {
	connection = mock(Connection.class);
	statement = mock(Statement.class);
	resultSet = mock(ResultSet.class);
	resultSetMetaData = mock(ResultSetMetaData.class);

	given(connection.createStatement()).willReturn(statement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(resultSet.getMetaData()).willReturn(resultSetMetaData);

	given(resultSet.next()).willReturn(true, false);
	given(resultSet.getString(1)).willReturn("Bubba");
	given(resultSet.getLong(2)).willReturn(22L);
	given(resultSet.getTimestamp(3)).willReturn(new Timestamp(1221222L));
	given(resultSet.getObject(anyInt(), any(Class.class))).willThrow(new SQLFeatureNotSupportedException());
	given(resultSet.getDate(3)).willReturn(new java.sql.Date(1221222L));
	given(resultSet.getBigDecimal(4)).willReturn(new BigDecimal("1234.56"));
	given(resultSet.wasNull()).willReturn(type == MockType.TWO);

	given(resultSetMetaData.getColumnCount()).willReturn(4);
	given(resultSetMetaData.getColumnLabel(1)).willReturn(
			type == MockType.THREE ? "Last Name" : "name");
	given(resultSetMetaData.getColumnLabel(2)).willReturn("age");
	given(resultSetMetaData.getColumnLabel(3)).willReturn("birth_date");
	given(resultSetMetaData.getColumnLabel(4)).willReturn("balance");

	jdbcTemplate = new JdbcTemplate();
	jdbcTemplate.setDataSource(new SingleConnectionDataSource(connection, false));
	jdbcTemplate.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	jdbcTemplate.afterPropertiesSet();
}
 
Example #30
Source File: RowMapperTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Before
public void setUp() throws SQLException {
	given(connection.createStatement()).willReturn(statement);
	given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
	given(statement.executeQuery(anyString())).willReturn(resultSet);
	given(preparedStatement.executeQuery()).willReturn(resultSet);
	given(resultSet.next()).willReturn(true, true, false);
	given(resultSet.getString(1)).willReturn("tb1", "tb2");
	given(resultSet.getInt(2)).willReturn(1, 2);

	template.setDataSource(new SingleConnectionDataSource(connection, false));
	template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
	template.afterPropertiesSet();
}