How to solve error: No server chosen by ReadPreferenceServerSelector - java

I'm very new to Java and MongoDB (or any databases) and I have been building this Java program to test the connection. It's supposed to just simply establish the connection and list all existing database names.
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCursor;
public class test {
public static void main(String[] args) {
try{
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
MongoCursor<String> dbsCursor = mongoClient.listDatabaseNames().iterator();
while(dbsCursor.hasNext()) {
System.out.println(dbsCursor.next());
}
}catch(Exception e){
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
}
}
}
The MongoDB server is already started. However, when I run this app, it shows errors like these
Jun 25, 2016 3:35:06 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
Jun 25, 2016 3:35:06 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, all=[ServerDescription{address=localhost:27017, type=UNKNOWN, state=CONNECTING}]}. Waiting for 30000 ms before timing out
Jun 25, 2016 3:35:06 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketWriteException: Exception sending message
at com.mongodb.connection.InternalStreamConnection.translateWriteException(InternalStreamConnection.java:462)
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:205)
at com.mongodb.connection.CommandHelper.sendMessage(CommandHelper.java:89)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:83)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:43)
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: java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at com.mongodb.connection.SocketStream.write(SocketStream.java:75)
at com.mongodb.connection.InternalStreamConnection.sendMessage(InternalStreamConnection.java:201)
... 7 more
com.mongodb.MongoTimeoutException: Timed out after 30000 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.MongoSocketWriteException: Exception sending message}, caused by {java.net.SocketException: Software caused connection abort: socket write error}}]
Process finished with exit code 0
What could these mean? Am I suppose to set ReadPreferenceServerSelector? But I can't find any related documents online.

The ReadPreferenceServerSelector is used internally when firing requests to Mongo. In your scenario, you do not need to go into that detail.
The error of importance to me is this. The linked answer describes why this error might be coming. But it should not be repeating on multiple attempts.
Software caused connection abort: socket write error
Can you check if mongo is running on the port 27017 and is accessible via command line ?
Simply using the mongo-java-driver should be sufficient for your to run a test like this. Just make sure the jar version matches the installed mongodb version. A better idea would be to use something like maven as described in this tutorial.
Please post if the error persists after trying these things.

Related

com.mongodb.MongoSocketOpenException Exception opening socket

Problem statement:
I have two Amazon EC2 instances running on same VPC. One ec2 is running web application (a spring mvc java website), while second instance is running mongodb.
I can do ssh from my local machine to both instances as well as to two instances from each other. Also telnet works perfectly fine from each other using private ip.
I also can connect to ec2 mongodb instance from my personal (local) workspace, as necessary rules are created to accept connections from local and web application's ec2 instance.
However, my web application instance cannot connect to this mongodb instance and throwing following exception whenever trying to load index page.
Exception:
com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[xxx.xx.xx.xxx:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server xxx.xx.xx.xxx:27017
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:113)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.ConnectException: Permission denied (connect failed)
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 com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:57)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
com.mongodb.diagnostics.logging.JULLogger log
INFO: No server chosen by ReadPreferenceServerSelector{readPreference=primary} from cluster description ClusterDescription{type=UNKNOWN, connectionMode=SINGLE, serverDescriptions=[ServerDescription{address=xxx.xx.xx.xxx:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.ConnectException: Permission denied (connect failed)}}]}. Waiting for 30000 ms before timing out
Other details:
- Two security group have been created. 1 for Web application 2 Mongodb
- EC2 Web application is running on RHEL + Java 1.8 + Tomcat
- EC2 Mongo instance is running on RHEL (followed instructions from https://docs.mongodb.com/manual/tutorial/install-mongodb-on-red-hat/)
- Java Driver is used to connect to MongoDB is { driver: { name: "mongo-java-driver", version: "3.4.1" }
- bind_ip is set to 0.0.0.0 and no administrative security at this moment.
Assumption:
I am certain that mongodb ec2 instance is accepting connection as i can connect from local workspace.
Any clue or direction in this regards will be really helpful. Thanks.
bind_ip set to 0.0.0.0
Security groups are accepting connections from pretty much everywhere and inbound and outbound 0.0.0.0/0
iptables rules set for INPUT and OUTPUT on both instances.

Connection to a derby database in eclipse [duplicate]

i am create a java project and i want to use derby data base and and i am configured database and create database with the name of /home/user/TestDB and create a table user and insert 3 to 4 values into it and write a code to get the data from database but when i connect dada base i got connection refuse error, i am use
DB URL : jdbc:derby://localhost:1527/home/user/TestDB
error logs :
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at test.derby.util.DerbyUtil.getConnecation(DerbyUtil.java:34)
at test.derby.dao.TestDAO.getData(TestDAO.java:20)
at test.derby.dao.TestDAO.main(TestDAO.java:39)
Caused by: org.apache.derby.client.am.DisconnectException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.
at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
at org.apache.derby.client.am.Connection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection40.<init>(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(Unknown Source)
... 6 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
i think you are not start your derver server in specific port which you are using. you need to start server using below command on localhost with default port 1527
startNetworkServer -h 0.0.0.0
if you want to change the port you can use below command :
startNetworkServer -p 3301 // new port number
for more you can refer below link;
http://www.vogella.com/tutorials/ApacheDerby/article.html
may be this error occur because of following reasons:
1) Firewall is not permitted for host-port combination
2) Client and Server, either or both of them are not in the network.
3) The server is running but not listening on the port, a client is trying to connect.
4) Server is not running.
5) Incorrect protocol in Connection String
This error occurs just because your database is not connected.
NETBEANS
Go to Services>Database>Java DB>(right click)
After that simply right click on your database and connect database.
Best Solution
To execute the database program
Step 1:
First database server needs to be started
Open a command shell and change to a directory that will hold the database
files(in this following example the database going to stored in
D:\java2019\Database)
D:\java2019\Database>"C:\Program Files\Java\jdk1.8.0_60\db\bin\startNetworkServer“
Wed Mar 13 10:36:36 IST 2019 : Security manager installed using the Basic server security policy.
Wed Mar 13 10:36:37 IST 2019 : Apache Derby Network Server - 10.11.1.2 - (1629631) started and ready to accept connections on port 1527
The default port number is 1527 we can also change the port number by the following
cmd
D:\java2019\Database>"C:\Program Files\Java\jdk1.8.0_60\db\bin\startNetworkServer" -p 1567
Wed Mar 13 10:46:33 IST 2019 : Security manager installed using the Basic server security policy.
Wed Mar 13 10:46:33 IST 2019 : Apache Derby Network Server - 10.11.1.2 - (1629631) started and ready to accept connections on port 1567
Step2:
compile and execute the java program
Open another command shell and change to a directory that will hold the database files. set the classpath for derbyrun.jar
set classpath=".;C:\Program Files\Java\jdk1.8.0_66\db\lib\derbyrun.jar”
Step3:
Finally the database server needs to be stopped
Open another command shell and change
D:\java2019\Database>"C:\Program Files\Java\jdk1.8.0_60\db\bin\stopNetworkServer"
Wed Mar 13 10:56:04 IST 2019 : Apache Derby Network Server - 10.11.1.2 - (1629631) shutdown

