How to solve "javax.management.InstanceNotFoundException" when accessing JBoss 5.1.0.GA 's mbeans? - jboss5.x

I have the following error when accessing JBoss 5.1.0.GA's mebeans.
Exception in thread "main" javax.management.InstanceNotFoundException: jboss.system:type=ServerInfo
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getMBean(DefaultMBeanServerInterceptor.java:1094)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.getAttribute(DefaultMBeanServerInterceptor.java:662)
at com.sun.jmx.mbeanserver.JmxMBeanServer.getAttribute(JmxMBeanServer.java:638)
at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1404)
at javax.management.remote.rmi.RMIConnectionImpl.access$200(RMIConnectionImpl.java:72)
at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1265)
at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1360)
at javax.management.remote.rmi.RMIConnectionImpl.getAttribute(RMIConnectionImpl.java:600)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:305)
at sun.rmi.transport.Transport$1.run(Transport.java:159)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Transport.java:155)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:535)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:790)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:649)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(StreamRemoteCall.java:255)
at sun.rmi.transport.StreamRemoteCall.executeCall(StreamRemoteCall.java:233)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:142)
at com.sun.jmx.remote.internal.PRef.invoke(Unknown Source)
at javax.management.remote.rmi.RMIConnectionImpl_Stub.getAttribute(Unknown Source)
at javax.management.remote.rmi.RMIConnector$RemoteMBeanServerConnection.getAttribute(RMIConnector.java:878)
at test.mbean.JBossJMXClient.main(JBossJMXClient.java:30)
Here is my java class;
public class JBossJMXClient {
public static void main(String[] args) throws Exception {
String host = "192.168.0.249";// Your JBoss Bind Address default is
// localhost
int port = 4545; // management-native port
String urlString = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port
+ "/jmxrmi";
System.out.println(" \n\n\t**** urlString: " + urlString);
JMXServiceURL serviceURL = new JMXServiceURL(urlString);
JMXConnector jmxConnector = JMXConnectorFactory.connect(serviceURL,
null);
MBeanServerConnection connection = jmxConnector
.getMBeanServerConnection();
// Invoke on the JBoss AS MBean server
int count = connection.getMBeanCount();
System.out.println(count);
ObjectName objectName = new ObjectName("jboss.system:type=ServerInfo");
String javaVersion = (String)connection.getAttribute(objectName, "JavaVersion");
System.out.println(javaVersion);
jmxConnector.close();
}
}
I already ckecked firewall.It has no problem.How to solve this issue?

Try to use the RMI default port: 1090. Indeed, do a little change in your URL to;
String urlString = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxconnector";
Look at the last part of url: from "jmxrmi" to "jmxconnector".

Related

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.

Groovy program to connect mongo db

