Java JAR problem - java

My Java is very rusty and I'm having a bit of a headache here.
Here's my server.java:
import java.io.IOException;
import net.tootallnate.websocket.WebSocket;
import net.tootallnate.websocket.WebSocketServer;
public class server extends WebSocketServer
{
public server(int port)
{
super(port, Draft.AUTO);
}
public void onClientOpen(WebSocket conn)
{
System.out.println("onopen");
/*try
{
this.sendToAll(conn+" entered the room!");
}
catch(IOException ex)
{
ex.printStackTrace();
}*/
}
public void onClientClose(WebSocket conn)
{
System.out.println("onclose");
}
public void onClientMessage(WebSocket conn,String message)
{
System.out.println("onmessage"+message);
}
public static void main(String[] args)
{
int port = 8000;
try
{
port=Integer.parseInt(args[0]);
}
catch(Exception ex)
{
}
server s = new server(port);
s.start();
System.out.println("ChatServer started on port: "+s.getPort());
}
}
I need to include a jar file: ./Java-WebSocket/dist/WebSocket.jar (available from http://github.com/TooTallNate/Java-WebSocket/)
It compiles OK:
prompt> javac -classpath ./Java-WebSocket/dist/WebSocket.jar server.java
However, when I go to run:
prompt> java -classpath ./Java-WebSocket/dist/WebSocket.jar server
Exception in thread "main" java.lang.NoClassDefFoundError: server
Caused by: java.lang.ClassNotFoundException: server
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)
Could not find the main class: server. Program will exit.
I hope someone can help.
Thanks in advance,

java -classpath .:./Java-WebSocket/dist/WebSocket.jar server
^^
Or on Windows:
java -classpath .;./Java-WebSocket/dist/WebSocket.jar server
^^
The classpath defaults to the current directory. You need to point to your classes as well as the library.

Isn't server placed into a package ? If it is, specify the full class name.
e.g. prompt> java -classpath ./Java-WebSocket/dist/WebSocket.jar app.core.server
I would also uppercase the class name, though.

Have you tried using the full class name (your.package.server)?

Related

Error running RMI application in Visual Studio Code [duplicate]

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Why can't java find my class?

I have a class that compiles without error. The class has a main method. But when I try to run it on ubuntu linux from the classes' directory I get a class not found error. I am pretty sure I am missing something dead obvious but I don't see it.
Here is my ls operation:
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ ls
CreateGroup.java LsGroup.class LsGroup.java zookeeper-3.4.5.jar
Here is what happens when I to run LsGroup
zookeeper#zookeeper-virtual-machine:~/zookeeper-3.4.5/programs$ java -cp "zookeeper-3.4.5.jar" LsGroup
Exception in thread "main" java.lang.NoClassDefFoundError: LsGroup
Caused by: java.lang.ClassNotFoundException: LsGroup
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: LsGroup. Program will exit.
Here is the code for LsGroup
package org.zookeeper;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.Watcher.Event.KeeperState;
public class LsGroup implements Watcher {
private static final int SESSION_TIMEOUT = 5000;
private ZooKeeper zk;
private CountDownLatch connectedSignal = new CountDownLatch(1);
public void connect(String hosts) throws IOException, InterruptedException {
zk = new ZooKeeper(hosts, SESSION_TIMEOUT, this);
connectedSignal.await();
}
#Override
public void process(WatchedEvent event) { // Watcher interface
if (event.getState() == KeeperState.SyncConnected) {
connectedSignal.countDown();
}
}
public void ls(String groupName) throws KeeperException, InterruptedException {
String path = "/" + groupName;
try {
List<String> children = zk.getChildren(path, false);
for (String child : children) {
System.out.println(path+"/"+child);
System.out.println(zk.getChildren(path +"/"+ child, false));
}
} catch (KeeperException.NoNodeException e) {
System.out.printf("Group %s does not exist\n", groupName);
System.exit(1);
}
}
public void close() throws InterruptedException {
zk.close();
}
public static void main(String[] args) throws Exception {
LsGroup lsGroup = new LsGroup();
lsGroup.connect(args[0]);
lsGroup.ls(args[1]);
lsGroup.close();
}
}
The original problem was that your class was in a package, but you were trying to load it as if it weren't in a package. You'd normally organize your source code to match your package hierarchy, then from the root of the hierarchy, you'd run something like:
java -cp .:zookeeper-3.4.5.jar org.zookeeper.LsGroup
Now that you've temporarily worked around the package issue by moving the code out of a package, the next problem is that the current directory isn't in the classpath. So instead of this:
java -cp "zookeeper-3.4.5.jar" LsGroup
You want:
java -cp .:zookeeper-3.4.5.jar LsGroup
Once you've got that working, you should move the classes back into packages, as per normal Java best practice.
You could remove the package declaration:
package org.zookeeper;
...or just place your LsGroup class in org/zookeeper directory.
The class file is supposed to live in a path like:
org/zookeeper/LsGroup.class
The -cp must include the directory that contains the org/ directory. Then you can
java -cp parent-of-org org.zookeeper.LsGroup
The message "wrong name: org/zookeeper/LsGroup" means, you have to respect the package structure of Java. Use the following directory structure:
./org/zookeeper/LsGroup.class
Then launch java org.zookeeper.LsGroup from within the current directory. The package separator "." will be translated to corresponding directory.
Your files are not under package org.zookeeper
You should be running your class from ~/zookeeper-3.4.5/org/zookeeper
Otherwise JVM won't find the classes to load.
Your class is part of the org.zookeeper package but you keep it in the root folder of your project (/zookeeper-3.4.5/programs).
The qualified name of the package member and the path name to the file are parallel (see Managing Source and Class Files), so if your package is org.zookeeper the class file should be kept in /zookeeper-3.4.5/programs/org/zookeeper
You made two mistakes:
1) You tried to run java LsGroup but you have to use the complete name including packages java org.zookeeper.LsGroup
2) your directory structure is not correct: the package org.zookeeper corresponds with the directory structure ./org/zookeeper/
If you change the directory structure and then run java from the top of this directory structure it should work

