Why Wildfly does not find the postgresql driver - java

I am developping a multi-tier software using java. The middle tier is a java ejb accessing the postgresql database. But when I run the client java application, I have the following error messages:
INFO: EJBCLIENT000069: Using legacy jboss-ejb-client.properties security configuration
Exception in thread "main" javax.ejb.EJBException: WFLYEJB0442: Unexpected Error
....
Caused by: java.lang.NoClassDefFoundError: org/postgresql/Driver
...
Caused by: java.lang.ClassNotFoundException: org.postgresql.Driver
The content of the module.xml file is:
<?xml version="1.0" encoding="utf-8" ?>
<module xmlns="urn:jboss:module:1.3" name="org.postgresql">
<resources>
<!--the name of your driver -->
<resource-root path="postgresql-42.2.6.jar"/>
</resources>
<dependencies>
<module name="javax.api"/>
<module name="javax.transaction.api"/>
</dependencies>
</module>
The following lines have been added to the standalone.xml file:
<driver name="postgresql" module="org.postgresql">
<driver-class>org.postgresql.Driver</driver-class>
<xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-
class>
</driver>
The driver and the module.xml are in folder \modules\org\postgresql\main. I have successfully tested my code by moving it to a single-tier java application. I am using Eclipse jee latest verion, wildfly 16, postgresql 11. the driver is postgresql-42.2.6.jar
I have already spent several days battling with the problem, but no success. Help most welcome.
package loginPackage;
import java.sql.Connection;
import java.sql.DriverManager;
import org.postgresql.Driver;
import java.sql.SQLException;
public class LoginDao {
static String errorMessage;
static String connectionResult;
public static String getConnectionResult() {
return connectionResult;
}
public static void setConnectionResult(String connectResult) {
connectionResult = connectResult;
}
public String getErrorMessage() {
return errorMessage;
}
public static void setErrorMessage(String errorMsg) {
errorMessage = errorMsg;
}
public static void LoginCheck(String userCode, String userPswd) {
setConnectionResult(userConnect(userCode, userPswd));
}
public static String userConnect(String userCode, String userPaswd) {
try {
//Connection conn = null;
setConnectionResult("OK");
setErrorMessage("OK");
Driver driver = new org.postgresql.Driver();
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/TestDb", userCode, userPaswd);
System.out.println("Connected to PostgreSQL database!");
return "SUCCESS";
}
catch (Exception e) {
System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
setErrorMessage(userCode + ", " + userPaswd + ", " + e.toString() + ", " + e.getMessage() + ", " + e.getStackTrace());
return "FAILURE" ;
}
}
}

Related

Class Not Found Exception org//h2//Driver

