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

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());
}
}
}

Related

how do i insert data with no authentication in MongoDB

Software Gui
Using mongo java driver 3.4.2
I am running Mongodb with this command in CMD "mongod". I am not using "mongod --auth" ! I don't know why it's still giving me Exception.
like in CMD we don't have to provide username and password if server is not running on --auth. similarly i want achieve.
i have created application which inserts data into mongo db
Actually its inserting data successfully only that i am still getting exception and its making slower to my application since i am using swingworker therefore my application freeze for a while during exception time.
Is that MongoDB driver has limitation ? That we cannot insert data without
authentication.
public void doJob() {
server.progressbar.setVisible(true);
server.progressbar.setIndeterminate(true);
SwingWorker worker = new SwingWorker() {
#Override
protected void done() {
server.progressbar.setIndeterminate(false);
server.progressbar.setVisible(false);
server.total.setText("");
CoonectToDB obj=new CoonectToDB();
obj.callcollections();
NoAuthCoonectToDB obj2=new NoAuthCoonectToDB();
obj2.NoAuthconnectDB();
}
#Override
protected void process(List chunks) {
// Here you can process the result of "doInBackGround()"
// Set a variable in the dialog or etc.
}
#Override
protected Object doInBackground() {
try{
server.newcol.setEnabled(false);
server.ecoll.setEnabled(false);
server.ubtn.setEnabled(false);
String logid="Log-"+logname.getText();
JList dataList=(loglist);
int sixe=dataList.getModel().getSize();
ArrayList arrayList = new ArrayList();
for (int i = 0; i <sixe; i++) {
arrayList.add(dataList.getModel().getElementAt(i));
server.total.setText("Total Log-"+i);
}
System.out.println(arrayList);
Iterator itr = arrayList.iterator();
String host=hname.getText();
String port=spport.getValue().toString();
Integer pt = Integer.valueOf(port);
MongoClient mongoClient = new MongoClient(new ServerAddress(host, pt),
MongoClientOptions.builder()
.serverSelectionTimeout(2000)
.build());
DB db = mongoClient.getDB( dbname.getText());
DBCollection bookCollection = db.getCollection(collectionss.getSelectedValue().toString());
BasicDBObject doc = new BasicDBObject(logid, arrayList);
bookCollection.insert(doc);
Icon icon = new ImageIcon("src\\images\\done.png");
processimage.setIcon(icon);
server.consolelog.setText("INFO: Data is inserted succsesfully");
}catch(Exception e){
server.consolelog.setText(e.toString());
}finally{
server.newcol.setEnabled(true);
server.ecoll.setEnabled(true);
server.ubtn.setEnabled(true);
}
return null;
}
};
worker.execute();
}
here is the Exception
com.mongodb.MongoTimeoutException: Timed out after 2000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=localhost:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='', source='admin', password=<hidden>, mechanismProperties={}}}, caused by {com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "Authentication failed.", "code" : 18, "codeName" : "AuthenticationFailed" }}}]
Thank you for helping me
Actually its solved i don't know why ist working after i change this line .
collectionss.getSelectedValue().toString();// Jlist
to
Object value = collectionss.getSelectedValue().toString() ;
DBCollection bookCollection = db.getCollection(value.toString);
i don't know exactly but i think it has to do something with this SCRAM-SHA-1.

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.

Mongo Timeout Exception

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 ^^

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

Categories