org.springframework.jdbc.datasource.DriverManagerDataSource Java Examples

The following examples show how to use org.springframework.jdbc.datasource.DriverManagerDataSource. 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 Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void shouldThrowIllegalStateExceptionInCaseOfDataIntegrityViolationException() throws SQLException
{
    DataIntegrityViolationException cause =
            new DataIntegrityViolationException("A result was returned when none was expected.");
    Statement stmt = mock(Statement.class);
    when(stmt.executeUpdate(QUERY)).thenThrow(cause);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    when(dataSources.get(DB_KEY)).thenReturn(dataSource);
    IllegalStateException actual = assertThrows(IllegalStateException.class,
        () -> databaseSteps.executeSql(QUERY, DB_KEY));
    assertEquals(cause, actual.getCause());
    assertEquals(actual.getMessage(), "Exception occured during query execution.\n"
            + "If you are trying execute SELECT query consider using step:"
            + "When I execute SQL query '$sqlQuery' and save the result to the $scopes variable '$variableName'");
}
 
Example #2
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testWaitTwiceUntilQueryReturnedDataEqualToTable() throws Exception
{
    mockRowsFilterAsNOOP();

    ResultSet rsFirst = mockResultSet(COL1, VAL1);
    ResultSet rsSecond = mockResultSet(COL1, VAL2);
    Statement stmt = mock(Statement.class);
    when(stmt.executeQuery(QUERY)).thenReturn(rsFirst).thenReturn(rsSecond);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    lenient().when(dataSources.get(DB_KEY)).thenReturn(dataSource);

    when(softAssert.assertTrue(QUERY_RESULTS_ARE_EQUAL, true)).thenReturn(true);
    databaseSteps.waitForDataAppearance(TWO_SECONDS, 10, QUERY, DB_KEY, new ExamplesTable(EXAMPLES_TABLE));
    verify(attachmentPublisher).publishAttachment(eq(QUERIES_STATISTICS_FTL),
            any(Map.class), eq(QUERIES_STATISTICS));
    verify(softAssert).assertTrue(QUERY_RESULTS_ARE_EQUAL, true);
}
 
Example #3
Source Project: luckwheel   Author: s6056826   File: MyDataSource.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public JdbcTemplate mydataSource(){
    // JDBC模板依赖于连接池来获得数据的连接,所以必须先要构造连接池
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.jdbc.Driver");
    dataSource.setUrl(url);
    dataSource.setUsername(name);
    dataSource.setPassword(pass);

    // 创建JDBC模板
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    // 这里也可以使用构造方法
    jdbcTemplate.setDataSource(dataSource);

    return jdbcTemplate;
}
 
Example #4
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlAccountManagementService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ResourceItem createItem(ResourceItem item) {
    Map<String, String> additionalProperties = item.getAdditionalPropertiesMap();
    String username = additionalProperties.get("username");
    String password = additionalProperties.get("password");
    if (username == null || password == null) {
        throw new WecubeCoreException("Username or password is missing");
    }

    DriverManagerDataSource dataSource = newDatasource(item);
    try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();) {
        log.info("password before decrypt={}", password);
        String rawPassword = EncryptionUtils.decryptWithAes(password,
                resourceProperties.getPasswordEncryptionSeed(), item.getName());
        statement.executeUpdate(String.format("CREATE USER `%s` IDENTIFIED BY '%s'", username, rawPassword));
        statement.executeUpdate(String.format("GRANT ALL ON %s.* TO %[email protected]'%%' IDENTIFIED BY '%s'", item.getName(),
                username, rawPassword));
    } catch (Exception e) {
        String errorMessage = String.format("Failed to create account [username = %s]", username);
        log.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
    return item;
}
 
Example #5
Source Project: Hands-On-High-Performance-with-Spring-5   Author: PacktPublishing   File: coreJDBC.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	//Postgres database we are using
       dataSource.setDriverClassName("org.postgresql.Driver");
       dataSource.setUrl("jdbc:postgresql://localhost:5432/TestDB");
       dataSource.setUsername("test");
       dataSource.setPassword("test");        
       
	String query = "SELECT COUNT(*) FROM ACCOUNT";	    
    try (Connection conn = dataSource.getConnection();
    		Statement statement =  conn.createStatement(); 
    		ResultSet rsltSet = statement.executeQuery(query)) 
    {
      if(rsltSet.next()){ 
      int count = rsltSet.getInt(1);
      System.out.println("count : " + count);
      }
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }   
    
}
 
