Failed to instantiate SLF4J LoggerFactory - mysql

So,
I'm working from this example BONECP:
package javasampleapps;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;
/** A test project demonstrating the use of BoneCP in a JDBC environment.
* #author wwadge
*/
public class BoneCPExample {
/** Start test
* #param args none expected.
*/
public static void main(String[] args) {
BoneCP connectionPool = null;
Connection connection = null;
try {
// load the database driver (make sure this is in your classpath!)
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
// setup the connection pool
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://domain/db");
config.setUsername("root");
config.setPassword("pass");
config.setMinConnectionsPerPartition(5);
config.setMaxConnectionsPerPartition(10);
config.setPartitionCount(1);
connectionPool = new BoneCP(config); // setup the connection pool
connection = connectionPool.getConnection(); // fetch a connection
if (connection != null){
System.out.println("Connection successful!");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id from batches limit 1"); // do something with the connection.
while(rs.next()){
System.out.println(rs.getString(1)); // should print out "1"'
}
}
connectionPool.shutdown(); // shutdown connection pool.
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
I added slf4j in my Libraries menu in netbeans, adding
D:/Documents%20and%20Settings/DavidH/My%20Documents/NetBeansProjects/jars/slf4j-api-1.6.4.jar
and
D:/Documents%20and%20Settings/DavidH/My%20Documents/NetBeansProjects/jars/slf4j-log4j12-1.6.4.jar
to the library.
Then I made a Google Guava library and added the jar that they distribute for that to another library.
I then added both of the libraries to the project and hit run.
I now get this error:
Failed to instantiate SLF4J LoggerFactory
Reported exception:
java.lang.NoClassDefFoundError: org/apache/log4j/Level
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:128)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:108)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:279)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:252)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:265)
at com.jolbox.bonecp.BoneCPConfig.<clinit>(BoneCPConfig.java:60)
at javasampleapps.BoneCPExample.main(BoneCPExample.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Level
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 7 more
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/Level
at org.slf4j.LoggerFactory.bind(LoggerFactory.java:128)
at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:108)
at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:279)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:252)
at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:265)
at com.jolbox.bonecp.BoneCPConfig.<clinit>(BoneCPConfig.java:60)
at javasampleapps.BoneCPExample.main(BoneCPExample.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.Level
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
... 7 more
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
What can I do to fix this?

If you include slf4j-log4j12-1.6.4.jar, then you must also include the log4j jar. Slf4j is a logging facade, which means it gives you a uniform interface to multiple other logging APIs.
The slf4j-log4j12 provides a conversion to the log4j API. As you don't include the log4j library, it throws an error. Not including the slf4j-log4j12 library should be enough (if only the slf4j-api library is included, then it should then default to a no-operation logger AFAIK).

Related

Cordapp- Hikari Connection Pool class not found for MySql ConnectionPoolDataSource

I am building an workflow for Corda. I want to use the Hikari connection pool library for connecting to MySql database. I AM NOT trying to replace the, ledger H2 database. This database is for storing/retrieving some information, which is not needed in the ledger. I am able to connect to MySql WITHOUT Hikari. However when I use Hikari, I get an error.
java.lang.ClassNotFoundException: com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
I have tested the Hikari code, as a standalone jar file. It works fine. It is a combination of the way corda loads and runs the jar files, inside cordapps directory, which is causing the issue. Since the class is part of the jar. This seems it a little off
I have added the MySql dependency, inline with what is mentioned in https://docs.corda.net/cordapp-build-systems.html#setting-your-dependencies
I am also able to connect to the MySql DB, if I am not using Hikari.
I explored the cordapp jar .
And I could see that the requisite jar is present inside the cordapp jar.
Gradle dependencies for the cordapp
dependencies {
testCompile "junit:junit:$junit_version"
// Corda dependencies.
cordaCompile "$corda_release_group:corda-core:$corda_release_version"
cordaRuntime "$corda_release_group:corda:$corda_release_version"
testCompile "$corda_release_group:corda-node-driver:$corda_release_version"
runtime "mysql:mysql-connector-java:8.0.11"
cordaCompile "com.zaxxer:HikariCP:2.5.1"
// CorDapp dependencies.
cordapp project(":contracts")
}
Sample code
public class DataSource {
private static final Logger logger = LoggerFactory.getLogger(DataSource.class);
private static HikariConfig config = new HikariConfig();
private static HikariDataSource ds;
static {
try {
logger.info("Connecting with connection pool datasource");
config.setDataSourceClassName("com.mysql.cj.jdbc.MysqlConnectionPoolDataSource");
config.addDataSourceProperty("useSSL", "false");
config.addDataSourceProperty("user", "username");
config.addDataSourceProperty("password", "password");
config.addDataSourceProperty("serverName", "localhost");
config.addDataSourceProperty("useSSL", "false");
config.addDataSourceProperty("port",Integer.parseInt("3306"));
config.addDataSourceProperty("cachePrepStmts", "true");
config.addDataSourceProperty("prepStmtCacheSize", "250");
config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
config.addDataSourceProperty("requireSSL", "false");
config.addDataSourceProperty("serverTimezone", "UTC");
config.addDataSourceProperty("useServerPrepStmts", "true");
config.addDataSourceProperty("allowPublicKeyRetrieval", "true");
config.addDataSourceProperty("databaseName", "database");
config.setPoolName("Hikari-MySql Pool Name");
logger.error("-- Create Hikari Datasource with config {} --", config);
ds = new HikariDataSource(config);
} catch (Throwable t) {
logger.error("Error Occurred during Datasource Initializaiton", t);
throw t;
}
}
private DataSource() {
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
public class MySqlConnection {
static private final Logger logger = LoggerFactory.getLogger(MySqlConnection.class);
public Connection getMySqlConnection() {
Connection conn = null;
try {
conn = DataSource.getConnection();
logger.info("------------> Got conne :: " + conn);
} catch (SQLException e) {
logger.error("SQLException :: " + e);
}
return conn;
}
}
public class DataSourceTest {
static private final Logger logger = LoggerFactory.getLogger(DataSourceTest.class);
public static void main(String[] args) {
MySqlConnection mySqlConnection = new MySqlConnection();
Connection conn = null;
try {
conn = mySqlConnection.getMySqlConnection();
logger.info("------------> Got connection :: " + conn);
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("{some select statement}");
} catch (SQLException e) {
logger.error("SQLException :: " + e);
}
}
}
Exception:
Caused by: java.lang.RuntimeException: java.lang.ClassNotFoundException: com.mysql.cj.jdbc.MysqlConnectionPoolDataSource
at com.zaxxer.hikari.util.UtilityElf.createInstance(UtilityElf.java:90) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.pool.PoolBase.initializeDataSource(PoolBase.java:314) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.pool.PoolBase.<init>(PoolBase.java:108) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:99) ~[HikariCP-2.5.1.jar:?]
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:71) ~[HikariCP-2.5.1.jar:?]
If I run the code from a main class inside a jar, it works. But it does not work from inside a cordapp
In MySQL for HikariCP use setJdbcUrl instead of setDataSourceClassName
config.setJdbcUrl("jdbc:mysql://localhost:3306/simpsons");
The MySQL DataSource is known to be broken with respect to network timeout support. Use jdbcUrl configuration instead.
Check your dependency tree. I think you have some collision with "mysql-connector-java" dependency, which cause mess in class loader.

derby In memory database + junit

I got an exception below when trying to use derby in memory database in JUNITTEST.
java.sql.SQLNonTransientConnectionException: Database 'memory:testDB'
dropped. at
org.apache.derby.iapi.error.StandardException.newException(Unknown
Source)
#Before
public void setUp() throws Exception {
String driver = "org.apache.derby.jdbc.EmbeddedDriver";
String connectionURL = "jdbc:derby:memory:testDB;create=true";
Class.forName(driver);
Connection conn = DriverManager.getConnection(connectionURL);
super.setUp();
}
#After
public void tearDown() throws Exception {
String connectionURL = "jdbc:derby:memory:testDB;drop=true";
DriverManager.getConnection(connectionURL);
}
If you are using Maven for your build, you can use the derby-maven-plugin, which I wrote and is available on GitHub and via Maven Central. It will take care of starting and stopping the database for you before your tests.
You can check here for my answer to a similar question.

Groovy: RedHat: java.sql.SQLException: No suitable driver found for jdbc:mysql:

I tryed to execute groovy-script under RH shell
[localhost]# groovy /home/rualas4/script.groovy
but received exception
Caught: java.sql.SQLException: No suitable driver found for jdbc:mysql:/localhost:3306/
java.sql.SQLException: No suitable driver found for jdbc:mysql:/localhost:3306/
at script.run(script.groovy:13)
I had installed next packages:
unixODBC-2.2.14-12.el6_3.x86_64
mysql-connector-odbc-5.3.2-1.el6.x86_64
and my code:
#GrabConfig(systemClassLoader = true)
#Grab(group='mysql', module='mysql-connector-java', version='5.1.25')
import groovy.sql.Sql
import groovy.io.FileType
println "Initialize connection"
url="jdbc:mysql://localhost:3306/"
username = "test"
password = "test"
driver = "com.mysql.jdbc.Driver"
sql = Sql.newInstance(url, username, password, driver)
also I have mysql-connector-java-5.1.25-bin.jar in my groovy (/opt/groovy/lib) directory
Please, provide a solution for resolve error exception
You are missing a / character in your connection url, when com.mysql.jdbc.Driver parse your url is looking for jdbc:mysql://:
com.mysql.jdbc.Driver class:
package com.mysql.jdbc;
import java.sql.SQLException;
public class Driver extends NonRegisteringDriver implements java.sql.Driver {
// ~ Static fields/initializers
// ---------------------------------------------
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
// ~ Constructors
// -----------------------------------------------------------
/**
* Construct a new driver and register it with DriverManager
*
* #throws SQLException
* if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}
com.mysql.jdbc.NonRegisteringDriver class:
package com.mysql.jdbc;
import java.sql.SQLException;
public class NonRegisteringDriver implements java.sql.Driver {
...
private static final String URL_PREFIX = "jdbc:mysql://";
...
public Properties parseURL(String url, Properties defaults)
throws java.sql.SQLException {
Properties urlProps = (defaults != null) ? new Properties(defaults)
: new Properties();
if (url == null) {
return null;
}
if (!StringUtils.startsWithIgnoreCase(url, URL_PREFIX)
&& !StringUtils.startsWithIgnoreCase(url, MXJ_URL_PREFIX)
&& !StringUtils.startsWithIgnoreCase(url,
LOADBALANCE_URL_PREFIX)
&& !StringUtils.startsWithIgnoreCase(url,
REPLICATION_URL_PREFIX)) {
return null;
}
...
}
therefore:
Change:
jdbc:mysql:/localhost:3306/
To:
jdbc:mysql://localhost:3306/
Hope this helps,

Access to MySQL using Java Servlet?

The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?
You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.
David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);
First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test

SQLException - Connection reset error

I am trying to establish a jdbc connection with SQL Server 2008 R2, using the SQLJDBC4 jar file and JDK 1.6. I am using Netbeans IDE and have added the SQLJDBC4 jar and added the path to the database in the 'databases' section in the services. The code is as below:
package connect2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Connect2 {
public static void main(String[] args) throws SQLException {
Connection conn;
conn = null;
System.out.println("Done....");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection ("jdbc:sqlserver://172.17.39.13\\CRM:1433;databaseName=crm_xchanging","crm_xchanging","Welcome001");
System.out.println ("Database connection established");
}
catch (ClassNotFoundException e)
{
System.out.println (e);
}
catch (SQLException ex)
{
System.out.println(" error");
}
finally
{
if (conn != null)
{
try{
Statement st = conn.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM usertable");
System.out.println("User Name: " );
while (res.next()) {
String employeeName = res.getString("user_name");
System.out.println(employeeName);
}
conn.close();
}
catch(SQLException ex){
System.err.println("SQLException information");
while(ex!=null) {
System.err.println ("Error msg: " + ex.getMessage());
System.err.println ("SQLSTATE: " + ex.getSQLState());
System.err.println ("Error code: " + ex.getErrorCode());
ex = ex.getNextException();
// For drivers that support chained exceptions
}}
}
}
}
}
This is the output I'm getting:
run:
Done....
Database connection established
SQLException information
Error msg: Connection reset
SQLSTATE: 08S01
Error code: 0
BUILD SUCCESSFUL (total time: 1 second)
I don't think there is any mistake in the code or the JDK. I have also tried to set the max no. of active connections for SQL Server as 0 (infinite). How do I solve this problem?
There is a known bug introduced in Java 6u29 that causes SSL failure specifically with SQL Server 2008 R2. An Atlassian Fisheye troubleshooting page suggests a fix was incomplete.
Oracle delivered a fix in 6u30, although for at least one affected
client not even Java 1.7 worked.
On my development team we have found this bug to impact Java 8 at as well. One of the recommendation in the Fisheye article is to disable CBC protection using a JVM flag and that has also worked for me for SSL Java 8 SSL with a SQL Server 2008 R2 connection.
-Djsse.enableCBCProtection=false
The other suggestion is to revert to Java 1.6.0_24.