Exception in thread "main" java.rmi.NotBoundException [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
i have problem that when i run my rmi server i got an exception notbound exception
even i export the remote object and bind it to registry
here is my remote interface code
import java.rmi.Remote;
public interface fact extends Remote {
public int factory(int a);
}
and here the interface implementation
public class factimport implements fact {
#Override
public int factory(int a) {
int mult=1;
for (int i=1;i<=a;i++)
mult=mult*i;
return mult;
}
}
and server code
import java.net.MalformedURLException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
public class Server extends UnicastRemoteObject {
/**
*
*/
private static final long serialVersionUID = 1L;
protected Server() throws RemoteException {
super();
}
public static void main() throws RemoteException, MalformedURLException{
factimport fi=new factimport();
Registry reg=LocateRegistry.createRegistry(1099);
reg.rebind("factobject", exportObject(fi));
System.out.println("server started");
}
}
and client
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Client {
/**
* #param args
* #throws NotBoundException
* #throws RemoteException
* #throws MalformedURLException
*/
public static void main(String[] args) throws MalformedURLException, RemoteException, NotBoundException {
// TODO Auto-generated method stub
Registry reg=LocateRegistry.getRegistry("127.0.0.1",1099);
factimport x=(factimport)reg.lookup("factobject");
System.out.println(x.factory(5));
}
}

Unless you're running the server and client on the same host, which makes RMI pretty pointless, your getRegistry() call in the client needs to be modified to point to the server host, not the client host (itself).
Your remote method must be declared to throw RemoteException in the remote interface.
Unless you have run rmic on the remote interface, which you can't have done or you would have detected (2), you need to change the exportObject() call to exportObject(fi, 0), for reasons explained in the preamble to the Javadoc for UnicastRemoteObject.
Your Server.main() method doesn't have a correct signature so it won't execute. It should be public static void main(String[] args) ...
You should make the Registry reg variable in the server static to prevent it from being garbage-collected.
In your client, your variable of type factimport should be of type fact, and you should cast the lookup result to fact.
If the BindException was really the result of running this code in this state on a single machine, it can only mean that you ignored runtime exceptions when starting the server.

Your code is a little unorthodox. I don't know if this will help, but it might.
Normally, the remote object implementation would extend UnicastRemoteObject. So, you have this factimport class:
public class factimport implements fact extends UnicastRemoteObject {
#Override
public int factory(int a) {
int mult=1;
for (int i=1;i<=a;i++)
mult=mult*i;
return mult;
}
}
And the server class:
public class Server {
/**
*
*/
private static final long serialVersionUID = 1L;
protected Server() throws RemoteException {
super();
}
public static void main() throws RemoteException, MalformedURLException{
factimport fi=new factimport();
Registry reg=LocateRegistry.createRegistry(1099);
reg.rebind("factobject", fi);
System.out.println("server started");
}
}
I hope this will work.

Related

com.sun.proxy.$Proxy0 cannot be cast to

I have the following RMI Connection code which returns a com.sun.proxy.$Proxy0 cannot be cast to Client.AdditionInterface error. I created two separate packages Client & Server and putted the Interface in both of them. Here is my complete code:
package Serveur;
import java.rmi.*;
import java.rmi.registry.LocateRegistry;
public class AdditionServer {
public static void main (String[] argv) {
try {
LocateRegistry.createRegistry(1099);
Addition Hello = new Addition();
Naming.rebind("rmi://"+java.net.InetAddress.getLocalHost().getHostName()+"/ABC", Hello);
System.out.println("Addition Server is ready.");
}
catch (Exception e) {
System.out.println("Addition Server failed: " + e);
}
}
}
//////////////////////////////////////
package Serveur;
import java.rmi.*;
import java.rmi.server.*;
public class Addition extends UnicastRemoteObject implements AdditionInterface {
public Addition () throws RemoteException {
super();
}
#Override
public int add(int a, int b) throws RemoteException {
int result=a+b;
return result;
}
#Override
public String aff(int a, int b) throws RemoteException {
return String.valueOf(add(a, b));
}
}
////////////////////////////
package Client;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface AdditionInterface extends Remote {
public int add(int a,int b) throws RemoteException;
public String aff(int a, int b) throws RemoteException;
}
////////////////////////////
package Client;
import java.rmi.*;
public class AdditionClient {
public static void main (String[] args) throws Exception {
AdditionInterface add = (AdditionInterface) Naming.lookup("rmi://"+java.net.InetAddress.getLocalHost().getHostName()+"/ABC");
System.out.println("Result is :"+add.add(9, 10));
System.out.println(add.aff(26, 45));
}
}
Any help please? Thank you.
As in both a Client.AdditionInterface for the client and a Server.AdditionInterface for the server? Effectively the error is saying Server.AdditionInterface cannot be cast to Client.AdditionInterface.
With RMI you must have the same interface class on both client and server, but then clearly the server implementation class (AdditionServer) just on the server. The interface could be in a shared package (e.g. common.AdditionInterface ).

Exception Exception is not compatible with throws clause in Server.main(String[]) [duplicate]

This question already has answers here:
What are reasons for Exceptions not to be compatible with throws clauses?
(4 answers)
Closed 4 years ago.
I'm running the Lip reading code on Eclipse Indigo from the following link :
https://github.com/sagioto/LipReading/blob/master/lipreading-core/src/main/java/edu/lipreading/WebFeatureExtractor.java
package main.java.edu.lipreading;
import com.googlecode.javacpp.BytePointer;
import com.googlecode.javacv.cpp.opencv_core;
import main.java.edu.lipreading.vision.AbstractFeatureExtractor;
import main.java.edu.lipreading.vision.NoMoreStickersFeatureExtractor;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketHandler;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.logging.Logger;
import static com.googlecode.javacv.cpp.opencv_core.CV_8UC1;
import static com.googlecode.javacv.cpp.opencv_core.cvMat;
import static com.googlecode.javacv.cpp.opencv_highgui.cvDecodeImage;
/**
* Created with IntelliJ IDEA.
* User: Sagi
* Date: 25/04/13
* Time: 21:47
*/
public class WebFeatureExtractor extends Server {
private final static Logger LOG = Logger.getLogger(WebFeatureExtractor.class.getSimpleName());
private final static AbstractFeatureExtractor fe = new NoMoreStickersFeatureExtractor();
public WebFeatureExtractor(int port) {
SelectChannelConnector connector = new SelectChannelConnector();
connector.setPort(port);
addConnector(connector);
WebSocketHandler wsHandler = new WebSocketHandler() {
public WebSocket doWebSocketConnect(HttpServletRequest request, String protocol) {
return new FeatureExtractorWebSocket();
}
};
setHandler(wsHandler);
}
/**
* Simple innerclass that is used to handle websocket connections.
*
* #author jos
*/
private static class FeatureExtractorWebSocket implements WebSocket, WebSocket.OnBinaryMessage, WebSocket.OnTextMessage {
private Connection connection;
public FeatureExtractorWebSocket() {
super();
}
/**
* On open we set the connection locally, and enable
* binary support
*/
#Override
public void onOpen(Connection connection) {
LOG.info("got connection open");
this.connection = connection;
this.connection.setMaxBinaryMessageSize(1024 * 512);
}
/**
* Cleanup if needed. Not used for this example
*/
#Override
public void onClose(int code, String message) {
LOG.info("got connection closed");
}
/**
* When we receive a binary message we assume it is an image. We then run this
* image through our face detection algorithm and send back the response.
*/
#Override
public void onMessage(byte[] data, int offset, int length) {
//LOG.info("got data message");
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
bOut.write(data, offset, length);
try {
String result = convert(bOut.toByteArray());
this.connection.sendMessage(result);
} catch (Exception e) {
LOG.severe("Error in facedetection, ignoring message:" + e.getMessage());
}
}
#Override
public void onMessage(String data) {
LOG.info("got string message");
}
}
public static String convert(byte[] imageData) throws Exception {
opencv_core.IplImage originalImage = cvDecodeImage(cvMat(1, imageData.length, CV_8UC1, new BytePointer(imageData)));
List<Integer> points = fe.getPoints(originalImage);
if(points == null)
return "null";
String ans = "";
for (Integer point : points) {
ans += point + ",";
}
return ans;
}
/**
* Start the server on port 999
*/
public static void main(String[] args) throws Exception {
WebFeatureExtractor server = new WebFeatureExtractor(9999);
server.start();
server.join();
}
}
In the following line :
public static void main(String[] args) throws Exception {
I'm getting the following error :
Exception Exception is not compatible with throws clause in Server.main(String[])
Please help me solve this.
There are two condition you need to check.
1) when declaring a method in interface you need to add throws exception for that method and similarly with the interface implementation class where the method is implemented.
for example
service.java
#Component
public interface UserService {
User getUser(Login login) throws Exception;
}
serviceimpl.java
public User getUser(Login login)throws Exception
{
}
2) by doing the above statement the error still doesn't vanish. make sure to save both the files.
Doest the server API handle all exceptions for itself. Why not try removing the throws in your code. I know its not good programming practice but might solve the problem.
The problem is that the Server class you are extending already contains a public static void main(String[]) method that does not have the same throws declaration. I didn't take a look at it, but I'd bet that method doesn't throw anything at all.
A solution would be to remove your throws clause in your main method and rely on try-catches instead.
EDIT: Why you cannot add a different throws clause in your case.
Let's assume the following scenario:
class A {
public static void foo() throws SomeException { ... }
}
class B extends A {
public static void foo() throws DifferentException { ... }
}
The Java standard says you are hiding the A.foo() method (or at least trying to). Thing is, you're only allowed to do that if the throws clause in B.foo() is already contained in the clause of A.foo(). So for the above scenario, you're perfectly legal only if DifferentException is a subclass of SomeException. Otherwise the compiler will yell.
I had the same issue, in my case I have implemented a method from an interface that did not declared to throw an exception.
In your case, I would guess that Server class also has a main method that didn't throw an exception. To quickly solve it. I would declare Server.main to throw an exception.
This link helped me
What are reasons for Exceptions not to be compatible with throws clauses?

