How to configure tomcat to work with mysql in OpenShift? - mysql

I just discovered OpenShift and i love it! And i would like to try it with a tomcat app that communicates with mysql.I was able to install tomcat through this tutorial
and my tomcat server is up and running !I also installed mysql and phpmyadmin,but now i have to deploy my servlet in the tomcat server .My servlet communicates with mysql but i cant find where to insert the variables that Openshift give me !Does anyone have any idea?
Thnx in advandce Andi :)
OPENSHIFT VARIABLES ARE:
Root User :andi
RootPassword: andi
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
MY SERVLET:
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorldServlet() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String titulli = request.getParameter("titulli");
String ingredientet = request.getParameter("ingredientet");
String receta = request.getParameter("receta");
final String url = "jdbc:mysql://localhost/andi";
final String user = "andi";
final String password = "andi";
try {
// jdbc try
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(url, user,
password);
// insert values into the first table
PreparedStatement s = (PreparedStatement) con
.prepareStatement("INSERT INTO recetat(titulli,ingredientet,receta) VALUES (?,?,?)");
s.setString(1, titulli);
s.setString(2, ingredientet);
s.setString(3, receta);
s.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
PrintWriter out = response.getWriter();
out.println("Receta u ruajt me sukses ne server !");
System.out.println(titulli+ingredientet+receta);
}
}
like you can see i dont know where to insert the
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
variable...

OpenShift puts the MySQL host and port as environment variables on exactly that name. In Java terms, they are available by
String host = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
String port = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
Then, compose the JDBC URL as follows
String url = String.format("jdbc:mysql://%s:%s/andi", host, port);
The normal approach, however, is to create a connection pooled datasource in context.xml and obtain that by JNDI instead.

Somewhat related - you can now install tomcat directly (without following the DIY steps) but running
rhc app create <name> jbossews-1.0
JBoss EWS is a maintained and supported version of Tomcat from Red Hat - all the same bits. Also, starting next week the rhc client tools will support
rhc app create <name> tomcat6
To make it even simpler.

Related

How to fix "No suitable driver found for jdbc:mysql//localhost:3306/gaming_site" error

I'm setting up a new database connection but ended with "java.sql.SQLException: No suitable driver found for jdbc:mysql//localhost:3306/gaming_site" error!
Please help me to fix this!
I'm using mysql v8.0
Therefore I added mysql connector v8.0.12 in java build path's libraries
Code for establishing database connection:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public static Connection getConnection() throws ClassNotFoundException, SQLException {
String dbDriver = "com.mysql.jdbc.Driver";
String dbURL = "jdbc:mysql//localhost:3306/gaming_site";
String dbUserName = "root";
String dbPassword = "root";
Class.forName(dbDriver);
Connection con = DriverManager.getConnection(dbURL,dbUserName,dbPassword);
return con;
}
}
You're missing a colon in the JDBC URL:
jdbc:mysql://localhost:3306/gaming_site
^
Add this.
See the syntax at https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-reference-jdbc-url-format.html

Configure SSL certificates with Hibernate, Spring and JDBC

