NPE - java.lang.reflect.UndeclaredThrowableException - java

I'm working on web java application with OSGI. I get this error when I try to open JSF page: java.lang.reflect.UndeclaredThrowableException
This is the source code that I'm working on:
package org.DX_57.osgi.SH_27.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.DX_57.osgi.SH_27.api.SessionHandle;
public class SessionHandleImpl implements SessionHandle {
#Resource(name="jdbc/Oracle")
public DataSource ds;
public String sayHello(String name) {
return "Howdy " + name;
}
public String CheckUserDB(String userToCheck){
String storedPassword = null;
String error_Message = null;
String SQL_Statement = null;
String error_Database;
Connection conn;
try {
conn = ds.getConnection();
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
SQL_Statement = "SELECT Passwd from USERS WHERE Username = ?";
PreparedStatement passwordQuery = conn.prepareStatement(SQL_Statement);
passwordQuery.setString(1, userToCheck);
ResultSet result = passwordQuery.executeQuery();
if(result.next()){
storedPassword = result.getString("Passwd");
}
conn.commit();
committed = true;
} finally {
if (!committed) conn.rollback();
}
}
finally {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
return storedPassword;
}
}
This is the error stack of the Glassfish server: http://pastebin.com/tvHmspjh
I can successfully compile the code but when I try to open JSF page I get error. Maybe I have mistaken the try-catch statements.
Best wishes

Related

Netbeans MySQL Connection - not to do with jbdc

I have a login app that needs to connect to a server to check the username and password. I am using netbeans and the jbdc is installed and working in the services tab(thanks stack overflow!). By the jbdc is work I mean that i can execute SQL script through it.
I have set this up with MS Server 16 and MySQL so I am convied it is the code:
Connection method:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
private static final String USERNAME = "root";
private static final String PASSWORD = "mess";
private static final String SQCONN = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection()throws SQLException{
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(SQCONN, USERNAME, PASSWORD);
}catch (ClassNotFoundException e) {
}
return null;
}
}
loginmodel:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
Connection connection;
public LogInModel() {
try{
this.connection = dbConnection.getConnection();
}catch(SQLException e){
}
if(this.connection == null){
System.out.println("here");
// System.exit(1);
}
}
public boolean isDatabaseConnected(){
return this.connection != null;
}
public boolean isLogin(String username, String password) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
boolean bool1;
if(rs.next()){
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally {
{
pr.close();
rs.close();
}
}
}
}
I believe the issue is the return null; from the dbConnection file. The if(this.connection==Null) comes back true and the system is exiting.
Thank you in advance.
Your dbConnection class is a bad idea. Why hard wire those values when you can pass them in?
Your application will only have one Connection if you code it this way. A more practical solution will use a connection pool.
Learn Java coding standards. Your code doesn't follow them; it makes it harder to read and understand.
Here's a couple of recommendations:
package dbUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class dbConnection {
public static final String DRIVER = "com.mysql.jdbc.Driver";
public static final String USERNAME = "root";
public static final String PASSWORD = "mess";
public static final String URL = "jdbc:mysql://localhost:1434/MessyLogin?zeroDateTimeBehavior=convertToNull";
public static Connection getConnection(String driver, String url, String username, String password) throws ClassNotFoundException, SQLException {
Class.forName(driver);
return DriverManager.getConnection(url, username, password);
}
}
I might write that LogInModel this way:
package LogIn;
import dbUtil.dbConnection;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class LogInModel {
private static final String sql = "SELECT * FROM MessyLogin where username = ? and Password = ?";
private Connection connection;
public LogInModel(Connection connection) {
this.connection = connection;
}
public boolean isLogin(String username, String password) {
boolean isValidUser = false;
PreparedStatement pr = null;
ResultSet rs = null;
try {
pr = this.connection.prepareStatement(sql);
pr.setString(1, username);
pr.setString(2, password);
rs = pr.executeQuery();
while (rs.hasNext()) {
isValidUser = true;
}
} catch (SQLException ex) {
e.printStackTrace();
isValidUser = false;
} finally {
dbUtils.close(rs);
dbUtils.close(pr);
}
return isValidUser;
}
}
Here's my guess as to why your code fails: You don't have the MySQL JDBC driver JAR in your runtime CLASSPATH. There's an exception thrown when it can't find the driver class, but you didn't know it because you swallowed the exception.

Writing data into MySQL table with JavaFX

