smack api giving error to login gtalk - xmpp

I used all the api's related to smack so that i could login and use the gtalk in my and app. All the api's (smack 3.22, asmack, qsmack) give me same error. Error is coppied from logcat and pasted below. Please help me i am almost frustated now :(
XMPPConnection xmppConnection;
String host = "talk.google.com";
int port = 6222;
String service = "gmail.com";
String username = "test1";
String password = "password";
try {
xmppConnection = new XMPPConnection(new ConnectionConfiguration(host,
port, service));
xmppConnection.connect();
xmppConnection.login(username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
No response from the server.:
at org.jivesoftware.smack.NonSASLAuthentication.authenticate(NonSASLAuthentication.java:74)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:404)
at org.jivesoftware.smack.XMPPConnection.login(XMPPConnection.java:349)
at com.android.xmppproject.XmppManager.performLogin(XmppManager.java:56)
at com.android.xmppproject.XMPPProjectActivity.onCreate(XMPPProjectActivity.java:29)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
at android.app.ActivityThread.access$2300(ActivityThread.java:125)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4627)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)

I think you have provided incorrect GTalk port.
Please try port = 5222

Related

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?

Mongo db authentication failure in java code does not go to catch block

I am trying to write code where mongo DB authentication is tested.
However when authentication fails the code does not reach to the catch block.
Here is the code :
MongoClient client = null;
try {
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(
MongoCredential.createScramSha1Credential(
"abc",
"test",
"abc#123".toCharArray()
)
);
client = new MongoClient(host,credentials, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
} catch (Exception e) {
client = new MongoClient(host, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
// e.printStackTrace();
}
client.getDatabase("admin").runCommand(new Document("ping",1));
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='abc', source='test', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Unknown Source)
This code never falls through into the catch block and runs the line just after the catch block.
Can you tell me how to handle this situation.

mongoDB async driver java - unable to connect with authentication

Recently we've updated our mongoDB with port 35489 and also with authentication and roles to the database.
I've granted readWrite and readWriteAnyDatabase roles for a user and can successfully connect from our c# coding from mentioning it from the web.config
My web.config:
<add key="MongoConnectionString" value="mongodb://readWriteUser:********#192.168.1.225:35489/admin" />
Now, my problem is I'm uanble to connect to mongoDB from java async driver and it is throwing an exception like
Exception
Exception in monitor thread while connecting to server localhost:35489 com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='AdminAllDatabases', source='admin', password=, mechanismProperties={}} at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61) at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99) at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44) at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115) at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) at java.lang.Thread.run(Unknown Source) Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost:35489. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." } at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170) at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123) at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) at com.mongodb.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:99) at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:58) ... 6 common frames omitted
My async java driver code:
public static final String DEFAULT_URI = "mongodb://readWriteUser:******#localhost:35489/";
public static synchronized ConnectionString getConnectionString()
{
if (connectionString == null)
{
connectionString = new ConnectionString(DEFAULT_URI);
}
return connectionString;
}
public static synchronized MongoClient getMongoClient()
{
if (mongoClient == null)
{
mongoClient = MongoClients.create(getConnectionString());
}
return mongoClient;
}
we've tried with both localhost and ip address, but nothing seems to work.
Can anyone suggest me the right way to do this?

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.