Example #6
Source Project: my-site   Author: WinterChenS   File: TaleUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取新的数据源
 *
 * @return
 */
public static DataSource getNewDataSource() {
    if (newDataSource == null) synchronized (TaleUtils.class) {
        if (newDataSource == null) {
            Properties properties = TaleUtils.getPropFromFile("application-default.properties");
            if (properties.size() == 0) {
                return newDataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            newDataSource = managerDataSource;
        }
    }
    return newDataSource;
}
 
Example #7
Source Project: Jantent   Author: JayTange   File: MyUtils.java    License: MIT License 6 votes vote down vote up
public static DataSource getNewDataSource() {
    lock.lock();
    try {
        if (dataSource == null) {
            Properties properties = MyUtils.getPropFromFile("classpath:application-jdbc.properties");
            if (properties.size() == 0) {
                return dataSource;
            }
            DriverManagerDataSource managerDataSource = new DriverManagerDataSource();
            managerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
            managerDataSource.setPassword(properties.getProperty("spring.datasource.password"));
            String str = "jdbc:mysql://" + properties.getProperty("spring.datasource.url") + "/" + properties.getProperty("spring.datasource.dbname") + "?useUnicode=true&characterEncoding=utf-8&useSSL=false";
            managerDataSource.setUrl(str);
            managerDataSource.setUsername(properties.getProperty("spring.datasource.username"));
            dataSource = managerDataSource;
        }

    } finally {
        lock.unlock();
    }
    return dataSource;
}
 
Example #8
Source Project: vividus   Author: vividus-framework   File: DatabaseSteps.java    License: Apache License 2.0 5 votes vote down vote up
private QueriesStatistic(JdbcTemplate sourceJdbcTemplate, JdbcTemplate targetJdbcTemplate)
{
    String sourceUrl = ((DriverManagerDataSource) sourceJdbcTemplate.getDataSource()).getUrl();
    String targetUrl = ((DriverManagerDataSource) targetJdbcTemplate.getDataSource()).getUrl();
    source = new QueryStatistic(sourceUrl);
    target = new QueryStatistic(targetUrl);
}
 
Example #9
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldExecuteSqlQuery() throws SQLException
{
    Statement stmt = mock(Statement.class);
    when(stmt.executeUpdate(QUERY)).thenReturn(1);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    when(dataSources.get(DB_KEY)).thenReturn(dataSource);
    databaseSteps.executeSql(QUERY, DB_KEY);
    assertThat(LOGGER.getLoggingEvents(), equalTo(List.of(info("Executed query: {}\nAffected rows:{}", QUERY, 1))));
}
 
Example #10
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressFBWarnings("ODR_OPEN_DATABASE_RESOURCE")
@Test
void shouldCompareSqlStatesSQLExceptionIsThrown() throws SQLException
{
    String sqlState = "28000";
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSources.get(DB_KEY)).thenReturn(dataSource);
    SQLException exception = mock(SQLException.class);
    when(exception.getSQLState()).thenReturn(sqlState);
    doThrow(exception).when(dataSource).getConnection(ADMIN, ADMIN);
    databaseSteps.verifySqlState(DB_KEY, ADMIN, ADMIN, StringComparisonRule.IS_EQUAL_TO, sqlState);
    verifyShouldCompareSqlStates(sqlState);
}
 
Example #11
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldCompareSqlStatesSuccessConnection() throws SQLException
{
    String sqlState = "00000";
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSources.get(DB_KEY)).thenReturn(dataSource);
    Connection connection = mock(Connection.class);
    when(dataSource.getConnection(ADMIN, ADMIN)).thenReturn(connection);
    databaseSteps.verifySqlState(DB_KEY, ADMIN, ADMIN, StringComparisonRule.IS_EQUAL_TO, sqlState);
    verifyShouldCompareSqlStates(sqlState);
}
 
Example #12
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldThrowTimeoutExceptionIfQueryTakesTooMuchTime()
{
    databaseSteps.setDbQueryTimeout(Duration.ofNanos(0));
    when(dataSources.get(DB_KEY)).thenReturn(mock(DriverManagerDataSource.class));
    assertThrows(TimeoutException.class,
        () -> databaseSteps.compareData(QUERY, DB_KEY, QUERY, DB_KEY, Set.of(COL1)));
    verifyNoInteractions(attachmentPublisher, softAssert);
}
 
