Not able to invoke remote method in RMI communication - rmi

I am trying to execute one RMI program but i am getting exception when i try to call the remote method from RMI client program.
Server program:
import java.rmi.*;
import java.rmi.registry.*;
import java.rmi.server.*;
public class Hello extends UnicastRemoteObject implements HelloInterface {
private String message;
public Hello() throws RemoteException{
int port=1024;
Registry registry;
try{
registry = LocateRegistry.createRegistry(port);
registry.rebind("samplermi", this);
System.out.println ("Server started and listening on port " + port);
}
catch(RemoteException e){
System.out.println("remote exception"+ e);
}
}
public String sayHi (String name) throws RemoteException {
message = "Hi .. Welcome " + name;
return message;
}
public static void main(String args[]){
try{
Hello serverObj = new Hello();
}
catch (Exception e){
e.printStackTrace();
System.exit(1);
}
}
}
Client Program:
registry=LocateRegistry.getRegistry(serverAddress,serverPort);
if(registry !=null){
String[] availRemoteServices = registry.list();
for(int i=0;i<availRemoteServices.length;i++){
System.out.println("Service " + i + ": " +availRemoteServices[i]);
}
}
rmiServer=(HelloInterface)(registry.lookup("samplermi"));
System.out.println("calling remote method!");
// call the remote method
welcomeMsg = rmiServer.sayHi(text);
System.out.println("Message from server: " + welcomeMsg);
I am getting connection exception only at the time of calling the remote method sayHI. It works fine for lookup and listing the service name.
R:\Deptapps\itdm\Sample_RMI>java NewSampleRMIClient
Getting Registry Object from server!!
Registry Object Created!!
Service 0: samplermi
Services listed successfully!
Look up successful!
calling remote method!
java.rmi.ConnectException: Connection refused to host; nested exception is:
java.net.ConnectException: Connection timed out: connect
at sun.rmi.transport.tcp.TCPEndpoint.newSocket(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.createConnection(Unknown Source)
at sun.rmi.transport.tcp.TCPChannel.newConnection(Unknown Source)
at sun.rmi.server.UnicastRef.invoke(Unknown Source)
at Hello_Stub.sayHi(Unknown Source)
at NewSampleRMIClient.main(NewSampleRMIClient.java:42)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
Note: The same program is working correctly when running server in solaris and client from windows. It is not working only when running server in AIX and client from windows.
Kindly can someone help in resolving this issue. I have been trying to fix this issue since 2 days but no use. Please help me!!

This is covered in Item A.1 of the RMI FAQ.

Run rmiregistry.exe before running Hello.class, it solved my problem.

RMi Working on the default port 1099. So no need to create the port.. If you are using default port number then exception may not be fired. and program may work properly.

Related

How to catch SOAP request message in CXF with WSS4JOutInterceptor when connection fails

I can catch SOAP request message according to
this SO answer.
However if the server is unavailable I get the following exception from SAAJOutInterceptor (added by WSS4JOutInterceptor) and LoggingCallback is not invoked hence message is not caugth:
org.apache.cxf.binding.soap.SoapFault: Connection refused: connect
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:221)
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:174)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308)
at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:531)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:440)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:355)
at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:313)
at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:140)
...
Caused by: com.ctc.wstx.exc.WstxIOException: Connection refused: connect
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:262)
at org.apache.cxf.binding.soap.saaj.SAAJOutInterceptor$SAAJOutEndingInterceptor.handleMessage(SAAJOutInterceptor.java:215)
...
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1199)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.setupWrappedStream(URLConnectionHTTPConduit.java:274)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleHeadersTrustCaching(HTTPConduit.java:1345)
at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.onFirstWrite(HTTPConduit.java:1306)
at org.apache.cxf.transport.http.URLConnectionHTTPConduit$URLConnectionWrappedOutputStream.onFirstWrite(URLConnectionHTTPConduit.java:307)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:47)
at org.apache.cxf.io.AbstractThresholdOutputStream.unBuffer(AbstractThresholdOutputStream.java:89)
at org.apache.cxf.io.AbstractThresholdOutputStream.write(AbstractThresholdOutputStream.java:63)
at org.apache.cxf.io.CacheAndWriteOutputStream.write(CacheAndWriteOutputStream.java:80)
at org.apache.cxf.io.CacheAndWriteOutputStream.write(CacheAndWriteOutputStream.java:80)
at org.apache.cxf.io.AbstractWrappedOutputStream.write(AbstractWrappedOutputStream.java:51)
at com.ctc.wstx.io.UTF8Writer.flush(UTF8Writer.java:100)
at com.ctc.wstx.sw.BufferingXmlWriter.flush(BufferingXmlWriter.java:242)
at com.ctc.wstx.sw.BaseStreamWriter.flush(BaseStreamWriter.java:260)
...
I need to save request SOAP message with all the security stuff added by WSS4JOutInterceptor (certificate, signature ...) regardless of whether the message was successfully send or whether the server is even up.
The thing is that you must first write to the output stream where you catch the message and write to network connection only in onClose callback:
class RequestInterceptor extends AbstractPhaseInterceptor<Message> {
OutputStream outputStream
OutputStream originalOutputStream
public RequestInterceptor() {
super(Phase.PRE_STREAM);
}
#Override
public void handleMessage(Message message) throws Fault {
originalOutputStream = message.getContent(OutputStream.class)
CacheAndWriteOutputStream newOutputStream = new CacheAndWriteOutputStream(outputStream)
message.setContent(OutputStream.class, newOutputStream)
newOutputStream.registerCallback(new CachedOutputStreamCallback() {
void onFlush(CachedOutputStream cos) {
}
void onClose(CachedOutputStream cos) {
cos.writeCacheTo(originalOutputStream)
originalOutputStream.close()
}
})
}
}