I have linked up a database to my Java application using the JDBC in Netbeans.
But whenever I try to write something from a TextField to a MySQL table, it doesn't work.
I have a pre-made class to make the database connection.
Here is my database class:
package testswitch;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Maarten
*/
public class Database {
public final static String DB_DRIVER_URL = "com.mysql.jdbc.Driver";
public final static String DB_DRIVER_PREFIX = "jdbc:mysql://";
private Connection connection = null;
public Database(String dataBaseName, String serverURL, String userName, String passWord) {
try {
// verify that a proper JDBC driver has been installed and linked
if (!selectDriver(DB_DRIVER_URL)) {
return;
}
if (serverURL == null || serverURL.isEmpty()) {
serverURL = "localhost:3306";
}
// establish a connection to a named Database on a specified server
connection = DriverManager.getConnection(DB_DRIVER_PREFIX + serverURL + "/" + dataBaseName, userName, passWord);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
private static boolean selectDriver(String driverName) {
// Selects proper loading of the named driver for Database connections.
// This is relevant if there are multiple drivers installed that match the JDBC type.
try {
Class.forName(driverName);
// Put all non-prefered drivers to the end, such that driver selection hits the first
Enumeration<Driver> drivers = DriverManager.getDrivers();
while (drivers.hasMoreElements()) {
Driver d = drivers.nextElement();
if (!d.getClass().getName().equals(driverName)) {
// move the driver to the end of the list
DriverManager.deregisterDriver(d);
DriverManager.registerDriver(d);
}
}
} catch (ClassNotFoundException | SQLException ex) {
logException(ex);
return false;
}
return true;
}
public void executeNonQuery(String query) {
try (Statement statement = connection.createStatement()) {
statement.executeUpdate(query);
} catch (SQLException eSQL) {
logException(eSQL);
}
}
public ResultSet executeQuery(String query) {
Statement statement;
try {
statement = connection.createStatement();
ResultSet result = statement.executeQuery(query);
return result;
} catch (SQLException eSQL) {
logException(eSQL);
}
return null;
}
private static void logException(Exception e) {
System.out.println(e.getClass().getName() + ": " + e.getMessage());
e.printStackTrace();
}
}
And here's my JavaFX controller.
What I want is that when the "handle" button is pressed, that the data filled in the TextField gets inserted into the database.
package testswitch;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import testswitch.Database;
/**
*
* #author Maarten
*/
public class gebruikerToevoegenController {
//TextFields
#FXML
private TextField FXVoornaam, FXTussenvoegsel, FXAchternaam, FXGebruikersnaam;
#FXML
private TextField FXWachtwoord, FXEmail, FXTelefoonnummer;
//Boolean checkbox positie
#FXML
private CheckBox ManagerPosition;
#FXML
private Button gebruikerButton;
public final String DB_NAME = "testDatabase";
public final String DB_SERVER = "localhost:3306";
public final String DB_ACCOUNT = "root";
public final String DB_PASSWORD = "root";
Database database = new Database(DB_NAME, DB_SERVER, DB_ACCOUNT, DB_PASSWORD);
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES " + FXVoornaam.getText();
try {
database.executeQuery(query);
} catch (Exception e) {
}
}
}
Thanks in advance
The string in your SQL query doesn't seem to be properly quoted. It's best to use PreparedStatement for this scenario:
public class Database {
public PreparedStatement prepareStatement(String query) throws SQLException {
return connection.prepareStatement(query);
}
...
public void handle(ActionEvent event) throws SQLException {
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES (?);";
PreparedStatement statement = database.prepareStatement(query);
try {
statement.setString(1, FXVoornaam.getText());
statement.executeUpdate();
} catch (Exception e) {
// log info somewhere at least until it's properly tested/
// you implement a better way of handling the error
e.printStackTrace(System.err);
}
}
You have to add like this in JavaFx :
String query = "INSERT INTO testDatabase.Gebruikers (Voornaam) VALUES ('{FXVoornaam.getText()}') ";
String query = "INSERT INTO testDatabase.Gebruikers(Voornaam)
VALUES('" + FXVoornaam.getText() + "')";

MySql J/Connector 5.1.39 not working when you use select ... order by

I've updated J/connector in my program from Connector 5.1.7 to Connector 5.1.39 and I saw selections stop working.
After digging more I realize that only ordered selects don't work. If I remove the order by from sql query everything is nice.
Here is my program
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MysqlVersion {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&character_set_server=utf8mb4&useSSL=false";
String user = "root";
String password = "root";
try {
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("select * from `scripts` order by id desc");
//this returns false when order by is in the query
System.out.println(rs.next());
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MysqlVersion.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MysqlVersion.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
Always System.out.println(rs.next()); will return false when 'order by' is in query.
If I go back to earlier version everything works ok. Am I doing something wrong. Is there a special setup I need to do? Or this is a bug?
I'm using MySql 5.7.14

SQLException Operation not allowed after ResultSet closed

I am attempting to write a JUnit test for a query which is retrieved via a textbox in an html form. The text retrieval has been tested and works but my unit test is failing. I am using 2 relevant classes: QueryController and QueryControllerTest. I have been playing around with when and what I am closing in these two classes and keep getting the error: Operation not allowed after ResultSet closed.
QueryControllerTest.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.junit.Test;
import static org.junit.Assert.*;
public class QueryControllerTest {
#Test
public void testQuery() {
ResultSet testRs = null;
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "GCImage";
conn = DriverManager.getConnection(connectionUrl,
connectionUser, connectionPassword);
Query testQuery = new Query();
testQuery
.setQuery("select * from service_request where FN_contact = 'Greg'");
testRs = QueryController.executeSelect(conn, testQuery);
assertEquals("Laughlin", testRs.getString("LN_contact"));
assertEquals("Hello World", testRs.getString("Notes"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
testRs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
QueryController.java
import java.util.Map;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class QueryController {
#RequestMapping(value = "/query")
public String processRegistration(#ModelAttribute("query") Query query,
Map<String, Object> model) {
String queryString = query.getQuery();
if (queryString != null && !queryString.isEmpty()) {
System.out.println("query (from controller): " + queryString);
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String connectionUrl = "jdbc:mysql://localhost:3306/test";
String connectionUser = "root";
String connectionPassword = "GCImage";
conn = DriverManager.getConnection(connectionUrl,
connectionUser, connectionPassword);
if (queryString.toLowerCase().startsWith("select")) {
ResultSet rs = executeSelect(conn, query);
} else {
int rowsUpdated = executeUpdate(conn, query);
System.out.println(rowsUpdated + " rows updated");
}
} catch (Exception e) {
e.printStackTrace();
}
}
return "query";
}
public static ResultSet executeSelect(Connection conn, Query query) {
ResultSet rs = null;
Statement stmt = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(query.getQuery());
while (rs.next()) {
String id = rs.getString("ID");
String firstName = rs.getString("FN_Contact");
String lastName = rs.getString("LN_Contact");
String notes = rs.getString("Notes");
System.out.println("ID: " + id + ", First Name: " + firstName
+ ", Last Name: " + lastName + ", Notes: " + notes);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs!=null){
rs.close();
}
if(stmt != null){
stmt.close();
}
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return rs;
}
}
QueryController.executeSelect is calling rs.close(), but then your assertEquals in QueryControllerTest.testQuery are calling methods on testRS. As executeSelect is returning the resultset, closing it first doesn't make sense. Further, executeSelect is being passed the connection, so it shouldn't be closing that either (what happens if the caller wants to do two different selects on the same connection?).
I think the problem is because you are creating two connections. Try to only instantiate the connection of QueryController class for your test. You will need to provide the connection. After you store it in a variable to run the query.
Connection con = QueryController.getConnection ();

Cannot find place to insert finally block to get rid of the error: Insert Finally to complete TryStatement

I've tried several spots to insert the finally block but no matter what I try it ends up making the code worse.
Here is my code, the 4th to last ending curly bracket is the one giving me the error. Any thoughts?
package com.tunestore.action;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.owasp.validator.html.*;
import org.owasp.esapi.*;
public class DownloadAction extends Action
{
private static final Log log = LogFactory.getLog(DownloadAction.class);
public static String DB_URL;
static
{
if (System.getProperty("tunestore.db.location") != null)
{
DB_URL = "jdbc:derby://localhost:1527/" + System.getProperty("tunestore.db.location");
}
else
{
DB_URL = "jdbc:derby://localhost:1527/" + System.getProperty("user.home") + "/.tunestore";
}
System.setProperty("jdbc.tunestore.url", DB_URL);
}
public static Connection getConnection() throws Exception
{
log.info("Opening database at " + DB_URL);
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL);
return conn;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
DynaActionForm daf = (DynaActionForm)form;
String user = (String)request.getSession(true).getAttribute("USERNAME");
if(user != null)
{
Connection conn = null;
try
{
conn = DownloadAction.getConnection();
String sql2 = "SELECT ID FROM CD WHERE CD.BITS = ?";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(1, request.getParameter("cd"));
ResultSet rs2 = stmt2.executeQuery();
rs2.next();
String sql = "SELECT COUNT(*) "
+ "FROM TUNEUSER_CD "
+ "WHERE TUNEUSER_CD.TUNEUSER = ? AND TUNEUSER_CD.CD = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, user);
stmt.setInt(2, rs2.getInt(1));
ResultSet rs = stmt.executeQuery();
rs.next();
int owned = rs.getInt(1);
if(owned == 1)
{
try
{
// Try to open the stream first - if there's a goof, it'll be here
InputStream is = this.getServlet().getServletContext().getResourceAsStream("/WEB-INF/bits/" + request.getParameter("cd"));
if (is != null)
{
response.setContentType("audio/mpeg");
response.setHeader("Content-disposition", "attachment; filename=" + daf.getString("cd"));
byte[] buff = new byte[4096];
int bread = 0;
while ((bread = is.read(buff)) >= 0)
{
response.getOutputStream().write(buff, 0, bread);
}
}
else
{
ActionMessages errors = getErrors(request);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("download.error"));
saveErrors(request, errors);
return mapping.findForward("error");
}
}
catch (Exception e)
{
e.printStackTrace();
ActionMessages errors = getErrors(request);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("download.error"));
saveErrors(request, errors);
return mapping.findForward("error");
}
return null;
}
}
}
}
}
That bracket is the location where your outer try block ends. It has no catch block and no finally block, so you get an error. Just add one or the other immediately after the bracket, or remove the try if it's not needed.
You only have one catch block, but two trys. Add a catch block for the first try-catch and you should have your issue solved.
Edit: Why are you nesting try-catch in the first place? I don't believe there is any need to do so.

Categories