下面列出了javax.validation.constraints.AssertTrue#com.mysql.jdbc.Driver 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Provides
@Singleton
@ForBaseJdbc
public static ConnectionFactory createConnectionFactory(BaseJdbcConfig config, CredentialProvider credentialProvider, MySqlConfig mySqlConfig)
throws SQLException
{
Properties connectionProperties = new Properties();
connectionProperties.setProperty("useInformationSchema", Boolean.toString(mySqlConfig.isDriverUseInformationSchema()));
connectionProperties.setProperty("nullCatalogMeansCurrent", "false");
connectionProperties.setProperty("useUnicode", "true");
connectionProperties.setProperty("characterEncoding", "utf8");
connectionProperties.setProperty("tinyInt1isBit", "false");
if (mySqlConfig.isAutoReconnect()) {
connectionProperties.setProperty("autoReconnect", String.valueOf(mySqlConfig.isAutoReconnect()));
connectionProperties.setProperty("maxReconnects", String.valueOf(mySqlConfig.getMaxReconnects()));
}
if (mySqlConfig.getConnectionTimeout() != null) {
connectionProperties.setProperty("connectTimeout", String.valueOf(mySqlConfig.getConnectionTimeout().toMillis()));
}
return new DriverConnectionFactory(
new Driver(),
config.getConnectionUrl(),
connectionProperties,
credentialProvider);
}
@Test
public void accessors() {
Map<String, Object> customProperties = new HashMap<String, Object>();
customProperties.put(DbKeys.PORT_KEY, 123);
DbConnMySQL dbConnection = new DbConnMySQL("host", "db", "user", "pass", customProperties);
assertEquals(DbConnMySQL.DATABASE_TYPE, dbConnection.getDbType());
assertEquals("host", dbConnection.getHost());
assertEquals("db", dbConnection.getDb());
assertEquals("user", dbConnection.getUser());
assertEquals("pass", dbConnection.getPassword());
assertEquals("jdbc:mysql://host:123/db", dbConnection.getURL());
assertTrue(dbConnection.getConnHash().startsWith("host_123_db"));
assertEquals("MySQL connection to host:123/db", dbConnection.getDescription());
assertEquals(Driver.class, dbConnection.getDriverClass());
}
/**
* Test for Driver.connect() behavior clarifications:
* - connect() throws SQLException if URL is null.
*/
public void testDriverConnectNullArgument() throws Exception {
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
Driver mysqlDriver = new Driver();
mysqlDriver.connect(null, null);
return null;
}
});
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
DriverManager.getConnection(null);
return null;
}
});
}
/**
* Test for Driver.connect() behavior clarifications:
* - connect() throws SQLException if URL is null.
*/
public void testDriverConnectNullArgument() throws Exception {
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
Driver mysqlDriver = new Driver();
mysqlDriver.connect(null, null);
return null;
}
});
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
DriverManager.getConnection(null);
return null;
}
});
}
public List<HashMap<String,Object>> runMysqlQuery(ServicesControl mysql,
MySQLConfiguration configuration,
String query,
boolean runAsRoot) {
Statement statement;
BasicDataSource dataSource = initDatasource(mysql, configuration, Driver.class.getName(), runAsRoot);
try (Connection connection = dataSource.getConnection()) {
statement = connection.createStatement();
LOG.debug("Executing query - " + query);
if (!query.trim().equals("")) {
statement.execute(query);
}
ResultSet result = statement.getResultSet();
return convertResultSetToList(result);
} catch (Exception exception) {
LOG.warn(String.format("error executing query \"%s\": %s",
query, exception.getMessage()));
return null;
}
}
private void druidSettings(DruidDataSource druidDataSource) throws Exception {
druidDataSource.setMaxActive(1000);
druidDataSource.setInitialSize(0);
druidDataSource.setMinIdle(0);
druidDataSource.setMaxWait(60000);
druidDataSource.setPoolPreparedStatements(true);
druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(100);
druidDataSource.setTestOnBorrow(false);
druidDataSource.setTestOnReturn(false);
druidDataSource.setTestWhileIdle(true);
druidDataSource.setTimeBetweenEvictionRunsMillis(6000);
druidDataSource.setMinEvictableIdleTimeMillis(2520000);
druidDataSource.setRemoveAbandoned(true);
druidDataSource.setRemoveAbandonedTimeout(18000);
druidDataSource.setLogAbandoned(true);
druidDataSource.setFilters("mergeStat");
druidDataSource.setDriver(new Driver());
}
/**
* Test for Driver.connect() behavior clarifications:
* - connect() throws SQLException if URL is null.
*/
public void testDriverConnectNullArgument() throws Exception {
assertThrows(SQLException.class,
"Cannot load connection class because of underlying exception: com.mysql.cj.exceptions.WrongArgumentException: The database URL cannot be null.",
new Callable<Void>() {
public Void call() throws Exception {
Driver mysqlDriver = new Driver();
mysqlDriver.connect(null, null);
return null;
}
});
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
DriverManager.getConnection(null);
return null;
}
});
}
@AssertTrue(message = "Invalid JDBC URL for MySQL connector")
public boolean isUrlValid()
{
try {
Driver driver = new Driver();
Properties properties = driver.parseURL(getConnectionUrl(), null);
return properties != null;
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
@AssertTrue(message = "Database (catalog) must not be specified in JDBC URL for MySQL connector")
public boolean isUrlWithoutDatabase()
{
try {
Driver driver = new Driver();
Properties properties = driver.parseURL(getConnectionUrl(), null);
return (properties == null) || (driver.database(properties) == null);
}
catch (SQLException e) {
throw new RuntimeException(e);
}
}
public MetaDataBuilder(MysqlConnection connection,
HashMap<Consumer, ProducerSink> consumerSink) throws SQLException {
this.consumerSink = consumerSink;
Set<String> merged = consumerSink.keySet().stream().map(Consumer::getRepos)
.flatMap(Set::stream).map(Repo::getConnectionName).collect(Collectors.toSet());
calculatedSchemaName = getSchemaName(merged);
jdbcUrl = connection.toConnectionUrl(calculatedSchemaName);
dataSource = new DriverDataSource(jdbcUrl,
Driver.class.getName(), new Properties(),
connection.getUser(), connection.getPassword());
dataSource.setLoginTimeout(TIMEOUT);
}
public static TableMeta tableMeta(MysqlConnection connection, String schema, String table) throws SQLException {
String jdbcUrl = connection.toConnectionUrl(schema);
DataSource dataSource = new DriverDataSource(jdbcUrl, Driver.class.getName(), new Properties(),
connection.getUser(), connection.getPassword());
Consumer single = Consumer.singleTable(schema, table);
HashMap<Consumer, List<SchemaMeta>> res;
try (Connection dataSourceConnection = dataSource.getConnection()) {
DatabaseMetaData metaData = dataSourceConnection.getMetaData();
try (ResultSet tableResultSet = metaData
.getTables(schema, null, table, new String[]{"TABLE"})) {
res = getSchemaMeta(metaData, tableResultSet, Sets.newHashSet(single));
}
}
return res.get(single).get(0).findTable(schema, table);
}
public DataSource dataSource() {
String className = Driver.class.getName();
HikariConfig config = toConfig();
config.setDriverClassName(className);
// A value less than zero will not bypass any connection attempt and validation during startup,
// and therefore the pool will start immediately
config.setInitializationFailTimeout(-1);
return new HikariDataSource(config);
}
private static JdbcTemplate getJdbcTemplate() throws UnknownHostException {
MysqlConnection connection = new MysqlConnection("192.168.1.204", 3306, System.getenv("MYSQL_USER"), System.getenv("MYSQL_PASS"));
HikariConfig config = connection.toConfig();
config.setDriverClassName(Driver.class.getName());
config.setInitializationFailTimeout(-1);
HikariDataSource hikariDataSource = new HikariDataSource(config);
return new JdbcTemplate(hikariDataSource);
}
/**
* Test for Driver.acceptsURL() behavior clarification:
* - acceptsURL() throws SQLException if URL is null.
*/
public void testDriverAcceptsURLNullArgument() {
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
Driver mysqlDriver = new Driver();
mysqlDriver.acceptsURL(null);
return null;
}
});
}
/**
* Constructor for this BugReport, sets up JDBC driver used to create
* connections.
*/
public BaseBugReport() {
try {
this.driver = new Driver();
} catch (SQLException ex) {
throw new RuntimeException(ex.toString());
}
}
public static void codegen() throws Exception {
List<ForcedType> forcedTypes = JooqConfig.defaultForcedTypes();
HikariDataSource ds = CMSConnectionPools.processing();
Configuration configuration = new Configuration()
.withJdbc(new Jdbc()
.withDriver(Driver.class.getName())
.withUrl(ds.getJdbcUrl())
.withUser(ds.getUsername())
.withPassword(ds.getPassword()))
.withGenerator(new Generator()
.withDatabase(new Database()
.withName(MySQLDatabase.class.getName())
.withIncludes(".*")
.withExcludes("")
.withIncludeExcludeColumns(true)
.withForcedTypes(forcedTypes)
.withInputSchema("sj_cms"))
.withGenerate(new Generate()
.withJavaTimeTypes(true))
.withStrategy(new Strategy()
.withName(CustomGeneratorStrategy.class.getName()))
.withTarget(new Target()
.withPackageName("com.stubbornjava.cms.server.generated")
.withDirectory("src/generated/java")));
GenerationTool.generate(configuration);
}
/**
* Test for Driver.acceptsURL() behavior clarification:
* - acceptsURL() throws SQLException if URL is null.
*/
public void testDriverAcceptsURLNullArgument() {
assertThrows(SQLException.class, "The url cannot be null", new Callable<Void>() {
public Void call() throws Exception {
Driver mysqlDriver = new Driver();
mysqlDriver.acceptsURL(null);
return null;
}
});
}
/**
* Constructor for this BugReport, sets up JDBC driver used to create
* connections.
*/
public BaseBugReport() {
try {
this.driver = new Driver();
} catch (SQLException ex) {
throw new RuntimeException(ex.toString());
}
}
public boolean runMysqlScript(ServicesControl mysql,
MySQLConfiguration configuration,
String scriptFilePath,
Map<String, String> scriptParams,
boolean runAsRoot) {
Statement statement;
BasicDataSource dataSource = initDatasource(mysql, configuration, Driver.class.getName(), runAsRoot);
try (Connection connection = dataSource.getConnection()) {
statement = connection.createStatement();
LOG.info("Executing query from " + scriptFilePath);
String s;
StringBuilder sb = new StringBuilder();
File filehandle = new File(scriptFilePath);
FileReader fr = new FileReader(filehandle);
BufferedReader br = new BufferedReader(fr);
while ((s = br.readLine()) != null) {
sb.append(s);
}
br.close();
StrSubstitutor sub = new StrSubstitutor(scriptParams, "{", "}");
String subSb = sub.replace(sb);
String[] inst = subSb.split(";");
for (String query : inst) {
if (!query.trim().equals("")) {
statement.execute(query);
LOG.debug("Query executed - " + query);
}
}
return true;
} catch (Exception exception) {
throw new RuntimeException(String.format("error executing query \"%s\": %s",
scriptFilePath, exception.getMessage()));
}
}
public static void codegen() throws Exception {
List<ForcedType> forcedTypes = JooqConfig.defaultForcedTypes();
HikariDataSource ds = CMSConnectionPools.processing();
Configuration configuration = new Configuration()
.withJdbc(new Jdbc()
.withDriver(Driver.class.getName())
.withUrl(ds.getJdbcUrl())
.withUser(ds.getUsername())
.withPassword(ds.getPassword()))
.withGenerator(new Generator()
.withDatabase(new Database()
.withName(MySQLDatabase.class.getName())
.withIncludes(".*")
.withExcludes("")
.withIncludeExcludeColumns(true)
.withForcedTypes(forcedTypes)
.withInputSchema("sj_cms"))
.withGenerate(new Generate()
.withJavaTimeTypes(true))
.withStrategy(new Strategy()
.withName(CustomGeneratorStrategy.class.getName()))
.withTarget(new Target()
.withPackageName("com.stubbornjava.cms.server.generated")
.withDirectory("src/generated/java")));
GenerationTool.generate(configuration);
}
/**
* Test for Driver.acceptsURL() behavior clarification:
* - acceptsURL() throws SQLException if URL is null.
*/
public void testDriverAcceptsURLNullArgument() {
assertThrows(SQLException.class, "The database URL cannot be null.", new Callable<Void>() {
public Void call() throws Exception {
Driver mysqlDriver = new Driver();
mysqlDriver.acceptsURL(null);
return null;
}
});
}
/**
* Only works in DEBUG level.
* Prints the loaded .jar files at the start of Cygnus run.
*/
public static void printLoadedJars() {
// trace the file containing the httpclient library
URL myClassURL = PoolingClientConnectionManager.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading httpclient from " + myClassURL.toExternalForm());
// trace the file containing the httpcore library
myClassURL = DefaultBHttpServerConnection.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading httpcore from " + myClassURL.toExternalForm());
// trace the file containing the junit library
myClassURL = ErrorCollector.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading junit from " + myClassURL.toExternalForm());
// trace the file containing the flume-ng-node library
myClassURL =
RegexExtractorInterceptorMillisSerializer.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading flume-ng-node from " + myClassURL.toExternalForm());
// trace the file containing the libthrift library
myClassURL = ListMetaData.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading libthrift from " + myClassURL.toExternalForm());
// trace the file containing the gson library
myClassURL = JsonPrimitive.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading gson from " + myClassURL.toExternalForm());
// trace the file containing the json-simple library
myClassURL = Yytoken.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading json-simple from " + myClassURL.toExternalForm());
// trace the file containing the mysql-connector-java library
myClassURL = Driver.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading mysql-connector-java from " + myClassURL.toExternalForm());
// trace the file containing the postgresql library
myClassURL = BlobOutputStream.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading postgresql from " + myClassURL.toExternalForm());
// trace the file containing the log4j library
myClassURL = SequenceNumberPatternConverter.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading log4j from " + myClassURL.toExternalForm());
// trace the file containing the hadoop-core library
myClassURL = AbstractMetricsContext.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading hadoop-core from " + myClassURL.toExternalForm());
// trace the file containing the hive-exec library
myClassURL = AbstractMapJoinOperator.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading hive-exec from " + myClassURL.toExternalForm());
// trace the file containing the hive-jdbc library
myClassURL = HivePreparedStatement.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading hive-jdbc from " + myClassURL.toExternalForm());
// trace the file containing the mongodb-driver library
myClassURL = AsyncReadWriteBinding.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading mongodb-driver from " + myClassURL.toExternalForm());
// trace the file containing the kafka-clients library
myClassURL = OffsetOutOfRangeException.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading kafka-clientsc from " + myClassURL.toExternalForm());
// trace the file containing the zkclient library
myClassURL = ZkNoNodeException.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading zkclient from " + myClassURL.toExternalForm());
// trace the file containing the kafka_2.11 library
myClassURL = KafkaMigrationTool.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading kafka_2.11 from " + myClassURL.toExternalForm());
// trace the file containing the aws-java-sdk-dynamodb library
myClassURL = WriteRequest.class.getProtectionDomain().getCodeSource().getLocation();
LOGGER.debug("Loading aws-java-sdk-dynamodb from " + myClassURL.toExternalForm());
}
/**
* Tests whether bogus parameters break Driver.getPropertyInfo().
*
* @throws Exception
* if an error occurs.
*/
public void testGetPropertyInfo() throws Exception {
new Driver().getPropertyInfo("", null);
}
/**
* Tests whether bogus parameters break Driver.getPropertyInfo().
*
* @throws Exception
* if an error occurs.
*/
public void testGetPropertyInfo() throws Exception {
new Driver().getPropertyInfo("", null);
}