Hazelcast need to be connected as client in the existing cluster instead of member

The changes which I made in server side:
#Bean(name = {"hazelcast"})
public HazelcastInstance hazelcastInstance() {
ClientConfig clientConfig = new ClientConfig();
clientConfig.getGroupConfig().setName(integrationSettings.getHazelcastClusterGroupName())
.setPassword(integrationSettings.getHazelcastClusterGroupPass());
final ClientNetworkConfig clientNetworkConfig = new ClientNetworkConfig();
clientNetworkConfig.addAddress("127.0.0.1:6701");
clientConfig.setNetworkConfig(clientNetworkConfig);
clientConfig.setInstanceName("INTEGRATION_INSTANCE");
final String hazelcastEnterpriseLicenseKey = null;
if (hazelcastEnterpriseLicenseKey != null) {
clientConfig.setLicenseKey(hazelcastEnterpriseLicenseKey);
}
return HazelcastClient.newHazelcastClient(clientConfig);
}
I will be getting my groupname and password from my property file.
My client side code:
ClientConfig clientConfig = new ClientConfig();
clientConfig.getGroupConfig().setName(hazelcastGroupName).setPassword(hazelcastGroupPwd);
clientConfig.getNetworkConfig().addAddress(serverAddress);
hazelcastInstance = HazelcastClient.newHazelcastClient(clientConfig);
My error log:
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.hazelcast.core.HazelcastInstance]: Factory method 'hazelcastInstance' threw exception; nested exception is java.lang.IllegalStateException: Unable to connect to any address in the config! The following addresses were tried: [[127.0.0.1]:6701]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 37 more
Caused by: java.lang.IllegalStateException: Unable to connect to any address in the config! The following addresses were tried: [[127.0.0.1]:6701]
at com.hazelcast.client.spi.impl.ClusterListenerSupport.connectToCluster(ClusterListenerSupport.java:178)
at com.hazelcast.client.spi.impl.ClientClusterServiceImpl.start(ClientClusterServiceImpl.java:189)
at com.hazelcast.client.impl.HazelcastClientInstanceImpl.start(HazelcastClientInstanceImpl.java:404)
at com.hazelcast.client.HazelcastClientManager.newHazelcastClient(HazelcastClientManager.java:78)
at com.hazelcast.client.HazelcastClient.newHazelcastClient(HazelcastClient.java:72)
at com.zafin.zrpe.integration.config.ZrpeIntegrationConfiguration.hazelcastInstance(ZrpeIntegrationConfiguration.java:85)
at com.zafin.zrpe.integration.config.ZrpeIntegrationConfiguration$$EnhancerBySpringCGLIB$$7af6798e.CGLIB$hazelcastInstance$6(<generated>)
at com.zafin.zrpe.integration.config.ZrpeIntegrationConfiguration$$EnhancerBySpringCGLIB$$7af6798e$$FastClassBySpringCGLIB$$25f010cb.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:358)
at com.zafin.zrpe.integration.config.ZrpeIntegrationConfiguration$$EnhancerBySpringCGLIB$$7af6798e.hazelcastInstance(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 38 more
I need to connect my hazelcast as a client, but this bean exception is failing the deployments. Is there is any other way of doing it?
Looking at your code you are creating "Hazelcast-Client" on the server side and Client Side. In the server side code , please create a hazelcast ServerMember instance by passing "Config" object and not "ClientConfig" more like
#Bean
public HazelcastInstance hazelcastInstance() throws Exception {
Config cfg = new Config();
...
...
HazelcastInstance instance = Hazelcast.newHazelcastInstance(cfg);
return instance;
}
The the Hazelcast-client can connect to the Hazelcast ServerMember. You also need to ensure the ServerMember is started before client can connect to it.

java.net.SocketTimeoutException: connect timed out when connecting to postgresql using jdbc

We are planning to switch DB from Oracle to PostgreSQL. After creating tables, I am about to load actual data into PostgreSQL tables. In order to do it, I connect to db using JDBC. It gives me error like below.
Connection Failed! Check output console
org.postgresql.util.PSQLException: The connection attempt failed.
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:275)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:49)
at org.postgresql.jdbc.PgConnection.<init>(PgConnection.java:194)
at org.postgresql.Driver.makeConnection(Driver.java:450)
at org.postgresql.Driver.connect(Driver.java:252)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at JDBCExample.main(JDBCExample.java:31)
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at org.postgresql.core.PGStream.<init>(PGStream.java:68)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:144)
... 7 more
At first I thought that data loading may take time and could cause this kind of problem, but I tested with following JDBC connection java. It still returns same error like above.
public class JDBCExample {
public static void main(String[] argv) {
System.out.println("-------- PostgreSQL "
+ "JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://aaa.bbb.ccc.ddd:5432/test", "tom",
"secret");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
catch (Exception e) {
e.printStackTrace();
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
}
}
In this case, what should I check first? There is some log file recording these errors in Postgresql? Is this something related with firewall? I even do not know our coporate has firewall? Could you give some guidance for this issue?

Cannot send request to MQSeries service

Im trying to send request with such code
import com.ibm.mq.jms.*;
import com.ibm.msg.client.wmq.WMQConstants;
import javax.jms.Session;
import javax.jms.TextMessage;
public class MQSend {
public static void main(String[] args)
{
try {
MQQueueConnectionFactory cf = new MQQueueConnectionFactory();
cf.setHostName("blabla");
cf.setPort(15000);
cf.setIntProperty(WMQConstants.WMQ_CONNECTION_MODE, WMQConstants.WMQ_CM_CLIENT);
cf.setQueueManager("");
cf.setChannel("blabla");
MQQueueConnection connection = (MQQueueConnection) cf.createQueueConnection("blabla","blabla");
MQQueueSession session = (MQQueueSession) connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
MQQueue queue = (MQQueue) session.createQueue("blabla");
MQQueueSender sender = (MQQueueSender) session.createSender(queue);
long uniqueNumber = System.currentTimeMillis() % 1000;
TextMessage message = (TextMessage) session.createTextMessage("Basic Queue Test "+ uniqueNumber);
// Start the connection
connection.start();
// sender.send(message);
System.out.println("Sent message to Queue MyTestQueue: " + message.getText());
// sender.close();
session.close();
connection.close();
System.out.println("Message Sent OK.\n");
}
catch (Exception ex) {
System.out.println(ex);
System.out.println("Message Send Failure\n");
}
}
}
I got
Exception in thread "main" java.lang.NoClassDefFoundError: com/ibm/msg/client/commonservices/trace/Trace
at com.ibm.msg.client.jms.internal.JmsReadablePropertyContextImpl.<clinit>(JmsReadablePropertyContextImpl.java:51)
at com.hsbc.hbfr.test.automation.tools.jrb.plugins.itm.MQSend.main(MQSend.java:14)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.ClassNotFoundException: com.ibm.msg.client.commonservices.trace.Trace
So issue is that java can't get appropriate jar for com/ibm/msg/client/commonservices/trace/Trace
But I even don't use such dependency in code, any suggestions?
thanks
Did you install MQ Client on the server? Did you put ALL of the MQ jar files in the CLASSPATH as per the docs? Looks like you missed at least one.

rmi java.lang.ClassNotFoundException: RMIServerImpl_Stub

when i start rmiserver implementation class it displays this error message
Remote exception: java.rmi.ServerException: RemoteException occurred in server t
hread; nested exception is:
java.rmi.UnmarshalException: error unmarshalling arguments; nested excep
tion is:
java.lang.ClassNotFoundException: RMIServerImpl_Stub
commands ran
start rmiregistry
start java -Djava.security.policy=policyfile RMIServerImpl
what can i do to resolve this. Please help
This is my rmi server code
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;
public class RMIServerImpl extends UnicastRemoteObject
implements RMIServer {
RMIServerImpl() throws RemoteException {
super();
}
public static void main(String args[]) {
try {
System.setSecurityManager(new RMISecurityManager());
RMIServerImpl Server = new RMIServerImpl();
Naming.rebind("SAMPLE-SERVER", Server);
System.out.println("Server waiting.....");
} catch (java.net.MalformedURLException mue) {
System.out.println("Malformed URL: " + mue.toString());
} catch (RemoteException re) {
System.out.println("Remote exception: " + re.toString());
}
}
}
Sounds like you didn't run the rmic compiler to generate stubs and skeletons.
It's been so long since I've done raw RMI by hand that I don't know if that step is still required. But it was the last time I did RMI.
If you did run rmic, then I'd guess that you didn't package the stub and skeleton properly with the server and client sides. If you can find those .class files, check your packaging and deployment.