I'm trying to move from an unencrypted JDBC connection using a username and password to log in to my MySQL database server, to a connection using SSL and certificate-based authentication. I'm using Hibernate with Spring MVC. My WebAppConfig file looks like this:
package com.****.PolicyManager.init;
import java.util.Properties;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.JstlView;
import org.springframework.web.servlet.view.UrlBasedViewResolver;
#Configuration
#ComponentScan("com.sprhib")
#EnableWebMvc
#EnableTransactionManagement
#PropertySource("classpath:application.properties")
public class WebAppConfig {
private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
private static final String PROPERTY_NAME_DATABASE_URL = "db.urlSSL";
private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";
private static final String PROPERTY_NAME_HIBERNATE_DIALECT = "hibernate.dialect";
private static final String PROPERTY_NAME_HIBERNATE_SHOW_SQL = "hibernate.show_sql";
private static final String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = "entitymanager.packages.to.scan";
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(
PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
sessionFactoryBean.setHibernateProperties(hibProperties());
return sessionFactoryBean;
}
private Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT,
env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL,
env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
return properties;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager transactionManager =
new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
#Bean
public UrlBasedViewResolver setupViewResolver() {
UrlBasedViewResolver resolver = new UrlBasedViewResolver();
resolver.setPrefix("/WEB-INF/pages/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
And my properties config file (application.properties) as follows:
#DB properties:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/PolicyManager
db.urlSSL=jdbc:mysql://localhost:3306/PolicyManager?autoReconnect=true&verifyServerCertificate=false&useSSL=true&requireSSL=true
db.username=myuser
db.password=mypass
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
entitymanager.packages.to.scan=com.****.PolicyManager.model
I've generated the right certificates inside /etc/mysql/certs and have edited my.cnf to point to then, but can't find any info online about how to configure my specific method of database initialisation to use certificate-based authentication to remove the need to store my database username and password in plain text on the server.
Can anyone suggest a solution or point me to a tutorial that uses this WebAppConfig.java file (hib properties, DriverManagerDataSource and LocalSessionFactoryBean) for it's configuration?
The MySQL guide has information on what to do on the client side, this bug also has some detailed information.
It basically comes done to the following steps
Create a keystore and truststore with your clients certificate
Configure your environment (or a MysqlDataSource) to use these keystore and truststore
Configure the connection URL properly (which is what you apparently already have done).
And that should be it. The key is to have the correct certificates on the client side.
More information:
Secure JDBC connection to MySQL from GlassFish
Secure JDBC connection to MySQL from Java
MySQL SSL Documentation

Access to MySQL using Java Servlet?

The Solution:
I added this code
Class.forName("com.mysql.jdbc.Driver");
brfore
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
Thank you all for reply my question
====================
I have problem, I try to insert data into mysql db using servlet, but I couldn'y access to MySQL
Database name: test
Table name: test
I already added jdbc connector to the project library
I'm using JDK 1.7, NetBeans 7.3, MySQL 5.6, Tomcat 7.0, Connector/J 5.1.24
1- this is "form action" in sign_up.jsp page:
<form action="RegisterUser" method="post">
<td><input type="submit" value="Submit"></td>
</form>
2- this is RegisterUser.java servlet:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
#WebServlet(urlPatterns = {"/RegisterUser"})
public class RegisterUser extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan3";
int phone = 123456;
String insert = "INSERT INTO test VALUES ('\" + name + \"', \" + phone + \")";
s.executeUpdate(insert);
s.close();
con.close();
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (SQLException ex) {
Logger.getLogger(RegisterUser.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
3- the exception result:
HTTP Status 500 - Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
type Exception report
message Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.SecurityException: Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
RegisterUser.processRequest(RegisterUser.java:66)
RegisterUser.doPost(RegisterUser.java:173)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.39 logs.
4- But when I use same code but in java file "without servlet or web app" it's working correctly:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Test {
public static void main(String[] args){
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "root");
Statement s = (Statement) con.createStatement();
String name = "Hassan4";
int phone = 8985895;
String insert = "INSERT INTO test VALUES ('" + name + "', " + phone + ")";
s.executeUpdate(insert);
s.close();
con.close();
System.out.println("done");
}catch(Exception e){
throw new SecurityException("Class not found " + e.toString());
}
}
}
so what is problem with servlet? Why the code works with java app. but it doesn't work with web app.?
You are getting Class not found java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/test
It means When you are running it from Web Application, JRE could not find Class in the Classpath.
If this code works in your Standalone it means you need to have a JAR file somewhere containing com.mysql.jdbc.Driver class (so called JDBC driver). This JAR needs to be visible in Tomcat. So, I would suggest placing mysql-jdbc.jar at a physical location to /WEB-INF/lib directory of your project.
Alternatively, you can add Third party libraries like JDBC driver here using
Right Click Project Name--> Properties
from your NetBeans IDE
Then restarting Tomcat should work.
Second, you don't need
import com.mysql.jdbc.Driver;
in your Servlet.
David is right and i want to add, you can also install the driver by pasting the jar file in the the installation folder of java.
\Program Files\Java\jre7\lib\ext
Well i dont like mysql very much and always use Mssql with a windows server 2008. This is the code i use for that, i might be your answer since mysql connection works pretty much the same as sql.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName="+database+";user="+user+";password="+password);
First, you should put that into a persistance layer.
1) Ensure that your JDBC driver is in place. Copy it into your classpath, e.g. /WEB-INF/lib directory. Link: MySQL JDBC Driver Download Page
2) Check your connect string: jdbc:mysql://<server>:<port>/<database>, looks like the port is missing. Try jdbc:mysql://127.0.0.1:3306/test

