Yes, it's that newbie to Vaadin, again. This time, I'm trying to see if I can do one of the most basic of tasks: connect to a database.
We use MS SQL Server here (version 2012, I believe) and we've been able to connect to it fine in two other Java programs that I've written. When attempting to do the same thing using a newly-created Vaadin project, however, I am told that No suitable driver found for jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014. I have checked and made sure that all three .jars from Microsoft are in the build path: sqljdbc.jar, sqljdbc4.jar, and sqljdbc41.jar.
Here's the ConnectionManager class that I've written which only tests whether or not it can get a connection:
package info.chrismcgee.sky.vaadinsqltest.dbutil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Logger;
public class ConnectionManager {
Logger logger = Logger.getLogger(ConnectionManager.class.getName());
private static final String USERNAME = "web";
private static final String PASSWORD = "web";
private static final String CONN_STRING = "jdbc:sqlserver://192.168.0.248;databaseName=job_orders_2014";
public ConnectionManager() throws SQLException, ClassNotFoundException {
// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected!");
} catch (SQLException e) {
System.err.println(e);
} finally {
if (conn != null) {
conn.close();
}
}
}
}
The result is the SQLException message I mentioned earlier. I've tried it both with and without that Class.forName... line, which is apparently only necessary for Java versions below 7 (and we're using version 8). When that line is enabled, I get a ClassNotFoundException instead.
What gives?
EDIT 04/01/2015: To help clarify how this ConnectionManager class is called, I am simply creating an instance of it from the main class, thusly:
package info.chrismcgee.sky.vaadinsqltest;
import java.sql.SQLException;
import info.chrismcgee.sky.vaadinsqltest.dbutil.ConnectionManager;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
#SuppressWarnings("serial")
#Theme("vaadinsqltest")
public class VaadinsqltestUI extends UI {
#WebServlet(value = "/*", asyncSupported = true)
#VaadinServletConfiguration(productionMode = false, ui = VaadinsqltestUI.class)
public static class Servlet extends VaadinServlet {
}
#Override
protected void init(VaadinRequest request) {
final VerticalLayout layout = new VerticalLayout();
layout.setMargin(true);
setContent(layout);
Button button = new Button("Click Me");
button.addClickListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
try {
ConnectionManager connMan = new ConnectionManager();
} catch (SQLException | ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.addComponent(new Label("Thank you for clicking"));
}
});
layout.addComponent(button);
}
}
You need your dependencies in your runtime environment.
Please have a look at this answer here at stackoverflow:
https://stackoverflow.com/a/19630339
Related
I am trying to make a new user in a Mysql database using java code but the code is not working. This is the Database class which initializes the database connection and creates a user, sets the password, etc.
package app;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class Database {
public static MysqlDataSource dataSource;
public static void InitializeData() {
dataSource = new MysqlDataSource();
dataSource.setUser("Quiz");
dataSource.setPassword("Give the quiz");
dataSource.setServerName("localhost");
dataSource.setPort(3306);
dataSource.setDatabaseName("QUIZDATA");
Connection con = Main.getConnection();
try {
Statement st2 = con.createStatement();
st2.execute("CREATE TABLE IF NOT EXISTS Subject1(Question VARCHAR, Option1 VARCHAR, Option2 VARCHAR, Option3 VARCHAR, Option4 VARCHAR, Answer VARCHAR)");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
And here is my Main class.
package app;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Stage;
import java.sql.Connection;
import java.sql.SQLException;
public class Main extends Application {
#Override
public void start(Stage stage) throws Exception
{
Parent scene = FXMLLoader.load(getClass().getResource("quiz.fxml"));
stage.setTitle("Quiz");
stage.setScene(new Scene(scene));
stage.show();
}
public static void main(String[] args)
{
launch(args);
Database.InitializeData();
}
public static Connection getConnection()
{
Connection con = null;
try
{
con = Database.dataSource.getConnection();
}
catch (SQLException e)
{
Alert alert = new Alert(Alert.AlertType.ERROR, "Database error", ButtonType.OK);
alert.showAndWait();
}
return con;
}
}
But when I am scanning for any new server in the Mysql workbench, it is not showing any new server.
Add:- When I am right clicking on the blank area(Mysql Workbench), there is a option to "to add connections from clipboard"(Although I don't know what it is doing), it is returning an error :- "Could not parse connection parameters from string "Give the quiz" " (which is the password)"
But when I am scanning for any new server in the Mysql workbench, it
is not showing any new server.
This is not related to your program. First, you need to make sure that your MySQL database is running and then try to execute your program.
Apart from this, although you will be able to run your program once you ensure that your MySQL server is up and running, your program has not been designed well e.g. you should consider the following:
MysqlDataSource dataSource should be marked as private and then you should have public getter for it
Connection getConnection() should be defined in your class Database
You should have constructors and field getters and setters in your class Database
Please note that the above-mentioned points are just a few recommendations and it is not a complete list. I recommend you understand OOPS concept well and apply it in all your programs.
This question already has answers here:
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Connect Java to a MySQL database
(14 answers)
Closed 3 years ago.
I followed a tutorial online and there were some mistakes here and there but I understood the ideas behind it and the mindset. I have a school project on developing a Web App and I decided to do it in Java EE (since I was comfortable with Java).
My source code consists of 5 packages (Beans, Connection, Filter, Servlets and Utilities).
The problem consists of the JDBC Filter, as told in the title. It checks that everywhere on the website, I'm still connected to the MySQL Database. However, whenever it goes on anything of a localhost:8080/*, an SQL Exception is enabled, complaining about the Driver. Except this error doesn't arrive when opening files directly in the path, instead of using URL Patterns.
So I decided to do some investigating. Checked the console and climbed up the errors. It complained about the ConnectionUtils class, specifically the getMySQLConnection method, which comes from the MySQLConnUtils class.
The problem is that when I try the method itself in the mainmethod, it works !
package Connection;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectionUtils {
public static Connection getMyConnection() throws SQLException, ClassNotFoundException{
return MySQLConnUtils.getMySQLConnection();
}
public static void closeQuietly(Connection conn)
{
try{
conn.close();
}catch(Exception e){
}
}
public static void rollbackQuietly(Connection conn){
try{
conn.rollback();
}catch(Exception e){
}
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
System.out.println("Get connection...");
Connection conn = ConnectionUtils.getMyConnection();
System.out.println("Get connection " + conn);
System.out.println("Done!");
}
}
package Connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySQLConnUtils {
public static Connection getMySQLConnection() throws SQLException{
String userName = "username";
String password="pwd";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("CLASS NOT FOUND");
}
String connectionURL = "jdbc:mysql://localhost:3306/flytogo";
Connection conn = DriverManager.getConnection(connectionURL,userName,password);
return conn;
}
}
Here's the filter proving that the url-pattern it applies to is "/*" :
package Filter;
import java.io.IOException;
import java.sql.Connection;
import java.util.Collection;
import java.util.Map;
import Connection.ConnectionUtils;
import Utils.MyUtils;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
#WebFilter(filterName = "jdbcFilter", urlPatterns = { "/*" })
public class JDBCFilter implements Filter {
public JDBCFilter() {
}
#Override
public void init(FilterConfig fConfig) throws ServletException {
}
#Override
public void destroy() {
}
// Check the target of the request is a servlet?
private boolean needJDBC(HttpServletRequest request) {
System.out.println("JDBC Filter");
//
// Servlet Url-pattern: /spath/*
//
// => /spath
String servletPath = request.getServletPath();
// => /abc/mnp
String pathInfo = request.getPathInfo();
String urlPattern = servletPath;
if (pathInfo != null) {
// => /spath/*
urlPattern = servletPath + "/*";
}
// Key: servletName.
// Value: ServletRegistration
Map<String, ? extends ServletRegistration> servletRegistrations = request.getServletContext()
.getServletRegistrations();
// Collection of all servlet in your Webapp.
Collection<? extends ServletRegistration> values = servletRegistrations.values();
for (ServletRegistration sr : values) {
Collection<String> mappings = sr.getMappings();
if (mappings.contains(urlPattern)) {
return true;
}
}
return false;
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
// Only open connections for the special requests.
// (For example, the path to the servlet, JSP, ..)
//
// Avoid open connection for commons request.
// (For example: image, css, javascript,... )
//
if (this.needJDBC(req)) {
System.out.println("Open Connection for: " + req.getServletPath());
Connection conn = null;
try {
// Create a Connection.
conn = ConnectionUtils.getMyConnection();
// Set outo commit to false.
conn.setAutoCommit(false);
// Store Connection object in attribute of request.
MyUtils.storeConnection(request, conn);
// Allow request to go forward
// (Go to the next filter or target)
chain.doFilter(request, response);
// Invoke the commit() method to complete the transaction with the DB.
conn.commit();
} catch (Exception e) {
e.printStackTrace();
ConnectionUtils.rollbackQuietly(conn);
throw new ServletException();
} finally {
ConnectionUtils.closeQuietly(conn);
}
}
// With commons requests (images, css, html, ..)
// No need to open the connection.
else {
// Allow request to go forward
// (Go to the next filter or target)
chain.doFilter(request, response);
}
}
}
Anyways, thanks in advance to anyone who would know what could be the source of mistakes or error.
I used dhtmlxgantt in my Java EE project, I downloaded the java connector and I copied this example from this link Java Connector for dhtmlxGantt but mix() and enable_order() are ignored by JsonGanttConnector.Thanks.
Test_conector.java
import com.dhtmlx.connector.DBType;
import com.dhtmlx.connector.JSONGanttConnector;
import java.sql.Connection;
import java.sql.DriverManager;
import com.dhtmlx.connector.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test_conector extends ThreadSafeConnectorServlet {
#Override
protected void configure(HttpServletRequest req, HttpServletResponse res) {
Connection conn=null;
try {
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection("jdbc:mysql://localhost/parc","root","");
} catch (Throwable e) {
e.printStackTrace();
}
JSONGanttConnector gantt = new JSONGanttConnector(conn, DBType.MySQL);
gantt.servlet(req, res);
gantt.mix("open", "1");
gantt.enable_order("sortorder");
gantt.render_links("gantt_links", "id", "source,target,type");
gantt.render_table("gantts", "id","text", "start_date,duration,progress,sortorder,parent");
}
}
.mix and .enable_order API is available in PHP version of connector only.
You can use beforeRender behavior to define open property for the data objects. There is no alternative for the enable_order API as far as I can see.
I have a web application I am making using a websocket API to handle the websockets, here is the code for that part
package comm2.hello;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.catalina.session.*;
#ServerEndpoint(value = "/echo")
public class wschat {
private static ArrayList<Session> sessionList = new ArrayList<Session>();
#OnOpen
public void onOpen(Session session) {
try {
sessionList.add(session);
// asynchronous communication
session.getBasicRemote().sendText("hello");
} catch (IOException e) {
}
}
public void send(String text, Session session) throws IOException {
session.getBasicRemote().sendText(text);
}
}
I am trying to have another java class then call into the send method to send messages, using the following code.
package comms;
import java.io.IOException;
import java.util.ArrayList;
import javax.websocket.Session;
import javax.websocket.Session;
import comm2.hello.*;
public class main {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
wschat h = new wschat();
String text = "hello";
//session shouldn't be null but not sure what to make it
Session session = null;
h.send(text,session);
}
}
As you can see, I have the session variable in the main.java class set to null which will thus always produce a null pointer error. This is because I am not sure what to make session equal to, does anyone have any idea what to initialize the session variable to in main.java?
I am trying to create a simple servlet (tomcat) that accesses a database, then a USDA web service. I've successfully deployed/tested the database connectivity. When I added the web service access, eclipse reports the problem: AwdbWebService_Service cannot be resolved to a type.
The hour is late... I just don't see why this won't resolve as a service instance.
The error is tripped by this line:
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
Here is the code:
package localdomain.localhost;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URL; //added for usda webservice
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.ServletConfig;
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 javax.sql.DataSource;
import javax.xml.namespace.QName; // added for usda webservice
import usda.nrcs.wcc.awdbWebService.*;
#WebServlet(value = "/MyServlet")
public class MyServlet extends HttpServlet {
// use this for usda reservoir station values later
static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
protected final Logger logger = Logger.getLogger(getClass().getName());
#Resource(name = "jdbc/mydb", lookup = "jdbc/mydb")
private DataSource dataSource;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
logger.info("Init");
System.out.println(getClass().getName() + ".init");
}
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
PrintWriter writer = resp.getWriter();
writer.println("<html>");
writer.println("<head><title>MyServlet</title></head>");
writer.println("<body><h1>MyServlet</h1>");
writer.println("<h2>DataSource</h2>");
Connection conn = null;
try {
writer.println("Datasource: " + dataSource + "<br/><br/>");
conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rst = stmt.executeQuery("select 1");
while (rst.next()) {
writer.println("Resultset result: " + rst.getString(1) + "<br/><br/>");
}
rst.close();
stmt.close();
conn.close();
writer.println("SUCCESS to access the datasource");
// Now try accessing usda
URL wsURL = new URL("http://www.wcc.nrcs.usda.gov/awdbWebService/services?wsdl");
AwdbWebService_Service lookup = new AwdbWebService_Service(wsURL,new QName("http://www.wcc.nrcs.usda.gov/ns/awdbWebService","AwdbWebService"));
m_webService = lookup.getAwdbWebServiceImplPort();
} catch (Exception e) {
e.printStackTrace(writer);
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
writer.println("</body></html>");
}
}
For those following this thread:
The package statement at the start of the java classes I generated with wsimport begins with:
package gov.usda.nrcs.wcc.awdbWebService
My import statement however looked like this:
import usda.nrcs.wcc.awdbWebService.*;
In essence I placed the source # the wrong level and defined the build config to point incorrectly for the package references in the java classes. I removed the build reference, moved the tree to begin pointing on the gov level. Now that there wasn't a mismatch, the unresolved type error vanished.