Mongo Timeout Exception - java

I've been searching for hours, and I can't find out why this isn't working, could you give me a hand guys? I'm trying to implement mongodb on my project, it seems to connect all right, but when I try to modify/access something on it, it gives me this "Mongo Timeout Exception".
try {
MongoCredential credential = MongoCredential.createCredential(USER, DATABASE, PASSWORD.toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress(HOST), Arrays.asList(credential));
DB database = mongoClient.getDB(DATABASE);
DBCollection collection = database.getCollection(COLLECTION);
DBCursor cursor = collection.find();
cursor.next();
System.out.println("Success!");
} catch(Exception ex) { ex.printStackTrace(); }
com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=104.236.68.242:27017, type=Unknown, state=Connecting}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
at com.mongodb.DBTCPConnector.getClusterDescription(DBTCPConnector.java:394)
at com.mongodb.DBTCPConnector.getType(DBTCPConnector.java:571)
at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:368)
at com.mongodb.Mongo.isMongosConnection(Mongo.java:622)
at com.mongodb.DBCursor._check(DBCursor.java:494)
at com.mongodb.DBCursor._next(DBCursor.java:551)
at com.mongodb.DBCursor.next(DBCursor.java:701)
at net.Heiden.DB.Testing.main(Testing.java:29)
Any Help is apreciated.
Thanks ^^

Related

MongoDB Authentication failure from mongo java client

I tried to connect to mongo db version 3.2 using mongo java client version 3.2 and getting the following exception, any idea what went wrong here?
com.mongodb.MongoSecurityException: Exception authenticating
at com.mongodb.connection.NativeAuthenticator.authenticate(NativeAuthenticator.java:48)
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(Thread.java:745)
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server 10.100.5.41:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }
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.NativeAuthenticator.authenticate(NativeAuthenticator.java:46)
... 5 more
Following is the code I used to connect.
MongoClient mongoClient = null;
try {
MongoCredential credential = MongoCredential.createMongoCRCredential("admin", "mydatabase", "admin123".toCharArray());
mongoClient = new MongoClient(new ServerAddress("10.100.5.41", 27017), Arrays.asList(credential));
MongoDatabase database = mongoClient.getDatabase("mydatabase");
System.out.println(database.getName());
MongoCollection collection = database.getCollection("user");
MongoCursor cursor = collection.find().iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} catch (Exception e) {
e.printStackTrace();
}
After hours of debugging, db administrator told that, he has changed the username and password. At times I wonder why I become a Software Engineer.

Accessing MongoDB through Android app. Not Working

Things I Have tried:
InetAddress address = InetAddress.getByName("MyPCName");
MongoClientOptions.Builder builder = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress(address.getHostAddress(), 3001), builder.build());
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Mongo is down");
mongo.close();
}
Second try:
InetAddress address = InetAddress.getByName("MyPCName");
MongoClientURI uri = new MongoClientURI( "mongodb://"+address.getHostAddress()+":27017/"+TEST_SKETCH_APP );
MongoClient instance = MongoDatabaseConnection.getInstance(uri);
try {
instance .getAddress();
} catch (Exception e) {
System.out.println("Mongo is down");
instance .close();
}
FireWall configured properly :
netsh advfirewall firewall add rule name="Allowing mongod" dir=in action=allow program=" C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe"
But Still when I try to connect to do an insert operation I get this error message :
Timed out after 3000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=192.168.138.1:3001, type=Unknown, state=Connecting}]
I am doing the save operation in an AsyncTask. My mongo db server is running in the "MyPCName" computer. My Mongodb config has bind ip commented too. And I have also tried the bind Ip to keep this bind_ip = 127.0.0.1,***.***.***.*,0.0.0.0
The '*' mark is the ip address which I get when I do a address.getHostAddress().
I am now stuck here.
Try this code:
MongoClientURI mongoUri = new MongoClientURI("mongodb://Dbuser:dbpass#ds047692.mongolab.com:47692");
MongoClient mongoClient = new MongoClient(mongoUri);
DB db = mongoClient.getDB("testdb");
Set<String> collectionNames = db.getCollectionNames();
In addition, you should check this answer: https://stackoverflow.com/a/21555200/4810206.

com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect

I assumed this question was asked several times but I had to reask it again. Because solutions provided for this question did not give me an exact answer to get rid of this bloody error.
I use mongo-java-driver-2.12.4 and mongo.jar when I try to insert document to db I get following error. Any help is appreciated.
Error :
Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=127.0.0.1:27000, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27001, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27002, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
Code :
public class MongoDbConnectDatabase {
public static void main(String[] args) {
// To connect to mongodb server
try {
List<ServerAddress> lstServer = new ArrayList<ServerAddress>();
lstServer.add(new ServerAddress("127.0.0.1", 27000));
lstServer.add(new ServerAddress("127.0.0.1", 27002));
lstServer.add(new ServerAddress("127.0.0.1", 27001));
MongoClient mongoClient = new MongoClient(lstServer);
// Now connect to your database
DB db = mongoClient.getDB("test");
System.out.println("connect to database successfully");
DBCollection coll = db.createCollection("mycol", null);
System.out.println("Collection created successfully");
DBCollection colReceived= db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("url", "http://www.tutorialspoint.com/mongodb/").
append("by", "tutorials point");
colReceived.insert(doc);
System.out.println("Document inserted successfully");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You obtain a Connection refused. Are you sure mongod is running?
Try to connect with mongoclient:
mongo 127.0.0.1:27000/test
and this for all the three instances (27000, 27002, 27001).
If you have problem also with mongoclient, check your logs.
another reason for this error can be that the version of mongo-java-driver is not compatible with your mongo application. My case : I was using mongo-java-driver version 2.12.3 with mongo 3.0.8 -> doesn't work. (https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-java)
Here is all the possible reason for this error are listed. In my case it was due to replicaset not initialised. Initialise replicaset using rs.initiate().
In my case I used the volume created from production data and used it in staging. Since the local db was having old replicaset config, it was not able to become PRIMARY. I did the following thing to make it PRIMARY:
>use local
> db.dropDatabase();
{ "dropped" : "local", "ok" : 1 }
> rs.initiate()
>myrepl:PRMIARY
Now the client was able to connect and perform read/write operations.
Giving a snippet that might give a basic idea.
package com.mkyong.core;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
public class MongoTest {
static DBCollection table;
public static void main(String[] args) {
MongoClient mongo = null;
try {
mongo = new MongoClient("localhost", 27017);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DB db = mongo.getDB("lending");
table = db.getCollection("bureaudata");
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("id", "63057298");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
}

Timed out Exception in Mongodb using Java driver

I have the following Java code to save new entry to MongoDB if the entry is not in DB. I run it in Java Timer for every 2 seconds.
MongoClient mongoClient = null;
try {
mongoClient = new MongoClient("localhost", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
DB db = mongoClient.getDB("testdb");
DBCollection coll = db.getCollection("testcollection");
// Search for existing entries
BasicDBObject query = new BasicDBObject("link", entry_url);
DBCursor cursor = coll.find(query);
try {
// If it is a new entry, insert
if (cursor.hasNext() == false) {
// Insert new entry
BasicDBObject doc = new BasicDBObject("link", entry_url)
.append("a_time", accept_time).append(
"p_time", formatter.format(date));
coll.insert(doc);
}
} finally {
cursor.close();
}
The problem is after several minutes, there is a com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=localhost:27017, type=Unknown, state=Connecting}] from mongoDB. It refers to cursor.hasNext(). Any suggestions for this problem?
Exception in thread "Timer-0" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=localhost:27017, type=Unknown, state=Connecting}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
at com.mongodb.DBTCPConnector.getClusterDescription(DBTCPConnector.java:396)
at com.mongodb.DBTCPConnector.getType(DBTCPConnector.java:569)
at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:370)
at com.mongodb.Mongo.isMongosConnection(Mongo.java:623)
at com.mongodb.DBCursor._check(DBCursor.java:494)
at com.mongodb.DBCursor._hasNext(DBCursor.java:621)
at com.mongodb.DBCursor.hasNext(DBCursor.java:657)
The Timer implementation
try {
Timer timer = new Timer();
timer.schedule(new STimer(), 0, 2 * 1000);
} catch (Exception e) {
e.printStackTrace();
}
Based on the comments below, I closed the mongoClient connection. Problem solved.
You must also ensure MongoClient is properly closed

MongoDB and Java

I'm trying to use MongoDB in a Java Web Service.
As suggested in Mongo tutorial I should have a MongoClient, let it be dbInstance, connection pool and call dbinstance to get a connection to the database, which is in localhost.
So this is what I have:
private static MongoClient dbInstance = null;
public static DB getDBInstance() {
if (dbInstance == null) {
try {
dbInstance = new MongoClient();
registerShutdownHook();
}
catch (Exception exc) {
System.out.println("Exception");
}
}
return dbInstance.getDB("SAED");
}
What I don't understand is how I can understand if I'm connected to the DB, because, also il mongo isn't working (by starting mongod service) it doesn't throw exceptions.
And another question, I have multiple thread calling Class.getDBInstance, should I synchronize it, and if yes, how can I do that?
You will be thrown an exception when the mongo is not running while you try to connect.
When you do the MongoClient(), it will always look for in the localhost for port 27017 to connect. You can also parameterize this to connect to a different machine and/or port.
You can read more in depth details about this at Mongo Documentation.
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
Regarding your synchronization question,
Yes, you can synchronize at a block level to make it better instead of at the method level.

Categories