I am learning Spring Framework and trying to inject properties from the .properties file.
This is my .properties file
sprint.datasource.username=hamnghi
sprint.datasource.password=hamnghi
sprint.datasource.url=jdbc:h2:~/test;
sprint.datasource.driver=org.h2.Driver;
When I tried to pass the driver field into the Class.forName(drive), the program could not connect to the
database and threw a java.lang.ClassNotFoundException: org/h2/Driver; but it printed the driver variable as "org.h2.Driver" to the console just fine.
My console screenshot
I also ran the program with Class.forName("org.h2.Driver"), and it ran fine; however, when I replaced it with the driver, it didn't work
This is my class.
package H2Database.db_connection;
import H2Database.functionality.Logging;
import org.springframework.beans.factory.annotation.Value;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
public class H2Connection {
private final static Logger logger = Logging.getLogger();
#Value("${sprint.datasource.url}")
private String url;
#Value("${sprint.datasource.username}")
private String username;
#Value("${sprint.datasource.password}")
private String password;
#Value("${sprint.datasource.driver}")
private String driver;
public Connection open(){
try {
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
#Override
public String toString() {
return "H2Connection{" +
"url='" + url + '\'' +
", username='" + username + '\'' +
", driver='" + driver + '\'' +
'}';
}
}
EDITED
You have trailing ; in your config. remove it
The exception means the specific class is not found in the classpath.
You need to add the dependency contains the corresponding implemenation for h2:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
You should complete the following steps to Configure the H2 database to your Spring MVC application.
Step 1: Add the following dependency in the pom.xml file
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Step 2: configure these properties in the application.properties file.
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
Note: Spring MVC does not auto configure the properties of the
application.properties. You should configure it using configuration
class.
Step 3: Configure the Database.
#Configuration
#PropertySource("classpath:application.properties")
public class DataSourceConfig {
#Value("${sprint.datasource.url}")
private String url;
#Value("${sprint.datasource.username}")
private String username;
#Value("${sprint.datasource.password}")
private String password;
#Value("${sprint.datasource.driver}")
private String driver;
#Bean
public DataSource testDataSource() {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName(driver);
bds.setUrl(url);
bds.setUsername(username);
bds.setPassword(password);
return bds;
}
}

Tomcat and MYSQL porting to AWS

I have a working java 7 app that runs on tomcat 7 and MYSQL. I am trying to get it running on the basic (free tier) platform offered by Amazon AWS. I have succesfully loaded data to the RDS instance of MYSQL Community and set up an Elastic Beanstalk instance where basic JSPs are running correctly.
I am new to AWS so main problem should be my lack of knowledge.
I am not able to connect to the database from my code.
This is the code I am using to create the connection pool:
package com.authz.pap;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class DBConnections {
private static DataSource dataSource;
private static final DBConnections instance = new DBConnections();
static
{
try
{
Context c = new InitialContext();
dataSource = (DataSource)c.lookup("java:comp/env/jdbc/authzDB");
}
catch (Exception e)
{
dataSource = null;
}
}
private DBConnections()
{
}
public static DBConnections getInstance()
{
return instance;
}
public static DataSource getGeoServDS() {
//if(dataSource==null) instance = new DBConnections();
return dataSource;
}
}
And this:
public DbCon() {
conn=null;
ProcessStatus stat = new ProcessStatus();
stat.function="DbCon.DbCon";
stat.message = "Initializing DB";
stat.retcode=0;
stat.record();
try {
conn=DBConnections.getGeoServDS().getConnection();
conn.setAutoCommit(false);
} catch (Exception e) {
stat.message = e.toString();
stat.retcode=-1;
stat.record();
}
}
And this is the content of the context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/rest">
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxActive="8" maxIdle="4" name="jdbc/authzDB" password="xxxx" type="javax.sql.DataSource" url="jdbc:mysql://x.x.x.x:3306/authzDB?autoReconnect=true&allowMultiQueries=true" username="root"/>
<ResourceLink global="jdbc/authzDB" name="jdbc/authzDB" type="javax.sql.DataSource"/>
</Context>
What I get is a java.lang.NullPointerException on DB initialization.
What am I doing wrong?
UPDATE:
This is the content of the web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" id="WebApp_ID" version="2.5">
<display-name>paprest</display-name>
<servlet>
<servlet-name>PAP rest interface</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>com.authz.pap.intfc</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest interface</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
Double response:
1- I have not been able to use the data from context.xml file. I have ised a different solution:
private static Connection getRemoteConnection() {
ProcessStatus stat = new ProcessStatus();
try {
Class.forName("com.mysql.jdbc.Driver");
String dbName = "xxxxDB";
String userName = "xxxxx";
String password = "xxxxxx";
String hostname = "xxxxxxxx";
String port = "3306";
String jdbcUrl = "jdbc:mysql://" + hostname + ":" + port + "/" + dbName + "?user=" + userName + "&password=" + password + "&autoReconnect=true&allowMultiQueries=true";
Connection con = DriverManager.getConnection(jdbcUrl);
return con;
}
catch (ClassNotFoundException e) { stat.error(e.toString());}
catch (SQLException e) { stat.error(e.toString());}
return null;
}
2- I had a different problem, as the RDS instance is not to be created independently but related to the Elastic Beanstalk. This allows the comunication betwen tomcat and Mysql.

NoClassDefFoundError: io/netty/util/Timer

Just wanted to try Cassandra Java driver from eclipse and copied a sample code from "Practical Cassandra"
But faced error below output by eclipse:
Exception in thread "main" java.lang.NoClassDefFoundError: io/netty/util/Timer
at com.datastax.driver.core.Configuration$Builder.build(Configuration.java:294)
at com.datastax.driver.core.Cluster$Builder.getConfiguration(Cluster.java:1247)
at com.datastax.driver.core.Cluster.<init>(Cluster.java:116)
at com.datastax.driver.core.Cluster.buildFrom(Cluster.java:181)
at com.datastax.driver.core.Cluster$Builder.build(Cluster.java:1264)
at SampleApp.connect(SampleApp.java:13)
at SampleApp.main(SampleApp.java:64)
Caused by: java.lang.ClassNotFoundException: io.netty.util.Timer
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 7 more
here is the sample code:
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
public class SampleApp {
private Cluster cluster;
private Session session;
public void connect(String node) {
cluster = Cluster.builder().addContactPoint(node).build();
Metadata metadata = cluster.getMetadata();
System.out.printf("Cluster: %s\n", metadata.getClusterName());
for ( Host host : metadata.getAllHosts() ) {
System.out.printf("Host: %s \n",host.getAddress());
}
session = cluster.connect();
}
public void close(){
cluster.close();
}
public void createSchema(){
session.execute("CREATE KEYSPACE IF NOT EXISTS portfolio_demo " +
"WITH REPLICATION 5 { ‘class’: ‘SimpleStrategy’, " +
"'replication_factor’: 1 };");
session.execute("CREATE TABLE IF NOT EXISTS portfolio_demo.portfolio (" +
"portfolio_id UUID, ticker TEXT, " +
"current_price DECIMAL, current_change DECIMAL, " +
"current_change_percent FLOAT, " +
"PRIMARY KEY(portfolio_id, ticker));");
}
public void loadData(){
session.execute("INSERT INTO portfolio_demo.portfolio " +
"(portfolio_id, ticker, current_price, " +
" current_change, current_change_percent) VALUES " +
"(756716f7-2e54-4715-9f00-91dcbea6cf50, ‘GOOG’, " +
" 889.07, -4.00, -0.45);");
session.execute("INSERT INTO portfolio_demo.portfolio " +
"(portfolio_id, ticker, current_price, " +
" current_change, current_change_percent) VALUES " +
"(756716f7-2e54-4715-9f00-91dcbea6cf50, ‘AMZN’, " +
" 297.92, -0.94, -0.31);");
}
public void printResults(){
ResultSet results = session.execute("SELECT * FROM " +
"portfolio_demo.portfolio WHERE portfolio_id 5 " +
"756716f7-2e54-4715-9f00-91dcbea6cf50;");
for (Row row : results) {
System.out.println(String.format("%-7s\t%-7s\t%-7s\t%-7s \n%s",
"Ticker", "Price", "Change", "PCT",
"........1........1........1........"));
System.out.println(String.format("%-7s\t%0.2f\t%0.2f\t%0.2f",
row.getString("ticker"),
row.getDecimal("current_price"),
row.getDecimal("current_change"),
row.getFloat("current_change_percent") ));
}
}
public static void main(String[] args) {
SampleApp client = new SampleApp();
client.connect("127.0.0.1");
client.createSchema();
client.loadData();
client.printResults();
client.close();
}
}
And I also added several external JARs which are downloaded or comes with eclipse:
cassandra-driver-core-3.0.0.jar
guava-18.0.jar
netty-3.10.6.Final-20160303.120156-121.jar
org.apache.log4j_1.2.15.v201012070815.jar (from eclipse plugin)
org.slf4j.api_1.7.2.v20121108-1250.jar (from eclipse plugin)
org.slf4j.impl.log4j12_1.7.2.v20131105-2200.jar (from eclipse plugin)
I saw the same questions about the netty error but still could not figure out what was wrong with my code.
Thanks a lot.
This is the wrong Netty version. Version 3.0.0 of the driver uses 4.0.33.
You can view the driver's dependencies in the POM. The properties such as ${netty.version} are defined in the parent POM.

Not able to lookup Remote EJB in JBoss 7.x

I am trying to connect to a Remote EJB that is deployed in a JBoss 7 Server. I tried to figure out what the JNDI name is by looking at the JNDI dump that I got from the JBoss CLI.
No matter what I try I cannot lookup the EJB.
I think that the jndi name should be: java:global/XNet/api/ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote
Here is the client that I am using:
package com.mycompany.mavenproject1;
import com.mycompany.receiving.api.ReceivingAPI_EJBRemote;
import com.mycompany.receiving.api.ReceivingAPI;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import java.util.Properties;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args ) throws NamingException
{
System.out.println( "Hello World!" );
//ReceivingAPI ejbRemote = DomainHelper.getHQApi(com.mycompany.receiving.api.ReceivingAPI.class);
ReceivingAPI_EJBRemote ejbRemote = App.lookupRemoteStatelessCalculator();
ejbRemote.getOpenRcvdocForSite(null, 7);
}
// private static ReceivingAPI_EJBRemote lookupRemoteStatelessReceiving() throws NamingException {
//
// }
//
private static ReceivingAPI_EJBRemote lookupRemoteStatelessCalculator() throws NamingException {
final Properties jndiProperties = new Properties();
jndiProperties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
jndiProperties.put(Context.PROVIDER_URL,"remote://someserver.xmx.com:1199");
// username
jndiProperties.put(Context.SECURITY_PRINCIPAL, "mycompany1");
// password
jndiProperties.put(Context.SECURITY_CREDENTIALS, "<removed>");
//final Context context = new InitialContext(jndiProperties);
jndiProperties.put("jboss.naming.client.ejb.context", true);
InitialContext context = new InitialContext( jndiProperties );
// The app name is the application name of the deployed EJBs. This is typically the ear name
// without the .ear suffix. However, the application name could be overridden in the application.xml of the
// EJB deployment on the server.
// Since we haven't deployed the application as a .ear, the app name for us will be an empty string
final String appName = "XNet";
// This is the module name of the deployed EJBs on the server. This is typically the jar name of the
// EJB deployment, without the .jar suffix, but can be overridden via the ejb-jar.xml
// In this example, we have deployed the EJBs in a jboss-as-ejb-remote-app.jar, so the module name is
// jboss-as-ejb-remote-app
final String moduleName = "api";
// AS7 allows each deployment to have an (optional) distinct name. We haven't specified a distinct name for
// our EJB deployment, so this is an empty string
final String distinctName = "hq";
// The EJB name which by default is the simple class name of the bean implementation class
final String beanName = com.mycompany.receiving.api.ReceivingAPI.class.getSimpleName();
// the remote view fully qualified class name
final String viewClassName = ReceivingAPI_EJBRemote.class.getName();
// let's do the lookup
try {
ReceivingAPI test1 = (ReceivingAPI)context.lookup("java:global/XNet/api/" + beanName + "_EJB!" + viewClassName);
System.out.println("Test1 = " + test1.getClass().getName());
} catch(Throwable t) {
System.out.println(t);
}
try {
ReceivingAPI test = (ReceivingAPI)context.lookup("java:global/XNet/api/hq/" + beanName + "_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote");
System.out.println("Test = " + test.getClass().getName());
} catch(Throwable t) {
System.out.println(t);
}
try {
ReceivingAPI test = (ReceivingAPI)context.lookup("ejb:XNet/api/hq/" + beanName + "_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote");
System.out.println("Test = " + test.getClass().getName());
} catch(Throwable t) {
System.out.println(t);
}
return (ReceivingAPI_EJBRemote) context.lookup("ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "_EJB!" + viewClassName);
}
}
The output from the run of the previous java class:
Hello World!
javax.naming.NameNotFoundException: global/XNet/api/ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote -- service jboss.naming.context.java.jboss.exported.global.XNet.api."ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote"
javax.naming.NameNotFoundException: global/XNet/api/hq/ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote -- service jboss.naming.context.java.jboss.exported.global.XNet.api.hq."ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote"
javax.naming.NameNotFoundException: ejb:XNet/api/hq/ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote -- service jboss.naming.context.java.jboss.exported.ejb:XNet.api.hq."ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote"
Exception in thread "main" javax.naming.NameNotFoundException: ejb:XNet/api/hq/ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote -- service jboss.naming.context.java.jboss.exported.ejb:XNet.api.hq."ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote"
at org.jboss.as.naming.ServiceBasedNamingStore.lookup(ServiceBasedNamingStore.java:97)
at org.jboss.as.naming.NamingContext.lookup(NamingContext.java:178)
at org.jboss.naming.remote.protocol.v1.Protocol$1.handleServerMessage(Protocol.java:127)
at org.jboss.naming.remote.protocol.v1.RemoteNamingServerV1$MessageReciever$1.run(RemoteNamingServerV1.java:73)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Here is the dump of the JNDI CLI Command:
[jboss1#hmudev01 bin]$ ./jboss-cli.sh --connect controller=localhost:10099
[standalone#localhost:10099 /] /subsystem=naming:jndi-view
{
"outcome" => "success",
"result" => {
"java: contexts" => {
"java:global" => {
"XNet" => {
"class-name" => "javax.naming.Context",
"children" => {
"api" => {
"class-name" => "javax.naming.Context",
"children" => {
"ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBLocal" => {
"class-name" => "com.mycompany.receiving.api.ReceivingAPI_EJBLocal$$$view46",
"value" => "Proxy for view class: com.mycompany.receiving.api.ReceivingAPI_EJBLocal of EJB: ReceivingAPI_EJB"
},
"ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote" => {
"class-name" => "com.sun.proxy.$Proxy272",
"value" => "Proxy for remote EJB StatelessEJBLocator{appName='XNet', moduleName='api', distinctName='hq', beanName='ReceivingAPI_EJB', view='interface com.mycompany.receiving.api.ReceivingAPI_EJBRemote'}"
},
}
}
}
}
}
}
...
}
}
[standalone#localhost:10099 /]
Any my maven deps are as follows:
<dependencies>
<dependency>
<groupId>com.mycompany.receiving</groupId>
<artifactId>xnet-domain-receiving-client</artifactId>
<version>2.5.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.jboss.as</groupId>
<artifactId>jboss-as-naming</artifactId>
<version>7.1.3.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.marshalling</groupId>
<artifactId>jboss-marshalling-river</artifactId>
<version>1.4.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.client</groupId>
<artifactId>jbossall-client</artifactId>
<version>5.0.0.GA</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.ejb</groupId>
<artifactId>jboss-ejb-api_3.1_spec</artifactId>
<version>1.0.2.Final</version>
</dependency>
</dependencies>
In the comment above Rhys was right about the jndi string looking "funky". I tried everything I thought. Here is what worked for my situation.
The JNDI URL needs to look like this:
XNet/api/ReceivingAPI_EJB!com.mycompany.receiving.api.ReceivingAPI_EJBRemote
I also had to add add a dependency to the others shown in the question:
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>

Connect mysql with java

I am trying to connect to mysql in java (I use Wamp) so I used the following code : (I'm using Eclipse)
package genererPlanning;
import java.sql.*;
public class genererPlanning{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/mysql";
static final String USER = "root";
static final String PASS = "";
public static void main(String[] args){
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql","root", "");
}
catch (SQLException ex){
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
}
But it returned me this text :
SQLException: No suitable driver found for jdbc:mysql://localhost:3306/mysql
SQLState: 08001
VendorError: 0
Do you know why it does not work?
PS : I looked at theses links but don't find my answer :
- stackoverflow
- stackoverflow
- stackoverflow
- commentcamarche
Thanks for all.
You need to use the mysql-connector.jar
Here's the link with instructions as to how to set it to your classpath.
http://code.google.com/p/find-ur-pal/downloads/detail?name=mysql-connector-java-5.1.18-bin.jar&
You need mysql jdbc connector..download from this site

Categories

Resources