set mysql connection behind ssh in groovy script SoapUI - mysql

From groovy script in SoapUI I need to connect to a mysql database to perform some queries. The problem is that due to security reasons no external access is possible.
Therefore it is required to get an ssh access (like a tunnel) and invoke mysql locally.
Initially I was reading the below project properties and then connect to mysql:
ServerUrl=jdbc:mysql://10.255.255.122:3306/db
ServerDbUser=user
ServerDbPwd=password
ServerDriver=com.mysql.jdbc.Driver
def url=testRunner.testCase.testSuite.project.getPropertyValue("ServerUrl")
def usr=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbUser")
def pwd=testRunner.testCase.testSuite.project.getPropertyValue("ServerDbPwd")
def driver=testRunner.testCase.testSuite.project.getPropertyValue("ServerDriver")
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver(driver)
sqlServer = Sql.newInstance(url, usr, pwd, driver)`
But this didn't work so now it is required to establish first a ssh connection to the server with the IP 10.255.255.122 and then open the mysql connection locally. So I guess the Server Url will change to:
ServerUrl=jdbc:mysql://127.0.0.1:3306/db
But I don't know how to set first the ssh connection to the server.
Can someone help me with this?
Thanks.

Have a look at http://forum.soapui.org/viewtopic.php?t=15400 and connect to remote mysql database through ssh using java
It will give you an idea about implementing it in soapUI.
Below is the code by Ripon Al Wasim which is available as an answer at the stackoverflow link mentioned above
package mypackage;
import java.sql.*;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class UpdateMySqlDatabase {
static int lport;
static String rhost;
static int rport;
public static void go(){
String user = "ripon";
String password = "wasim";
String host = "myhost.ripon.wasim";
int port=22;
try
{
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
lport = 4321;
rhost = "localhost";
rport = 3306;
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
int assinged_port=session.setPortForwardingL(lport, rhost, rport);
System.out.println("localhost:"+assinged_port+" -> "+rhost+":"+rport);
}
catch(Exception e){System.err.print(e);}
}
public static void main(String[] args) {
try{
go();
} catch(Exception ex){
ex.printStackTrace();
}
System.out.println("An example for updating a Row from Mysql Database!");
Connection con = null;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://" + rhost +":" + lport + "/";
String db = "testDB";
String dbUser = "wasim";
String dbPasswd = "riponalwasim123";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, dbUser, dbPasswd);
try{
Statement st = con.createStatement();
String sql = "UPDATE MyTableName " +
"SET email = 'ripon.wasim#smile.com' WHERE email='peace#happy.com'";
int update = st.executeUpdate(sql);
if(update >= 1){
System.out.println("Row is updated.");
}
else{
System.out.println("Row is not updated.");
}
}
catch (SQLException s){
System.out.println("SQL statement is not executed!");
}
}
catch (Exception e){
e.printStackTrace();
}
}
}

Related

MySQL JDBC connection stop working

String url = "jdbc:mysql://localhost:3306/mysql";
String user = "root";
String pass = "root1";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, pass);
System.out.println("Connected to database");
} catch (Exception e) {
System.out.println(e);
System.out.println("Could not connect to database");
}
Password should be "root". The program does not display the message in the catch block and stops working. Can anyone tell me what happens?
[UPDATE]
I apologise I asked a bad question. The problem is already solved, Thanks. This helps to properly check whether the connection exists.
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
There are three different ways to connect to SQL data base as shown in below code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class MySQLConnectExample {
public static void main(String[] args) {
// creates three different Connection objects
Connection conn1 = null;
Connection conn2 = null;
Connection conn3 = null;
try {
// connect way #1
String url1 = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "secret";
conn1 = DriverManager.getConnection(url1, user, password);
if (conn1 != null) {
System.out.println("Connected to the database test1");
}
// connect way #2
String url2 = "jdbc:mysql://localhost:3306/test2?user=root&password=secret";
conn2 = DriverManager.getConnection(url2);
if (conn2 != null) {
System.out.println("Connected to the database test2");
}
// connect way #3
String url3 = "jdbc:mysql://localhost:3306/test3";
Properties info = new Properties();
info.put("user", "root");
info.put("password", "secret");
conn3 = DriverManager.getConnection(url3, info);
if (conn3 != null) {
System.out.println("Connected to the database test3");
}
} catch (SQLException ex) {
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}

Database connectivity using mssql2008 and jdbc

So I have setup my code like so
public static Connection getConnection() {
try {
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=HRDB;
String user = "sa";
String pass = "r";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection(dbURL, user, pass);
return conn;
} catch (ClassNotFoundException c) {
return null;
} catch (SQLException s) {
System.out.println(s.toString());
return null;
}
}
However, when I try to connect to the database I get the following exceptions.
com.microsoft.sqlserver.jdbc.SQLServerException: The driver could not establish a secure connection to SQL Server by using Secure Sockets Layer (SSL) encryption. Error: "java.lang.RuntimeException: Could not generate DH keypair".

SQL exception thrown when the method is called otherwise working fine

I am making a web application project using JSP in Netbeans IDE.
I have a java Class called Login which has a static method called authenticate.When I am running this file it gives me the required output. Now I have a web page called auth.jsp which calls the method authenticate but when I try to run this web page the value returned by the method is "error" that is sql exception is being thrown by the method. Could someone please tell why this is happening? Thanks in advance.
package server;
import java.sql.*;
public class Login {
public static void main(String args[]) {
System.out.print(authenticate("260","abc"));
}
public static String authenticate(String username, String password) {
String auth="",pass="";
int blocked_status=0;
String url = "jdbc:mysql://localhost:3306/radio";
try{
Connection conn = DriverManager.getConnection(url,"root","rishabh");
Statement stmt = conn.createStatement();
String sql = "select password,blocked from user where username = \"" + username + "\"";
ResultSet rs = stmt.executeQuery(sql);
int flag=0;
while(rs.next()){
pass = rs.getString("password");
blocked_status = rs.getInt("blocked");
flag++;
}
if(flag>0) {
if(blocked_status==1)
auth = "blocked";
else if(pass.equals(password))
auth = "authenticated";
else if(pass.equalsIgnoreCase(pass))
auth = "wrong_case";
else
auth = "wrong_password";
}
else{
auth = "incorrect_username";
}
} catch(SQLException e){
auth = "sqlerror";
System.out.print(" ERROR " );
}
return auth;
}
}

jsp mysql server connection timeout

hi i am doing an jsp project. and i deploy my project on apache tomcat. i use mysql as databese.
when i deploy project on remote server it is run good. but after some hours it gives me sql error. then i go back my apache server and start projecet again it run and after some hours it gives me same sql error again. i dont know the problem. is that caused from my java connection code or it is about mysql server. can some one tell me why it gives me sql error.?
public class ConnectionManager {
private String className = "com.mysql.jdbc.Driver";
private String userName ="username";
private String password = "password";
private String url = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
/**
* #uml.property name="connectionInstance"
* #uml.associationEnd
*/
private static ConnectionManager connectionInstance = null;
public ConnectionManager(){
}
public static synchronized ConnectionManager getInstance() {
if(connectionInstance == null) {
connectionInstance = new ConnectionManager();
}
return connectionInstance;
}
public Connection getConnection(){
Connection conn = null;
try {
Class.forName(className);
conn = DriverManager.getConnection (url, userName, password);
System.out.println("Connection Established");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
MySQL has a default connection timeout of 8 hours. So this means that you've kept a SQL connection open for too long. Your code suggests that you're creating only one connection on application's startup and reusing it application wide. This is very bad. This is not threadsafe.
You need to change your code so that you're not declaring and storing the SQL Connection as a static or instance variable anywhere in your code. Instead, it should be declared, created and closed within the shortest possible scope. Preferably within the very same method block as where you're executing the SQL query.
Here's a minor rewrite of your ConnectionManager which does the job properly:
public class ConnectionManager {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String USERNAME ="username";
private static final String PASSWORD = "password";
private static final String URL = "jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8";
static {
try {
Class.forName(DRIVER);
}
catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(DRIVER + " missing in classpath!", e);
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
}
Use it as follows:
public class SomeDAO {
public SomeEntity find(Long id) throws SQLException {
Connection connection = null;
// ...
try {
connection = ConnectionManager.getConnection();
// ...
}
finally {
// ...
if (connection != null) try { connection.close(); } catch(SQLException ignore) {}
}
return someEntity;
}
To improve connecting performance, use a connection pool instead of DriverManager.
See also:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
Are you closing connections properly after using them.

jdbc connection of mysql to html

Hi i have the following file to connect mysql database to html files. But i am having trouble connecting it. Can anyone tell me where i find the locations.
What should i replace "jdbc:mysql://localhost/zulfiqar" with for it to work on my computer? where do i find this?
And is there anything else i have to change to make it work on my computer? this was a piece of code i found on the internet which i am trying to make work so i can understand how to do it, but i am struggling.
Thanks in advance!
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUserEnquiryForm extends HttpServlet{
public void init(ServletConfig config) throws ServletException{
super.init(config);
}
/**Process the HTTP Get request*/
public void doPost(HttpServletRequest req,
HttpServletResponse res) throws ServletException,
IOException{
String connectionURL = "C:\Program Files(x86)\MySQL Server 5.0\bin\mysql.exe";
Connection connection=null;
ResultSet rs;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
//get the variables entered in the form
String uId = req.getParameter("userId");
String fname = req.getParameter("firstname");
String sname = req.getParameter("surname");
String address1 = req.getParameter("address1");
String address2 = req.getParameter("address2");
String town = req.getParameter("town");
String county = req.getParameter("country");
String zipcode = req.getParameter("zipcode");
try {
// Load the database driver
Class.forName("org.gjt.mm.mysql.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection
(connectionURL, "root", "admin");
//Add the data into the database
String sql =
"insert into emp_details values (?,?,?,?,?,?,?,?)";
PreparedStatement pst =
connection.prepareStatement(sql);
pst.setString(1, uId);
pst.setString(2, fname);
pst.setString(3, sname);
pst.setString(4, address1);
pst.setString(5, address2);
pst.setString(6, town);
pst.setString(7, county);
pst.setString(8, zipcode);
int numRowsChanged = pst.executeUpdate();
// show that the new account has been created
out.println(" Hello : ");
out.println(" '"+fname+"'");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: "
+ e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: "
+ e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
// Always close the database connection.
try {
if (connection != null) connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
Some additional information about how it's failing might be useful.
1) Is it failing to make the socket connection (implying your service isn't running), or
2) Did it fail to initialize the driver? I'm not familiar with the one you listed. A more common alternative is "sun.jdbc.odbc.JdbcOdbcDriver".
3) Did you connect and simply fail authentication with user "root" and password "admin"?
What should i replace "jdbc:mysql://localhost/zulfiqar" with
Ans: It is the connection url. It does mean your MySQL database is running on localhost server (with default port) and you are connecting to 'zulfiqar' database. So first line under doPost() should be :
String connectionURL = "jdbc:mysql://localhost/zulfiqar";
Next, you are using org.gjt.mm.mysql.Driver driver for JDBC connection. It was initially developed by a hobbyist. It's later donated to MySQL where they renamed the package/classname. The old classname is kept for backwards compatibility reasons, but you should update it to com.mysql.jdbc.Driver and add mysql-connector-java-*-bin.jar in your WEB-INF/lib folder.
Next thing you are using :
connection = DriverManager.getConnection(connectionURL, "root", "admin");
So you are loading a connection from the connectionURL and accessing it with root user and admin password. Make sure these are correct in your case.
Last point is, you are inserting into emp_details table. Make sure you have this table already created in zulfiqar database with all required columns. And the number of '?' marks in the sql string should match the number of times you are doing pst.setString(index, data), otherwise you will get Invalid parameter index error.