Error connecting to server localhost on port 1527 with message Connection refused

i am create a java project and i want to use derby data base and and i am configured database and create database with the name of /home/user/TestDB and create a table user and insert 3 to 4 values into it and write a code to get the data from database but when i connect dada base i got connection refuse error, i am use
DB URL : jdbc:derby://localhost:1527/home/user/TestDB
error logs :
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.
at org.apache.derby.client.am.SQLExceptionFactory40.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.jdbc.ClientDriver.connect(Unknown Source)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:208)
at test.derby.util.DerbyUtil.getConnecation(DerbyUtil.java:34)
at test.derby.dao.TestDAO.getData(TestDAO.java:20)
at test.derby.dao.TestDAO.main(TestDAO.java:39)
Caused by: org.apache.derby.client.am.DisconnectException: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused.
at org.apache.derby.client.net.NetAgent.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.newAgent_(Unknown Source)
at org.apache.derby.client.am.Connection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection.<init>(Unknown Source)
at org.apache.derby.client.net.NetConnection40.<init>(Unknown Source)
at org.apache.derby.client.net.ClientJDBCObjectFactoryImpl40.newNetConnection(Unknown Source)
... 6 more
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
i think you are not start your derver server in specific port which you are using. you need to start server using below command on localhost with default port 1527
startNetworkServer -h 0.0.0.0
if you want to change the port you can use below command :
startNetworkServer -p 3301 // new port number
for more you can refer below link;
http://www.vogella.com/tutorials/ApacheDerby/article.html
may be this error occur because of following reasons:
1) Firewall is not permitted for host-port combination
2) Client and Server, either or both of them are not in the network.
3) The server is running but not listening on the port, a client is trying to connect.
4) Server is not running.
5) Incorrect protocol in Connection String
This error occurs just because your database is not connected.
NETBEANS
Go to Services>Database>Java DB>(right click)
After that simply right click on your database and connect database.
Best Solution
To execute the database program
Step 1:
First database server needs to be started
Open a command shell and change to a directory that will hold the database
files(in this following example the database going to stored in
D:\java2019\Database)
D:\java2019\Database>"C:\Program Files\Java\jdk1.8.0_60\db\bin\startNetworkServer“
Wed Mar 13 10:36:36 IST 2019 : Security manager installed using the Basic server security policy.
Wed Mar 13 10:36:37 IST 2019 : Apache Derby Network Server - 10.11.1.2 - (1629631) started and ready to accept connections on port 1527
The default port number is 1527 we can also change the port number by the following
cmd
D:\java2019\Database>"C:\Program Files\Java\jdk1.8.0_60\db\bin\startNetworkServer" -p 1567
Wed Mar 13 10:46:33 IST 2019 : Security manager installed using the Basic server security policy.
Wed Mar 13 10:46:33 IST 2019 : Apache Derby Network Server - 10.11.1.2 - (1629631) started and ready to accept connections on port 1567
Step2:
compile and execute the java program
Open another command shell and change to a directory that will hold the database files. set the classpath for derbyrun.jar
set classpath=".;C:\Program Files\Java\jdk1.8.0_66\db\lib\derbyrun.jar”
Step3:
Finally the database server needs to be stopped
Open another command shell and change
D:\java2019\Database>"C:\Program Files\Java\jdk1.8.0_60\db\bin\stopNetworkServer"
Wed Mar 13 10:56:04 IST 2019 : Apache Derby Network Server - 10.11.1.2 - (1629631) shutdown

