thanks for any help, I am a complete noob here but trying to learn.
the below code is simply trying to create a connection to a database. I am getting this error back:
java.lang.ClassNotFoundException: org.postgres.Driver
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 java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at CreateDB.main(CreateDB.java:11)
java.lang.ClassNotFoundException: org.postgres.Driver
having researched online the solution i come across is to check the library is added to to build path. i can confirm that i have (I think). to do this i right clicked the prject -> Properties -> Java Build Path -> external JARS and navigated to the postgresql - 42.41.4..jar which is located in "...\eclipse-workspace\libraries\"
I can see that the library is added under referenced libraries within the project.
not a clue now im stuck. any help is genuinely appreciated.
I am learning from here https://www.tutorialspoint.com/postgresql/postgresql_java.htm
import java.sql.Connection;
import java.sql.DriverManager;
public class CreateDB {
public static void main(String Args[]) {
Connection c = null;
try {
Class.forName("org.postgres.Driver");
c = DriverManager.getConnection("jdbc.postgresql://localhost:1080/VEM", "postgres", "Diablo12" ); //creates connection with U&P
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() +": " + e.getMessage());
System.exit(0);
}
System.out.println("Database opened successfully");
}
}
The correct driver name is: org.postgresql.Driver. So your code should look like this:
import java.sql.Connection;
import java.sql.DriverManager;
public class CreateDB {
public static void main(String args[]) {
Connection c = null;
try {
Class.forName("org.postgresql.Driver");
c = DriverManager.getConnection("jdbc.postgresql://localhost:1080/VEM", "postgres", "Diablo12" ); //creates connection with U&P
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() +": " + e.getMessage());
System.exit(0);
}
System.out.println("Database opened successfully");
}
}
The false driver name causes java to throw the ClassNotFoundException because the class with the passed name could not be found in the classpath.
Since Java 6 the loading of the driver via Class.forName() is not needed any more, like a_horse_with_no_name pointed out in his comment.
Related
I am working on a project to generate BIRT reports in PDF format. The application is not meant to be a web application. I tried to follow the Report Engine API example on this link http://wiki.eclipse.org/Simple_Execute_(BIRT)_2.1 but I get an error when I run (Run as -> Java Application) the code. My code is as below.
My code is as follows:
package birt.classicmodels.offices;
import java.util.logging.Level;
import org.eclipse.birt.core.framework.Platform;
import org.eclipse.birt.report.engine.api.EngineConfig;
import org.eclipse.birt.report.engine.api.EngineException;
import org.eclipse.birt.report.engine.api.IReportEngine;
import org.eclipse.birt.report.engine.api.IReportEngineFactory;
import org.eclipse.birt.report.engine.api.IReportRunnable;
import org.eclipse.birt.report.engine.api.IRunAndRenderTask;
import org.eclipse.birt.report.engine.api.PDFRenderOption;
public class ExecuteReport {
public static void main(String[] args) {
ExecuteReport er = new ExecuteReport();
try {
er.executeReport();
} catch(Exception ex) {
System.out.println(ex.toString());
}
}
public void executeReport() throws EngineException {
IReportEngine engine = null;
EngineConfig config = null;
IReportEngineFactory factory = null;
Object factoryObj = null;
try {
config = new EngineConfig();
config.setBIRTHome("C:\\birt-runtime-4.6.0-20160607\\ReportEngine");
config.setLogConfig("C:\\temp\\test", Level.FINEST);
Platform.startup(config);
factoryObj = Platform.createFactoryObject(IReportEngineFactory.EXTENSION_REPORT_ENGINE_FACTORY);
factory = (IReportEngineFactory) factoryObj;
engine = factory.createReportEngine(config);
// Open the report design
IReportRunnable design = null;
String designPath = "C:\\birt-runtime-4.6.0-20160607\\ReportEngine\\samples\\hello_world.rptdesign";
design = engine.openReportDesign(designPath);
IRunAndRenderTask task = engine.createRunAndRenderTask(design);
PDFRenderOption PDF_OPTIONS = new PDFRenderOption();
PDF_OPTIONS.setOutputFileName("C:\\temp\\test.pdf");
PDF_OPTIONS.setOutputFormat("pdf");
task.setRenderOption(PDF_OPTIONS);
task.run();
task.close();
engine.destroy();
} catch(final Exception ex) {
ex.printStackTrace();
} finally {
Platform.shutdown();
}
}
}
SETUP:
I installed the BIRT designer using the complete BIRT designer download.
I added all the .jars under the libs folder of the BIRT runtime folder to my build path.
The main method was not part of the example I added it with the intention of getting the report saved to my file system.
The design template I'm referencing is the design example that comes with the BIRT engine.
ISSUES:
When I run the code (Run as -> Java Application) I get the following errors:
A pop up dialog with the message:
Java Virtual Machine Launcher
Error: A JNI error has occured, please check your installation and try again
After I click OK on the message dialog, the console is populated with the following error:
Exception in thread "main" java.lang.NoClassDefFoundError:
org/eclipse/birt/core/framework/PlatformConfig
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
at java.lang.Class.privateGetMethodRecursive(Unknown Source)
at java.lang.Class.getMethod0(Unknown Source)
at java.lang.Class.getMethod(Unknown Source)
at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException:
org.eclipse.birt.core.framework.PlatformConfig
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)
I think you are missing following dependency
<dependency>
<groupId>org.eclipse.birt.runtime</groupId>
<artifactId>org.eclipse.birt.runtime</artifactId>
<version>4.6.0-20160607</version>
</dependency>
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.
This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
I am trying to connect to data base.Earlier it was working fine. but now some jars has got deleted or something I don't know (red cross were coming on them). But I downloaded all jars again (mysql-connector,commons-io-2.4)still I am getting classnotfound exception at Class.forName("com.mysql.jdbc.Driver");
Here is my code
package abc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBC_oracle {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1 load the driver class
Class.forName("com.mysql.jdbc.Driver");
//step2 create the connection object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_name", "pswrd");
//step3 create the statement object
Statement statement = connection.createStatement();
statement.executeUpdate("sql_query");
ResultSet rs=statement.executeQuery("sql_query");
while(rs.next())
System.out.println("I am triyng to print data");
//step5 close the connection object
connection.close();
}
}
This is error
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
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 java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at deiniteguide.JDBC_example.main(JDBC_example.java:24)
I have tried using try catch also it is not working for me.
If you are using netbeans, you can go to your library folder in your project. Right click and add library and select mysql driver. Sorry couldn't comment due to less reputation and it would be easier if you can post with what error message you get. Also use try catch in your program so that it will be easier to locate the error. Your code can be like this:
public class JDBC_oracle {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//step1 load the driver class
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(Exception e){
System.out.println("Class not found" +e);
//step2 create the connection object
try{
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/database_name","user_name", "pswrd");
}catch(Exception es){
System.out.println("connection couldn't be made "+es);
}
//step3 create the statement object
try{
Statement statement = connection.createStatement();
statement.executeUpdate("sql_query");
ResultSet rs=statement.executeQuery("sql_query"); }
catch(Exception er){
System.out.println("Query wasnot executed "+er);
}
while(rs.next())
System.out.println("I am triyng to print data");
//step5 close the connection object
connection.close();
}
}
I have a web app that needs to be able open a file locally on a client machine, with the ability to save the file after editing. The web app generates a document on the server in a folder that is shared out via WebDAV & FTP and this folder is mounted on the client machine.
I cannot use a file:// type URI as it would not permit saving back to the server.
I intend trying to solve the problem with a small java applet embedded in the web app that handles this file opening, but I am having difficulties with permissions in Java. (Java isn't my field of expertise). Anyhow, I've narrowed the code down to the following:
localfile.html
<html>
<body>
<input id="input" value="Call from Javascript" type="button" onclick="callApplet('/Users/conor/1.txt')">
<script type='text/javascript'>
function callApplet(path) {
applet = document.getElementById('localfile');
applet.openFile(path);
}
</script>
<applet id="localfile" code="localfile.class" archive="localfile.jar" width="150" height="50"></applet>
</body>
</html>
localfile.java
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.lang.*;
import java.text.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I have compiled, created a jar file and signed it from the java source.
This produces a page with two buttons - a Java one (for testing) and a Javascript one. The Java button works fine as expected - and I can save the file etc. I want to pass the file path to the applet though so it is really the Javascript button I wish to get working. The Javascript one throws the following though:
Stack Trace
java.security.AccessControlException: access denied ("java.awt.AWTPermission" "showWindowWithoutWarningBanner")
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:366)
at java.security.AccessController.checkPermission(AccessController.java:560)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
at java.awt.Desktop.checkAWTPermission(Desktop.java:239)
at java.awt.Desktop.open(Desktop.java:267)
at localfile.openFile(localfile.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSInvoke.invoke(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at sun.plugin.javascript.JSClassLoader.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MethodInfo.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass$MemberBundle.invoke(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke0(Unknown Source)
at sun.plugin2.liveconnect.JavaClass.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$DefaultInvocationDelegate.invoke(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo.doObjectOp(Unknown Source)
at sun.plugin2.main.client.LiveConnectSupport$PerAppletInfo$LiveConnectWorker.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)
I have also tried embedding the desktop.open call into a doPrivileged block, as follows:
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
but that throws error for javascript & java buttons as follows:
java.lang.SecurityException: class "localfile$1" does not match trust level of other classes in the same package
Any help would be appreciated.
Got it to work, so thought I'd post the solution here...
When I was compiling the java file with the doPrivileged call in it, the javac compiler creates two files - localfile.class and localfile$1.class. I wasn't sure initially what the localfile$1.class was and just presumed it was a temporary file of some sort. It was however a class file corresponding to the anonymous class within the doPrilileged block and needed to be included in the .jar file and properly signed.
So anyway, html file is as before, and final java file is as follows:
localfile.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.security.*;
public class localfile extends Applet {
private static final long serialVersionUID = 1L;
public localfile() {
Panel p = new Panel();
p.add(new Button("Call from Java"));
add("North",p);
}
public void openFile(String path) {
System.out.println("File: " + path);
final File ffile = new File(path);
System.out.println("Got file.");
if (Desktop.isDesktopSupported()) {
System.out.println("Desktop is supported.");
final Desktop desktop = Desktop.getDesktop();
System.out.println("Got Desktop Handle.");
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
try {
desktop.open(ffile);
} catch(Exception ex) {
ex.printStackTrace();
}
return null;
}
});
System.out.println("File Opened.");
}
}
public boolean action(Event evt, Object arg) {
openFile("/Users/conor/1.txt");
return true;
}
}
I also found that there was no need to have the javascript in the html file create the applet and insert it into the DOM. I think this was mentioned in the link #VGR linked to but it worked for me without it.
Thanks for all the help guys!
I've spent almost five hours trying to resolve this, to no avail. I've created an application that uses RMI. It compiles fine, but I can't it get it to run.
All my class files are in C:\Users\Benji\Desktop\ass2\build (short for "assignment"; nothing dirty). All source files are in C:\Users\Benji\Desktop\ass2\src.
I've put everything in a single package to make things more comprehensible (and changed the import statements in the source to reflect this).
I have put a batch file in C:\Users\Benji\Desktop\ass2\ . Its contains the execution statement:
java -classpath ./build -Djava.rmi.server.codebase=file:/C:/Users/Benji/Desktop/ass2/build -Djava.security.policy=broker.policy BrokerReception Broker 16890
(The two args "Broker" and "16890" are needed by the program).
The file broker.policy is also in C:\Users\Benji\Desktop\ass2\ . Its contents are:
grant
{
permission java.security.AllPermission;
};
(and yes, I realise this isn't a good security policy. I'll work on this later).
There are actually three Main classes, one for a client, one for a broker (a mediator for the client) and a server. I am trying to start the Broker. Code for the Broker interface is as follows:
import java.io.FileNotFoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
public interface Broker extends Remote
{
public boolean getAvailability(int startDate, int endDate) throws FileNotFoundException, RemoteException;
public ArrayList<CityInfo> getCities() throws FileNotFoundException, RemoteException;
public ArrayList<HotelInfo> getCityHotels(int cityNumber) throws FileNotFoundException, RemoteException;
public int getHotelRoomRate(int hotelNumber) throws FileNotFoundException, RemoteException;
public boolean makeBooking(String firstName, String lastName, String contact, String creditCardNo) throws FileNotFoundException, RemoteException;
}
And the implementation class:
import java.io.FileNotFoundException;
import java.util.ArrayList;
public class BrokerClientLiaison implements Broker
{
private BrokerDatabase directory;
private BrokerHotelsLiaison liaison;
public BrokerClientLiaison(BrokerDatabase directory, int activeHotelNumber)
{
this.liaison = new BrokerHotelsLiaison(activeHotelNumber);
this.directory = directory;
}
public boolean getAvailability(int startDate, int endDate) throws FileNotFoundException
{
return liaison.getAvailability(startDate, endDate);
}
public ArrayList<CityInfo> getCities() throws FileNotFoundException
{
return directory.getCities();
}
public ArrayList<HotelInfo> getCityHotels(int cityNumber) throws FileNotFoundException
{
return directory.getCityHotels(cityNumber);
}
public int getHotelRoomRate(int hotelNumber) throws FileNotFoundException
{
return liaison.getHotelRoomRate(hotelNumber);
}
public boolean makeBooking(String firstName, String lastName, String contact, String creditCardNo) throws FileNotFoundException
{
return liaison.makeBooking(firstName, lastName, contact, creditCardNo);
}
}
And finally, the main class to start the implementation class:
import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.SQLException;
public class BrokerReception
{
public static void main(String[] args)
{
System.out.println("Args are:");
for(String arg : args)
{
System.out.println(arg);
}
System.out.println();
try
{
BrokerDatabase directory = new BrokerDatabase();
directory.connect(args[0]);
int activeHotelNumber = Integer.parseInt(args[1]);
if(directory.checkActiveHotelExists(activeHotelNumber))
{
BrokerClientLiaison liaison = new BrokerClientLiaison(directory, activeHotelNumber);
Broker liaisonStub = (Broker) UnicastRemoteObject.exportObject(liaison, 0);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(Protocol.BROKER_INTERFACE_NAME, liaisonStub);
}
else
{
throw new FileNotFoundException();
}
}
catch(ArrayIndexOutOfBoundsException aioobe)
{
System.err.println("Args required:");
System.err.println("1. Name of database file");
System.err.println("2. Number of active hotel");
System.exit(1);
}
catch(ClassNotFoundException cnfe)
{
System.err.println("Couldn't load database driver");
System.exit(2);
}
catch(SQLException sqle)
{
System.err.println("Couldn't establish connection to database");
System.err.println("Check that the database has been properly registerd,");
System.err.println("and that you provided the correct name");
System.exit(3);
}
catch(NumberFormatException nfe)
{
System.err.println("Second argument must be an integer");
System.exit(4);
}
catch(FileNotFoundException fnfe)
{
System.err.println("The database contains no entries with that hotel number");
System.exit(5);
}
catch(RemoteException re)
{
System.err.println("Unable to bind as " + Protocol.BROKER_INTERFACE_NAME);
re.printStackTrace();
System.exit(6);
}
}
}
"Directory" in the above code is a class that accesses a database.
I don't know what other information I need to give. Can anybody tell me what I'm doing wrong?
Incidentally, I went back and did Oracle's RMI tutorial at http://download.oracle.com/javase/1.5.0/docs/guide/rmi/hello/hello-world.html, to see if I could figure out what's wrong. The tutorial makes no mention of codebase or security policy, but provides all the code and precise instructions for compilation and execution. I followed these instructions to the letter, and yet even this didn't work!
Stack trace:
java.rmi.ServerException: RemoteException occurred in server thread; nested exce
ption is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: Broker
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:396
)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:250)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:5
35)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTranspor
t.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport
.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:908)
at java.lang.Thread.run(Thread.java:662)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Stream
RemoteCall.java:255)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:
233)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:359)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at BrokerReception.main(BrokerReception.java:32)
Caused by: java.rmi.UnmarshalException: error unmarshalling arguments; nested ex
ception is:
java.lang.ClassNotFoundException: Broker
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:386
)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:250)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:5
35)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTranspor
t.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport
.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExec
utor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor
.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.ClassNotFoundException: Broker
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 java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at sun.rmi.server.LoaderHandler.loadProxyInterfaces(LoaderHandler.java:7
11)
at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:655)
at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:592)
at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:6
28)
at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294
)
at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStrea
m.java:238)
at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1530)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1492)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1
731)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1328)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:350)
... 12 more
if you are running your registry as a second process, it needs access to your remote classes. the easiest way to do this is to add the appropriate classpath argument to the commandline when starting the registry.
if you are trying to use remote class loading, i believe you need to setup an rmi security manager in your application, either on the commandline or in the main method. (personally, distributing the classes usually works for 99% of situations and is 100 times easier to get right).