Mongodb database connection failed - java

I am trying to connect to a Mongodb database using Java.I have added the following dependencies to my project in eclipse:
bson-3.0.1.jar
mongodb-driver-core-3.0.1.jar
mongodb-driver-3.0.1.jar
Here is the code snippet I have written to connect to mongodb:
public void connectToDB()
{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
DB db = mongoClient.getDB( "messenJ" );
System.out.println("Connected to database successfully");
}
However , I am getting following error after I run my code:
java.lang.NoSuchMethodError: com.mongodb.ReadPreference.primary()Lcom/mongodb/ReadPreference;
How can I fix this problem?
Thanks.

You should rather download a newer version of the MongoDB Java Driver here.
It includes the latest Bson version aswell!
The API changed too:
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoDatabase database = mongoClient.getDatabase("yourDatabase");
(See: http://mongodb.github.io/mongo-java-driver/3.3/driver/getting-started/quick-tour/)
Hope this helps a bit :)

Related

Java MongoDB driver version 3.8 -- how to set timeout?

I am maintaining a JSP/Servlet application that uses the MongoDB 3.8 Java driver. At this point, I cannot change versions to a newer one.
I have occasionally experienced some timeouts when connecting from the application to the database. Based on what I read in https://mongodb.github.io/mongo-java-driver/3.8/driver/tutorials/connect-to-mongodb/ I wrote the following code:
CodecRegistry pojoCodecRegistry = fromRegistries(com.mongodb.MongoClient.getDefaultCodecRegistry(),
fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoCredential credential
= MongoCredential.createCredential(theuser, database, thepassword.toCharArray());
MongoClientSettings settings = MongoClientSettings.builder()
.credential(credential)
.codecRegistry(pojoCodecRegistry)
.applyToClusterSettings(builder
-> builder.hosts(Arrays.asList(new ServerAddress(addr, 27017))))
.build();
MongoClient client = MongoClients.create(settings);
This works, but with the eventual timeout (usually when reloading a JSP page).
I figured out I could create a SocketSettings instance with:
SocketSettings socketOptions = SocketSettings.builder().connectTimeout(60,TimeUnit.SECONDS).build();
But I cannot figure out how to apply these settings to the creation of the instance of MongoClient. Any hints?
thanks

Attempting to connect to Atlas via Lambda: No address associated with hostname

I'm trying to upload a document from a Lambda script, however I've been stuck where I keep getting the following whenever the Lambda script starts:
com.mongodb.MongoSocketException: cluster0-whnfd.mongodb.net: No address associated with hostname
The error seems obvious, however I can connect using that same URL via Mongo Compass. The Java class I'm using looks like:
public class MongoStore {
private final static String MONGO_ADDRESS = "mongodb+srv://<USERNAME>:<PASSWORD>#cluster0-whnfd.mongodb.net/test";
private MongoCollection<Document> collection;
public MongoStore() {
final MongoClientURI uri = new MongoClientURI(MONGO_ADDRESS);
final MongoClient mongoClient = new MongoClient(uri);
final MongoDatabase database = mongoClient.getDatabase("test");
this.collection = database.getCollection("test");
}
public void save(String payload) {
Document document = new Document();
document.append("message", payload);
collection.insertOne(document);
}
}
Have I just misconfigured my Java class, or is there something more tricky going on here?
The same problem I had with freshly created MongoDB Atlas database, when I started the migration of my Python web application from Heroku.
So I've realised the DNS name cluster0.hgmft.mongodb.net just doesn't exist.
The magic happened when I've installed the library dnspython (my app is written in Python), with this library MongoDB client was able to connect to my database in Mongo Atlas.

How to add more than one host in MongoDB connection URI in java

I am adding multiple host in MongoDb connection URI in java .It is working fine if all the host are up and running, But it is giving exception when any of the host in the URI is not responding.
I want if in any case my Primary mongo server goes down then already configured secondary mongo come into action and connection should not break in any case.
mongoURI = mongodb://user name:password#first-host:port,second-host:port/db
Here second host in not working.
Code:
MongoClient mongo = new MongoClient(new MongoClientURI(mongoURI));
Exception: ERROR : Mongo Connection java.net.UnknownHostException.
I assume these hosts are replica sets.
Then you can do
MongoClient mongoClient = new MongoClient(Arrays.asList(
new ServerAddress("localhost", 27017),
new ServerAddress("localhost", 27018),
new ServerAddress("localhost", 27019)));
Check the doc if needed.

issue populating v$session properties in oracle datasource

I have a issue populating v$session properties in oracle datasource ie after starting tomcat server my application would be using connection , now if I query DB with below query I should get a row from DB, currently I am not getting any row for 1st approach ,but 2nd approach works
select schemaname, osuser, machine, program
from v$session
where program = 'Test';
below are the configuration and tools I am using , any help regaring this is appriciated .
Thanks
1.Tomcate 6.0.35.3
2.Oracle version :Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
3.Spring and JPA
Approach 1:-
server.xml :
<Resource
name="jdbc/oraclepool"
auth="Container"
factory="oracle.ucp.jdbc.PoolDataSourceImpl"
type="oracle.ucp.jdbc.PoolDataSource"
description="main DB"
connectionFactoryClassName="oracle.jdbc.pool.OracleDataSource"
connectionPoolName="UCPPool"
url="${db.url}"
user="${db.username}"
password="${db.password.encrypted}"
initialPoolSize="3"
minPoolSize="1"
maxPoolSize="5"
maxIdleTime="${db.maxIdleTime}"
inactiveConnectionTimeout="${db.inactiveConnectionTimeout}"
abandonedConnectionTimeout="${db.abandonedConnectionTimeout}"
timeToLiveConnectionTimeout="${db.timeToLiveConnectionTimeout}"
maxStatements="${db.maxOpenPreparedStatements}"
timeoutCheckInterval="${db.timeoutCheckInterval}"
connectionWaitTimeout="${db.connectionWaitTimeout}"
sqlForValidateConnection="${db.validationQuery}"
connectionProperties="v$session.program=Test;"
/>
Approach 2 :-
Added below code snippet in java class , it worked .
When I queried the db with below query , I was getting the row .
select schemaname, osuser, machine, program
from v$session
where program = 'Test';
Connection conn=null;
// set connection properties
Properties info = new java.util.Properties();
info.put("v$session.program", "Test");
// connect to database
Context context = new InitialContext();
PoolDataSourceImpl ds = (PoolDataSourceImpl)context.lookup("java:comp/env/jdbc/oraclepool");
((PoolDataSourceImpl)ds).setConnectionProperties(info);
conn = ds.getConnection();
Can anybody tell what is the issue with first approach
Thanks again .

unable to connect mongo on cloud using java

I deployed my java web application on jelastic.I created a node for glassfish and mongodb on jelastic.I am not able to connect to the database deployed on code.
I used the following way to connect to the database-
Mongo mongo = new Mongo("http://arpitsolanki.jelastic.servint.net/", 27017);
but it throws a Number Format Exception
java.lang.NumberFormatException: For input string: "//arpitsolanki.jelastic.servint.net/"
What is the right way of connecting with the database?
I have used Mongo Client for connection and it works fine for me
// import com.mongodb.MongoClient;
// import com.mongodb.DBObject;
MongoClient mongoClient = new MongoClient("URL", PORT);
DB db = mongoClient.getDB("dbName");
boolean auth = db.authenticate("username", password.toCharArray());

Categories

Resources