MongoDB: check connection to DB - java

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

Related

Does MariaDB disconnect automatically or Should i have to disconnect Manually?

I got to use MariaDB for my University Project.
it's my first time doing it, so I dont't know well how to use and code JDBC Driver and mariaDB.
Now I'm implementing the code in many places while looking at examples.
As I see, All the examples seems to creating Statement and making connection by using "DriverManager.getConnection"
Now I have a question.
I'm going to create a DBmanager Class that can connect, create tables, execute queries, and execute the code that updates data on tables in a single line.
I thought all the examples would run alone in one method and came from different places, so I could only try a new connection and create a code that would not close. But I have a gut feeling that this will be a problem.
Is there any way I can leave a connection connected at a single connection to send a command, and disconnect it to DB.disconnect()? And I'd appreciate it if you could tell me whether what I'm thinking is right or wrong.
The code below is the code I've written so far.
I am sorry if you find my English difficult to read or understand. I am Using translator, So, my English could not be display as I intended.
import java.sql.*;
import java.util.Properties;
public class DBManager {
/*********INNITIAL DEFINES********/
final static private String HOST="sumewhere.azure.com";//Azure DB URL
final static private String USER="id#somewhere";//root ID
final static private String PW="*****";//Server Password
final static private String DRIVER="org.mariadb.jdbc.Driver";//DB Driver info
private String database="user";
/***************API***************/
void setDB(String databaseinfo){
database=databaseinfo;
}
private void checkDriver() throws Exception
{
try
{
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
}
public void checkOnline(String databaseinfo) throws Exception
{
setDB(databaseinfo);
this.checkDriver();
Connection connection = null;
try
{
String url = String.format("jdbc:mariadb://%s/%s", HOST, database);
// Set connection properties.
Properties properties = new Properties();
properties.setProperty("user", USER);
properties.setProperty("password", PW);
properties.setProperty("useSSL", "true");
properties.setProperty("verifyServerCertificate", "true");
properties.setProperty("requireSSL", "false");
// get connection
connection = DriverManager.getConnection(url, properties);
}
catch (SQLException e)
{
throw new SQLException("Failed to create connection to database.", e);
}
if (connection != null)
{
System.out.println("Successfully created connection to database.");
}
else {
System.out.println("Failed to create connection to database.");
}
System.out.println("Execution finished.");
}
void makeCcnnection() throws ClassNotFoundException
{
// Check DB driver Exists
try
{
Class.forName("org.mariadb.jdbc");
}
catch (ClassNotFoundException e)
{
throw new ClassNotFoundException("MariaDB JDBC driver NOT detected in library path.", e);
}
System.out.println("MariaDB JDBC driver detected in library path.");
Connection connection = null;
}
public void updateTable(){}
public static void main(String[] args) throws Exception {
DBManager DB = new DBManager();
DB.checkOnline("DB");
}
}
For a studying project it's okay to give a connection from your DB Manager to client code and close it there automatically using try-with-resources construction.
Maybe you will find it possible to check Connection Pool tools and apply it further in your project or use as example (like HikariCP, here is a good introduction).
Read about Java try with resources. I think that this link could be usefull for your problem.
JDBC with try with resources

Collecting command responses from mocked SSH server (Apache MINA)

So what I'm trying to do, is create unit test that checks if invoked command (on shell via ssh connection) has a proper response. The problem is that I can't read those responses. There are not many tutorials regarding Apache MINA, so I thought maybe some of you could help me out. Here's a code
#Before
public void setUpSSHd() {
sshd=SshServer.setUpDefaultServer();
sshd.setPort(22999);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
sshd.setPasswordAuthenticator(new PasswordAuthenticator() {
public boolean authenticate(String username, String password, ServerSession session) {
// TODO Auto-generated method stub
return true;
}
});
List<NamedFactory<KeyExchange>> keyExchangeFactories;
keyExchangeFactories = sshd.getKeyExchangeFactories();
sshd.setKeyExchangeFactories(keyExchangeFactories);
try {
sshd.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#After
public void teardown() throws Exception { sshd.stop(); }
#Test
public void testCommands() throws Exception {
SshClient client = SshClient.setUpDefaultClient();
client.start();
ClientSession session = null;
try {
session = client.connect("localhost", 22999).await().getSession();
session.authPassword("none", "none").await().isSuccess();
System.out.println("Connection established");
final ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
ByteArrayOutputStream sent = new ByteArrayOutputStream();
PipedOutputStream pipedIn = new TeePipedOutputStream(sent);
channel.setIn(new PipedInputStream(pipedIn));
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayOutputStream err = new ByteArrayOutputStream();
channel.setOut(out);
channel.setErr(err);
channel.open();
pipedIn.write("dir\r\n".getBytes());
pipedIn.flush();
channel.waitFor(ClientChannel.CLOSED, 0);
channel.close(false);
client.stop();
System.out.println(out.toString());
} catch (Exception e) {
e.printStackTrace();
fail("Cannot establish a connection");
} finally {
if (session != null)
session.close(true);
}
}
For now I simply try to print out collected response. However I get empty string everytime I try to do that. I assume there might be a problem with ssh server configuration (what shell is it supposed to use?). The best scenario would be if I could define my own commands and responses on server side and then, only check it on client side
EDIT: I've tried to manually connect to this mocked ssh server but I've got
Unable to negotiate with ::1 port 22999: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
error message.
I would suggest you to update Apache SSH. Based the source repository the version 0.5.0 is 7 years old.
using your posted code with the default JCE provider and Apache SSH
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>0.5.0</version>
<dependency>
the connect with a ssh client fails with
Their offer: diffie-hellman-group1-sha1
using a more recent Apache SSH release
<dependency>
<groupId>org.apache.sshd</groupId>
<artifactId>sshd-core</artifactId>
<version>1.4.0</version>
<dependency>
the connect is successful

how can i handle multiple server MongoDB

Hi all i am new to spring maven project, and i am using MongoDB. I want to use two tomcats/ MongoDB both of theri IP address are different. when first DB is down i need to connect with second one how it is possible
I am using following code
public boolean mongoRunningAt(String uri) {
try {
Mongo mongo = new Mongo(new MongoURI(uri));
try {
Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
socket.connect(mongo.getAddress().getSocketAddress());
socket.close();
} catch (IOException ex) {
mongo = new Mongo(new MongoURI(uri_second));
Socket socket = mongo.getMongoOptions().socketFactory.createSocket();
socket.connect(mongo.getAddress().getSocketAddress());
socket.close();
//return false;
}
mongo.close();
return true;
} catch (UnknownHostException e) {
return false;
}
}
Using this code i tried with first one successfully connected, now stoped first DB now restarted server it is connected with second db.
But if i didn't restart server it is always pointing to First only... how should i work on this
Thanks in advance
You deployed 2 servers, are they in a replica set. If not you can follow the link.
When they are already in a replica set you can use a connectionstring containing the 2 servers.
Like this:
mongodb://db1.example.net,db2.example.net:2500/?replicaSet=test

Mongo client {Mongo-Java-driver} creation hangs duration . No exception thrown

I have a cron-job running at a Linux machine running after every 5 minutes. The job executes a Java class.
private MongoClient createConnection(int retry,List<ServerAddress> host){
try {
System.out.println("Retrying----------"+retry);
MongoClient client = new MongoClient(host, MongoClientOptions.builder()
.connectionsPerHost(10)
.threadsAllowedToBlockForConnectionMultiplier(5)
.connectTimeout(5000).writeConcern(WriteConcern.NORMAL).build());
client.getDB("admin").command("ping").throwOnError();
retry = 0;
return client;
} catch (Exception e) {
retry++;
if (retry < retryLimit) {
createConnection(retry,host);
} else {
System.out.println("Connection could not be established to host-"+host);
}
return null;
}
}
retry is the integer value denoting how many times client creation can be tried in case host is unreachable.
The host list that i am passing is -
public static List<ServerAddress> HOST_SCRIPT = new ArrayList<ServerAddress>() {
private static final long serialVersionUID = 1L;
{
try {
add(new ServerAddress("PrimaryHost23", 27017));
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
};
Code is Stuck when i MongoClient is being created. It does not happen always. Code works fine and NEVER hangs when i run on my local machine. There is no exception thrown.
I recently upgraded Linux machine OS (from CentOS 5 to CentOS 6). Can this be responsible for this because this script was working fine earlier.
Please help.
Regards,
Vibhav
The thing what you can do is you can throw mongo exception try out that of mongo client is stuck you will get to know try out this https://api.mongodb.org/java/2.6/com/mongodb/MongoException.html
Yes of course, actually i was creating crawler in java which fetch all the links of any particular website and validate the css and html structure Using the Jsoup and jcabi api but when i used to store links to the database it was not throwing any exception and even not storing the data also. so i did this
catch (MongoException e){
System.err.print(e.getClass().getName()+": "+e.getMessage());
}
Have you checked the compatibility like of jar that you have uploaded for your project like before it was like Mongo mongo = new Mongo(host,port); but That is deprecated. Try to check that and even your MongoDb jar.

Java Kryonet servers, client not receiving server response

I am trying to teach myself some networking in Java using the Kryonet library. The following code is almost identical to the code in the kyronet tutorial. https://code.google.com/p/kryonet/#Running_a_server
The client is successfully sending the message "Here is the request!" to the server (the server is printing it out) however the client is not receiving any response from the server even though the server is sending one.
I've tried unsuccessfully to fix it, can anyone see or suggest a possible problem/solution with the code?
(The code follows)
Client
public class Client_test {
Client client = new Client();
public Client_test() {
Kryo kryo = client.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
client.start();
try {
client.connect(50000, "127.0.0.1", 54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeResponse) {
SomeResponse response = (SomeResponse)object;
System.out.println(response.text);
}
}
});
SomeRequest request = new SomeRequest();
request.text = "Here is the request!";
client.sendTCP(request);
}
}
Server
public class ServerGame {
Server server = new Server();
public ServerGame() {
Kryo kryo = server.getKryo();
kryo.register(SomeRequest.class);
kryo.register(SomeResponse.class);
server.start();
try {
server.bind(54555, 54777);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
server.addListener(new Listener() {
public void received (Connection connection, Object object) {
if (object instanceof SomeRequest) {
SomeRequest request = (SomeRequest)object;
System.out.println(request.text);
SomeResponse response = new SomeResponse();
response.text = "Thanks!";
connection.sendTCP(response);
}
}
});
}
}
Response & Request classes
public class SomeRequest {
public String text;
public SomeRequest(){}
}
public class SomeResponse {
public String text;
public SomeResponse(){}
}
After many hours watching youtube videos and sifting through the web I found the answer. Which I will post on here as it seems that quite a few people have had this problem so I would like to spread the word.
Basically the client would shut down immediately, before it could receive and output the message packet. This is because "Starting with r122, client update threads were made into daemon threads, causing the child processes to close as soon as they finish initializing.", the solution is "Maybe you could use this? new Thread(client).start();".
So basically instead of using
client.start();
to start the client thread you must use
new Thread(client).start();
Which I believe stops the thread being made into a daemon thread which therefore stops the problem.
Source: https://groups.google.com/forum/?fromgroups#!topic/kryonet-users/QTHiVmqljgE
Yes, inject a tool like Fiddler in between the two so you can see the traffic going back and forth. It's always easier to debug with greater transparency, more information.

Categories