Exceptions not being handled correctly with MongoDB Java driver

I'm having an issue with the MongoDB Java driver (Using driver version 3.0.4 and MongoDB version 3.2.3). I'm trying to check whether a connection opens to the MongoDB server and throw an exception if not. I should be able to catch it with:
servName = "Username";
servPW = "Password";
try {
MongoCredential cred = MongoCredential.createCredential(servName, "DatabaseName", servPW.toCharArray());
MongoClient mongo = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(cred));
} catch (MongoException e){
System.out.println("ERROR");
}
System.out.println("WE ARE HERE");
The problem I'm having is that the exception that is thrown isn't caught, it seems to be coming from a thread that I can't access maybe? For testing I don't have a Mongo server running just to see the exception that gets thrown. Similar to the issue in this question (MongoDB java driver 3.0 can't catch exception when authenticate). This is the output:
Mar 02, 2016 12:24:17 PM com.mongodb.diagnostics.logging.JULLogger
log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN,
serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
WE ARE HERE
Mar 02, 2016 12:24:18 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Exception in monitor thread while connecting to server localhost:27017
com.mongodb.MongoSocketOpenException: Exception opening socket at com.mongodb.connection.SocketStream.open(SocketStream.java:63) at
com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114)
at
com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
at
java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85)
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.PlainSocketImpl.connect(PlainSocketImpl.java:172) at
java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at
java.net.Socket.connect(Socket.java:589) at
com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
I've tried to catch "com.mongodb.MongoSocketOpenException", "Exception" and a number of others but nothing seems to work! Is anybody able to help me with where I'm going wrong?
I was unable to find an answer to this question and couldn't work it out myself. In order to work around this issue I downgraded to driver version 2.11.1 and used that!
From what I can gather, the move to Mongo 3 drivers alters the behaviour of creating a Mongo Client - it becomes a non-blocking operation and you only find out whether you actually have a working connection when you try to use it.
The video I watched about this (https://www.mongodb.com/presentations/mongodb-drivers-and-high-availability-deep-dive ) suggests using the client immediately after creating it to check whether it has been successful - it recommends using the command that asks whether or not the connected server is the "master" ( not sure what this is in Java ) .

Solr Read Timeout (only in production environment)

I am working with a Java application that uses SolrJ to index documents to a Solr server.
In my local test environment, I run a local Solr instance on a Tomcat server on my windows xp box. When I run the Java app from a different Windows box, the indexing completes successfully and the Solr log files look normal.
However, running the same Java application deployed on linux webserver communicating to another linux webserver running Solr, I receive "read timed out" messages after every solr update command:
Jul 14, 2011 3:12:31 AM org.apache.solr.core.SolrCore execute INFO: []
webapp=/solr path=/update params={wt=javabin&version=1} status=400
QTime=20020 Jul 14, 2011 3:12:51 AM
org.apache.solr.update.processor.LogUpdateProcessor finish INFO: {} 0
20021 Jul 14, 2011 3:12:51 AM org.apache.solr.common.SolrException log
SEVERE: org.apache.solr.common.SolrException:
java.net.SocketTimeoutException: Read timed out at
org.apache.solr.handler.XMLLoader.load(XMLLoader.java:72) at
org.apache.solr.handler.ContentStreamHandlerBase.handleRequestBody(ContentStreamHandlerBase.java:54)
at...
Caused by:
javax.xml.stream.XMLStreamException: java.net.SocketTimeoutException:
Read timed out
Any idea why this might be happening? My suspicion is that something is closing these connections after they are initiated (e.g. web filtering software, firewall...), but the network admins at my workplace say that no traffic is being blocked.
Is it getting timedout only with updates or even with querying?
Check the server settings on the linux server machine whether it has very less timeout value.

Categories

Resources