Java runtime ClassNotFoundException - java

Just had a question about an odd runtime error that I'm having. I'm working with a JSON server that responds with a JSON object when prompted by an outside source. As of right now, however, I'm simply trying to get the JSON object up and running before sending it out. My code compiles without specifying any classpath, but when it comes to runtime, it throws a NoClassDefFoundError as seen here:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/lang/exception/NestableRuntimeException
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at ExampleServer.sendData(ExampleServer.java:76)
at ExampleServer.runServer(ExampleServer.java:30)
at ExampleServer.main(ExampleServer.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.lang.exception.NestableRuntimeException
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:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 15 more
My code follows here:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.lang.*;
import net.sf.json.*;
public class ExampleServer{
private DataOutputStream output;
private DataInputStream input;
private ServerSocket server;
private Socket connection;
public static void main(String[] args){
new ExampleServer().runServer();
}
public void ExampleServer(){
System.out.println("Server object created");
}
public void runServer(){
try{
server = new ServerSocket(12345,100);
while(true){
try{
waitForConnection();
getStreams();
processConnection();
sendData("Text");
} catch(Exception e){
System.out.println("Server Terminated Exception.");
} finally {
closeConnection();
}
}
} catch(Exception e){
e.printStackTrace();
}
}
private void waitForConnection(){
try{
System.out.println("Waiting for connection.");
connection = server.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
} catch (IOException e){
System.out.println(e);
}
}
private void getStreams() throws IOException{
output = new DataOutputStream(connection.getOutputStream());
input = new DataInputStream(connection.getInputStream());
System.out.println("Got streams");
}
private void processConnection() throws IOException{
sendData("This is a test message");
}
private void closeConnection(){
try{
if(output != null && connection != null){
sendData("SEVER>>> TERMINATE");
output.close();
connection.close();
}
} catch (IOException e){
e.printStackTrace();
}
}
private void sendData(String message){
try{
JSONObject g = new JSONObject();
g.put("message", message);
System.out.println(g.toString());
} catch (Exception e){
System.out.println("Error writing object");
}
}
}
and the JSON folder is in the same directory as ExampleServer.java, with the JSON classes residing in net/sf/json as specified in my imports. Why is it not working until runtime? Is my classpath not right for some reason? What would be the appropriate syntax for including a necessary classpath?
Thanks in advance

From json-lib homepage:
Json-lib requires (at least) the following dependencies in your
classpath:
jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6
That your implementation compiles only shows that the compiler can find the right classes and methods. The implementation of those classes and methods may however depend on other libraries.
More information on project dependencies can be found here.

Related

RMI client-server NotBoundException

I am trying to run the rmi tutorial on oracles' website. I am able to run the server, but I receive an error running the client. The error I receive when try to run the cleint is a noNotBoundException exception. How do I fix this error?
Below is the code and exception
Exception
Client exception: java.rmi.NotBoundException: Hello
java.rmi.NotBoundException: Hello
at sun.rmi.registry.RegistryImpl.lookup(RegistryImpl.java:166)
at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source)
at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:411)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:272)
at sun.rmi.transport.Transport$1.run(Transport.java:200)
at sun.rmi.transport.Transport$1.run(Transport.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(TCPTransport.java:683)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source)
at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at sun.rmi.registry.RegistryImpl_Stub.lookup(Unknown Source)
at example.hello.Client.main(Client.java:52)
Server
package example.hello;
import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class Server implements Hello {
public Server() {}
public String sayHello() {
return "Hello, world!";
}
public static void main(String args[]) {
try {
Server obj = new Server();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
// Bind the remote object's stub in the registry
Registry registry = LocateRegistry.getRegistry();
registry.bind("Hello", stub);
System.err.println("Server ready");
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Client
package example.hello;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
private Client() {}
public static void main(String[] args) {
String host = (args.length < 1) ? null : args[0];
try {
Registry registry = LocateRegistry.getRegistry(host);
Hello stub = (Hello) registry.lookup("Hello");
String response = stub.sayHello();
System.out.println("response: " + response);
} catch (Exception e) {
System.err.println("Client exception: " + e.toString());
e.printStackTrace();
}
}
}
Interface
package example.hello;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface Hello extends Remote {
String sayHello() throws RemoteException;
}
You need to launch the [RMI] registry. Method getRegistry() does not launch the registry. Method createRegistry(int) launches the registry. You need to change this line in your class Server
Registry registry = LocateRegistry.getRegistry();
to this
Registry registry = LocateRegistry.createRegistry(1099);
Note that 1099 is the default port used by RMI.

RMI: Connection refused to host - Editing /etc/hosts and setProperty() not working

I know that this question has been asked before but the answers I found so far did not help. I tried editing my /etc/hosts-file by adding the line
127.0.0.1 java.rmi.server.hostname
Next, I tried adding
System.setProperty("java.rmi.server.hostname","127.0.0.1");
to my code (also tried with my "external" IP-Address). However, I keep getting this error:
java.rmi.ConnectException: Connection refused to host: 192.168.178.22; nested exception is:
java.net.ConnectException: Connection refused
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(TCPEndpoint.java:619)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:216)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:202)
at sun.rmi.server.UnicastRef.newCall(UnicastRef.java:342)
at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source)
at java.rmi.Naming.rebind(Naming.java:177)
Here is my server's code:
public class CounterServer {
public static void main(String args[]) {
try {
System.setProperty("java.rmi.server.hostname","192.168.178.22");
LocateRegistry.createRegistry(4711);
ICounter counter = new Counter();
Naming.rebind("Counter", counter);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
Any ideas how I can get this fixed? I am running on a Mac OSX!
Holy moly, so stupid :-) The problem had nothing to do with setProperty() or my /etc/hosts. When you start your RMI-Registry from code, make sure to call rebind on that registry and not on Naming. Here is the correct code and everything runs like a charm!
public class CounterServer {
public static void main(String args[]) {
try {
Registry r = LocateRegistry.createRegistry(4711);
ICounter counter = new Counter();
r.rebind("Counter", counter);
} catch (RemoteException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

Unable to create new directory in documents or Program Files in Java

I apologize in advance if this is nooby, however I am new to dealing with files that are not in the same directory as the jar.
I'm unable to create new directory in documents or Program Files using the following:
private JSONObject readSaveFile() { // line 17
File file;
String programPath = new JFileChooser().getFileSystemView().getDefaultDirectory().toString();
System.out.println(programPath);
if (programPath != null) {
System.out.println(new File(programPath + "/HWFetcherSave").mkdir());
programPath += "/HWFetcherSave/data.json";
file = new File(programPath);
try {
file.createNewFile();
//TODO log error
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jsonObject = JSONUtils.readFile(file.getAbsolutePath());
if (jsonObject == null) jsonObject = new JSONObject();
return jsonObject;
}
return null;
}
And the trace:
C:\Users\Ethan\Documents
false
java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
at HomeworkFetcher.readSaveFile(HomeworkFetcher.java:27)
at HomeworkFetcher.main(HomeworkFetcher.java:14)
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:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
java.io.FileNotFoundException: C:\Users\Ethan\Documents\HWFetcherSave\data.json (The system cannot find the path specified)
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)
The specified path could not be used to find a file.
at JSONUtils.readFile(JSONUtils.java:58)
at HomeworkFetcher.readSaveFile(HomeworkFetcher.java:32)
at HomeworkFetcher.main(HomeworkFetcher.java:14)
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:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
What I'm really trying to do is save data to a location other than the desktop, however it seems that I can't do this. Anyone know something I don't?
By request, the static method in JsonUtils
public static JSONObject readFile(String path) {
try {
return readFile(new BufferedReader(new FileReader(path)));
} catch (FileNotFoundException e) {
System.out.println("The specified path could not be used to find a file.");
e.printStackTrace();
}
return null;
}
public static JSONObject readFile(BufferedReader reader) {
try {
return (JSONObject) new JSONParser().parse(reader);
} catch (ParseException e) {
System.out.println("Failed to parse file.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
return null;
}
Have you tried the following? :
JSONObject jsonObject = JSONUtils.readFile(file);
I don't know the version of the library which contains JSONUtils class, but i think its method "readFile" must have the file as parameter instead the path of the file.
I hope it helps.

Smack throws "java.lang.ClassNotFoundException: org.xmlpull.v1.XmlPullParserFactory:"

So im using Smack to run my chat bot for league of legends, however I can't even get the bot to show up because of a missing class error that I can't seem to figure out. Code and error below, Thanks for any help, -Nick
Also: yes, this code was taken from an example because when I tried it myself I still got the same error.
package com.nickparks.bot;
import java.util.*;
import java.io.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
public class JabberSmackAPI implements MessageListener{
XMPPConnection connection;
public void login(String userName, String password) throws XMPPException
{
ConnectionConfiguration config = new ConnectionConfiguration("chat.na1.lol.riotgames.com",5223);
connection = new XMPPTCPConnection(config);
try {
connection.connect();
connection.login(userName, password, "xiff");
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void displayBuddyList()
{
Roster roster = connection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
System.out.println("\n\n" + entries.size() + " buddy(ies):");
for(RosterEntry r:entries)
{
System.out.println(r.getUser());
}
}
public void disconnect()
{
try {
connection.disconnect();
} catch (SmackException.NotConnectedException e) {
e.printStackTrace();
}
}
public void processMessage(Chat chat, Message message)
{
if(message.getType() == Message.Type.chat)
System.out.println(chat.getParticipant() + " says: " + message.getBody());
}
public static void main(String args[]) throws XMPPException, IOException
{
// declare variables
JabberSmackAPI c = new JabberSmackAPI();
// Enter your login information here
c.login("bot", "Password");
c.displayBuddyList();
System.out.println("-----");
System.out.println("Who do you want to talk to? - Type contacts full email address:");
String talkTo = br.readLine();
System.out.println("-----");
System.out.println("All messages will be sent to " + talkTo);
System.out.println("Enter your message in the console:");
System.out.println("-----\n");
while( !(msg=br.readLine()).equals("bye"))
{
System.out.println("test");
}
c.disconnect();
System.exit(0);
}
}
And here's the error I get:
Exception in thread "main" java.lang.NoClassDefFoundError: org/xmlpull/v1/XmlPullParserFactory at org.jivesoftware.smack.SmackConfiguration.processConfigFile(SmackConfiguration.java:321)
atorg.jivesoftware.smack.SmackConfiguration.processConfigFile(SmackConfiguration.java:316)
at org.jivesoftware.smack.SmackConfiguration.<clinit>(SmackConfiguration.java:148)
at org.jivesoftware.smack.ConnectionConfiguration.<init>(ConnectionConfiguration.java:65)
at com.nickparks.bot.JabberSmackAPI.login(JabberSmackAPI.java:16)
at com.nickparks.bot.JabberSmackAPI.main(JabberSmackAPI.java:67)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
atsun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.lang.ClassNotFoundException: org.xmlpull.v1.XmlPullParserFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 11 more
You need to have XPP3 (XML Pull Parser 3) in your classpath. Smack 4 does no longer bundle it (unlike Smack 3).
I also recommend using a build system with dependency resolution like maven or gradle, which would automatically fetch the required dependencies.

I get NoClassDefFoundError, how can i fix it? [duplicate]

This question already has answers here:
Why am I getting a NoClassDefFoundError in Java?
(31 answers)
Closed 8 years ago.
when i run my java application with eclipse i don't get any problem but when i run it with the command prompt i get NoClassDefFoundError.
C:\Windows\System32>cd C:\Users\Caco\workspace\Bisquit_server\bin\bisquit_server
C:\Users\Caco\workspace\Bisquit_server\bin\bisquit_server>java ReceiveMsg
Exception in thread "main" java.lang.NoClassDefFoundError: ReceiveMsg (wrong nam
e: bisquit_server/ReceiveMsg)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:791)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:449)
at java.net.URLClassLoader.access$100(URLClassLoader.java:71)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)
C:\Users\Caco\workspace\Bisquit_server\bin\bisquit_server>
this is my java code:
package bisquit_server;
import java.io.*;
import java.net.*;
public class ReceiveMsg {
private ServerSocket server_socket;
private Socket socket;
ObjectInputStream input_stream;
private static String msg;
public ReceiveMsg() throws IOException, ClassNotFoundException{
try
{
server_socket=new ServerSocket(50000,1);
while(true){
listen();
System.out.print("Server is ready to connect to a client");
createStreams();
initProcessing();
}
}
finally {close();}
}
private void listen() throws IOException{
socket= server_socket.accept();
ReceiveMsgTh rmth = new ReceiveMsgTh();
Thread t = new Thread(rmth);
}
private void createStreams() throws IOException{
input_stream= new ObjectInputStream(socket.getInputStream());
}
private void initProcessing() throws ClassNotFoundException, IOException{
msg = "";
msg = (String)input_stream.readObject();
}
private void close() throws IOException{
if (input_stream!=null && socket != null){
input_stream.close();
socket.close();
}
}
public static void main(String[] args) //throws ClassNotFoundException, IOException
{
try {
new ReceiveMsg();
}
catch(ClassNotFoundException | IOException e){}
new Store().StoreMsg(msg,new String[]{"0987654321,"1234567890"},"1234567890");
}
}
package bisquit_server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class ReceiveMsgTh implements Runnable {
private ServerSocket server_socket;
private Socket socket;
ObjectInputStream input_stream;
public void StartProcess() throws IOException, ClassNotFoundException{
try
{
server_socket=new ServerSocket(50000,1);
while(true){
listen();
createStreams();
initProcessing();
}
}
finally {close();}
}
private void listen() throws IOException{
socket= server_socket.accept();
}
private void createStreams() throws IOException{
input_stream= new ObjectInputStream(socket.getInputStream());
}
private void initProcessing() throws ClassNotFoundException, IOException{
String msg = "";
msg = (String)input_stream.readObject();
new Store().StoreMsg(msg,new String[]{"0987654321","1234567890"},"1234567890");
}
private void close() throws IOException{
if (input_stream!=null && socket != null){
input_stream.close();
socket.close();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
StartProcess();
} catch (ClassNotFoundException | IOException e) {
// TODO Auto-generated catch block
}
}
}
package bisquit_server;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Store {
public void StoreMsg(String msg, String[] mobileNumbers, String whoWrite){
File f = new File("C:\\Users\\Caco\\workspace\\Conversations\\"+mobileNumbers[0]+mobileNumbers[1]+".txt");
try (
BufferedWriter bw = new BufferedWriter(new FileWriter(f,true));
)
{
bw.write(whoWrite);
bw.write(" ");
bw.write(msg);
bw.write("\r\n");
}
catch(IOException e) {
System.out.print("Error writing file");
}
}
}
I'm really frustrated because it's three days that i try to fix it without succes!
Can you help me?
Thankyou
Just
cd ..
java bisquit_server.ReceiveMsg
Remember, you don't execute files with the java command, but classes. You need to give the fully qualified class name to the java command.
Also, it mmust be possible to find the class file that contains the class. This is done via the so-called class-path, which is just the current directory when you don't give one. So, to find bisquit_server.ReceiveMsgjava will look up a directory bisquit_server/ in the class path and in that directory, it will look for the ReceiveMsg.class file.
This way, you can run your program from a different location:
cd /temp
java -cp C:\Users\Caco\workspace\Bisquit_server\bin bisquit_server.ReceiveMsg
run javac command first to create .class files. after that run with java command
javac ReceiveMsg.java
and after that
cd..
java bisquit_server.ReceiveMsg

Categories

Resources