How to connect to a Cloud Foundry MySQL database connection in Java? - java

create mysql as service on Cloud Foundry and tunnel to mysql database
this provides me connection string to mysql database i pass that information to my app.
it works from my machine but when i deployed that app on Cloud Foundry server then it gives an error in connection
this is my connection code, tell me what needs to change to be deployed on Cloud Foundry
public class DB {
private static Connection connection = null;
public static Connection getConnection() {
String url = "jdbc:mysql://127.0.0.1:10100/db8dad2d02e114ef6bc9d24e68367e33e";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,"uC0ag3NRJCT8c","p1nyZ38zadwfa");
System.out.println("Connect success fully");
return connection;
} catch (Exception e) {
System.out.println("Error");
System.out.println(e);
e.printStackTrace();
}
return null;
}
}

jayesh's answer is technically correct, but basically, the best way to deal with retrieving those information when inside a java app (assuming non-spring) is to use the cloudfoundry-runtime library: https://github.com/cloudfoundry/vcap-java/tree/master/cloudfoundry-runtime The README has examples of usage.
For completness, if using Spring, then things are even easier and chances are you don't even need to do anything special

Problem is here:
jdbc:mysql://127.0.0.1:10100
In this you're connecting to 127.0.0.1, it is a localhost, try giving the actual IP of your cloud server. Then it should work fine.

try {
String vcap_services = System.getenv("VCAP_SERVICES");
String hostname = "";
String dbname = "";
String user = "";
String password = "";
String port = "";
//for cloud config
if (vcap_services != null && vcap_services.length() > 0) {
JsonRootNode root = new JdomParser().parse(vcap_services);
JsonNode mysqlNode = root.getNode("mysql-5.1");
JsonNode credentials = mysqlNode.getNode(0).getNode(
"credentials");
dbname = credentials.getStringValue("name");
hostname = credentials.getStringValue("hostname");
user = credentials.getStringValue("user");
password = credentials.getStringValue("password");
port = credentials.getNumberValue("port");
String dbUrl = "jdbc:mysql://" + hostname + ":" + port + "/"
+ dbname;
System.out.println(dbUrl);
System.out.println(user + "password " + password);
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(dbUrl, user, password);
return connection;
} else {
//for local configuration
Class.forName("com.mysql.jdbc.Driver");
String url = jdbc:mysql://127.0.0.1:10100/db8dad2d02e114ef6bc9d24e68367e33e
connection = DriverManager.getConnection(url, "user name",
"password");
return connection;
}
} catch (Exception e) {
e.printStackTrace();
}

You're using information from vmc tunnel to try to connect. This is not going to work on the Cloud. You need to do what jayesh shows, and read the connection credentials from the Cloud Foundry environment instead. Eric's answer is even more complete :-)

I have the same problem. You must notice that "10100" is a port fortwarding to the mysql remote service.
you could use this just locally.Deploying your program locally with your database connection pointing to the forwarding port (101100).
But this won't work when you push your war to the Cloud Foundry Instance-
One solution is to use Spring based cloud beans. In my case i don't wan't to use this approach so i'm trying another solution...
I don't know if with the credentials (user, password, tc) created for the remote connection you could stablish a connection once you pushed your war to Cloud Foundry changing the forwarding port and using the default mysql port (3360)
In my case i don't want to use Spring Cloud Beans because the production application won't be deployed into a cloud storage.

Related

Moving a database in netbeans to another computer

