Connect exception after notifyObservers - java

I'm getting this error:
Error al notificar: Connection refused to host: 192.168.1.6; nested
exception is: java.net.ConnectException: Connection refused: connect
After I try to notify the remoteObservers, in this case being a controller.
Here is some part of the code.
This is from the Server:
public void notificarObservadores(Object aux) throws RemoteException{
for(IRemoteObserver o: colObservadores){
try {
o.update(this, aux);
} catch (RemoteException ex) {
System.out.println("Error al notificar: " + ex.getMessage());
colObservadores.remove(this);
System.out.println("Eliminado observer remoto no conectable");
}
}
}
And this from the controller in the client:
public class ControladorMesa extends UnicastRemoteObject implements IRemoteObserver,ActionListener{
private IFachadaServidor servidor;
private iFrmMesa formulario;
public ControladorMesa(IFachadaServidor servidor, iFrmMesa frm) throws RemoteException{
this.servidor = servidor;
this.formulario = frm;
this.servidor.agregarObservador(this);
this.formulario.setController(this);
this.formulario.setListaProductos(servidor.obtenerProductos());
}
#Override
public void update(IFachadaServidor fachada, Object aux) throws RemoteException {
this.formulario.setListaProductosgregados(fachada.ProductosAgregados(this.formulario.getMesa()));
}

Related

channel is already closed due to channel error rabbitmq

I am triying to develop a publish/subscribe system using RabbitMQ. The RabbitMQ server is in my laptop.
I have coded the Consumer and Producer Classes. The producer is connected correctly to the broker, but I have a com.rabbitmq.client.ShutdownSignalException when I run the consumer class.
My code is as follow.
I have a Functions.class :
public class Functions {
public static String EXCHANGE_NAME = "exchange";
private static ConnectionFactory factory;
/**
* Initialization for ConnectionFactory
*/
static {
factory = new ConnectionFactory();
factory.setAutomaticRecoveryEnabled(true);
factory.setHost("localhost");
}
public static Connection createConnection() {
try {
return factory.newConnection();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}}
Then the MyCosumer.java Class:
public class MyConsumer {
private Connection connection;
private Channel channel;
private String queueName = "consumer";
public MyConsumer() {
}
public void connect() throws IOException {
connection = Functions.createConnection();
channel = connection.createChannel();
channel.exchangeDeclare(Functions.EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
channel.queueDeclare(queueName, true, false, false, new HashMap<String, Object>()).getQueue();
}
public void setRoutingKeys(String... keys) throws IOException {
for (String bindingKey : keys) {
channel.queueBind(queueName, Functions.EXCHANGE_NAME, bindingKey);
}
}
public void clearRoutingKeys(String... keys) throws IOException {
for (String bindingKey : keys) {
channel.queueUnbind(queueName, Functions.EXCHANGE_NAME, bindingKey);
}
}
public void recieveMessages() throws IOException {
Consumer consumer = new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + envelope.getRoutingKey() + "':'" + message + "'");
}
};
channel.basicConsume(queueName, true, consumer);
}
public void disconnect() throws IOException, TimeoutException {
channel.close();
connection.close();
}
}
And the MyProducer.java Class :
public class MyProducer {
private Connection connection;
private Channel channel;
public MyProducer() {
}
public void connect() throws Exception {
connection = Functions.createConnection();
channel = connection.createChannel();
channel.exchangeDeclare(Functions.EXCHANGE_NAME, "topic");
}
public void sendMessage(String routingKey, String message) throws IOException {
channel.basicPublish(Functions.EXCHANGE_NAME, routingKey, null, message.getBytes());
System.out.println(" [x] Sent '" + routingKey + "':'" + message + "'");
}
public void disconnect() throws IOException, TimeoutException {
channel.close();
connection.close();
}}
The main classes are as follow :
the Producer main:
public class MainProducer {
public static String[] categorias = { "Beauty", "Drinks", "Diary", "Vegetable" };
public static void main(String[] args) throws Exception {
MyProducer productor = new MyProducer();
productor.connect();
send(productor, categorias[1], "Makeup", "Discount 20% in loreal lipstick");
send(productor, categorias[0], "Soap", "2x1 in Herbal Essence soap");
send(productor, categorias[0], "Makeup", "Discount 10% in l'ocitane lipstick");
send(productor, categorias[0], "Loreal Makeup", "Discount 20% in loreal lipstick");
productor.disconnect();
}
private static void send(MyProducer productor, String categoria, String producto, String mensaje) {
String routingKey = "offers." + categoria + "." + producto;
try {
productor.sendMessage(routingKey, mensaje);
} catch (IOException e) {
e.printStackTrace();
}
}}
THe consumer Main:
public class MainConsumer {
public static void main(String[] args) throws Exception {
MyConsumer consumer = new MyConsumer();
consumer.connect();
consumer.setRoutingKeys("kern");
consumer.recieveMessages();
}}
The obtained exception is :
Exception in thread "main" java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:124)
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:120)
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:142)
at com.rabbitmq.client.impl.ChannelN.queueDeclare(ChannelN.java:952)
at com.rabbitmq.client.impl.recovery.AutorecoveringChannel.queueDeclare(AutorecoveringChannel.java:333)
at main.MyConsumer.connect(MyConsumer.java:44)
at main.MainConsumer.main(MainConsumer.java:7)
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - home node 'rabbit#souhaila-UX430UAR' of durable queue 'consumer' in vhost '/' is down or inaccessible, class-id=50, method-id=10)
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:443)
at com.rabbitmq.client.impl.AMQChannel.privateRpc(AMQChannel.java:263)
at com.rabbitmq.client.impl.AMQChannel.exnWrappingRpc(AMQChannel.java:136)
... 4 more
Caused by: com.rabbitmq.client.ShutdownSignalException: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - home node 'rabbit#souhaila-UX430UAR' of durable queue 'consumer' in vhost '/' is down or inaccessible, class-id=50, method-id=10)
at com.rabbitmq.client.impl.ChannelN.asyncShutdown(ChannelN.java:509)
at com.rabbitmq.client.impl.ChannelN.processAsync(ChannelN.java:340)
at com.rabbitmq.client.impl.AMQChannel.handleCompleteInboundCommand(AMQChannel.java:162)
at com.rabbitmq.client.impl.AMQChannel.handleFrame(AMQChannel.java:109)
at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:643)
at com.rabbitmq.client.impl.AMQConnection.access$300(AMQConnection.java:47)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:581)
at java.lang.Thread.run(Thread.java:748)

