Connecting to multiple MySQL db instances using jooq in spring boot application - spring-boot

I have a spring boot application which is using gradle as build tool and jooq for dao class generation and db connection. Previously my application was connecting to single mysql instance. Below are the configuration we used for connecting to single db instance:
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.name=ds_name
spring.datasource.schema=ds_schema
spring.jooq.sql-dialect=MYSQL
Current project structure is
a) Main application project MainApp having application.properties with above key-value pairs.
b) Separate application project as DBProject which has jooq's generated DAO classes. MainApp include DBProject as a jar.
I am using gradle as build tool for this.
Everything is working fine till here. But now I have to connect to one more instance of MySQL. So, I have created another db project as DBProject2 which also contains dao classes generated by jooq using another mysql schema. I have created DBProject2 exactly as DBProject is created.
Now, my question is if I include both DBProjects in MainApp as jar then both will use same db configuration as in application.properties. How I can make separate db jars to point to their respective db schemas. I googled alot about this but couldn't find helpful solution.

This is what I do to connect to multiple (additional) data sources in my Play app. I am not sure if it is the best approach, but it works great for me. I have changed names below to be generic.
// In my application.conf
// default data source
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost:3306/myDb?useSSL=false"
db.default.username=myuser
db.default.password="mypassword"
// additional data source
db.anothersource.driver=com.mysql.jdbc.Driver
db.anothersource.url="jdbc:mysql://localhost:3306/myothersource?useSSL=false"
db.anothersource.username=myuser
db.anothersource.password="mypassword"
// Then in Java, I create a JooqContextProvider class to expose both connections.
public class JooqContextProvider {
#Inject
Database db;
#Inject
play.Configuration config;
public JooqContextProvider(){}
/**
* Creates a default database connection for data access.
* #return DSLConext.
*/
public DSLContext dsl() {
return DSL.using(new JooqConnectionProvider(db), SQLDialect.MYSQL);
}
/**
* Creates an anothersource database connection for data access.
* #return DSLConext for anothersource.
*/
public DSLContext anotherDsl() {
return DSL.using(
new JooqAnotherSourceConnectionProvider(
config.getString("db.anothersource.url"),
config.getString("db.anothersource.username"),
config.getString("db.anothersource.password")),
SQLDialect.MYSQL);
}
}
// Then I needed to implement my JooqAnotherSourceConnectionProvider
public class JooqAnotherSourceConnectionProvider implements ConnectionProvider {
private Connection connection = null;
String url;
String username;
String password;
public JooqAnotherSourceConnectionProvider(String url, String username, String password){
this.url = url;
this.username = username;
this.password = password;
}
#Override
public Connection acquire() throws DataAccessException {
try {
connection = DriverManager.getConnection(url, username, password);
return connection;
}
catch (java.sql.SQLException ex) {
throw new DataAccessException("Error getting connection from data source", ex);
}
}
#Override
public void release(Connection releasedConnection) throws DataAccessException {
if (connection != releasedConnection) {
throw new IllegalArgumentException("Expected " + connection + " but got " + releasedConnection);
}
try {
connection.close();
connection = null;
}
catch (SQLException e) {
throw new DataAccessException("Error closing connection " + connection, e);
}
}
}
// Then in Java code where I need to access one or the other data sources...
jooq.dsl().select().from().where()...
jooq.anotherDsl().select().from().where()...

Related

java.lang.ClassNotFoundException: jdbc:mysql Exception [duplicate]

