So I have a MySQL database, and I have a datasource on a local instance of WebLogic which is connected to that database. I am trying to write some client code which will simply connect and query. I am having issues with obtaining a connection from the datasource. Here's my code thus far. I am running WebLogic 12c.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ConnectionTest {
public static void main(String... args) {
ConnectionTest tCon = new ConnectionTest();
tCon.TestConnection();
}
public void TestConnection() {
Context ctx = null;
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("java.naming.factory.initial",
"weblogic.jndi.WLInitialContextFactory");
props.put("java.naming.provider.url", "t3://localhost:7001");
props.put("java.naming.security.principal", "weblogic");
props.put("java.naming.security.credentials", "welcome1");
ctx = new InitialContext(props);
DataSource ds = (DataSource) ctx.lookup("RegexDB");
System.out.println(ds);
DAO dao = new DAO();
conn = ds.getConnection();
stmt = conn.createStatement();
stmt.execute("select * from regular_ex");
rs = stmt.getResultSet();
ArrayList<HashMap<String, Object>> results = dao
.resultSetToArrayList(rs);
dao.printArrayList(results);
stmt.close();
conn.close();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null)
stmt.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
This fails at ds.getConnection() with the following exception:
java.lang.ClassCastException: weblogic.jdbc.common.internal.ConnectionEnv cannot be cast to java.io.Serializable
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2285)
at weblogic.utils.io.ObjectStreamClass.writeFields(ObjectStreamClass.java:414)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:235)
at weblogic.corba.utils.ValueHandlerImpl.writeValueData(ValueHandlerImpl.java:225)
at weblogic.corba.utils.ValueHandlerImpl.writeValue(ValueHandlerImpl.java:182)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:1983)
at weblogic.iiop.IIOPOutputStream.write_value(IIOPOutputStream.java:2021)
at weblogic.iiop.IIOPOutputStream.writeObject(IIOPOutputStream.java:2285)
at weblogic.jdbc.common.internal.RmiDataSource_WLSkel.invoke(Unknown Source)
at weblogic.rmi.internal.BasicServerRef.invoke(BasicServerRef.java:695)
at weblogic.rmi.cluster.ClusterableServerRef.invoke(ClusterableServerRef.java:230)
at weblogic.rmi.internal.BasicServerRef$1.run(BasicServerRef.java:520)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:363)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:146)
at weblogic.rmi.internal.BasicServerRef.handleRequest(BasicServerRef.java:516)
at weblogic.rmi.internal.wls.WLSExecuteRequest.run(WLSExecuteRequest.java:118)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:256)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:221)
I have wlclient.jar, wlsafclient.jar, and weblogic.jar in my buildpath. I have tried all sorts of combinations of adding/removing these jars, but I still get the same error regardless of what I do. Any help would be greatly appreciated.
After doing some research, I am deleting my old answer and starting over.
There is a large table of client types in the Oracle Doc for WebLogic Standalone Clients. For each type of client, listed, the table shows the required jar files. For certain types of clients, you need to build an additional jar (wlfullclient.jar) and include that.
Hope this helps.
I have also face this problem and I tried to add "wlfullclient.jar" to my directory to fix it out but I didn't find this jar file in weblogic installation folder.
But at the last I have set all required jar files form weblogic by using setDomainEnv.cmd and it works fine. Here we don't have to care about which jar files required or not it'll simply set classpath for all required jar file for your program.
I am using Weblogic 11g.
In Weblogic 12c, copy the weblogic.jar file to some other directory. Rename the file to weblogic-classes.jar and then build the jar file using wljarbuilder.
Add the newly created wlfullclient.jar file to your Class Path in eclipse.
Build wlfullclient.jar and add just this jar to the build path.
It solved the problem for me.
By the way weblogic.jar from Weblogic 12 is missing some classes as compared to weblogic.jar from Weblogic 10.3
Related
This question already has answers here:
Why am I getting a NoClassDefFoundError in Java?
(31 answers)
Closed 6 years ago.
I'm so noob at external stuff to Bukkit programming, so I'm sorry if it's so easy to solve :P
I have a problem, and it's that when I try to use HikariCP in my project, it returns in an error (the title one).
I'm using it in a BungeeCord plugin.
The weird thing is that I have done this successfully couples of times, and I don't know why it isn't working this time.
The error / log:
06:13:36 [ADVERTENCIA] Exception encountered when loading plugin: DiverseReport java.lang.NoClassDefFoundError: com/zaxxer/hikari/HikariDataSource at net.srlegsini.DiverseReport.Bungee.MClass.onEnable(MClass.java:44) at net.md_5.bungee.api.plugin.PluginManager.enablePlugins(PluginManager.java:227) at net.md_5.bungee.BungeeCord.start(BungeeCord.java:272) at net.md_5.bungee.BungeeCordLauncher.main(BungeeCordLauncher.java:55) at net.md_5.bungee.Bootstrap.main(Bootstrap.java:15) Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariDataSource at net.md_5.bungee.api.plugin.PluginClassloader.loadClass0(PluginClassloader.java:53) at net.md_5.bungee.api.plugin.PluginClassloader.loadClass(PluginClassloader.java:27) at java.lang.ClassLoader.loadClass(Unknown Source) ... 5 more
My main class:
package net.srlegsini.DiverseReport.Bungee;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import com.zaxxer.hikari.HikariDataSource;
import net.md_5.bungee.BungeeCord;
import net.md_5.bungee.api.plugin.Plugin;
import net.md_5.bungee.config.Configuration;
import net.md_5.bungee.config.ConfigurationProvider;
import net.md_5.bungee.config.YamlConfiguration;
import net.srlegsini.DiverseReport.Bukkit.UUIDFetcher;
public class MClass extends Plugin {
static Configuration config;
static MClass plugin;
static HikariDataSource hikari;
static Connection connection;
public void onEnable() {
BungeeCord.getInstance().getPluginManager().registerListener(this, new ChannelListener());
BungeeCord.getInstance().registerChannel("Return");
loadCfg();
if (!config.contains("MySQL")) {
config.set("MySQL.Enable", false);
config.set("MySQL.Host", "localhost");
config.set("MySQL.Port", 3306);
config.set("MySQL.User", "user");
config.set("MySQL.Pass", "pass");
config.set("MySQL.Database", "Sr_DiverseReport");
}
saveCfg(getDataFolder());
hikari = new HikariDataSource();
hikari.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
hikari.addDataSourceProperty("serverName", config.getString("MySQL.Host"));
hikari.addDataSourceProperty("port", 3306);
hikari.addDataSourceProperty("databaseName", config.getString("MySQL.Database"));
hikari.addDataSourceProperty("user", config.getString("MySQL.User"));
hikari.addDataSourceProperty("password", config.getString("MySQL.Pass"));
try {
Class.forName("com.mysql.jdbc.Driver");
connection = hikari.getConnection();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
}
saveCfg(getDataFolder());
}
public void loadCfg() {
try {
File file = new File(getDataFolder(), "config.yml");
if (!getDataFolder().exists()) {
getDataFolder().mkdir();
}
if (!file.exists()) {
file.createNewFile();
}
config = ConfigurationProvider.getProvider(YamlConfiguration.class)
.load(new File(getDataFolder(), "config.yml"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static void saveCfg(File dataFolder) {
try {
ConfigurationProvider.getProvider(YamlConfiguration.class).save(config, new File(dataFolder, "config.yml"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings({ "unused", "deprecation" })
public static String getUUID(String playerName) {
UUIDFetcher fetcher = new UUIDFetcher(Arrays.asList("evilmidget38", "mbaxter"));
String playerUUID = null;
try {
playerUUID = UUIDFetcher.getUUIDOf(playerName).toString();
} catch (Exception e2) {
playerUUID = BungeeCord.getInstance().getPlayer(playerName).getUniqueId().toString();
}
return playerUUID;
}
}
My procedure:
Create the project, import BungeeCord.jar, HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar in buildpath, import HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar
It worked in other projects, but magically, it's broken.
I don't want to use Maven, just because it must have a fix, because as I said, I used this same procedure so many times in the past.
Thank you for taking the time to read this :)
EDIT:
Image of the project
It's all in the exception:
Caused by: java.lang.ClassNotFoundException: com.zaxxer.hikari.HikariDataSource
The HikariDataSource is missing at runtime, you need to provide it somehow, for example by copying the relevant .jar with 'drivers' into your server libraries folder.
Also see some related questions:
How to set up datasource with Spring for HikariCP? and
How do I configure HikariCP in my Spring Boot app in my application.properties files?
From the exception it is clear that HikariCP-2.6.0.jar was in classpath during compile time but is missing in runtime and from the image of the project structure, it is also clear that both HikariCP-2.6.0.jar and slf4j-api-1.7.21.jar are missing as library reference in the ide. You need to keep these jar in your classpath library during compile time and runtime.
hello i am trying to load my jdbc diver through classloader
here i am code but why i get this error if possible than give me some example
i don not what to set class path variable
i am making a database application and this application need to connect database again and again and i want to give this application to my friend but my friend not know about class path he is like normal user ,
my application can connect 4 type of database MS-Access,MySQL,Oracle,SQLlite...
in user system i have to set 5 class path variable and provide 5 jar file
if i give this application 100 people than they have set set class path variable
i can include jar file with my application but how can i set class path dynamically ....
please provide some example...
package classload;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class ClassLoad {
static Connection con;
public static void main(String[] args) {
File jar = new File("C:\\query\\Driver.jar").getAbsoluteFile();
if(jar.exists()){
System.out.print("File exits");
}
URL urls[] = null;
try {
urls = new URL[] {
jar.toURI().toURL()
};
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ClassLoader cl = new URLClassLoader(urls);
try {
Class.forName("com.mysql.jdbc.Driver", true, cl);
con=DriverManager.getConnection("jdbc:mysql://localhost", "root", "anil");
Statement stm=con.createStatement();
ResultSet result=stm.executeQuery("select *from actor");
while(result.next()){
System.out.print(result.getInt(1)+" "+result.getString(2)+" "+result.getString(3));
System.out.println("");
}
} catch (SQLException e) {
System.out.println(e);
}catch(ClassNotFoundException e){
System.out.println(e);
}
}
}
exception is
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost
Just use One-Jar to package the application and all of the dependencies into single fat jar. Your solution is no good. Your friend would have to use the same folder structure as you are in order for it to work.
This error is coming probably because the required jar file mysql-connector has not been included in your project. Try including jar file as shown here. And try this code to load Driver class:
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/jlcstudents","root","password");
In this code class.forname it show error that class not found
so help me with this code because my is a local database application
I am using sqlite database.
package appview;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Databaseconnection {
Connection connection = null;
public static Connection connection2()
{
try
{
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Jainam\\Java Application\\JPH\\src\\database\\jph_db.sqlite");
return connection;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
}
You have to declare the url this way: jdbc:sqlite:/DRIVE:/dirA/dirB/dbfile
DriverManager.getConnection("jdbc:sqlite:/C:/Users/Jainam/Java Application/JPH/src/database/jph_db.sqlite");
See Here for more informations
ClassNotFoundException means Java is not able to find the org.sqlite.JDBC class. You need to Download sqlite-jdbc-3.6.20.1.jar and put it in your class-path before running it.
here check database connectivity.
class not found ? then go for DDMS->FILE EXP-> SDCARD -> INSERT UR SQLITE.DB file.It will run proper.
I need to use .properties file in Java to store database information.
Here is my database connector class. It's giving NullPointerException. What is the issue with my code ?
Note, that I haven't' assign those property file values. DB connection values are still hard coded.
import java.io.IOException;
import java.io.InputStream;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class Database {
public Connection connection;
private Statement statement;
private Properties property;
public static Database database;
private Database() {
String url = "jdbc:mysql://localhost:3306/";
String dbName = "edus";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
InputStream is = Database.class.getClassLoader().getResourceAsStream(
"config.properties");
property.load(is);
System.out.println(property.getProperty("db_user"));
System.out.println(property.getProperty("db_password"));
System.out.println(property.getProperty("db_name"));
Class.forName(driver).newInstance();
this.connection = (Connection) DriverManager.getConnection(url + dbName,
userName, password);
}catch (IOException ex) {
Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
System.out.println("JDBC driver is missing");
} catch (InstantiationException | IllegalAccessException | SQLException e) {
e.printStackTrace();
}
}
public static synchronized Database getDatabaseConnection() {
if (database == null) {
database = new Database();
}
return database;
}
}
config.properties is not lying under classpath. It should be under classes folder.
you can also try
Database.class.getClassLoader().getResourceAsStream(
"com/lk/apiit/eduservice/config.properties");
As Roman C pointed out you also need to initialize Properties Object first
Properties property = new Properties();
You forgot to initialize
Properties property = new Properties();
This is an issue of NullPointerException in your code, because you referenced not initialized variable.
If you open a stream you should close it after it's not used. Do it by adding finally block.
The code where you getting a connection to the database you can move to the corresponding method. If the connection is closed you will not reinitialize the database again just reopen a connection or get a new one.
Dont keep config properties file in a package. Keep it directly inside the source folder, so that the config properties file comes directly in the build/classes folder after the build is done.
The issue is that your config properties in in the folder com/ik/apiit/eduservice folder but your code is expecting it to be directly in the classes folder (the root folder of classpath).
try this
FileInputStream in = new FileInputStream(System.getProperty("WEB-INF/dbConnection.properties"));
prop.load(in);
I am trying to connect to mysql from java web application in eclipse.
Connection con = null;
try {
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/db_name","root" ,"");
if(!con.isClosed())
System.out.println("Successfully connected to " +
"MySQL server using TCP/IP...");
} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {
System.out.println(e.toString());
}
}
I am always getting the Exception: com.mysql.jdbc.Driver
I have downloaded this jar http://forums.mysql.com/read.php?39,218287,220327
import it to the "java build path/lib"
the mysql version is 5.1.3 under.
running:
mysql 5.1.3 (db is up and running queries form PHP)
windows XP
Java EE
you say you placed the JAR on the build path, is it in the runtime class path? you said "java EE", so i assume you are deploying this as a web app? in that case you need to put the JDBC JAR file into WEB-INF/lib of your web app.
You have to download the mysql jdbc connector und use it as lib. You can get it here:
http://www.mysql.com/downloads/connector/j/
Have u added it in your build configuration also, if the location is not in classpath then it wont work by mere keeping it in lib folder.
check your .classpath file
You can find a full documentation (Chapter 14) on how to connect to MySQL database through any web application (JBOSS, Glassfish etc...), if you download the MySQL JDBC driver.
After doing your configuration, you have to get the connection from your server by getting your server connection ressource.
Here is a sample code of how to get a connection ressource from a Glassfish server :
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.Stateless;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
#Stateless
public class AppConnection {
private InitialContext context;
private DataSource source;
private Connection connection;
public AppConnection() {
this.initConnection();
}
private void initConnection() {
try {
context = new InitialContext();
source = (DataSource)context.lookup("jdbc/MySQLDataSource");
connection = source.getConnection();
} catch (SQLException ex) {
Logger.getLogger(AppConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (NamingException ex) {
Logger.getLogger(AppConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
public Connection getContextConnection() {
return connection;
}
public void closeContextConnection() throws SQLException {
if(connection != null) {
connection.close();
}
}
}
Note that this class is an EJB and "jdbc/MySQLDataSource" is the name of the connection configured on your server. It can be inject in other EJB to get your current connection and create other needed objects as Statements or Resultsets.