How can the RMI registry be stopped programatically? [duplicate]

A RMI server which works fine without the stopServer functionality.
public class HelloServer extends UnicastRemoteObject implements HelloInterface
{
private final static int PORT=1102;
private final String serverName="server";
private Timer timer;
public HelloServer() throws RemoteException
{
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new StopServerTask(), 5000);
}
#Override
public String serverResponse(String request) throws RemoteException
{
return "Hello"+request;
}
public static void main(String[] args)
{
try
{
HelloServer skeleton=new HelloServer();
System.out.println("Starting server");
skeleton.startServer();
System.out.println("Server started");
}
catch (RemoteException ex)
{
ex.printStackTrace();
}
}
public void startServer()
{
try {
HelloServer skeleton=new HelloServer();
Registry reg=LocateRegistry.createRegistry(PORT);
reg.rebind(serverName, skeleton);
System.out.println("Server is ready");
} catch (RemoteException ex)
{
Logger.getLogger(HelloInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void stopServer()
{
System.out.println("Stopping server");
try {
Registry rmiRegistry = LocateRegistry.getRegistry(PORT);
HelloInterface myService = (HelloInterface) rmiRegistry.lookup(serverName);
rmiRegistry.unbind(serverName);
UnicastRemoteObject.unexportObject(rmiRegistry, true);
} catch (NoSuchObjectException e)
{
e.printStackTrace();
} catch (NotBoundException e)
{
e.printStackTrace();
} catch (RemoteException ex) {
Logger.getLogger(HelloServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
class StopServerTask extends TimerTask
{
#Override
public void run()
{
stopServer();
}
}
}
Whenever stopServer() in invoked exception is thrown at
UnicastRemoteObject.unexportObject(rmiRegistry, true);
Here is the stack Trace
java.rmi.NoSuchObjectException: object not exported
at sun.rmi.transport.ObjectTable.unexportObject(ObjectTable.java:153)
at java.rmi.server.UnicastRemoteObject.unexportObject(UnicastRemoteObject.java:297)
at rmi.HelloServer.stopServer(HelloServer.java:84)
Things are same even when I clean the service object by using
UnicastRemoteObject.unexportObject(myService, true);
Could someone suggest a clean way to stop the server which also releases the port for reuse.
You need to store the result of LocateRegistry.createRegistry(), and unexport that. At present you're trying to unexport a stub.
I implemented a shutdown-service in my rmi-server. If I want to shut it down, I call it with a password. Simple Example:
public interface ShutdownInterface extends Remote {
public void shutdownService(String password) throws RemoteException;
}
The serverside implementation can look something like:
public class ShutdownService extends UnicastRemoteObject implements ShutdownInterface {
private static final long serialVersionUID = 1L;
private boolean doShutdown = false;
public ShutdownService() throws RemoteException {
super();
}
#Override
public void shutdownService(String password) throws RemoteException {
if ("abcde12345".equals(password)) {
System.out.println("shutdown requested.");
this.doShutdown = true;
} else {
System.out.println("wrong pwd for shutdown");
}
}
public boolean isDoShutdown() {
return this.doShutdown;
}
}
Now the server itself keeps a reference to this:
public class BackendServer {
public final static int RMI_PORT = 1974;
private Registry registry = null;
private ShutdownService shutdownService = null;
public BackendServer() throws RemoteException {
registry = LocateRegistry.createRegistry(RMI_PORT);
this.shutdownService = new ShutdownService();
}
public void initialize() throws AccessException, RemoteException, AlreadyBoundException {
shutdownService = new ShutdownService();
registry.bind("ShutdownService", shutdownService);
registry.bind("MyDataService", new MyDataService());
}
public void stop() throws NoSuchObjectException {
System.out.println("stopping rmi server.");
UnicastRemoteObject.unexportObject(registry, true);
System.exit(0);
}
public boolean shouldStop() {
return this.shutdownService.isDoShutdown();
}
public static void main(String args[]) {
try {
BackendServer bs = new BackendServer();
bs.initialize();
System.out.println("Server ready.");
while (!bs.shouldStop()) {
Thread.sleep(1000);
}
bs.stop();
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Of course, this can be realized in a more beautiful way, but this should give you an idea of how to easily implement a shutdown yourself. You can call it from the main client or from a small commandline-tool you code for your server.

Clean way to stop RMI server

A RMI server which works fine without the stopServer functionality.
public class HelloServer extends UnicastRemoteObject implements HelloInterface
{
private final static int PORT=1102;
private final String serverName="server";
private Timer timer;
public HelloServer() throws RemoteException
{
timer = new Timer(); //At this line a new Thread will be created
timer.schedule(new StopServerTask(), 5000);
}
#Override
public String serverResponse(String request) throws RemoteException
{
return "Hello"+request;
}
public static void main(String[] args)
{
try
{
HelloServer skeleton=new HelloServer();
System.out.println("Starting server");
skeleton.startServer();
System.out.println("Server started");
}
catch (RemoteException ex)
{
ex.printStackTrace();
}
}
public void startServer()
{
try {
HelloServer skeleton=new HelloServer();
Registry reg=LocateRegistry.createRegistry(PORT);
reg.rebind(serverName, skeleton);
System.out.println("Server is ready");
} catch (RemoteException ex)
{
Logger.getLogger(HelloInterface.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void stopServer()
{
System.out.println("Stopping server");
try {
Registry rmiRegistry = LocateRegistry.getRegistry(PORT);
HelloInterface myService = (HelloInterface) rmiRegistry.lookup(serverName);
rmiRegistry.unbind(serverName);
UnicastRemoteObject.unexportObject(rmiRegistry, true);
} catch (NoSuchObjectException e)
{
e.printStackTrace();
} catch (NotBoundException e)
{
e.printStackTrace();
} catch (RemoteException ex) {
Logger.getLogger(HelloServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
class StopServerTask extends TimerTask
{
#Override
public void run()
{
stopServer();
}
}
}
Whenever stopServer() in invoked exception is thrown at
UnicastRemoteObject.unexportObject(rmiRegistry, true);
Here is the stack Trace
java.rmi.NoSuchObjectException: object not exported
at sun.rmi.transport.ObjectTable.unexportObject(ObjectTable.java:153)
at java.rmi.server.UnicastRemoteObject.unexportObject(UnicastRemoteObject.java:297)
at rmi.HelloServer.stopServer(HelloServer.java:84)
Things are same even when I clean the service object by using
UnicastRemoteObject.unexportObject(myService, true);
Could someone suggest a clean way to stop the server which also releases the port for reuse.
You need to store the result of LocateRegistry.createRegistry(), and unexport that. At present you're trying to unexport a stub.
I implemented a shutdown-service in my rmi-server. If I want to shut it down, I call it with a password. Simple Example:
public interface ShutdownInterface extends Remote {
public void shutdownService(String password) throws RemoteException;
}
The serverside implementation can look something like:
public class ShutdownService extends UnicastRemoteObject implements ShutdownInterface {
private static final long serialVersionUID = 1L;
private boolean doShutdown = false;
public ShutdownService() throws RemoteException {
super();
}
#Override
public void shutdownService(String password) throws RemoteException {
if ("abcde12345".equals(password)) {
System.out.println("shutdown requested.");
this.doShutdown = true;
} else {
System.out.println("wrong pwd for shutdown");
}
}
public boolean isDoShutdown() {
return this.doShutdown;
}
}
Now the server itself keeps a reference to this:
public class BackendServer {
public final static int RMI_PORT = 1974;
private Registry registry = null;
private ShutdownService shutdownService = null;
public BackendServer() throws RemoteException {
registry = LocateRegistry.createRegistry(RMI_PORT);
this.shutdownService = new ShutdownService();
}
public void initialize() throws AccessException, RemoteException, AlreadyBoundException {
shutdownService = new ShutdownService();
registry.bind("ShutdownService", shutdownService);
registry.bind("MyDataService", new MyDataService());
}
public void stop() throws NoSuchObjectException {
System.out.println("stopping rmi server.");
UnicastRemoteObject.unexportObject(registry, true);
System.exit(0);
}
public boolean shouldStop() {
return this.shutdownService.isDoShutdown();
}
public static void main(String args[]) {
try {
BackendServer bs = new BackendServer();
bs.initialize();
System.out.println("Server ready.");
while (!bs.shouldStop()) {
Thread.sleep(1000);
}
bs.stop();
} catch (Exception e) {
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
}
}
}
Of course, this can be realized in a more beautiful way, but this should give you an idea of how to easily implement a shutdown yourself. You can call it from the main client or from a small commandline-tool you code for your server.

Connection refused to host using RMI

First of here is the Exception that I'm getting: http://i.imgur.com/dE5Ou.png
Just to give little background I'm trying to write simple RMI program that connects two remote computers (Client/Server) using java's RMI. I have my Server program up and running but when I run my Client program I get the exception showed above in the link. Since I'm telling it to connect to 192.168.0.104 why is it saying "Connection refused to host: 127.0.1.1"???
Client
public class Client
{
public static void main(String[] args)
{
ServerInterface server;
Registry registry;
try
{
registry = LocateRegistry.getRegistry("192.168.0.104", (new Integer(1099)).intValue());
server = (ServerInterface)Naming.lookup("//192.168.0.104/ServerTest");
String serverString = server.getAndSetMessage("Connecting");
System.out.println("Reply from the server is: " + serverString);
}
catch(Exception e)
{
e.printStackTrace();
System.exit(1);
}
}
}
Server
public class Server extends UnicastRemoteObject implements ServerInterface
{
static String hostName = "192.168.0.104";
String name;
public Server(String name) throws RemoteException
{
super();
this.name = name;
}
public String getAndSetMessage(String message) throws RemoteException
{
return("My name is " + name + " Thanks for message " + message);
}
public static void main(String args[])
{
try
{
String objectname = "ServerTest";
Server theServer = new Server(objectname);
Naming.rebind("//"+hostName+"/"+objectname,theServer);
System.out.println("//"+hostName+"/"+objectname);
System.out.println("I am Registered");
}
catch (Exception ex)
{
System.out.println(ex);
System.exit(1);
}
}
}
You could try to add the following code to the server:
System.setProperty("java.rmi.server.hostname", "192.168.0.104");

How to remotely shutdown a Java RMI Server

I have a very simple Java RMI Server that looks like the following:
import java.rmi.*;
import java.rmi.server.*;
public class CalculatorImpl extends UnicastRemoteObject implements Calculator {
private String mServerName;
public CalculatorImpl(String serverName) throws RemoteException
{
super();
mServerName = serverName;
}
public int calculate(int op1, int op2) throws RemoteException
{
return op1 + op2;
}
public void exit() throws RemoteException
{
try{
Naming.unbind(mServerName);
System.out.println("CalculatorServer exiting.");
}
catch(Exception e){}
System.exit(1);
}
public static void main(String args[]) throws Exception
{
System.out.println("Initializing CalculatorServer.");
String serverObjName = "rmi://localhost/Calculator";
Calculator calc = new CalculatorImpl(serverObjName);
Naming.rebind(serverObjName, calc);
System.out.println("CalculatorServer running.");
}
}
When I call the exit method, System.exit(1) throws the following exception:
CalculatorServer exiting.
java.rmi.UnmarshalException: Error unmarshaling return header; nested exception is:
java.io.EOFException
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:203)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:126)
at CalculatorImpl_Stub.exit(Unknown Source)
at CalculatorClient.<init>(CalculatorClient.java:17)
at CalculatorClient.main(CalculatorClient.java:29)
Caused by: java.io.EOFException
at java.io.DataInputStream.readByte(DataInputStream.java:243)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:189)
... 4 more
[2]+ Exit 1 java CalculatorImpl
What am I doing wrong in this method?
In case anyone is having a similar problem, I figured out the answer myself. Here is my exit() method:
public void exit() throws RemoteException
{
try{
// Unregister ourself
Naming.unbind(mServerName);
// Unexport; this will also remove us from the RMI runtime
UnicastRemoteObject.unexportObject(this, true);
System.out.println("CalculatorServer exiting.");
}
catch(Exception e){}
}
Actually just unregistering and immediately calling System.exit doesn't shut down cleanly. It basically breaks the connection before informing the client that the message was completed. What works is to start a small thread that shuts down the system like:
public void quit() throws RemoteException {
System.out.println("quit");
Registry registry = LocateRegistry.getRegistry();
try {
registry.unbind(_SERVICENAME);
UnicastRemoteObject.unexportObject(this, false);
} catch (NotBoundException e) {
throw new RemoteException("Could not unregister service, quiting anyway", e);
}
new Thread() {
#Override
public void run() {
System.out.print("Shutting down...");
try {
sleep(2000);
} catch (InterruptedException e) {
// I don't care
}
System.out.println("done");
System.exit(0);
}
}.start();
}
The thread is needed to be able to let something happen in the future while still returning from the quit method.

Categories