Example #13
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testWaitUntilQueryReturnedDataEqualToTableFailed() throws Exception
{
    mockRowsFilterAsNOOP();

    ResultSet rsFirst = mockResultSet(COL1, VAL1);
    ResultSet rsSecond = mockResultSet(COL1, VAL3);
    Statement stmt = mock(Statement.class);
    when(stmt.executeQuery(QUERY)).thenReturn(rsFirst).thenReturn(rsSecond);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    lenient().when(dataSources.get(DB_KEY)).thenReturn(dataSource);

    databaseSteps.waitForDataAppearance(
            Duration.parse("PT2S"), 2, QUERY, DB_KEY, new ExamplesTable(EXAMPLES_TABLE));
    String logMessage = "SQL result data is not equal to expected data in {} records";
    assertThat(LOGGER.getLoggingEvents(), equalTo(List.of(info(logMessage, 1), info(logMessage, 1))));
    verify(attachmentPublisher).publishAttachment(eq(QUERIES_STATISTICS_FTL),
            any(Map.class), eq(QUERIES_STATISTICS));
    verify(softAssert).assertTrue(QUERY_RESULTS_ARE_EQUAL, false);
    verify(attachmentPublisher).publishAttachment(eq(TEMPLATE_PATH), argThat(r -> {
        @SuppressWarnings("unchecked")
        List<List<EntryComparisonResult>> results = (List<List<EntryComparisonResult>>) ((Map<?, ?>) r)
                .get(RESULTS);
        List<EntryComparisonResult> firstRowResults = results.get(0);
        EntryComparisonResult result = firstRowResults.get(0);
        return 1 == results.size()
            && 1 == firstRowResults.size()
            && VAL2.equals(result.getLeft())
            && VAL3.equals(result.getRight())
            && !result.isPassed();
    }),
           eq(QUERIES_COMPARISON_RESULT));
}
 
Example #14
Source Project: vividus   Author: vividus-framework   File: DatabaseStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
private DriverManagerDataSource mockDataSource(String query, String dbKey, ResultSet rs) throws SQLException
{
    Statement stmt = mock(Statement.class);
    when(stmt.executeQuery(query)).thenReturn(rs);
    Connection con = mock(Connection.class);
    when(con.createStatement()).thenReturn(stmt);
    DriverManagerDataSource dataSource = mock(DriverManagerDataSource.class);
    when(dataSource.getConnection()).thenReturn(con);
    lenient().when(dataSources.get(dbKey)).thenReturn(dataSource);
    return dataSource;
}
 
Example #15
Source Project: spring-analysis-note   Author: Vip-Augus   File: PersistenceXmlParsingTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testExample4() throws Exception {
	SimpleNamingContextBuilder builder = SimpleNamingContextBuilder.emptyActivatedContextBuilder();
	DataSource ds = new DriverManagerDataSource();
	builder.bind("java:comp/env/jdbc/MyDB", ds);

	PersistenceUnitReader reader = new PersistenceUnitReader(
			new PathMatchingResourcePatternResolver(), new JndiDataSourceLookup());
	String resource = "/org/springframework/orm/jpa/persistence-example4.xml";
	PersistenceUnitInfo[] info = reader.readPersistenceUnitInfos(resource);

	assertNotNull(info);
	assertEquals(1, info.length);
	assertEquals("OrderManagement4", info[0].getPersistenceUnitName());

	assertEquals(1, info[0].getMappingFileNames().size());
	assertEquals("order-mappings.xml", info[0].getMappingFileNames().get(0));

	assertEquals(3, info[0].getManagedClassNames().size());
	assertEquals("com.acme.Order", info[0].getManagedClassNames().get(0));
	assertEquals("com.acme.Customer", info[0].getManagedClassNames().get(1));
	assertEquals("com.acme.Item", info[0].getManagedClassNames().get(2));

	assertTrue("Exclude unlisted should be true when no value.", info[0].excludeUnlistedClasses());

	assertSame(PersistenceUnitTransactionType.RESOURCE_LOCAL, info[0].getTransactionType());
	assertEquals(0, info[0].getProperties().keySet().size());

	builder.clear();
}
 
Example #16
Source Project: spring-analysis-note   Author: Vip-Augus   File: RdbmsOperationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void setTypeAfterCompile() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.compile();
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			operation.setTypes(new int[] { Types.INTEGER }));
}
 
