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());
Related
I'm trying to connect to a remote machine which has docker installed. I want to exec into the docker container and connect to database and then fetch a table data using java.
Following are my commands that i'm trying to execute.
docker exec it containerID - to login to docker container
cqlsh -u username -p password -- to connect to cassandra DB
use keyspace; ---to connect to cassandra keyspace
desc tables; --- to view the tables that are available in keyspace.
Following is the Java code that I'm trying. Can someone let me know if this approach is correct or what should i do to make this code work. I'm completely new to java code.
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
public class ExecuteanyCommands {
public static void main(String[] args) throws JSchException, InterruptedException, IOException {
//JSch
JSch jsch = new JSch();
Session session = jsch.getSession("cambi", "10.10.96.20", 22);
session.setPassword("axone");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("exec");
InputStream in = channel.getInputStream();
((ChannelExec) channel).setCommand("docker exec -it containerID; cqlsh -u username -p password; use keyspace; desc tables;");
channel.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
channel.disconnect();
session.disconnect();
}
}
If you want to connect to a container from a remote machine over SSH, then the way to do it is to define an SSH tunnel, external to your Java program.
In addition, the idea of interacting with Cassandra by running cqlsh on the host is very unusual.
It's better to use the official Cassandra Java driver for that purpose.
To summarize:
Create an SSH tunnel between the client and the docker host
Write a Java program that uses the Java Driver to query Cassandra
I echo Jonathan Jacobson's point that your method isn't the correct. Running cqlsh which itself is an app/client to retrieve data from your Cassandra tables is incorrect.
You need to instead use one of the available Cassandra drivers to connect to your cluster. In your case, it would be the Java driver for Apache Cassandra.
On the Astra DB docs site, there's a fully working Java code example for connecting to a cluster. Here's a stripped down version that you can use:
import com.datastax.oss.driver.api.core.CqlSession;
import com.datastax.oss.driver.api.core.cql.ResultSet;
import com.datastax.oss.driver.api.core.cql.Row;
public class ConnectDatabase {
public static void main(String[] args) {
try (CqlSession session = CqlSession.builder()
.withAuthCredentials("your_username","your_password")
.build()) {
// select the release_version from the system.local table
ResultSet rs = session.execute("SELECT release_version FROM system.local");
Row row = rs.one();
// print the results to the console
if (row != null) {
System.out.println(row.getString("release_version"));
} else {
System.out.println("An error occurred.");
}
}
System.exit(0);
}
}
You'll need to get a copy of the example pom.xml file to compile the app. You can get more information about the Java driver here.
Note that you will need to expose the ports in Docker so that Cassandra is accessible from outside the container. For example, map the CQL port with -p 9042:9042.
If you're new to Cassandra, I recommend having a look at datastax.com/dev which has lots of free hands-on interactive learning resources. In particular, the Cassandra Fundamentals learning series lets you learn the basic concepts quickly.
For what it's worth, you can also use the Stargate.io data platform. It allows you to connect to a Cassandra cluster using APIs you're already familiar with. It is fully open-source so it's free to use. Here are links to the Stargate tutorials on datastax.com/dev: REST API, Document API, GraphQL API, and more recently gRPC API.
Finally, we also run live workshops for free to teach developers how to build apps for Cassandra. We provide all the materials including all the source code for fully working apps plus coding environments on the cloud so there's nothing for you to install. There are 2-3 workshops every week and details are at datastax.com/workshops. Cheers!
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.
I want to write a java application that uses a mysql database to store and retrieve information. I am still just a beginner and I do not have a lot of knowledge on web hosting providers and server architecture. In this application, several clients will have to access this remote database located on a server machine maybe.
Currently, I can connect to the database from the same computer that runs the mysql server (I am using workbench by the way). Any suggestions on what should I do?
public static Connection openDatabase()
{
Connection myConn;
try {
myConn =
DriverManager.getConnection(Configs.getProperty("DatabaseURL"));
return myConn;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
The url is:
jdbc:mysql://Atomic-PC:3306/test?autoReconnect=true&rewriteBatchedStatements=true&useSSL=false&user=root&password=password
First of all you have to find connection URL, port and credential from MySql workbench you are using. If hosting provider provides a public IP for DB server you should be able to access it from anywhere by using following code in Java.
import java.sql.Connection;
import java.sql.DriverManager;
public class Main {
public static void main(String[] argv) throws Exception {
String driver = "com.mysql.jdbc.Driver";
String connection = "jdbc:mysql://localhost:3306/YourDBName";
String user = "root";
String password = "root";
Class.forName(driver);
Connection con = DriverManager.getConnection(connection, user, password);
if (!con.isClosed()) {
con.close();
}
}
}
For this reason you have to import mysql connection driver to your application first.
If you are trying to connect to remote database then yo need to change the database url from localhost to remote server ip address.
jdbc:mysql://Atomic-PC:3306/test
to
jdbc:mysql://<db-server-ip-address>:<db-server-port>/<db-name>
Assuming, remote server ip address is 10.234.05.123 and database port number is 3300 and database name is remoteDB. Then,
jdbc:mysql://10.234.05.123:3300/remoteDB
your web hosting company should be able to provide you with the url:port which you can use in your connection string to connect to MySQL(or any other remote db for that matter)
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 :)
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.