I made a fairly small java program in netbeans, with the database saved in the scr folder under database/mainUserData, On my main pc, if i export it to a .jar folder, It works, If i copy all the data in the folder (70mb's worth) to another pc, it can't find the database any more, I made sure to add code that always uses the current directory in the jar folder as a url to the database, this is the connection code:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", "jacovanstryp", "Password1234");
Why is it when i move it to another computer (The whole file, it no longer knows where the database is?
What I have Tried:
URL url = this.getClass().getResource("/com/vanstryp/res/Database/MainUserData"); // This is the same directory as where the .jar is located
This just returns Null.
This is the top Error code it returns
java.sql.SQLNonTransientConnectionException: java.net.ConnectException : Error connecting to server localhost on port 1,527 with message Connection refused: connect.
This is the code for the method I used
public boolean checkLogin(String username, String password) {
try {
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//This code will connect the database to the java program
//Information to connect database obtained from --> https://www.youtube.com/watch?v=c7RZV4VLv3s
Connection myconObj = null; //allows to connect to database
Statement mystatObj = null; // create statement (Execute queries)
ResultSet myresObj = null; // get result
ResultSetMetaData mymeta = null;
try {
String query = "select * from JACOVANSTRYP.MAINUSERDATA";
URL databaseLocation = this.getClass().getResource("/com/vanstryp/database/MainUserData/");
myconObj = DriverManager.getConnection("jdbc:derby:/" + databaseLocation, "jacovanstryp", "Eduplex1234");
mystatObj = myconObj.createStatement();
myresObj = mystatObj.executeQuery(query);
mymeta = myresObj.getMetaData();
int colomnNo = mymeta.getColumnCount();
while (myresObj.next()) {
String dbUsername = myresObj.getString("Username");
String dbPassword = myresObj.getString("Password");
System.out.println();
if (username.equalsIgnoreCase(dbUsername) && password.equals(dbPassword)) {
PrintWriter activeUser = new PrintWriter(new FileWriter("activeUser.db"));
activeUser.println(dbUsername);
activeUser.close();
return true;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
} catch
(ClassNotFoundException ex) {
Logger.getLogger(commonMethods.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
This line:
myconObj = DriverManager.getConnection("jdbc:derby://localhost:1527/MainUserData", ...);
uses a connection string of "jdbc:derby://localhost:1527/MainUserData". That means that you have setup (maybe through Netbeans) a Derby server on that computer listening on port 1527.
Copying a jar and the file backing the database is not enough: you must start the Derby server on the new host or use the one from the old host:
myconObj = DriverManager.getConnection("jdbc:derby://other.host.full.name:1527/MainUserData", ...);
Alternatively, you could use the embedded mode of Derby. Then you just have to declare which folder contains the database file:
myconObj = DriverManager.getConnection("jdbc:derby:/path/to/MainUserData", ...);
In this mode, you can just copy both the jar (and its optional other files) and the database to the new system, and it should find the database if you give a correct path.

Cloud SQL/MySQL, App engine and bitcoinj

I'm developing a web app that uses app engine (java) as a backend. I need the backend to listen for received transactions and broadcast transactions on the bitcoin network. I have bitcoinj set up to handle this functionality but I can't seem to get the blockstore object initialize.
Bitcoinj allows me to use mysql to store blocks. The connection is set up like this:
public static void getBlockStore(){
int fullStoreDepth = 1000;
String db = "databasename";
String un = "root";
String pw = "";
String host = "/cloudsql/database-instance-id";//I have also used the ip address, but it didn't work
try {
blockStore = new MySQLFullPrunedBlockStore(network, fullStoreDepth, host, db, un, pw);
logger.info("Blockstore created is " + blockStore);
} catch (BlockStoreException e) {
logger.info("Blockstore error " + e);
}
}
But in the backend I receive a connection error when trying to connect to my database. I don't have or don't know which port to connect to. The other information is all correct. I have tried with another mysql db from godaddy but I got the same error.
How can I get connected to a mysql database either in cloud sql or a normal mysql database?

Connect to MySQL with Java - JDBC without showing credentials in Java source code

I am trying to learn how you would tackle the task of creating a Java console application, connect to a (in this case) MySQL DB and send or retrieve data, without showing your username and password in the source code of the Java application. I currently have no trouble
creating a connection showing credentials.
// JDBC driver name and database URL
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://192.168.1.159:3306/javahelper";
// Database credentials
private static final String USER = "xxxx";
private static final String PASS = "RandomString";
/**
* #return
*/
public Connection openConnection() {
Connection connection = null;
try {
Class.forName(JDBC_DRIVER);
// opening connection
connection = (Connection) DriverManager.getConnection(DB_URL,USER,PASS);
} catch (ClassNotFoundException e) {
System.out.println("This is from openConnection method");
e.printStackTrace();
} catch (SQLException f) {
System.out.println("This is from openConnection method");
f.printStackTrace();
}
return connection;
}
From what information I can gather you always need to show your credentials somewhere in the application. But how do you than achieve "safe" connection between a application and a DB, so others can't misuse your credentials for malicious reasons?
one way of doing it is using a properties file having your credentials or having your data in a xml file.
create a properties file like the one below
// database.properties
DB_URL=jdbc:mysql://localhost:3306/UserDB
DB_USERNAME=user_name
DB_PASSWORD=password
Use this information in your code to get the username and passwords.
Properties properties= new Properties();
FileInputStream input = null;
try{
input = new FileInputStream("database.properties");
props.load(input );
con = DriverManager.getConnection(props.getProperty("DB_URL"),props.getProperty("DB_USERNAME"),props.getProperty("DB_PASSWORD"));
}
you can use encrypt the username and password.The best opensource encryptor(My personal view) is jbcrypt
// Hash a password for the first time
String hashed = BCrypt.hashpw(password, BCrypt.gensalt());
// gensalt's log_rounds parameter determines the complexity
// the work factor is 2**log_rounds, and the default is 10
String hashed = BCrypt.hashpw(password, BCrypt.gensalt(12));
// Check that an unencrypted password matches one that has
// previously been hashed
if (BCrypt.checkpw(candidate, hashed))
System.out.println("It matches");
else
System.out.println("It does not match");
Sharing what i find
Creating and using the propertise file
I created a database.properties file(normal text file) and placed it in the src folder of the Java project.
JDBC_DRIVER=com.mysql.jdbc.Driver
USER=YourUser
PASS=YourPassword
DB_URL=jdbc:mysql://IP:PORT/DB
Afterwards i edited my openConnection() method to use the properties file for loading the credientials of the connection.
public Connection openConnection() {
Properties properties = new Properties();
Connection connection = null;
String path = System.getProperty("user.dir");
path += "/src/database.properties";
try(FileInputStream fin = new FileInputStream(path);) {
properties.load(fin);
try {
Class.forName(properties.getProperty("JDBC_DRIVER"));
// opening connection
connection = (Connection) DriverManager.getConnection(properties.getProperty("DB_URL"),properties.getProperty("USER"),properties.getProperty("PASS"));
} catch (ClassNotFoundException e) {
System.out.println("This is from openConnection method");
e.printStackTrace();
} catch (SQLException f) {
System.out.println("This is from openConnection method");
f.printStackTrace();
}
} catch (IOException io) {
System.out.println("This is from openConnection method");
io.printStackTrace();
}
return connection;
}
Sending username and password, Java application -> MySQL
From what i can read on the web, it dosent matter much if you encrypt or hash the password before you send it towards the sequel service from your Java application. An example i found is that the sequel service dosent have a "receive hash method and authenticate". And even if it did the hash would need to be in the program somewhere. And when the program has access to it, others also have access to it if they really want it. Also if the hash is whats needed to authenticate than your back to where you can just as well use the clear text password.
The discussion than ends on "what is the best approach". Some suggest a keyserver / auth system in between the application and sequel service, using a datastore setup on the server side, using the OS "wallet" (example Windows registry) or creating a database user with minimum permissions to just get the job done / or a read only DB "read_only=1 in my.cnf".
I tried the 3'rd option and created a "DBaccess" user, with only the select permission to retrieve data, no administrative rights and random generated password by MySQL.

Trying to connect to my sql database getting exception saying "no suitable driver found"

I'm using the tutorial at http://www.vogella.com/tutorials/MySQLJava/article.html
to try tp connect to my sql server on my server
When it executes the line:
Connection connect = DriverManager
.getConnection("jdbc:mysql:http://www.findmeontheweb.biz"
+ "user=findmeon_bitcoin&password=PASSWORD");
an exception gets thrown saying "No sutabled driver found for jdbc:mysql:http://www.findmeontheweb.biz
This is what I did
1. Downloaded the "mysql-connecter-java-5.1.33.bin.jar into my lib folder
2. added the jar to my project from preferences.
project code:
public class cStart {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main (String[] args) {
int g=0;
try {
// this will load the MySQL driver, each DB has its own driver
Class.forName("com.mysql.jdbc.Driver");
// setup the connection with the DB.
// EXCEPTION GOES OF HEAR
Connection connect = DriverManager
.getConnection("jdbc:mysql:http://www.findmeontheweb.biz"
+ "user=findmeon_bitcoin&password=PASSWORD");
} catch (Exception e) {
System.out.println("Exception...." );
}
}
}
The URL format should be look like this
jdbc:mysql://hostname/ databaseName
I think this is a much cleaner way to do it:
String URL = "jdbc:URL_TO_YOUR_DATBASE";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
As seen here: http://www.tutorialspoint.com/jdbc/jdbc-db-connections.htm
I say give that link a try with your driver. You also should make sure you have the actual jar for MySQL. It really might be invalid.
I would try the one here: http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm
And then add that to your project.
The URL to the database might be wrong.
If yes you should specify a correct one with including database name.
Else verify if the jdbc driver jar is added in the build-path, if yes try to put it in the lib folder of your webapp.

can't connect to MySQL on localhost

i am trying to connect to Mysql database using the code below , yet my attempt fails.
this is my attempt:
private static Connection conn = null;
private static String url = "jdbc:mysql://localhost/";
private static String dbName = "proj1";
private static String driver = "com.mysql.jdbc.Driver";
private static String userName = "root";
private static String password = "root";
public static int setupConnection ()
{
try{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,"root","root");
return 1;
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e.getMessage());
return 0;
}
}
when installing MySQL i remember entering the password "root" , but im not 100% sure if the username is autmatically assigned "root" , i really appreciate your help.
i get the error message : com.mysql.jdbc.Driver
You need to add the MySQL Connector/J driver to the build-path/classpath of your Netbeans project. Otherwise it cannot be loaded.
Unfortunately you did not mention what kind of failure you got.
But here are some tips.
My JDBC URL looks like the following. jdbc:mysql://localhost:3306/MYSCHEMA. So port and schema name are missing in yours.
To check your credentials try to connect to your DB using command line client:
mysql -uroot -proot
Read the error message if you fail. If you cannot restore credentials, re-install MySql. It takes 3 minutes. Do not try to connect to DB using your code unless you can do it using existing clients.
Good luck.
you should connect to port address 3306,
change the url as below :
private static String url = "jdbc:mysql://localhost:3306/";
I am considering that you are not getting any compilation error and you have added mysql java api..
Start by trying to log into mysql from a command shell. If you can't, JDBC won't be able to, either.
This might help if you can't remember:
http://www.cyberciti.biz/tips/recover-mysql-root-password.html

Categories

Resources