Getting error while Connecting to oracle XE with NetBeans IDE

I am getting the following error while executing this code
import java.sql.*;
public class DatabaseConnectivityTest {
public static void main(String args[]) throws ClassNotFoundException
{
Connection conn=null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Trying to connect to database");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","hr","hr");
System.out.println("Connected");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}
The error that i am getting is
Exception in thread "main" java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
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 sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
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:169)
at DatabaseConnectivityTest.main(DatabaseConnectivityTest.java:10)
right click on your project folder --> Properties --> Java Build Path --> Libriaries --> Add External Jar --> Your sql connector jar file directory
i hope i was able to help you :)
this is due to you have not included oracle driver in the classpath
If you are using eclipse then try the following
right click on your project
click buildpath->configure build path
click libraries tab
click add external jars and give the path of oracledriver jar file
Try this code:
import java.sql.*;
public class DatabaseConnectivityTest {
public static void main(String args[]){
Connection conn=null;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch(ClassNotFoundException e) {
System.err.println("The driver is not loaded properly");
}
try
{
System.out.println("Trying to connect to database");
conn=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE","hr","hr");
System.out.println("Connected");
}
catch(SQLException e)
{
System.err.println("Error while connecting!");
}
}
}
This code will give you clear idea where your program is failing. If you are getting a message "The driver is not loaded properly then add them to the build path. Download the correct jar file and add them to your project.

rmi java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub

I'm programming a simple rmi application, and I have a problem.
If I run the registry in the same directory, it works; but if I change the directory from which I run the registry, it does not.
The registry would work generically from another host, but only the change of directory stop his functionality.
I'm working on this problem by 3 days without solution, I change also every possible configuration of the codebase parameter but nothing.
I describe the situation and code with the directory:
fileserver.java :
`package testrmi2;
import java.rmi.*;
public interface fileserver extends Remote {
public void scrivifile(String nomefile, String arg) throws RemoteException;
}
`
fileserverimpl.java:
package testrmi2;
import java.io.*;
import java.rmi.*;
import java.rmi.server.*;
public class fileserverimpl extends UnicastRemoteObject implements fileserver{
public fileserverimpl() throws RemoteException {
super();
}
public void scrivifile(String nomefile, String arg) throws RemoteException {
try {
FileWriter myfile = new FileWriter(nomefile);
myfile.write(arg);
myfile.close(); }
catch (Exception e) {System.out.println(e);}
}
public static void main (String arg[]) {
try {
fileserverimpl s = new fileserverimpl();
if (System.getSecurityManager() == null) {
System.setSecurityManager(new RMISecurityManager());
}
String codebase = System.getProperty("classpath");
System.out.println("Trying to access code base: " + codebase+"\n\nuse is "+System.getProperty("useCodebaseOnly"));
Naming.rebind("//127.0.0.1:2005/fileserverimpl", s);
System.out.println("Server attivato.");
} catch (Exception e) {System.out.println("errore inizializzazione server\n\n"+e.getMessage()+"\n\n\n");
}}}
client.java:
package testrmi2;
import java.rmi.*;
import java.io.*;
public class client {
public static void main (String arg[]) {
fileserver myserver;
String nomefile=" ";
String testo=" ";
System.out.println("Scrivi il nome del file");
nomefile=ReadString();
System.out.println("Scrivi il testo");
testo=ReadString();
try {
myserver = (fileserver) Naming.lookup("//127.0.0.1:2005/fileserverimpl");
myserver.scrivifile(nomefile, testo);
} catch (Exception e) {System.out.println(e);}
}
public static String ReadString() {
BufferedReader stdIn =new BufferedReader(new InputStreamReader(System.in));
String s=" ";
try{
s=stdIn.readLine();
}
catch(IOException e) {System.out.println(e.getMessage()); }
return s;
}
}
and the policy file is:
grant {
// Allow everything for now
permission java.security.AllPermission;
};
all this files are on the directory:
/Users/franco/Desktop/prova
to compiling it I goes in the /Users/franco/Desktop/prova directory and do in terminal :
javac -cp . -d . *.java
rmic rmic testrmi2.fileserverimpl
jar cvf testrmi2.jar testrmi2/fileserver.class testrmi2/fileserverimpl_Stub.class
after I run registry in another terminal with the following commands but in another directory:
export classpath=""
rmiregistry 2005 &
Finally I would to run the filesereveimpl.class goes with terminal in the /Users/franco/Desktop/prova directory and write :
java -classpath /Users/franco/Desktop/prova/ -Djava.rmi.server.codebase=file:/Users/franco/Desktop/prova/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
But the results are:
Trying to access code base: null
use is null
errore inizializzazione server
RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: testrmi2.fileserverimpl_Stub
I also try to public he jar on a local webserver xampp and try to run with the following:
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2/ -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
or with :
java -classpath . -Djava.rmi.server.codebase=http://127.0.0.1/testrmi2.jar -Djava.security.policy=testrmi2/policy testrmi2.fileserverimpl &
but I have the same results.
Try to set the classpath var before to execute the rmregistry:
export classpath="/Users/franco/Desktop/prova/"
rmiregistry 2005 &
There are three cases.
You got that exception in the server when exporting/constructing the remote object. Solution: run rmic to generate the stub.
You got it in the server when binding/rebinding. Solution: make the stub class available to the Registry's CLASSPATH, or run the Registry in the server JVM via LocateRegistry.createRegistry().
You got it in the client, in lookup(). Solution: make the stub class available to the client's CLASSPATH.
These also apply to the remote interface itself, and any application classes it depends on, and so on recursively until closure.
Solution for stubs to all three: take the measures outlined in the Javadoc preamble to UnicastRemoteObject, so you don't need a stub at all.

