Java dynamic class loading fails on windows, but working fine on linux - class

I am trying to load a class dynamically from a jar file. It worked fine on a Ubuntu linux box ( Sun Java Version 1.6.0_24 (b07).
When I tried to run the same thing on Windows (Windows 7, Java version "1.6.0_14") it fails with Class Not Found exception.
Following is code :
try {
String jarFile = "/sqljdbc4.jar";
File newf = new File(jarFile);
System.out.println(newf.getAbsolutePath());
System.out.println("File exists ? :" + newf.exists());
String urlPath = "jar:file://" + newf.getAbsolutePath() + "!/";
System.out.println(urlPath);
ClassLoader cur = Thread.currentThread().getContextClassLoader();
URL[] jarUrlArray = { new URL(urlPath) };
URLClassLoader cl = URLClassLoader.newInstance(jarUrlArray, cur);
Class c = Class.forName(
"com.microsoft.sqlserver.jdbc.SQLServerDriver", true, cl);
Method m[] = c.getMethods();
for (Method mm : m) {
System.out.println(mm.getName());
}
} catch (Exception e) {
e.printStackTrace();
}
While running on Linux, jar is placed at root and for Windows its at c:\ (source and binaries are in some folder on C:\ so "/sqljdbc4.jar" resolves to c:\sqljdbc4.jar on windows, I have made sure that correct jar location in passed to classloader for both the platforms.
Following is the stack trace i get on windows
java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
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:306)
at java.net.FactoryURLClassLoader.loadClass(URLClassLoader.java:594)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at DemoClass.loadAClass(DemoClass.java:31)
at DemoClass.main(DemoClass.java:14)
NOTE : You can use any jar that u have to try this out. I was playing with MS SQL Server JDBC Driver jar.
Thanks !
-Abhijeet.

Try using this to create the URL rather than manually building the string:
URL[] jarUrlArray = { newf.toURI().toURL() };

Related

How do I use jGrasp's libraries?

I have a folder full of classes from a class I took. With a fresh install of jGrasp old projects that used to run fine are now full of "symbol not found" errors.
I still have the libraries, but I don't know how to import them. The way our class was set up, you didn't need import statements for anything that was in the library.
/* Turtle Drawing Program Lab 6, Part B */
/* Started by Celine Latulipe , modified by Bruce Long*/
public class Lab6PartB {
public static void main(String [] args)
{
/* Create the world */
World w = new World();
/* Create the turtle, call him Tom */
Turtle tom = new Turtle(w);
/* test the getDistance2() method */
int dist = tom.getDistance2();
System.out.println("This should print out the value 400. Value is: " + dist);
tom.moveTo(500, 400);
dist = tom.getDistance2();
System.out.println("This should print out the value 640. Value is: " + dist);
// TODO: Add a third test case that you make up
}
}
Error:
----jGRASP exec: java Lab6PartB
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: ModelDisplay
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: ModelDisplay
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
----jGRASP wedge2: exit code for process is 1.
----jGRASP: operation complete.
You can add the directory containing the class files to the classpath, either at the OS level, or using "Settings" > "PATH / CLASSPATH" > "Workspace" in jGRASP.
Also, you could copy all the class files/directories to the folder containing your new project classes.

Strange exception using Jersey with embedded Jetty

I have created an embedded Jetty application which utilizes Jersey in order to implement several RESTful services. I am using some standard code as described here in Stack Overflow as well as other websites:
public static void main(String[] args)
{
Server server = new Server(8080);
ServletContextHandler ctx = new ServletContextHandler(
ServletContextHandler.SESSIONS);
ctx.setContextPath("/");
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer.class", "/*");
holder.setInitOrder(0);
holder.setInitParameter("jersey.config.server.provider.classnames",
RestfulClass.class.getCanonicalName());
server.setHandler(ctx);
try
{
server.start();
server.join();
}
catch(Exception exe)
{
exe.printStackTrace();
}
}
I've used all the recommended jar files, and several other jar files that the various blogs and sites failed to mention. When running the Jetty application, I get the following exception:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer.class
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:86)
at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:95)
<several lines omitted for brevty>
Caused by: javax.servlet.UnavailableException: org.glassfish.jersey.servlet.ServletContainer.class
at org.eclipse.jetty.servlet.BaseHolder.doStart(BaseHolder.java:102)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:361)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:874)
... 11 more
It is the "UnavailableException" that I do not understand. The ServletContainer class is actually in one of the Jar files (in jersey-container-servlet-core.jar, to be precise), but for some reason it is identified as "unavailable". This is causing a class that is actually in a referenced Jar file to be "not found"!
Can anyone tell me what is causing this UnavailableException and (more importantly) how I can prevent it from being thrown?
Someone please advise...
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer.class", "/*");
You are using a String for the class name. When doing this, you don't use the .class suffix. That at only when you want to get the actual Class object. You have two options
Remove the .class from the String
ServletHolder holder = ctx.addServlet(
"org.glassfish.jersey.servlet.ServletContainer", "/*");
Remove the "" (double quotes) and just use the Class object1.
ServletHolder holder = ctx.addServlet(
org.glassfish.jersey.servlet.ServletContainer.class, "/*");
1 - See addServlet(Class, String)

Where to copy a file so I can open it from GWT Eclipse Google Plugin in dev mode?

I'm learning GWT with Google Eclipse Plugin, and I want to use some configuration file (generatorConfig.xml) from my server code, how do I upload it to the default devmode server? how do I open it from my Java code?
I've put the generatorConfig.xml file in the war/WEB-INF/deploy/[my app]/ but I can't open it...
String line;
BufferedReader in;
in = new BufferedReader(new FileReader("generatorConfig.xml"));
line = in.readLine();
I get this stack trace:
java.io.FileNotFoundException: generatorConfig.xml (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.io.FileInputStream.<init>(FileInputStream.java:101)
at java.io.FileReader.<init>(FileReader.java:58)
at bo.rowen.server.GreetingServiceImpl.greetServer(GreetingServiceImpl.java:50)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
You need to put it in /war/WEB-INF/ folder. Then you can:
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/WEB-INF/generatorConfig.xml");
Finally, I solved my problem including the file in the src folder and loading just with the file name, (my file now is named configuration.xml):
String resource = "configuration.xml";
try {
reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}

LuaJava Eclipse

I finally managed to get LuaJava to build on OSX and now I am running into trouble using it in Eclipse. I put the jnilib in my system path and when I go to the directory where I built it I can run the Console like this:
$ java -cp "luajava-1.1.jar" org.keplerproject.luajava.Console
API Lua Java - console mode.
> print("Hello World!")
Hello World!
> exit
$
So I'm guessing that means that it is built and installed correctly. I added the jar to my project using the "Add External Jar" in the Java Build Path property window. But when I try to use it I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: ScriptEngineSample
Caused by: java.lang.ClassNotFoundException: ScriptEngineSample
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Here is all of my code:
LuaWarrior.java
public class LuaWarrior
{
public static void main(String[] args)
{
new Game().start();
}
}
Game.java
import org.keplerproject.luajava.LuaState;
import org.keplerproject.luajava.LuaStateFactory;
public class Game
{
private LuaState _lua;
public Game()
{
_lua = LuaStateFactory.newLuaState();
_lua.openLibs();
}
public void start()
{
_lua.LdoFile("scripts/hello.lua");
}
}
It turns out that it doesn't need to be in the system path, but is needs to be in the JVM Library folder.
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Libraries/

com.mysql.jdbc.Driver not found when trying to add SQL features in Jitsi

I'm coding on Jitsi using Eclipse: I have to use JDBC to connect to MySQL database, so I've imported java.sql.* in my MainFrame class and I've included mysql-connector-java-5.1.18.jar into "Java Build Path" -> "Libraries".
When I run the project, I've this error:
IOException in readRegistry: java.io.EOFException
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver not found by [76]
at org.apache.felix.framework.ModuleImpl.findClassOrResourceByDelegation(ModuleImpl.java:787)
at org.apache.felix.framework.ModuleImpl.access$400(ModuleImpl.java:71)
at org.apache.felix.framework.ModuleImpl$ModuleClassLoader.loadClass(ModuleImpl.java:1768)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at net.java.sip.communicator.impl.gui.main.MainFrame.init(MainFrame.java:301)
at net.java.sip.communicator.impl.gui.main.MainFrame.<init>(MainFrame.java:239)
at net.java.sip.communicator.impl.gui.UIServiceImpl.loadApplicationGui(UIServiceImpl.java:133)
at net.java.sip.communicator.impl.gui.GuiActivator.start(GuiActivator.java:129)
at org.apache.felix.framework.util.SecureAction.startActivator(SecureAction.java:629)
at org.apache.felix.framework.Felix.activateBundle(Felix.java:1827)
at org.apache.felix.framework.Felix.startBundle(Felix.java:1744)
at org.apache.felix.framework.Felix.setActiveStartLevel(Felix.java:1148)
at org.apache.felix.framework.StartLevelImpl.run(StartLevelImpl.java:264)
at java.lang.Thread.run(Unknown Source)
I've created another project separated from Jitsi and I've tested my code following the same procedure (including java.sql.*; , adding the library), but the "new" project works fine and I can connect to my database, Jitsi doesn't.
Source:
import java.sql.*;
public class SQLFirstTime {
public static void main(String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/cdcol";
Connection con = DriverManager.getConnection(url,"user", "pass");
// ...
con.close();
} catch(SQLException sqlEx) {
System.out.println("Errore SQL");
sqlEx.printStackTrace();
} catch(ClassNotFoundException cnfEx) {
System.out.println("Class NOT FOUND!");
cnfEx.printStackTrace();
}
}
}
Thanks,
also if i'm using Ant to build the project how can I include the JDBC library?