I have a ppk file and username "x#domain.com", which I use to connect to Apache cassandra through putty from my windows system. What code snippet can be used in java using datastax to connect the same.I could see the IP of cassandra system from putty terminal.
package com.cassandra.tutorial;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class CassConnector {
private static Cluster cluster;
private static Session session;
public static Cluster connect(String node)
{
return cluster.builder().addContactPoint(node).build();
}
public static void main(String args[])
{
cluster=connect("172.31.yy.xx");
session=cluster.connect("core");
session.execute("USE core");
session.close();
cluster.close();
}
}
PPK file is used by Putty to connect to host with Cassandra via SSH protocol.
You can connect to Cassandra itself only by using username & password configured inside it. See corresponding part of Cassandra's documentation on how to enable & configure password-based authentication.
After you configure it, you just need to add the call of withCredentials function into your cluster building chain, and pass username & password to it.
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!
Has anyone managed to connect a java program to AWS DocumentDB where the java program is running outside of AWS and DocumentDB has tls enabled? Any examples or guidance provided would be greatly appreciated.
This is what I've done so far =>
I've been following AWS's developer guide and I understand to be able to do this I need an SSH tunnel set up to a jump box (EC2 instance) and then to the DB Cluster. I have done this and connected from my laptop.
I have then created the required .jks file from AWS's rds-combined-ca-bundle.pem file and referenced it in a basic java main class. From the java main class I have referenced the cluster as localhost:27017 as this is where I've set up the SSH tunnel from.
My test code is following the AWS example for Java and I get the following error when I run the program =>
Caused by: javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching localhost found.
public class CertsTestMain {
public static void main(String[] args) {
String template = "mongodb://%s:%s#%s/test?ssl=true&replicaSet=rs0&readpreference=%s";
String username = "dummy";
String password = "dummy";
String clusterEndpoint = "localhost:27017";
String readPreference = "secondaryPreferred";
String connectionString = String.format(template, username, password, clusterEndpoint, readPreference);
String truststore = "C:/Users/eclipse-workspace/certs/certs/rds-truststore.jks";
String truststorePassword = "test!";
System.setProperty("javax.net.ssl.trustStore", truststore);
System.setProperty("javax.net.ssl.trustStorePassword", truststorePassword);
MongoClient mongoClient = MongoClients.create(connectionString);
MongoDatabase testDB = mongoClient.getDatabase("test");
MongoCollection<Document> bookingCollection = testDB.getCollection("booking");
MongoCursor<Document> cursor = bookingCollection.find().iterator();
try {
while (cursor.hasNext()) {
System.out.println(cursor.next().toJson());
}
} finally {
cursor.close();
}
}
}
So, for me, to make this work I only had to alter the template to:
String template = "mongodb://%s:%s#%s/test?sl=true&tlsAllowInvalidHostnames&readpreference=%s";
As long as you have created your .jks file correctly
(I did this simply it by using a linux env and running the script AWS provide for Java in the following link in Point 2 => https://docs.aws.amazon.com/documentdb/latest/developerguide/connect_programmatically.html)
and you have a fully working ssh tunnel as described in https://docs.aws.amazon.com/documentdb/latest/developerguide/connect-from-outside-a-vpc.html
then the above code will work.
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 have created MySQL database for my website using cPanel and phpMyAdmin on remote host and now i want to connect to this database my simple java program.I try this code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Main {
public static void main(String[] args) {
try{
Connection con=DriverManager.getConnection("jdbc:mysql://sfg.ge/sfgge_mysql", "my_username", "my_password");
Statement state=(Statement) con.createStatement();
String name="shota";
int id=3;
String insert = "INSERT INTO student VALUES ("+ id +",'"+ name +"')";
state.executeUpdate(insert);
}
catch(Exception ex){
}
}
}
In this code
DriverManager.getConnection(String url, username, pass)
SQLException throws such error:
null, message from server:
"Host '188.129.228.176' is not allowed to connect to this MySQL server"
Any suggestions appreciated.
Add new account:
'user1'#'exact_host' - host is specified
CREATE USER 'user1'#'exact_host'
or
'user1'#'%' - for any host.
CREATE USER 'user1'#'%'
Grant privileges you need and connect with new account.
Also look at this:
Make sure that the server has not been configured to ignore network connections or (if you are attempting to connect remotely) that it has not been configured to listen only locally on its network interfaces. If the server was started with --skip-networking, it will not accept TCP/IP connections at all. If the server was started with --bind-address=127.0.0.1, it will listen for TCP/IP connections only locally on the loopback interface and will not accept remote connections
I am unable to connect to a MySQL server which is hosted on a linux server through netbeans.
All of these credentials work when connecting through MySQL Workbench "Standard TCP/IP through ssh".
Here is my code:
public class Database {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://john.myschool.edu:3306/cs3610";
private static final String USERNAME = "mbrooke";
private static final String PASSWORD = "mypass";
private Connection connection;
public Database() throws Exception{
try{
connect();
}catch(SQLException e){
if(connection !=null){
connection.close();
}
}
}
//Open connection to database
private void connect() throws Exception{
connection = null;
Class.forName (DRIVER).newInstance ();
connection = DriverManager.getConnection(URL,USERNAME,PASSWORD);
}
}
I am getting SQLException with #521 on the line that starts "connection = DriverManager..." and I'm not sure what is causing this problem. The driver seems to be installed correctly as, when stepping through, I make it past the "Class.forName(D..." line with no exceptions thrown.
It sounds like your Database server doesn't have port 3306 open, or your MySQL credentials aren't allowed to use remote connections.
MySQL Workbench's TCP/IP over SSH setting first opens an SSH connection to the SSH server, then connects to the database server (often localhost or 127.0.0.1). So the MySQL connection is actually initiated from the SSH server. So the ability to connect through that channel only demonstrates that your java code would work if it were running on the server into which you're SSHing. But you may still have a firewall or MySQL permissions issue when trying to run the code from another machine.
I would try downloading a MySQL client to your machine and seeing if you can connect using that method: mysql -h myDatabaseServer.school.edu cs3610 -u mbrooke -p'mypass' and see if that works. You'll likely either get a "connection not available" error or a "user mbrooke doesn't have permission to access remotely" which should give you some insight into which problem you're facing.
Try it without ending slash
URL = "jdbc:mysql://john.myschool.edu:3306/cs3610/";
like
URL = "jdbc:mysql://john.myschool.edu:3306/cs3610";
or you have a Database named "cs3610/"