Java RMI ServerException - java.lang.ClassNotFoundException: org.prog.rmi.RmiServer_Stub

I have inherited some Java RMI client/server code, and while it runs fine on one machine, I haven't been able to get it to run in my dev environment.
The problem is when I run the server using the following java.exe -Djava.security.policy=conf\server.policy -SRC;. -Djava.library.path=. org.prog.rmi.RmiServer
I get the following error:
java.rmi.ServerException: RemoteException occurred in server thread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested exception is:
java.lang.ClassNotFoundException: org.prog.rmi.RmiServer_Stub (no security manager: RMI class loader disabled)
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:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
...
My server.policy file is
grant {
permission java.security.AllPermission;
};
And my java code:
package org.prog.rmi;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.RMISecurityManager;
import java.rmi.server.UnicastRemoteObject;
import java.rmi.registry.*;
public class RmiServer extends UnicastRemoteObject
implements RmiServerIntf {
private BatchApi bapi;
private String iniFileLocation;
private String layoutOption;
private int addressCount = 0;
private RefInt apiHandle = new RefInt();
public RmiServer(String iniFileLocation,String layoutOption) throws RemoteException
{ super();
this.iniFileLocation = iniFileLocation;
this.layoutOption = layoutOption;
initAPI();
startupAPI();
openAPI();
}
public static void main(String args[])
{
System.out.println("RMI server started");
// Create and install a security manager
if (System.getSecurityManager() == null)
{
System.setSecurityManager(new RMISecurityManager());
System.out.println("Security manager installed.");
}
else
System.out.println("Security manager already exists.");
try //special exception handler for registry creation
{
LocateRegistry.createRegistry(1099);
System.out.println("java RMI registry created.");
}
catch (RemoteException e)
{
//do nothing, error means registry already exists
System.out.println("java RMI registry already exists.");
}
try
{
//Instantiate RmiServer
for (String arg: args){
System.out.println(arg);
}
RmiServer obj = new RmiServer(args[0],args[1]);
// Bind this object instance to the name "RmiServer"
Naming.rebind("//127.0.0.1/RmiServer", obj);
System.out.println("PeerServer bound in registry");
}
catch (Exception e)
{
System.err.println("RMI server exception:");
e.printStackTrace();
}
}
}
I've seen solutions relating to the java.rmi.server.codebase but didn't have any luck setting this either
You haven't regenerated the stub with rmic, or the Registry doesn't have access to it via its classpath.
After some further investigation and following RMI tutorials it appeared that there was a problem with the RMI registration server on port 1099.
When I stared the RMI registration server on another port (e.g. 2005) and changed these lines of code
LocateRegistry.createRegistry(2005);
and
Naming.rebind("//127.0.0.1:2055/RmiServer", obj);
This ran sucessfully without errors and my client was able to connect.
I hope this answer helps others with this error. Let me know if anyone needs any more detailed information.

Categories

Resources