I am trying to connect mongodb using Groovy language but i am getting error like this (which is posted below) and i have added necessary jar file.I am using mongodb verion : mongodb-driver-3.2.2.jar .
Please help me to solve this problem
Exception in thread "main" java.lang.NoClassDefFoundError: com/mongodb/operation/OperationExecutor
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getDeclaredConstructors(Unknown Source)
at org.codehaus.groovy.reflection.CachedClass$2$1.run(CachedClass.java:69)
at java.security.AccessController.doPrivileged(Native Method)
at org.codehaus.groovy.reflection.CachedClass$2.initValue(CachedClass.java:67)
at org.codehaus.groovy.reflection.CachedClass$2.initValue(CachedClass.java:64)
at org.codehaus.groovy.util.LazyReference.getLocked(LazyReference.java:46)
at org.codehaus.groovy.util.LazyReference.get(LazyReference.java:33)
at org.codehaus.groovy.reflection.CachedClass.getConstructors(CachedClass.java:258)
at groovy.lang.MetaClassImpl.<init>(MetaClassImpl.java:213)
at groovy.lang.MetaClassImpl.<init>(MetaClassImpl.java:223)
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.createNormalMetaClass(MetaClassRegistry.java:168)
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.createWithCustomLookup(MetaClassRegistry.java:158)
at groovy.lang.MetaClassRegistry$MetaClassCreationHandle.create(MetaClassRegistry.java:141)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClassUnderLock(ClassInfo.java:209)
at org.codehaus.groovy.reflection.ClassInfo.getMetaClass(ClassInfo.java:241)
at org.codehaus.groovy.runtime.metaclass.MetaClassRegistryImpl.getMetaClass(MetaClassRegistryImpl.java:255)
at org.codehaus.groovy.runtime.InvokerHelper.getMetaClass(InvokerHelper.java:859)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.createCallConstructorSite(CallSiteArray.java:84)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:182)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:194)
at com.sample.MongoService.client(MongoService.groovy:14)
at com.sample.MongoService.collection(MongoService.groovy:21)
at com.sample.MongoService$collection.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at com.sample.MongoDBController.method(MongoDBController.groovy:10)
at com.sample.MongoDBController$method.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at com.sample.GroovyDemoApp.main(GroovyDemoApp.groovy:12)
Caused by: java.lang.ClassNotFoundException: com.mongodb.operation.OperationExecutor
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClassInternal(Unknown Source)
... 35 more
Update :
This is my Groovy code. with this code i am trying to connect Mongodb
// error is in this line . i .e -
// The type com.mongodb.operation.CreateIndexesOperation cannot be resolved.
// It is indirectly referenced from required .class files )
package com.sample
import com.mongodb.*
class MongoService {
private static MongoClient mongoClient
private static host = "localhost" //your host name
private static port = 27017 //your port no.
private static databaseName = "db"
public static MongoClient client() {
if(mongoClient == null){
return new MongoClient(host,port)
}else {
return mongoClient
}
}
public DBCollection collection(collectionName) {
DB db = client().getDB(databaseName)
return db.getCollection(collectionName)
}
}
To use the MongoDB driver you can either use the JAR, or #Grab it from Maven.
Using the JAR
To use the JAR, you need to add it to Groovy's classpath. This is done with the -cp argument:
#!/usr/bin/env groovy -cp /path/to/jar/file
println 'Hello'
Using Maven
You can simply use Groovy's #Grab to take care of the dependency for you:
#Grab('org.mongodb:mongodb-driver:3.2.2')
println 'Hello'
Working example
Here's a working example based on the code you posted:
#Grab('org.mongodb:mongodb-driver:3.2.2')
import com.mongodb.MongoClient
import com.mongodb.DBCollection
import com.mongodb.DB
import com.mongodb.BasicDBObject
class MongoService {
private MongoClient mongoClient
def host = "localhost" //your host name
def port = 27017 //your port no.
def databaseName = 'test'
public MongoClient client() {
mongoClient = mongoClient ?: new MongoClient(host, port)
return mongoClient
}
public DBCollection collection(collectionName) {
DB db = client().getDB(databaseName)
return db.getCollection(collectionName)
}
}
def service = new MongoService(databaseName: 'db')
def foo = service.collection('foo')
def data = [
[firstName: 'Jane', lastName: 'Doe'],
[firstName: 'Elvis', lastName: 'Presley']
].collect { it as BasicDBObject }
foo.insert(data)
foo.find().toArray().each {
println it
}
I've never used MongoDB before, so whether my use case is useful or not is debatable.

Invalid Cursor State - No current row

I am very new to Java, and I am trying to complete one simple task of reading data from a table and passing it to form variables. However, I am getting this frustrating exception:
Invalid cursor state - no current row;
I tried everything but still no luck. I looked into Google but I'm not getting an answer that will fix this issue. Hope you guys can help.
public class MainFrame extends javax.swing.JFrame {
Connection con;
Statement stm;
ResultSet rs;
/**
* Creates new form MainFrame
*/
public MainFrame() {
initComponents();
DoConnect();
}
public void DoConnect() {
try{
String host = "jdbc:derby:studentinfo;create=true";
String uname = "sudeep";
String upass = "sunny";
con = DriverManager.getConnection(host, uname, upass);
stm = con.createStatement();
String sql = "SELECT * FROM APP.STUDENTID";
rs = stm.executeQuery(sql);
System.out.println("Query executed");
if(rs.next())
{
// This is where the exception is occurring!!!!!!
String id = rs.getString("STUDENTID");
String first = rs.getString("FIRST_NAME");
String second = rs.getString("SECOND_NAME");
ID.setText(id);
fnam1.setText(first);
lnam.setText(second);
System.out.println(id);
}
}
catch ( SQLException err) {
JOptionPane.showMessageDialog(MainFrame.this, err.getMessage());
System.out.println("ERROR GETCONNECTION");}
}
}
Here is the trace generated by the program
run:
[EL Info]: 2013-09-03 21:14:15.732--ServerSession(552364977)--EclipseLink, version: Eclipse Persistence Services - 2.5.0.v20130507-3faac2b
[EL Info]: connection: 2013-09-03 21:14:16.299--ServerSession(552364977)--file:/Users/vasundhra_sudeep/NetBeansProjects/StudentForm/build/classes/_jdbc:derby:studentinfo;create=truePU login successful
java.sql.SQLException: Invalid cursor state - no current row.
Invalid cursor state - no current row.
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.Util.generateCsSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedConnection.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.ConnectionChild.newSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.checkOnRow(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getColumnType(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getString(Unknown Source)
at org.apache.derby.impl.jdbc.EmbedResultSet.getString(Unknown Source)
at studentform.MainFrame.DoConnect(MainFrame.java:57)
at studentform.MainFrame.(MainFrame.java:35)
at studentform.MainFrame$7.run(MainFrame.java:579)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:715)
at java.awt.EventQueue.access$400(EventQueue.java:82)
at java.awt.EventQueue$2.run(EventQueue.java:676)
at java.awt.EventQueue$2.run(EventQueue.java:674)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:86)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:685)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.sql.SQLException: Invalid cursor state - no current row.
at org.apache.derby.impl.jdbc.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.impl.jdbc.SQLExceptionFactory40.wrapArgsForTransportAcrossDRDA(Unknown Source)
... 27 more
BUILD SUCCESSFUL (total time: 7 seconds)
It's likely that APP.STUDENTID has no data in it. Insert at least one record (aka row) of data into that table, run your program again, and see if the same exception occurs.