Example #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: RdbmsOperationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void declareParameterAfterCompile() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.compile();
	assertThatExceptionOfType(InvalidDataAccessApiUsageException.class).isThrownBy(() ->
			operation.declareParameter(new SqlParameter(Types.INTEGER)));
}
 
Example #18
Source Project: spring-analysis-note   Author: Vip-Augus   File: RdbmsOperationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void compileTwice() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("select * from mytable");
	operation.setTypes(null);
	operation.compile();
	operation.compile();
}
 
Example #19
Source Project: spring-analysis-note   Author: Vip-Augus   File: RdbmsOperationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void parameterPropagation() {
	SqlOperation operation = new SqlOperation() {};
	DataSource ds = new DriverManagerDataSource();
	operation.setDataSource(ds);
	operation.setFetchSize(10);
	operation.setMaxRows(20);
	JdbcTemplate jt = operation.getJdbcTemplate();
	assertEquals(ds, jt.getDataSource());
	assertEquals(10, jt.getFetchSize());
	assertEquals(20, jt.getMaxRows());
}
 
Example #20
Source Project: spring-analysis-note   Author: Vip-Augus   File: RdbmsOperationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void validateInOutParameter() {
	operation.setDataSource(new DriverManagerDataSource());
	operation.setSql("DUMMY_PROC");
	operation.declareParameter(new SqlOutParameter("DUMMY_OUT_PARAM", Types.VARCHAR));
	operation.declareParameter(new SqlInOutParameter("DUMMY_IN_OUT_PARAM", Types.VARCHAR));
	operation.validateParameters(new Object[] {"DUMMY_VALUE1", "DUMMY_VALUE2"});
}
 
Example #21
Source Project: spring-analysis-note   Author: Vip-Augus   File: RdbmsOperationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void parametersSetWithList() {
	DataSource ds = new DriverManagerDataSource();
	operation.setDataSource(ds);
	operation.setSql("select * from mytable where one = ? and two = ?");
	operation.setParameters(new SqlParameter[] {
			new SqlParameter("one", Types.NUMERIC),
			new SqlParameter("two", Types.NUMERIC)});
	operation.afterPropertiesSet();
	operation.validateParameters(new Object[] { 1, "2" });
	assertEquals(2, operation.getDeclaredParameters().size());
}
 
Example #22
Source Project: openemm   Author: agnitas-org   File: DBase.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public DataSource newDataSource (String driver, String connect, String login, String password) {
	Properties	p = new Properties ();
	
	p.put ("user", login);
	p.put ("password", password);
	p.put ("autocommit", "true");
	p.put ("defaultautocommit", "true");
	p.put ("autoreconnect", "true");
	return new DriverManagerDataSource (connect, p);
}
 
