I am trying to Configure Oracle DataSource Using Commons DBCP but its throwing subject error
I am working on CentOS
private String driverClassName="oracle.jdbc.driver.OracleDriver" ;
private String url="jdbc:oracle:thin:#164.173.28.18:1521:XE";
private String userName="username";
private String password="password";
private static int MAX_ACTIVE= 10;
private BasicDataSource ds = null;
public void init() throws SQLException{
ds = new BasicDataSource();
ds.setDriverClassName(driverClassName);
ds.setPassword(password);
ds.setUsername(userName);
ds.setUrl(url);
ds.setMaxActive(MAX_ACTIVE);
//check connections
ds.getConnection();
}
public Connection getOracleConnection() throws SQLException{
return ds.getConnection();
}
How can I fix
DB.java:27: error: cannot find symbol
ds.setMaxActive(MAX_ACTIVE); ^
symbol: method setMaxActive(int)
location: variable ds of type BasicDataSource
1 error
obviously, your datasource class doesn't support maxactive.
you need check your library version.
Related
I am getting the following error when I upgrade my Hikari version to 3.4.5
The configuration of the pool is sealed once started. Use HikariConfigMXBean for runtime changes.
I am running the following #BeforeEach test
dataSource.getHikariPoolMXBean().softEvictConnections();
dataSource.setConnectionInitSql("set search_path to " + getTestSchema() + ", public");
This is how I load my DataSource
public class DataSource {
private static HikariConfig config = new HikariConfig();
public static HikariDataSource ds;
static {
config.setJdbcUrl(
System.getProperty("jdbc.url", "jdbc:postgresql://localhost:123/abc"));
config.setUsername(System.getProperty("username", "xyz"));
config.setPassword(System.getProperty("password", "123"));
ds = new HikariDataSource(config);
}
private DataSource() {}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void evictConnection(Connection connection) {
ds.evictConnection(connection);
}
}
class TestClass extends DatabaseTestCase {
#Autowired
private HikariDataSource dataSource;
#BeforeEach
void initData() throws SQLException {
DataSource.ds = dataSource;
dataSource.getHikariPoolMXBean().softEvictConnections();
dataSource.setConnectionInitSql("set search_path to " + getTestVitmSchema() + ", public");
}
This is how I setSchema for the Test Cases
public abstract class DatabaseTestCase {
private String testSchema;
#BeforeEach
final void setupSchema() {
int classHash = Math.abs(getClass().getSimpleName().hashCode());
testSchema = String.format("test_%s", classHash);
Map<String, String> placeholders = new HashMap<>();
placeholders.put("schema", testSchema);
placeholders.put("name", "xyz");
placeholders.put("password", "123");
placeholders.putAll(getPlaceholderReplacement());
Flyway flyway =
Flyway.configure()
.dataSource(DataSource.ds)
.schemas(testSchema)
.placeholders(placeholders)
.load();
flyway.migrate();
}
How can I set Connection Init Sql without getting the error. Thank you.
You can't. You will need to create a new dataSource to do this. You can see why from looking at the source code.
so i got a very strange error message. Im currently working on a java web project with maven and testing the project with Eclipse and Tomcat. So I imported all the neccessary dependencys (mongo java driver, mongodb driver, mongodb driver core, bson and javax.servlet api), or so i thought. But still i'm getting this error over and over again.
If I run the code as part of a main method it works just fine...so im in the dark what could have caused this problem.
this is my MongoDB connector,
public class Connector {
final String HOST = "localhost";
final int PORT = 27017;
final String DBNAME = "mitfahrapp";
public static Connector instance;
public MongoClient connection;
public MongoDatabase database;
public Connector(){
this.connection = new MongoClient(this.HOST, this.PORT);
this.database = connection.getDatabase(DBNAME);
}
public MongoClient getClient() {
return connection;
}
public static Connector createInstance() throws UnknownHostException {
if (Connector.instance == null) {
Connector.instance = new Connector();
}
return Connector.instance;
}
public MongoCollection<Document> getCollection(String name) {
return this.database.getCollection(name);
}
public void CloseMongo() {
connection.close();
}
}
and this is part of my LoginServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Connector c = Connector.createInstance();
MongoCollection<Document> collection = c.getCollection("users");
String username = request.getParameter("username");
String password = request.getParameter("password");
Bson filterUsername = Filters.eq("username", username);
Bson filterPwd = Filters.eq("password", password);
Bson bsonFilter = Filters.and(filterUsername, filterPwd);
FindIterable<Document> doc = collection.find(bsonFilter);
if (doc != null) {
response.sendRedirect("welcome.jsp");
} else {
response.sendRedirect("login.jsp");
}
Thanks for any answers in advance!
This means that the classes are not included in the jar, if you are using maven you should use the maven shade plugin to include those.
I have the below configuration class definition in java springboot. However, it fails for reference to property values.
#org.springframework.context.annotation.Configuration
public class HbaseConfig {
#Value("${keytab.user.name}")
private String username;
#Value("${keytab.path}")
private String keytabpath;
#Bean
public Connection getHbaseConnect() throws IOException {
Configuration conf = HBaseConfiguration.create();
Connection connection = ConnectionFactory.createConnection(conf);
UserGroupInformation.setConfiguration(conf);
System.out.println("hbase connect..is connection closed..." + connection.isClosed());
UserGroupInformation.loginUserFromKeytabAndReturnUGI(username, keytabpath);
return connection;
}
#Bean
public Admin getHbaseAdmin(Connection connection) throws IOException{
Admin admin = connection.getAdmin();
return admin;
}
}
application.properties
keytab.user.name="username"
keytab.path="pathtokeytab"
To put it simple, I need the above keytab username and path read from a property file in my HbaseConfig class.
Can you please try out the below method,
#ConfigurationProperties(prefix = "keytab")
public class KeyTabConfig {
private String username;
private String path;
public String getUsername(){ return this.username; }
public String getPath(){ return this.path;}
}
Habseconfig class as follows
#Configuration
#EnableConfigurationProperties({ KeyTabConfig.class})
public class HbaseConfig {
#Bean
public Connection getHbaseConnect(KeyTabConfig keyTabConfig) throws IOException {
Configuration conf = HBaseConfiguration.create();
Connection connection =
ConnectionFactory.createConnection(conf);
UserGroupInformation.setConfiguration(conf);
System.out.println("hbase connect..is connection closed..." +
connection.isClosed());
UserGroupInformation.loginUserFromKeytabAndReturnUGI(keyTabConfig.getUsername(), keyTabConfig.getPath());
return connection;
}
#Bean
public Admin getHbaseAdmin(Connection connection) throws IOException{
Admin admin = connection.getAdmin();
return admin;
}
}
application.properties file as
keytab.username=uname
keytab.path=path
Make sure your property file name should application.properties and location should in
src/main/resources/application.properties
used only #Configuration at the class level and also use #PropertySource to define the location of our properties file.#PropertySource("classpath:configprops.properties") if your property file name is different.
Otherwise, Spring uses the default location (classpath:application.properties).
The actual processing of #Value annotation is performed by BeanPostProcessor and so we cannot use #Value within BeanPostProcessor types.
Examples: https://www.concretepage.com/spring-5/spring-value#placeholder
Link: How exactly does the Spring BeanPostProcessor work?
HikariCP Github page have the following code:
props.put("dataSource.logWriter", new PrintWriter(System.out));
But I'm getting NullPointerException beacuse LogWriter isn't supported,
DriverDataSource final HikariCP class:
#Override
public PrintWriter getLogWriter() throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
#Override
public void setLogWriter(PrintWriter logWriter) throws SQLException
{
throw new SQLFeatureNotSupportedException();
}
Is this solution for updating HikariCP logging is irrelevant?
I didn't get any answer in group
EDIT
Hikari initialization code uses PoolBase which is initializing datasource with DriverDataSource (which doesn't support logWriter):
else if (jdbcUrl != null && ds == null) {
ds = new DriverDataSource(jdbcUrl, driverClassName, dataSourceProperties, username, password);
I must send jdbcUrl in Oracle and I failed setDataSourceClassName in conjunction with setDriverClassName
In my application.properties i have some spring.datasource fields
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.datasource.url=jdbc:oracle:thin:#localhost:1521:XE
spring.datasource.username=talon
spring.datasource.password=talon
These should be retrieved from a #Configuration annotated class
#Configuration
public class Db {
#NotNull
private String username;
#NotNull
private String password;
#NotNull
private String url;
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setUrl(String url) {
this.url = url;
}
public Db() {
OracleDataSource dataSource = null;
try {
dataSource = new OracleDataSource();
dataSource.setUser(username);
dataSource.setPassword(password);
dataSource.setURL(url);
dataSource.setImplicitCachingEnabled(true);
dataSource.setFastConnectionFailoverEnabled(true);
Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from BOOK");
rs.next();
System.out.println(rs.getString(2));
} catch (SQLException e) {
e.printStackTrace();
}
}
}
But I'm unable to retrieve the username password and url from there, should I add another annotation somewhere or what am I doing
Like this I have the error:
java.sql.SQLException: Invalid Oracle URL specified: OracleDataSource.makeURL
If I set the proper url with dataSource.setURL("jdbc:oracle:thin:#localhost:1521:XE"); it can't read the username and password since they are null and I have java.sql.SQLException: ORA-01017: invalid username/password; logon denied
You have two issues:
You need to use another annotation in order for your fields to be populated. So annotate the class with #ConfigurationProperties("spring.datasource")
You cannot initialize your OracleDataSource directly in your constructor (i.e. Db()) because the properties (your username/password/url fields) are not populated during the call of the constructor, so one thing that you can do is create another method and annotate that with #PostContruct in order for your dataSource to be correctly created.
An example:
#PostConstruct
private void init() {
// your data source initialization
}
One advice would be to change the way to initialize your dataSource and instead of trying to create it inside your constructor, you can rather create a new method which you can annotate with #Bean and make it return your dataSource and you can use it later using #Autowired.