Having trouble mocking an email server using JUnit

I'm trying to mock sending an email (for the purposes of JUnit, v4.8.1, testing) and decided to use Dumbster, which I found through SO. I'm using version 1.6. I have this in my JUnit test …
SimpleSmtpServer server = SimpleSmtpServer.start();
boolean ret = m_emailSvc.sendEmail("me#me.com",
"you#you.com",
"localhost",
"Test",
"Test Body");
Assert.assertTrue(ret);
server.stop();
and I send an email this way …
public boolean sendEmail(final String toEmail,
final String fromEmail,
final String smtpHost,
final String subject,
final String body)
{
boolean ret = true;
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", smtpHost);
// Get the default Session object.
Session session = Session.getDefaultInstance(properties);
try{
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(fromEmail));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(body);
// Send message
Transport.send(message);
}catch (MessagingException mex) {
ret = false;
LOG.error(mex.getMessage(), mex);
} // try
return ret;
} // sendEmail
This fails with the exception below. Does anyone know what I'm doing wrong or is there an easier way to mock sending an email in a JUnit test?
java.net.BindException: Permission denied
at java.net.PlainSocketImpl.socketBind(Native Method)
at java.net.PlainSocketImpl.socketBind(PlainSocketImpl.java:521)
at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:414)
at java.net.ServerSocket.bind(ServerSocket.java:326)
at java.net.ServerSocket.<init>(ServerSocket.java:192)
at java.net.ServerSocket.<init>(ServerSocket.java:104)
at com.dumbster.smtp.SimpleSmtpServer.run(Unknown Source)
at java.lang.Thread.run(Thread.java:680)
[ERROR]: org.mainco.subco.email.service.EmailServiceImpl - Could not connect to SMTP host: localhost, port: 25
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at org.mainco.subco.email.service.EmailServiceImpl.sendEmail(EmailServiceImpl.java:62)
at org.mainco.subco.email.service.EmailServiceTest.testSendEmail(EmailServiceTest.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:382)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:241)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:228)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:527)
at java.net.Socket.connect(Socket.java:476)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
I decided to mock the static call from the Transport class instead, using PowerMock (v.1.5.1).
#RunWith(PowerMockRunner.class)
public class EmailServiceTest
{
#Autowired
private EmailService m_emailSvc = new EmailServiceImpl();
#Test
#PrepareForTest( Transport.class )
public final void testSendEmail()
{
suppress(methodsDeclaredIn(Transport.class));
boolean ret = m_emailSvc.sendEmail("me#me.com",
"you#you.com",
"localhost",
"Test",
"Test Body");
Assert.assertTrue(ret);
} // testSendEmail
What about wrapping the call to Transport is a mockable object? Inject the mock and verify the call.
What I mean is something like this...
class MyTransport{
public void send(MimeMessage message){
Transport.send(message);
}
}
Then inject an instance of this class into your class above. In your production env you have the same code. However, when doing testing you could pass in a Mock for MyTransport and thereby verify the call to send without the need of a server.

Not able to invoke remote method in RMI communication

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.