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.
Related
I'm studying the Vertx MongoClient API. I previously installed Restheart from Docker and it's own copy of mongodb, so now I have the default configuration for Restheart and the default configuration of Mongo in docker-compose.yml:
MONGO_INITDB_ROOT_USERNAME: restheart
MONGO_INITDB_ROOT_PASSWORD: R3ste4rt!
I put the Vertx Mongoclient into a Verticle:
public class MongoClientVerticle extends AbstractVerticle {
MongoClient mongoClient;
String db = "monica";
String collection = "sessions";
String uri = "mongodb://localhost:27017";
String username = "admin";
String password = "password";
MongoAuth authProvider;
#Override
public void start() throws Exception {
JsonObject config = Vertx.currentContext().config();
JsonObject mongoconfig = new JsonObject()
.put("connection_string", uri)
.put("db_name", db);
mongoClient = MongoClient.createShared(vertx, mongoconfig);
JsonObject authProperties = new JsonObject();
authProvider = MongoAuth.create(mongoClient, authProperties);
// authProvider.setHashAlgorithm(HashAlgorithm.SHA512);
JsonObject authInfo = new JsonObject()
.put("username", username)
.put("password", password);
authProvider.authenticate(authInfo, res -> {
if (res.succeeded()) {
User user = res.result();
System.out.println("User " + user.principal() + " is now authenticated");
} else {
res.cause().printStackTrace();
}
});
}
and I built a simple query:
public void find(int limit) {
JsonObject query = new JsonObject();
FindOptions options = new FindOptions();
options.setLimit(1000);
mongoClient.findWithOptions(collection, query, options, res -> {
if (res.succeeded()) {
List<JsonObject> result = res.result();
result.forEach(System.out::println);
} else {
res.cause().printStackTrace();
}
});
}
but when I access the db I get this error:
MongoQueryException: Query failed with error code 13 and error message 'there are no users authenticated' on server localhost:27017
What am I missing in the authentication process?
I'm using lastest restheart + mongodb and vertx 3.5.3
To be clear, RESTHeart doesn't come with its own copy of Mongodb but connects to any existing instance of Mongodb. The instance you can start via docker compose is for demo purposes only.
This question is much related to Vertx + Mongodb. I'm not an expert of it, but apparently Vert.x Auth Mongo does not use database accounts to authenticate users, it uses a specific collection (by default the "user" collection). You could double check the Vertx docs in case to be sure about this.
However, note that RESTHeart's main purpose is to provide direct HTTP access to Mongodb, without the need to program any specific client or driver. So the side point is that if you are using Vertx then you presumably don't need RESTHeart, and vice versa. Otherwise, you could simply connect to RESTHeart via Vertx's HTTP client, entirely skipping the MongoClient API.
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.
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());
}
}
}
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
I'm looking for best way to check connection to Mongo DB.
Situation: client makes request (api) to server. And server returns status of all databases.
What the best way to do it?
I use this:
Builder o = MongoClientOptions.builder().connectTimeout(3000);
MongoClient mongo = new MongoClient(new ServerAddress("192.168.0.1", 3001), o.build());
try {
mongo.getAddress();
} catch (Exception e) {
System.out.println("Mongo is down");
mongo.close();
return;
}
In Java MongoDriver 3.3.0 use ServerMonitorListener to determine whether server is up and connected or not.
Here is the example code,
public class ServerConnection implements ServerMonitorListener {
private MongoClient client;
public ServerConnection(){
try {
MongoClientOptions clientOptions = new MongoClientOptions.Builder()
.addServerMonitorListener(this)
.build();
client = new MongoClient(new ServerAddress("localhost", 27017), clientOptions);
} catch (Exception ex) {
}
}
#Override
public void serverHearbeatStarted(ServerHeartbeatStartedEvent serverHeartbeatStartedEvent) {
// Ping Started
}
#Override
public void serverHeartbeatSucceeded(ServerHeartbeatSucceededEvent serverHeartbeatSucceededEvent) {
// Ping Succeed, Connected to server
}
#Override
public void serverHeartbeatFailed(ServerHeartbeatFailedEvent serverHeartbeatFailedEvent) {
// Ping failed, server down or connection lost
}
}
The ping command is a no-op used to test whether a server is responding to commands. This command will return immediately even if the server is write-locked:
try{
DBObject ping = new BasicDBObject("ping", "1");
mongoTemplate.getDb().getMongo().getDB("DATABASE NAME"").command(ping);
} catch (Exception exp){
// MongoDb is down..
}
Use MongoClient for Java, all the info you need is here...
http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/
If I understand your question correctly you want to get state returned via a web service call. You can write a function that invokes db.serverStatus() and have it return the data. Check out the documentation here:
Monitoring for MongoDB