Example #23
Source Project: wecube-platform   Author: WeBankPartners   File: PluginInstanceService.java    License: Apache License 2.0 5 votes vote down vote up
private void initMysqlDatabaseTables(ResourceServer dbServer, PluginMysqlInstance mysqlInstance,
        PluginPackage pluginPackage) {

    String tmpFolderName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    String initSqlPath = SystemUtils.getTempFolderPath() + tmpFolderName + "/" + pluginProperties.getInitDbSql();

    String s3KeyName = pluginPackage.getName() + File.separator + pluginPackage.getVersion() + File.separator
            + pluginProperties.getInitDbSql();
    logger.info("Download init.sql from S3: {}", s3KeyName);

    s3Client.downFile(pluginProperties.getPluginPackageBucketName(), s3KeyName, initSqlPath);

    DriverManagerDataSource dataSource = new DriverManagerDataSource(
            "jdbc:mysql://" + dbServer.getHost() + ":" + dbServer.getPort() + "/" + mysqlInstance.getSchemaName()
                    + "?characterEncoding=utf8&serverTimezone=UTC",
            mysqlInstance.getUsername(), EncryptionUtils.decryptWithAes(mysqlInstance.getPassword(),
                    resourceProperties.getPasswordEncryptionSeed(), mysqlInstance.getSchemaName()));
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    File initSqlFile = new File(initSqlPath);
    List<Resource> scipts = newArrayList(new FileSystemResource(initSqlFile));
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.setContinueOnError(false);
    populator.setIgnoreFailedDrops(false);
    populator.setSeparator(";");
    scipts.forEach(populator::addScript);
    try {
        populator.execute(dataSource);
    } catch (Exception e) {
        String errorMessage = String.format("Failed to execute init.sql for schema[%s]",
                mysqlInstance.getSchemaName());
        logger.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
    logger.info(String.format("Init database[%s] tables has done..", mysqlInstance.getSchemaName()));
}
 
Example #24
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlAccountManagementService.java    License: Apache License 2.0 5 votes vote down vote up
public DriverManagerDataSource newMysqlDatasource(String host, String port, String username, String password, String database) {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    if(Strings.isNullOrEmpty(database)) {
        dataSource.setUrl("jdbc:mysql://" + host + ":" + port + "?characterEncoding=utf8&serverTimezone=UTC");
    }else {
        dataSource.setUrl("jdbc:mysql://" + host + ":" + port +"/"+ database +"?characterEncoding=utf8&serverTimezone=UTC");
    }
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example #25
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlAccountManagementService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteItem(ResourceItem item) {
    DriverManagerDataSource dataSource = newDatasource(item);
    try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();) {
        statement.executeUpdate(String.format("DROP USER %s", item.getName()));
    } catch (SQLException e) {
        String errorMessage = String.format("Failed to drop account [username = %s]", item.getName());
        log.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
}
 
Example #26
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlAccountManagementService.java    License: Apache License 2.0 5 votes vote down vote up
private DriverManagerDataSource newDatasource(ResourceItem item) {
    String password;
    try {
        password = EncryptionUtils.decryptWithAes(item.getResourceServer().getLoginPassword(),
                resourceProperties.getPasswordEncryptionSeed(), item.getResourceServer().getName());
    } catch (Exception e) {
        throw new WecubeCoreException(
                String.format("Failed to decrypt the login password of server [%s].", item.getResourceServer()), e);
    }

    DriverManagerDataSource dataSource = newMysqlDatasource(item.getResourceServer().getHost(),
            item.getResourceServer().getPort(), item.getResourceServer().getLoginUsername(), password);
    return dataSource;
}
 
Example #27
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlDatabaseManagementService.java    License: Apache License 2.0 5 votes vote down vote up
public DriverManagerDataSource newMysqlDatasource(String host, String port, String username, String password) {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://" + host + ":" + port + "?characterEncoding=utf8&serverTimezone=UTC");
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example #28
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlDatabaseManagementService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ResourceItem createItem(ResourceItem item) {
    DriverManagerDataSource dataSource = newDatasource(item);
    try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();) {
        statement.executeUpdate(String.format("CREATE SCHEMA %s", item.getName()));
        mysqlAccountManagementService.createItem(item);
    } catch (SQLException e) {
        String errorMessage = String.format("Failed to create schema [%s], meet error [%s].", item.getName(), e.getMessage());
        log.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
    return item;
}
 
Example #29
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlDatabaseManagementService.java    License: Apache License 2.0 5 votes vote down vote up
private DriverManagerDataSource newDatasource(ResourceItem item) {
    String password = EncryptionUtils.decryptWithAes(item.getResourceServer().getLoginPassword(), resourceProperties.getPasswordEncryptionSeed(), item.getResourceServer().getName());
    DriverManagerDataSource dataSource = newMysqlDatasource(
            item.getResourceServer().getHost(),
            item.getResourceServer().getPort(),
            item.getResourceServer().getLoginUsername(),
            password);
    log.info(String.format("Created new data source [host:%s,port:%s,username:%s]",item.getResourceServer().getHost(),item.getResourceServer().getPort(),
            item.getResourceServer().getLoginUsername()));
    return dataSource;
}
 
Example #30
Source Project: wecube-platform   Author: WeBankPartners   File: MysqlDatabaseManagementService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteItem(ResourceItem item) {
    DriverManagerDataSource dataSource = newDatasource(item);
    try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement();) {
        if (hasTables(connection, item.getName())) {
            throw new WecubeCoreException(String.format("Can not delete database [%s] : Database is not empty.", item.getName()));
        }
        mysqlAccountManagementService.deleteItem(item);
        statement.executeUpdate(String.format("DROP SCHEMA %s", item.getName()));
    } catch (SQLException e) {
        String errorMessage = String.format("Failed to delete schema [%s], meet error [%s].", item.getName(), e.getMessage());
        log.error(errorMessage);
        throw new WecubeCoreException(errorMessage, e);
    }
}