javafx connection to mysql [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
we are building javafx application which will be presenting information about stocks.
Here is the website:
http://analiza.host-ed.me/
But we've got a huge problem. Every free hosting doesn't allow remote mysql connection. And there is my question. When our site is on the server (which i linked) is this remote connection or local connection?
When we put this javafx app as a site it can't connect like it was on the local machine...
Is there any solution? Thanks for help.
(we need to use free hosting, because it's only a school project..)
You can access MySQL from JavaFX. But JavaFX runs on a client and something like php usually runs on a server. You will need a connection from your java app to MySQL. As your hosting provider won't allow you to directly connect to the database port from your Java Client App, you will need some other way to connect.
You could tunnel through port 80, you could run a servlet (or php server code, etc) to intercept incoming traffic and proxy database calls through a HTTP based REST interface or you could install the DB locally on the client.
I'm going to assume, for a school project, it's ok for each client machine to have it's own database. In which case, instead of using MySQL, use a lightweight Java database like H2, bundle it with your app by including it's jar as a dependent library, package the app plus DB jar as a signed WebStart application using the JavaFX packaging tools and host the files generated by the packaging tools at your hosting provider.
Update
Here is a sample application which uses a local H2 database on the client computer.
import java.sql.*;
import java.util.logging.*;
import javafx.application.Application;
import javafx.collections.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
public class H2app extends Application {
private static final Logger logger = Logger.getLogger(H2app.class.getName());
private static final String[] SAMPLE_NAME_DATA = { "John", "Jill", "Jack", "Jerry" };
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final ListView<String> nameView = new ListView();
final Button fetchNames = new Button("Fetch names from the database");
fetchNames.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
fetchNamesFromDatabaseToListView(nameView);
}
});
final Button clearNameList = new Button("Clear the name list");
clearNameList.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent event) {
nameView.getItems().clear();
}
});
VBox layout = new VBox(10);
layout.setStyle("-fx-background-color: cornsilk; -fx-padding: 15;");
layout.getChildren().setAll(
HBoxBuilder.create().spacing(10).children(
fetchNames,
clearNameList
).build(),
nameView
);
layout.setPrefHeight(200);
stage.setScene(new Scene(layout));
stage.show();
}
private void fetchNamesFromDatabaseToListView(ListView listView) {
try (Connection con = getConnection()) {
if (!schemaExists(con)) {
createSchema(con);
populateDatabase(con);
}
listView.setItems(fetchNames(con));
} catch (SQLException | ClassNotFoundException ex) {
logger.log(Level.SEVERE, null, ex);
}
}
private Connection getConnection() throws ClassNotFoundException, SQLException {
logger.info("Getting a database connection");
Class.forName("org.h2.Driver");
return DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
}
private void createSchema(Connection con) throws SQLException {
logger.info("Creating schema");
Statement st = con.createStatement();
String table = "create table employee(id integer, name varchar(64))";
st.executeUpdate(table);
logger.info("Created schema");
}
private void populateDatabase(Connection con) throws SQLException {
logger.info("Populating database");
Statement st = con.createStatement();
int i = 1;
for (String name: SAMPLE_NAME_DATA) {
st.executeUpdate("insert into employee values(i,'" + name + "')");
i++;
}
logger.info("Populated database");
}
private boolean schemaExists(Connection con) {
logger.info("Checking for Schema existence");
try {
Statement st = con.createStatement();
st.executeQuery("select count(*) from employee");
logger.info("Schema exists");
} catch (SQLException ex) {
logger.info("Existing DB not found will create a new one");
return false;
}
return true;
}
private ObservableList<String> fetchNames(Connection con) throws SQLException {
logger.info("Fetching names from database");
ObservableList<String> names = FXCollections.observableArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name from employee");
while (rs.next()) {
names.add(rs.getString("name"));
}
logger.info("Found " + names.size() + " names");
return names;
}
}
There is a corresponding NetBeans project for this sample which will generate a deployable application. The project can be tested in webstart and applet mode.
For the sample, the database is stored on the user's computer (not the server from which the application was downloaded) and persists between application runs.
The exact location depends on the jdbc connection initialization string. In the case of my sample the database goes in the user's directory jdbc:h2:~/test, which is OS and User specific. In the case of me for Windows it ends up at C:\Users\john_smith\test.h2.db. Using a jdbc connection string such as jdbc:h2:~/test is preferable to a string such as jdbc:h2:C:\\Baza because a string with C:\\ in it is platform specific and won't work well on non-windows systems. For further information on h2 jdbc connection strings refer to the connections settings in the h2 manual.
The h2 system works such that if the database file already exists, it is reused, otherwise a new database file is created. If you modify the database, shut the application down, then load the application again a week later, it is able to read the data created the week before.

Adding a java class file in an another java class file

I am doing a jsp project in which, I have a dbconn.java page in which database connection to MySQL database is created.
I want to call it in an another java page for getting the database connection.
I dont know how to include the page dbconn.java into my page. Please help.
I know its a simple question for you all, but I could not find the answer.
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import java.util.*;
import java.util.Date;
import java.sql.*;
package com.act;
public class dbconn {
public String execute() throws Exception
{
Connection con=null;
Statement stmt1=null;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabasename", "root", "password");
}
}
This is my dbconn.java page. Is this correct?
You need to return the Connection object from this utility class.
I rewrite your class with name ConnectionManager like this :
import java.sql.*;
public class ConnectionManager{
private Connection con = null;
public Connection getCon(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabasename","root", "password");
}
catch(Exception e){
e.printStackTrace();
}
return con;
}
}
Now in your other classes, call this class like this whenever you need a db-connection:
Connection con = new ConnectionManager().getCon();
PreparedStatement st = con.prepareStatement("YOUR SQL QUERY");