Database object is not working with a working RMI package

I have 2 projects. One works fine in ever department. I downloaded and modified it to better understand it. The 2nd one is a project in development phase.
Now, both these projects have almost exactly the same RMI package, which works fine in the first project, but not in the 2nd.
My test classes in each package are essentially identical as well.
The main difference is what objects there are attempting to access, which are both interfaces in a database package.
Now, the database package in the 2nd project otherwise works absolutely fine, it just wont work with the RMI.
In short:
database package works fine
RMI package works fine
RMI package and database together does not work fine.
Here is my DBInterface
public interface DB extends Remote {
public String[] read(int recNo) throws RecordNotFoundException;
public void update(int recNo, String[] data, long lockCookie)
throws RecordNotFoundException, SecurityException, IOException;
public void delete(int recNo, long lockCookie)
throws RecordNotFoundException, SecurityException, IOException;
public int[] find(String[] criteria);
public int create(String[] data) throws DuplicateKeyException, IOException;
public long lock(int recNo) throws RecordNotFoundException;
public void unlock(int recNo, long cookie)
throws RecordNotFoundException, SecurityException;
}
and here is my RMIInterface
public interface RMIInterface extends Remote{
public DB getClient() throws RemoteException;
}
My RMIImplementation
public class RMIImplementation extends UnicastRemoteObject
implements RMIInterface {
private static String dbLocation = null;
private DB a;
public RMIImplementation() throws RemoteException{
}
public RMIImplementation(String dbLocation) throws RemoteException{
System.out.println(dbLocation);
this.dbLocation = dbLocation;
}
public static DB getRemote(String hostname, String port)
throws RemoteException {
String url = "rmi://" + hostname + ":" + port + "/DvdMediator";
try {
RMIInterface factory
= (RMIInterface) Naming.lookup(url);
// at this point factory equals Proxy[RMIInterface,................etc
// i want the return to equal Proxy[DB,..............etc
return (DB) factory.getClient();
} catch (NotBoundException e) {
throw new RemoteException("Dvd Mediator not registered: ", e);
}
catch (java.net.MalformedURLException e) {
throw new RemoteException("cannot connect to " + hostname, e);
}
}
public DB getClient() throws RemoteException {
try {
a = new ContractorDatabase(dbLocation);
}
catch(Exception e){
System.out.println("NewClass exception: " + e.toString());
}
return a;
}
And my the RMI registry
public class RegDvdDatabase {
private RegDvdDatabase() {
}
public static void register()
throws RemoteException {
register(".", java.rmi.registry.Registry.REGISTRY_PORT);
}
public static void register(String dbLocation, int rmiPort)
throws RemoteException {
Registry r = java.rmi.registry.LocateRegistry.createRegistry(rmiPort);
r.rebind("DvdMediator", new RMIImplementation(dbLocation));
}
}
Getting these two to work together throws a
Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy0 cannot be cast to sjdproject.remote.RMIImplementation
Can u please help me find the database issue that prevents it from working.
You must cast it to the remote interface.
EDIT The Registry reference r in your server code must be static. I can't see any good reason for locating the client lookup code inside the implementation class. That class should only exist at the server, not the client.
If you dont have a debugger, I would suggest using reflection on the provided object and see which interfaces it implements. It appears to be a proxy object, so must implement some interfaces.
for(Class clazz : factory.getClass().getInterfaces()) {
System.out.println(clazz.getSimpleName());
}
My suspicion with multiple deployments is of course the jvm version and the classpath. Can you verify that they match?

need help to run RMI Registry

I'm implementing a simple RMI Server Client program in JAVA. I'm new to this actually. i have four java files.
Stack.java
import java.rmi.*;
public interface Stack extends Remote{
public void push(int p) throws RemoteException;
public int pop() throws RemoteException;
}
StackImp.java
import java.rmi.*;
import java.rmi.server.*;
public class StackImp extends UnicastRemoteObject implements Stack{
private int tos, data[], size;
public StackImp()throws RemoteException{
super();
}
public StackImp(int s)throws RemoteException{
super();
size = s;
data = new int[size];
tos=-1;
}
public void push(int p)throws RemoteException{
tos++;
data[tos]=p;
}
public int pop()throws RemoteException{
int temp = data[tos];
tos--;
return temp;
}
}
RMIServer.java
import java.rmi.*;
import java.io.*;
public class RMIServer{
public static void main(String[] argv) throws Exception{
StackImp s = new StackImp(10);
Naming.rebind("rmi://localhost:2000/xyz", s);
System.out.println("RMI Server ready....");
System.out.println("Waiting for Request...");
}
}
RMIClient.java
import java.rmi.*;
public class RMIClient{
public static void main(String[] argv)throws Exception{
Stack s = (Stack)Naming.lookup("rmi://localhost:2000/xyz");
s.push(25);
System.out.println("Push: "+s.push());
}
}
I'm using JDK1.5. The sequence in which i compiled the files is, first i compiled Stack.java then i compiled StackImp.java then i used this command rmic StackImp this all was successful. But when i tried to run the registry this way rmiregistery 2000, command prompt took too long. Nothing happened. I'm doing this all at my home PC. And this PC is not on the network. Please suggest me what to do to successfully work with this program.
command prompt took too long. Nothing happened.
Nothing is supposed to happen - the registry is running, and you can now start your server from another command prompt.
Alternatively, if you're only running the one RMI server process on this machine you can run the registry in the same process as the RMI server:
import java.rmi.*;
import java.rmi.registry.*;
import java.io.*;
public class RMIServer{
public static void main(String[] argv) throws Exception{
StackImp s = new StackImp(10);
Registry reg = LocateRegistry.createRegistry(2000);
reg.rebind("xyz", s);
System.out.println("RMI Server ready....");
System.out.println("Waiting for Request...");
}
}
This way you don't need a separate rmiregistry command, just run the server (which includes the registry) and then the client (which talks to the registry that is running in the server process).

factory method pattern with class registration produces a nullpointer exception

well, i searched the internet to this problem but didn't find any proper solution
in http://www.oodesign.com/factory-pattern.html
the author described away to register classes using reflection or object creation
i tried the object creation approach by the following code:
the factory class
package com.mf.egyptse;
import java.util.HashMap;
public abstract class ParserFactory {
private static HashMap parsers;
static
{
parsers= new HashMap();
System.out.println("This is first static block");
}
static void putParser(Object key,Object parser)
{
parsers.put(key, parser);
}
static Object getParser(Object key)
{
return parsers.get(key);
}
}
each parser register itself in the factory:
public class NormalParser extends ParserFactory implements ParsingBehavior{
/**
* Define the number of nested columns or tags to be parsed
*/
final static int NO_OF_COLOUMNS = 13;
static String input = null;
static String[] elements= {"name","sector", "p.c", "open", "close", "chgpercent", "lastprice", "high", "low","value","volume","trades","marketcap"};
static
{
ParserFactory.putParser("normal", new NormalParser());
}
and the main is :
public class Main {
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
// NileParser.parseNile();
// OTCParser.parseOTC();
// NormalParser.parseNormal();
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
the interface is:
package com.mf.egyptse;
import java.io.File;
import java.io.IOException;
public interface ParsingBehavior {
void parseToXML(CharSequence input,File file) throws IOException;
}
this code return always nullpointer exception while executing. the porblem is that the static block don't executed. so what is the solution ?
As answered by "Snicolas", your problem is that the HashMap is not populated by the time its being used. Your static block in main should load all the necessary parser classes such that these classes register themselves first.
public class Main {
static {
// Load necessary parser classes
Class.forName("normal");
}
/**
* #param args
* #throws IOException
* #throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
ParsingBehavior parser = (ParsingBehavior) ParserFactory.getParser("normal");
parser.parseToXML(null, null);
}
}
Getparser should return a ParsingBehavior.
Cast inside it.
But your problem comes from the fact that your parser class is not loaded by the jvm, as it is not used by your main. So static code is not executed.
Your are mixing your factory with a bus. Let the main register your parser in the factory.

Categories