How do you connect to a MySQL database in Java?
When I try, I get
java.sql.SQLException: No suitable driver found for jdbc:mysql://database/table
at java.sql.DriverManager.getConnection(DriverManager.java:689)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
Or
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
Or
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver
Here's a step by step explanation how to install MySQL and JDBC and how to use it:
Download and install the MySQL server. Just do it the usual way. Remember the port number whenever you've changed it. It's by default 3306.
Download the JDBC driver and put in classpath, extract the ZIP file and put the containing JAR file in the classpath. The vendor-specific JDBC driver is a concrete implementation of the JDBC API (tutorial here).
If you're using an IDE like Eclipse or Netbeans, then you can add it to the classpath by adding the JAR file as Library to the Build Path in project's properties.
If you're doing it "plain vanilla" in the command console, then you need to specify the path to the JAR file in the -cp or -classpath argument when executing your Java application.
java -cp .;/path/to/mysql-connector.jar com.example.YourClass
The . is just there to add the current directory to the classpath as well so that it can locate com.example.YourClass and the ; is the classpath separator as it is in Windows. In Unix and clones : should be used.
Create a database in MySQL. Let's create a database javabase. You of course want World Domination, so let's use UTF-8 as well.
CREATE DATABASE javabase DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;
Create a user for Java and grant it access. Simply because using root is a bad practice.
CREATE USER 'java'#'localhost' IDENTIFIED BY 'password';
GRANT ALL ON javabase.* TO 'java'#'localhost' IDENTIFIED BY 'password';
Yes, java is the username and password is the password here.
Determine the JDBC URL. To connect the MySQL database using Java you need an JDBC URL in the following syntax:
jdbc:mysql://hostname:port/databasename
hostname: The hostname where MySQL server is installed. If it's installed at the same machine where you run the Java code, then you can just use localhost. It can also be an IP address like 127.0.0.1. If you encounter connectivity problems and using 127.0.0.1 instead of localhost solved it, then you've a problem in your network/DNS/hosts config.
port: The TCP/IP port where MySQL server listens on. This is by default 3306.
databasename: The name of the database you'd like to connect to. That's javabase.
So the final URL should look like:
jdbc:mysql://localhost:3306/javabase
Test the connection to MySQL using Java. Create a simple Java class with a main() method to test the connection.
String url = "jdbc:mysql://localhost:3306/javabase";
String username = "java";
String password = "password";
System.out.println("Connecting database...");
try (Connection connection = DriverManager.getConnection(url, username, password)) {
System.out.println("Database connected!");
} catch (SQLException e) {
throw new IllegalStateException("Cannot connect the database!", e);
}
If you get a SQLException: No suitable driver, then it means that either the JDBC driver wasn't autoloaded at all or that the JDBC URL is wrong (i.e. it wasn't recognized by any of the loaded drivers). Normally, a JDBC 4.0 driver should be autoloaded when you just drop it in runtime classpath. To exclude one and other, you can always manually load it as below:
System.out.println("Loading driver...");
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver loaded!");
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot find the driver in the classpath!", e);
}
Note that the newInstance() call is not needed here. It's just to fix the old and buggy org.gjt.mm.mysql.Driver. Explanation here. If this line throws ClassNotFoundException, then the JAR file containing the JDBC driver class is simply not been placed in the classpath.
Note that you don't need to load the driver everytime before connecting. Just only once during application startup is enough.
If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:
IP address or hostname in JDBC URL is wrong.
Hostname in JDBC URL is not recognized by local DNS server.
Port number is missing or wrong in JDBC URL.
DB server is down.
DB server doesn't accept TCP/IP connections.
DB server has run out of connections.
Something in between Java and DB is blocking connections, e.g. a firewall or proxy.
To solve the one or the other, follow the following advices:
Verify and test them with ping.
Refresh DNS or use IP address in JDBC URL instead.
Verify it based on my.cnf of MySQL DB.
Start the DB.
Verify if mysqld is started without the --skip-networking option.
Restart the DB and fix your code accordingly that it closes connections in finally.
Disable firewall and/or configure firewall/proxy to allow/forward the port.
Note that closing the Connection is extremely important. If you don't close connections and keep getting a lot of them in a short time, then the database may run out of connections and your application may break. Always acquire the Connection in a try-with-resources statement. Or if you're not on Java 7 yet, explicitly close it in finally of a try-finally block. Closing in finally is just to ensure that it get closed as well in case of an exception. This also applies to Statement, PreparedStatement and ResultSet.
That was it as far the connectivity concerns. You can find here a more advanced tutorial how to load and store fullworthy Java model objects in a database with help of a basic DAO class.
Using a Singleton Pattern for the DB connection is a bad approach. See among other questions: Is it safe to use a static java.sql.Connection instance in a multithreaded system?. This is a #1 starters mistake.
DriverManager is a fairly old way of doing things. The better way is to get a DataSource, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
Initialize database constants
Create constant properties database username, password, URL and drivers, polling limit etc.
// init database constants
// com.mysql.jdbc.Driver
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250"; // set your own limit
Initialize Connection and Properties
Once the connection is established, it is better to store for reuse purpose.
// init connection object
private Connection connection;
// init properties object
private Properties properties;
Create Properties
The properties object hold the connection information, check if it is already set.
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
Connect the Database
Now connect to database using the constants and properties initialized.
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
// Java 7+
e.printStackTrace();
}
}
return connection;
}
Disconnect the database
Once you are done with database operations, just close the connection.
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Everything together
Use this class MysqlConnect directly after changing database_name, username and password etc.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MysqlConnect {
// init database constants
private static final String DATABASE_DRIVER = "com.mysql.cj.jdbc.Driver";
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database_name";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
private static final String MAX_POOL = "250";
// init connection object
private Connection connection;
// init properties object
private Properties properties;
// create properties
private Properties getProperties() {
if (properties == null) {
properties = new Properties();
properties.setProperty("user", USERNAME);
properties.setProperty("password", PASSWORD);
properties.setProperty("MaxPooledStatements", MAX_POOL);
}
return properties;
}
// connect database
public Connection connect() {
if (connection == null) {
try {
Class.forName(DATABASE_DRIVER);
connection = DriverManager.getConnection(DATABASE_URL, getProperties());
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
return connection;
}
// disconnect database
public void disconnect() {
if (connection != null) {
try {
connection.close();
connection = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
How to Use?
Initialize the database class.
// !_ note _! this is just init
// it will not create a connection
MysqlConnect mysqlConnect = new MysqlConnect();
Somewhere else in your code ...
String sql = "SELECT * FROM `stackoverflow`";
try {
PreparedStatement statement = mysqlConnect.connect().prepareStatement(sql);
... go on ...
... go on ...
... DONE ....
} catch (SQLException e) {
e.printStackTrace();
} finally {
mysqlConnect.disconnect();
}
This is all :) If anything to improve edit it! Hope this is helpful.
String url = "jdbc:mysql://127.0.0.1:3306/yourdatabase";
String user = "username";
String password = "password";
// Load the Connector/J driver
Class.forName("com.mysql.jdbc.Driver").newInstance();
// Establish connection to MySQL
Connection conn = DriverManager.getConnection(url, user, password);
Here's the very minimum you need to get data out of a MySQL database:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection
("jdbc:mysql://localhost:3306/foo", "root", "password");
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM `FOO.BAR`");
stmt.close();
conn.close();
Add exception handling, configuration etc. to taste.
you need to have mysql connector jar in your classpath.
in Java JDBC API makes everything with databases. using JDBC we can write Java applications to
1. Send queries or update SQL to DB(any relational Database)
2. Retrieve and process the results from DB
with below three steps we can able to retrieve data from any Database
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table");
while (rs.next()) {
int x = rs.getInt("a");
String s = rs.getString("b");
float f = rs.getFloat("c");
}
You can see all steps to connect MySQL database from Java application here. For other database, you just need to change the driver in first step only. Please make sure that you provide right path to database and correct username and password.
Visit http://apekshit.com/t/51/Steps-to-connect-Database-using-JAVA
MySQL JDBC Connection with useSSL.
private String db_server = BaseMethods.getSystemData("db_server");
private String db_user = BaseMethods.getSystemData("db_user");
private String db_password = BaseMethods.getSystemData("db_password");
private String connectToDb() throws Exception {
String jdbcDriver = "com.mysql.jdbc.Driver";
String dbUrl = "jdbc:mysql://" + db_server +
"?verifyServerCertificate=false" +
"&useSSL=true" +
"&requireSSL=true";
System.setProperty(jdbcDriver, "");
Class.forName(jdbcDriver).newInstance();
Connection conn = DriverManager.getConnection(dbUrl, db_user, db_password);
Statement statement = conn.createStatement();
String query = "SELECT EXTERNAL_ID FROM offer_letter where ID =" + "\"" + letterID + "\"";
ResultSet resultSet = statement.executeQuery(query);
resultSet.next();
return resultSet.getString(1);
}
Short and Sweet code.
try {
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/testDB","root","");
//Database Name - testDB, Username - "root", Password - ""
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
For SQL server 2012
try {
String url = "jdbc:sqlserver://KHILAN:1433;databaseName=testDB;user=Khilan;password=Tuxedo123";
//KHILAN is Host and 1433 is port number
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded");
conn = DriverManager.getConnection(url);
System.out.println("Connected...");
} catch(Exception e) {
e.printStackTrace();
}
Connection I was using some time ago, it was looking like the easiest way, but also there were recommendation to make there if statement- exactly
Connection con = DriverManager.getConnection(
"jdbc:myDriver:DatabaseName",
dBuserName,
dBuserPassword);
if (con != null){
//..handle your code there
}
Or something like in that way :)
Probably there's some case, while getConnection can return null :)
HOW
To set up the Driver to run a quick sample
1. Go to https://dev.mysql.com/downloads/connector/j/, get the latest version of Connector/J
2. Remember to set the classpath to include the path of the connector jar file.
If we don't set it correctly, below errors can occur:
No suitable driver found for jdbc:mysql://127.0.0.1:3306/msystem_development
java.lang.ClassNotFoundException: com.mysql.jdbc:Driver
To set up the CLASSPATH
Method 1: set the CLASSPATH variable.
export CLASSPATH=".:mysql-connector-java-VERSION.jar"
java MyClassFile
In the above command, I have set the CLASSPATH to the current folder and mysql-connector-java-VERSION.jar file. So when the java MyClassFile command executed, java application launcher will try to load all the Java class in CLASSPATH.
And it found the Drive class => BOOM errors was gone.
Method 2:
java -cp .:mysql-connector-java-VERSION.jar MyClassFile
Note: Class.forName("com.mysql.jdbc.Driver"); This is deprecated at this moment 2019 Apr.
Hope this can help someone!
MySql JDBC Connection:
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName","Username","Password");
Statement stmt=con.createStatement();
stmt = con.createStatement();
ResultSet rs=stmt.executeQuery("Select * from Table");
Short Code
public class DB {
public static Connection c;
public static Connection getConnection() throws Exception {
if (c == null) {
Class.forName("com.mysql.jdbc.Driver");
c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
}
return c;
}
// Send data TO Database
public static void setData(String sql) throws Exception {
DB.getConnection().createStatement().executeUpdate(sql);
}
// Get Data From Database
public static ResultSet getData(String sql) throws Exception {
ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
return rs;
}
}
Download JDBC Driver
Download link (Select platform independent): https://dev.mysql.com/downloads/connector/j/
Move JDBC Driver to C Drive
Unzip the files and move to C:\ drive. Your driver path should be like C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19
Run Your Java
java -cp "C:\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19\mysql-connector-java-8.0.19.jar" testMySQL.java
testMySQL.java
import java.sql.*;
import java.io.*;
public class testMySQL {
public static void main(String[] args) {
// TODO Auto-generated method stub
try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/db?useSSL=false&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC","root","");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("show databases;");
System.out.println("Connected");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

IBM Domino database configuration with Spring boot

I am trying to configure IBM domino database with spring boot to fetch the document from IBM domino server.I have added domino NCSO jar in local maven repo and I have wrote the sample Java program for domino connection. Now I want to convert it into spring boot code to connect with domino db and use the database connection in other services to get the data from views. Appreciated for any hits/instruction for the same.
JAVA Sample :
import lotus.domino.Database;
import lotus.domino.NotesFactory;
import lotus.domino.Session;
public class JavaAgent {
public static void main(String[] args) {
try {
String host = "test.xxx.xxx.com:63148";
Session s = NotesFactory.createSession(host);
String p = s.getCommonUserName();
System.out.println(p);
Database db = s.getDatabase("test.xxx.xxx.com", "s.nsf");
System.out.println(db.getFilePath());
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am able to connect in spring boot by adding below code in spring boot configuration class:
#Bean
public DbDirectory dominoConnection() throws NotesException {
Session session = NotesFactory.createSession(host, username, password);
String p = session.getCommonUserName();
DbDirectory dir = session.getDbDirectory(null);
String server = dir.getName();
return dir;
}
#Bean
public Session dominoDBSession() throws NotesException {
Session session = NotesFactory.createSession(host, username, password);
return session;
}

Facing Too many connection issue on HIkariCP

I have a Java JDBC application, after 100 queries of Select Jetty server crashed and return below error:
ERROR com.zaxxer.hikari.pool.HikariPool - dev-server - Exception during pool initialization.
java.sql.SQLNonTransientConnectionException: Too many connections
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:526)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1606)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:633)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:347)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:219)
at com.zaxxer.hikari.util.DriverDataSource.getConnection(DriverDataSource.java:95)
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:358)
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:201)
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:443)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:514)
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:111)
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:72)
at com.jrg.platform.commons.hikari.HikariDataSourceSupport.getDataSource(HikariDataSourceSupport.java:70)
at com.jrg.platform.commons.hikari.HikariDataSourceSupport.getConnection(HikariDataSourceSupport.java:82)
at com.jrg.platform.services.internal.pcms.data.campaign.CampaignAlertDaoImpl.getCampaignAlerts(CampaignAlertDaoImpl.java:40)
at com.jrg.platform.services.internal.pcms.service.CampaignAlertServiceImpl.campaignAlerts(CampaignAlertServiceImpl.java:43)
at com.jrg.platform.services.internal.pcms.resource.CampaignAlertResource.getCampaignAlerts(CampaignAlertResource.java:52)
at com.jrg.platform.services.internal.pcms.resource.CampaignAlertResource_$$_jvstf5a_6._d5getCampaignAlerts(CampaignAlertResource_$$_jvstf5a_6.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Unable to find the solution. I am just getting the connection from HikariDataSourceSupport and performing the query.
the sample code of getting connection is given below:
default HikariDataSource getDataSource(E e, boolean readOnly) throws IOException {
String key = this.getKey(e, readOnly);
Map<String, HikariDataSource> sources = this.getDataSources();
if(!sources.containsKey(key)) {
synchronized(this.getMonitor()) {
if(!sources.containsKey(key)) {
if(logger.isDebugEnabled()) {
logger.debug("creating new DataSource for {}", key);
}
Config config = this.getConfig(e, readOnly);
if(!config.hasPathOrNull("jdbcUrl")) {
throw new EnvironmentNotConfigured(e, readOnly);
}
sources.put(key, new HikariDataSource(new HikariConfig(ConfigUtils.asProperties(config))));
}
}
}
return (HikariDataSource)sources.get(key);
}
default Connection getConnection(E env, boolean readOnly) throws SQLException, IOException {
return this.getDataSource(env, readOnly).getConnection();
}
There was problem in configuration HikariCP. When request generated and try to get connection, the create connection method was creating the new datasource because the last state was destroy due to view scope of the bean.
now i have converted that class into to singalton and created the implementation of that interface to inject in the code. it is saving the state of previous data source connection. Now it is working perfect with minimum idle connections.
the code can be seen here:
APP.java
bind(HikariLucktasticDataSourceSupportImpl.class)
.to(HikariDataSourceSupport.class)
.named("hdsSupport")
.in(Singleton.class);
in DAO Layer:
#Inject
#Named("hdsSupport")
private HikariDataSourceSupport hdsSupport;

Weblogic,EJB, $Proxy99 class cast exception

Following are the modules in my project,
1. EJB module (version 3): We prepare ejb jar of this module and deploy on Weblogic11g server. It deals with database operation. It has #local, #Remote interface and #stateless classes implementing #local,#Remote interfaces.
2. Web Application : This web application takes inputs (user uploads file) from users, validates file and inserts data into database. It uses RMI.
Problem: On production (weblogic 11g server ) sometimes we observe exception saying $Proxy99 cannot be cast to "Remote interface name" (for different different classes) e.g com.xyz.fileProcessSetting.FileProcessSttgFacadeRemote.
But after some time when we again upload file, it gets uploaded successfully without any error.
Now, I do not understand how come these remote objects becomes temporarily unavailable? Never faced this issue on development/UAT environment. Also no idea how to reproduce and fix it.
Please help. Thanks in advance.
#Remote
public interface FileProcessSttgFacadeRemote {
//methods
}
#Local
public interface FileProcessSttgFacadeLocal {
//methods
}
#Stateless
public class FileProcessSttgFacade implements FileProcessSttgFacadeLocal, FileProcessSttgFacadeRemote {
//methods
}
in weblogic-ejb-jar.xml
<weblogic-enterprise-bean>
<ejb-name>FileProcessSttgFacade</ejb-name>
<stateless-session-descriptor>
<business-interface-jndi-name-map>
<business-remote>com.xyz.fileProcessSetting.FileProcessSttgFacadeRemote</business-remote>
<jndi-name>FileProcessSttgFacade</jndi-name>
</business-interface-jndi-name-map>
</stateless-session-descriptor>
</weblogic-enterprise-bean>
In web application also in ejb module whenever we want to call methods we use following lookup method to get remote object:
public class someclass extends EjbLocator {
public void someMethod(){
FileProcessSttgFacadeRemote fpfr = (FileProcessSttgFacadeRemote) getService("FileProcessSttgFacade");
//other code
}
}
Following is the class used for JNDI lookup:
public class EjbLocator {
public Object getService(final String jndiName) throws Exception {
try {
obj = getDefaultContext().lookup(jndiName);
} catch (final Exception exp) {
exp.printStackTrace();
}
return obj;
}
protected Context getDefaultContext() {
try {
final Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.SECURITY_PRINCIPAL,"weblogic");
env.put(Context.SECURITY_CREDENTIALS, "password");
env.put(Context.PROVIDER_URL, "t3://<ip>:<port>");
defaultContext = new InitialContext(env);
return defaultContext;
} catch (final NamingException nExp) {
nExp.printStackTrace();
}
return null;
}
}

