I have the typical error in Java. I have the next structure:
bin/
lib/
src/
junior/
databases/
homework/Main.java
My Main.java code is:
package junior.databases.homework;
import java.sql.*;
public class Main {
private static Connection connection = null;
public static void main(String[] args) throws SQLException, ClassNotFoundException {
initDatabase();
System.out.println("Done");
}
private static void initDatabase() throws SQLException, ClassNotFoundException {
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(
"jdbc:postgresql://192.168.136.129:5432/postgres", "postgres", "xxxx");
}
}
When I launch it like this:
root#debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src/junior/databases/homework# javac Main.java
root#debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src/junior/databases/homework#java Main
I got error:
Exception in thread "main" java.lang.NoClassDefFoundError: Main (wrong name: junior/databases/homework/Main)
I found in this post the solution Exception in thread "main" java.lang.NoClassDefFoundError: Hello
And my try:
root#debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src# javac junior/databases/homework/Main.java
root#debian:/python_codes/Junior/Level1/DB1/ORM/java/java/src# java junior.databases.homework.Main
works perfectly.
The problem is I can launch this code only from src/ folder((( Is there any way I can launch it from /src/junior/databases/homework folder? I need to go back to src each time I want to launch the code.
Here you are, assuming you are in src/junior/databases/homework directory:
javac ../../../junior/databases/homework/Main.java
java -cp ../../../ junior.databases.homework.Main
Related
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.
I'm getting NoClassDefFoundError exception when I run this main class through Eclipse
import org.json.simple.parser.JSONParser;
public class A {
public static void main(String args[]) throws IOException {
JSONParser jsonParser = new JSONParser();
// code
}
}
Exception:
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/parser/JSONParser
Caused by: java.lang.ClassNotFoundException: org.json.simple.parser.JSONParser
I am implementing below dependency in gradle file:
implementation 'com.googlecode.json-simple:json-simple:1.1.1'
Have you changed/set your classpath to your current project? Maybe that's why your program is giving you error
It's very interesting to use Class.forName() to load a class and get errors... I write one line code and get an error as above.
class UnsatisfiedLinkErrorTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Class.forName("java.net.SocketOutputStream"));
}
}
When I use java UnsatisfiedLinkErrorTest, I get an error:
> java UnsatisfiedLinkErrorTest
Exception in thread "main" java.lang.UnsatisfiedLinkError: java.net.SocketOutputStream.init()V
at java.net.SocketOutputStream.init(Native Method)
at java.net.SocketOutputStream.<clinit>(SocketOutputStream.java:44)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:259)
at UnsatisfiedLinkErrorTest.main(UnsatisfiedLinkErrorTest.java:3)
But when I run it in Idea, I get:
> java "-javaagent:/Applications/IntelliJ IDEA.app/Contents/lib/idea_rt.jar=49247:/Applications/IntelliJ IDEA.app/Contents/bin" UnsatisfiedLinkErrorTest
class java.net.SocketOutputStream
I don't know why in Idea I can get the true answer, (maybe jni?) I hope someone can tell me the reason. Thanks.
This question has been solved. I then cancelled the initialization of the class, then the error goes. The error is about the initialization, but not about finding the native library. So:
class UnsatisfiedLinkErrorTest {
public static void main(String[] args) throws ClassNotFoundException {
System.out.println(Class.forName("java.net.SocketOutputStream", false, null)); // will be okay!
}
}
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
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)?