Spring Boot and how to configure connection details to MongoDB?

Being new to Spring Boot I am wondering on how I can configure connection details for MongoDB.
I have tried the normal examples but none covers the connection details.
I want to specify the database that is going to be used and the url/port of the host that runs MongoDB.
Any hints or tips?
Just to quote Boot Docs:
You can set spring.data.mongodb.uri property to change the url, or alternatively specify a host/port. For example, you might declare the following in your application.properties:
spring.data.mongodb.host=mongoserver
spring.data.mongodb.port=27017
All available options for spring.data.mongodb prefix are fields of MongoProperties:
private String host;
private int port = DBPort.PORT;
private String uri = "mongodb://localhost/test";
private String database;
private String gridFsDatabase;
private String username;
private char[] password;
It's also important to note that MongoDB has the concept of "authentication database", which can be different than the database you are connecting to. For example, if you use the official Docker image for Mongo and specify the environment variables MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD, a user will be created on 'admin' database, which is probably not the database you want to use. In this case, you should specify parameters accordingly on your application.properties file using:
spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.authentication-database=admin
spring.data.mongodb.username=<username specified on MONGO_INITDB_ROOT_USERNAME>
spring.data.mongodb.password=<password specified on MONGO_INITDB_ROOT_PASSWORD>
spring.data.mongodb.database=<the db you want to use>
spring.data.mongodb.host and spring.data.mongodb.port are not supported if you’re using the Mongo 3.0 Java driver. In such cases, spring.data.mongodb.uri should be used to provide all of the configuration, like this:
spring.data.mongodb.uri=mongodb://user:secret#mongo1.example.com:12345
In a maven project create a file src/main/resources/application.yml with the following content:
spring.profiles: integration
# use local or embedded mongodb at localhost:27017
---
spring.profiles: production
spring.data.mongodb.uri: mongodb://<user>:<passwd>#<host>:<port>/<dbname>
Spring Boot will automatically use this file to configure your application. Then you can start your spring boot application either with the integration profile (and use your local MongoDB)
java -jar -Dspring.profiles.active=integration your-app.jar
or with the production profile (and use your production MongoDB)
java -jar -Dspring.profiles.active=production your-app.jar
You can define more details by extending AbstractMongoConfiguration.
#Configuration
#EnableMongoRepositories("demo.mongo.model")
public class SpringMongoConfig extends AbstractMongoConfiguration {
#Value("${spring.profiles.active}")
private String profileActive;
#Value("${spring.application.name}")
private String proAppName;
#Value("${spring.data.mongodb.host}")
private String mongoHost;
#Value("${spring.data.mongodb.port}")
private String mongoPort;
#Value("${spring.data.mongodb.database}")
private String mongoDB;
#Override
public MongoMappingContext mongoMappingContext()
throws ClassNotFoundException {
// TODO Auto-generated method stub
return super.mongoMappingContext();
}
#Override
#Bean
public Mongo mongo() throws Exception {
return new MongoClient(mongoHost + ":" + mongoPort);
}
#Override
protected String getDatabaseName() {
// TODO Auto-generated method stub
return mongoDB;
}
}
In case that somebody is trying to connect to a Atlas MongoDB Cluster in application.properties has to have a config like:
spring.data.mongodb.uri=mongodb+srv://databaseUsername:usernamePassword#cluster0.j4koa.mongodb.net/databaseUsername?retryWrites=true&w=majority
In my case I needed to set up MongoDB for integration tests using Testcontainers. Using properites file was not an option since Mongo port had to be specified during runtime. I wanted to preseve original MongoDB autoconfiguration provided by SpringBoot but override some of the properties. This can be achieved by defining a bean of type MongoClientSettingsBuilderCustomizer which can be used to customize mongo settings :
#Bean
public MongoClientSettingsBuilderCustomizer clientSettingsBuilderCustomizer(final GenericContainer<?> mongoDBContainer) {
String database = environment.getProperty("spring.data.mongodb.database");
ConnectionString connectionString = new ConnectionString(String.format("mongodb://localhost:%s/%s", mongoDBContainer.getFirstMappedPort(), database));
return settings -> settings.applyConnectionString(connectionString);
}
If you simply want to read a MongoDB connection string from an environment variable, one way is to set the following environment variable:
SPRING_DATA_MONGODB_URI=mongodb://localhost:27017/trying-mongo
This doesn't require any changes in the application.properties as the spring data mongo will read the value from the above environment variable by default.
Here is How you can do in Spring Boot 2.0 by creating custom MongoClient adding Providing more control for Connection ,
Please follow github Link for Full Source Code
#Configuration
#EnableMongoRepositories(basePackages = { "com.frugalis.repository" })
#ComponentScan(basePackages = { "com.frugalis.*" })
#PropertySource("classpath:application.properties")
public class MongoJPAConfig extends AbstractMongoConfiguration {
#Value("${com.frugalis.mongo.database}")
private String database;
#Value("${com.frugalis.mongo.server}")
private String host;
#Value("${com.frugalis.mongo.port}")
private String port;
#Value("${com.frugalis.mongo.username}")
private String username;
#Value("${com.frugalis.mongo.password}")
private String password;
#Override
protected String getDatabaseName() {
return database;
}
#Override
protected String getMappingBasePackage() {
return "com.frugalis.entity.mongo";
}
#Bean
public MongoTemplate mongoTemplate() throws Exception {
return new MongoTemplate(mongoClient(), getDatabaseName());
}
#Override
#Bean
public MongoClient mongoClient() {
List<MongoCredential> allCred = new ArrayList<MongoCredential>();
System.out.println("???????????????????"+username+" "+database+" "+password+" "+host+" "+port);
allCred.add(MongoCredential.createCredential(username, database, password.toCharArray()));
MongoClient client = new MongoClient((new ServerAddress(host, Integer.parseInt(port))), allCred);
client.setWriteConcern(WriteConcern.ACKNOWLEDGED);
return client;
}}

Resources