Null Pointer Exception in my code - java

Hello am developing a web-app using mvc architecture am trying to insert data from form to database through service layer but it throwing a null pointer exception:
Below is my Servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Affiliate af= new Affiliate();
af.setFisrtName(request.getParameter("txtFname"));
af.setLastName(request.getParameter("txtLname"));
af.setGender(request.getParameter("txtGender"));
af.setCategory(request.getParameter("txtCategory"));
String dob=(request.getParameter("txtDob"));
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date date;
try {
date = (Date)formatter.parse(dob);
af.setDate(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
af.setAge(Integer.parseInt(request.getParameter("txtAge")));
af.setAddress(request.getParameter("txtAddr"));
af.setCountry("India");
af.setState(request.getParameter("txtState"));
af.setCity(request.getParameter("txtCity"));
af.setPinCode(Integer.parseInt(request.getParameter("txtPin")));
af.setEmailId(request.getParameter("txtEmail"));
af.setStd(Integer.parseInt(request.getParameter("txtStd")));
af.setContactNo(Integer.parseInt(request.getParameter("txtPhone")));
af.setMobileNo(Long.parseLong(request.getParameter("txtMobile"),10));
AffiliateService afs=new AffiliateService();
**afs.createAffiliate(af);**
}
}
and my service code is:
public class AffiliateService {
Affiliate affiliate=null;
public Affiliate createAffiliate( Affiliate affiliate) {
**validateAffiliate(affiliate);**
return affiliate;
}
private Affiliate validateAffiliate(Affiliate affiliate) {
this.affiliate=affiliate;
if(affiliate!=null){
AffiliateDAO afd=new AffiliateDAO();
**afd.insertAffiliate(affiliate);**
}
return affiliate;
}
}
and my DAO code is as below:
public class AffiliateDAO {
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public List<Affiliate> addAffiliate(){
ArrayList<Affiliate> affiliates = new ArrayList<Affiliate>();
return affiliates;
}
public void updateAffiliate(Affiliate affiliate){
}
public void delteAffiliate(Affiliate affiliate){
}
public void selectAffiliate(Affiliate affiliate){
}
public void insertAffiliate(Affiliate affiliate){
String sql="INSERT INTO REGISTER " +"(id,FisrtName,LastName,Gender,Category,DateOfBirth,Age,Address,Country,State,City,PinCode,EmailId,Std,ContactNo,MobileNo)VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
Connection conn = null;
try {
**conn = dataSource.createConnection();**
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, affiliate.getId());
ps.setString(2, affiliate.getFisrtName());
ps.setString(3, affiliate.getLastName());
ps.setString(4,affiliate.getGender());
ps.setString(5, affiliate.getCategory());
ps.setDate(6, (Date) affiliate.getDate());
ps.setInt(7, affiliate.getAge());
ps.setString(8, affiliate.getAddress());
ps.setString(9,affiliate.getCountry());
ps.setString(10,affiliate.getState());
ps.setString(11, affiliate.getCity());
ps.setInt(12, affiliate.getPinCode());
ps.setString(13, affiliate.getEmailId());
ps.setInt(14,affiliate.getStd());
ps.setInt(15, affiliate.getContactNo());
ps.setLong(16, affiliate.getMobileNo());
ps.executeUpdate();
ps.close();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
public Affiliate searchById(int id){
String sql = "SELECT * FROM REGISTER WHERE id = ?";
Connection conn = null;
try {
conn = dataSource.createConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
Affiliate affiliate = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
rs.getInt("id");
rs.getString("FisrtName");
rs.getString("LastName");
rs.getString("Gender");
rs.getString("Category");
rs.getDate("DateOfBirth");
rs.getString("Age");
rs.getString("Address");
rs.getString("Country");
rs.getString("State");
rs.getString("City");
rs.getInt("PinCode");
rs.getString("EmailId");
rs.getInt("Std+ContactNo");
rs.getString("MobileNo");
}
rs.close();
ps.close();
return affiliate;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {}
}
}
}
}
and this is my dataSource class:
public class DataSource {
Connection connection=null;
BasicDataSource bdsource=new BasicDataSource();
public DataSource(){
bdsource.setUrl("dbUrl");
bdsource.setUsername("dbuserName");
bdsource.setPassword("dbPassword");
bdsource.setDriverClassName("com.mysql.jdbc.Driver");
}
public Connection createConnection(){
Connection con=null;
try{
if(connection !=null){
System.out.println("Can't create a new connection");
}
else{
con=bdsource.getConnection();
}
}
catch(Exception e){
e.printStackTrace();
}
return con;
}
}
and my stack trace is as below:
java.lang.NullPointerException
com.affiliate.DAO.AffiliateDAO.insertAffiliate(AffiliateDAO.java:43)
com.affiliate.service.AffiliateService.validateAffiliate(AffiliateService.java:21)
com.affiliate.service.AffiliateService.createAffiliate(AffiliateService.java:12)
com.affiliate.servlet.AffiliateServlet.doPost(AffiliateServlet.java:71)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
com.affiliate.servlet.RegisterServlet.doPost(RegisterServlet.java:42)
javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
All the bolded lines in the codes are correspoding to the stack trace.
Please help me fix this..I doubt my validate method...

Looks like dataSource is null because setDataSource is never called.

You need to modify you validateAffiliate(Affiliate affiliate) method of the AffiliateService class. You have never initialized the Data Source which is causing NPE to occur.
Check this:
private Affiliate validateAffiliate(Affiliate affiliate) {
this.affiliate=affiliate;
if(affiliate!=null){
AffiliateDAO afd=new AffiliateDAO();
// This was causing NPE. Data source must be set before using it.
afd.setDataSource(passDataSourceInstance);
afd.insertAffiliate(affiliate);
}

Initialize dataSource before call to conn = dataSource.createConnection();
can be in AffiliateDAO constructor.

Related

Hi, How can i do operation of others dao with one transaction?

I have dao which methods should be within one transaction What is the best way to do it correctly?
Car dao has following method
public Car findCar(int numOfPas,String carCategory){
String query = "SELECT*FROM car_info WHERE numOfPas = ? AND carCategory=? AND carState='ready' ORDER BY RAND() LIMIT 1;";
Car foundCar = null;
ResultSet resultSet = null;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement statement = connection.prepareStatement(query)){
statement.setInt(1,numOfPas);
statement.setString(2,carCategory);
resultSet =statement.executeQuery();
if(resultSet.next()){
foundCar = new Car();
foundCar.setCarId(resultSet.getInt("carId"));
foundCar.setCarCategory(resultSet.getString("carCategory"));
foundCar.setNumOfPas(resultSet.getInt("numOfPas"));
foundCar.setCarState(resultSet.getString("carState"));
foundCar.setCarName(resultSet.getString("carName"));
foundCar.setCarImage(manager.byteToImage(resultSet.getBytes("carImage")));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
if(resultSet!=null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return foundCar;
}
And Order Dao has following
#Override
public boolean insertOrder(Order order) {
int rowNum = 0;
String query = "INSERT INTO user_order(userId,carId,userAddress,userDestination,orderCost,orderDate) values(?,?,?,?,?,?)";
ResultSet keys = null;
try (Connection connection = MySQLDAOFactory.getConnection();
PreparedStatement statement = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS)){
statement.setInt(1,order.getUserId());
statement.setInt(2,order.getCarId());
statement.setString(3, order.getUserAddress());
statement.setString(4, order.getUserDestination());
statement.setDouble(5,order.getOrderCost());
statement.setTimestamp(6, Timestamp.valueOf(order.getOrderDate()));
rowNum = statement.executeUpdate();
keys = statement.getGeneratedKeys();
if(keys.next()){
order.setOrderId(keys.getInt(1));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return rowNum>0;
}
How can I put these action in one transaction? I receive connection by Apache dhcp connection pool.
Edited
This is class
where I get connection
public class MySQLDAOFactory extends DAOFactory {
public static Connection getConnection(){
Connection conn = null;
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
DataSource ds = (DataSource) envContext.lookup("jdbc/UsersDB");
conn = ds.getConnection();
} catch (NamingException | SQLException e) {
e.printStackTrace();
}
return conn;
}
#Override
public CarDao getCarDao() {
return new MySQLCarDao();
}
#Override
public UserDao getUserDao() {
return new MySQLUserDao();
}
#Override
public OrderDao getOrderDao() {
return new MySQLOrderDao();
}
#Override
public CarCategoryDao getCarCategoryDao() {
return new MySQLCarCategoryDao();
}
}
There are a lot of different ways to manage transactions. Given your code, the simplest way would be to:
in a try block:
Create your connection in the caller that wraps both calls
Execute connection.setAutoCommit(false)
Call each of the methods findCar() and insertOrder()
Call connection.commit();
in the catch block:
call connection.rollback()
The connection is not created outside those functions, so don't forget to remove the connection setup from each function.

How to return object for GetMapping path id

The controller code :
#GetMapping("/show/{id}")
public ResponseEntity<Student> findId(#PathVariable Student student) throws Exception {
Student showId = studentService.findId(student);
return new ResponseEntity<Student>(showId, HttpStatus.OK);
}
needs to return an object for a path id
Repository code:
public Student findId(Student student) throws Exception {
Connection connect = null;
Statement st = null;
ResultSet rec = null;
PreparedStatement pre = null;
List<Student> userlist = new ArrayList<Student>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase" +"?user=root&password=root&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC");
connect.setAutoCommit(false);
st = connect.createStatement();
String sql = "SELECT * FROM student WHERE studentid = ? ";
pre = connect.prepareStatement(sql);
pre.setLong(1, student.getId());
pre.executeQuery();
} catch (Exception e) {
if (connect != null) {
try {
st.close();
connect.rollback();
} catch(SQLException e2) {
e2.printStackTrace();
}
}
} finally {
if (st != null) {
try {
st.close();
connect.setAutoCommit(true);
} catch(SQLException e) {
e.printStackTrace();
}
}
}
try {
connect.close();
} catch (SQLException e) {
e.printStackTrace();
}
return student;
}
ResultSet result = pre.executeQuery();
while (result.next()) {
long id = resultSet.getLong("studentId");
String name = resultSet.getString("name");
// another fields
return new Student(id, name);
}
And for controller if need only id (#PathVariable Long id) is more light.
Student response = studentService.findById(id);
return ResponseEntity.ok(response);

JDBC: can't send parameters from client to Derby DB by using servlet and Apache Tomcat

I'm try to send the parameters from servlet to db and I get errors in my connection.
Steps of my works:
In eclipse I create a Dynamic Web Project with Tomcat server
Create a model (without any technology as a Spring , Hibernate, JSP, JSF and so on. ) for to use with DML methodology (clearing java code).
I tested the created module (by using some main test class) and it works so good (connections , inserting, deleting..).
After that , I can a simple HTML doc for client side.
process for running a web module step by step:
Before start Web project I start to run Derby DB - works OK.
Starting a Web project with Apache Tomcat.
insert data to the HTML and submitted it. - works OK
In the Servlet class the data gated to the doGet(...) method. - works OK.
From the Servlet (doGet(...) method) when I try to send the parameter to the DB I get errors in my conector class.
How can I set right that?
Thanks.
Codes:
Servlet Class:
#WebServlet({ "/StudentServlet", "/Student" })
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private StudentDbDao sf = new StudentDbDao();
private Student student = new Student();
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter writer = response.getWriter();
String studentId = request.getParameter("sudentId");
Long id = Long.parseLong(studentId);
String studentFullName = request.getParameter("studentFullName");
String studentGendre = request.getParameter("studentGendre");
String studentGrade = request.getParameter("studentGrade");
try {
student.setId(id);
student.setFullName(studentFullName);
student.setGender(studentGendre);
student.setGrade(studentGrade);
sf.createStudent(student);
writer.println("The student #" + id + " inserted.");
} catch (StudentSystemException e) {
e.printStackTrace();
}
}
}
class StudentDbDao that response for DML functionality:
package dao.Db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import bean.Student;
import bean.StudentSystemException;
import dao.StudentDao;
import dao.connector.ConnectionPool;
public class StudentDbDao implements StudentDao {
private Connection conn;
public StudentDbDao() {
}
#Override
public void createStudent(Student student) throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "INSERT INTO Students(ID, FULLNAME, GENDER, GRADE) VALUES(?, ?, ?, ?)";
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, student.getId());
pstmt.setString(2, student.getFullName());
pstmt.setString(3, student.getGender());
pstmt.setString(4, student.getGrade());
pstmt.executeUpdate();
System.out.println(student.getFullName() + " created successfully");
} catch (SQLException e) {
throw new StudentSystemException("Failed!", e);
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
}
#Override
public void removeStudent(Student student) throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "DELETE FROM Students WHERE ID = " + student.getId();
PreparedStatement pstmt;
try {
pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
System.out.println(student.getId() + " removed successfully.");
} catch (SQLException e) {
throw new StudentSystemException("Failed!", e);
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
}
#Override
public Student getStudentById(long id) throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "SELECT * FROM Students WHERE ID = " + id;
Student student = new Student();
PreparedStatement pstmt;
ResultSet rs;
try {
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
if (rs.next()) {
student.setId(rs.getLong(1));
student.setFullName(rs.getString(2));
student.setGender(rs.getString(3));
student.setGrade(rs.getString(4));
}
// else {
// System.out.print("Student with PID #" + id + " not exists. ");
// }
return student;
} catch (SQLException e) {
throw new StudentSystemException("Failed!", e);
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
}
public long getMaxRows() throws StudentSystemException {
conn = ConnectionPool.getInstance().getConnection();
String sql = "SELECT COUNT(*) FROM Students";
PreparedStatement pstmt;
int count = 0;
try {
pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
rs.next();
count = rs.getInt(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
ConnectionPool.getInstance().returnConnection(conn);
}
return count;
}
}
class ConnectionPool where code is falls when Servlet try to set the parameters:
public class ConnectionPool {
// static final int MAX_CONS = 1;
private Connection myconn = null;
// private Set<Connection> connections = new HashSet<Connection>();
private static ConnectionPool instance = new ConnectionPool();
String url = "jdbc:derby://localhost:1527/StudentDB";
private ConnectionPool() {
try {
myconn = DriverManager.getConnection(url);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static ConnectionPool getInstance() {
return instance;
}
public Connection getConnection() {
// Connection conn = myconn;
return this.myconn;
}
public void returnConnection(Connection conn) {
this.myconn = conn;
// myconn.add(conn);
}
public void closeAllConnections() throws StudentSystemException {
Connection connection = myconn;
try {
connection.close();
} catch (SQLException e) {
throw new StudentSystemException("Failed to close connection: ", e);
}
}
attached before submit and after print-screens:
before:
after:

SQL populate Table from Database

I have a problem with trying to populate a jtable. I have searched all over and cannot seem to find a solution to my code, I would appreciate any kind of help.
Here is the method I have to get the information:
public class MovieDAO extends Dao implements MovieDAOInterface{
#Override
public List<Movie> getAllMovies() {
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
List<Movie> movies = new ArrayList<>();
try {
con = getConnection();
String query = "Select * from Movie";
ps = con.prepareStatement(query);
rs = ps.executeQuery();
while (rs.next()) {
Movie AllMovies = new Movie(rs.getInt("MovieId"), rs.getString("MovieTitle"), rs.getString("MovieGenre"), rs.getInt("MovieLicence"));
movies.add(AllMovies);
}
} catch (SQLException e) {
System.out.println("Exception occured in the getAllMovies() method");
e.getMessage();
} finally {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (con != null) {
freeConnection(con);
}
} catch (SQLException e) {
System.out.println("Exception occured in the finally section of the getAllMovies() method");
e.getMessage();
}
}
return movies;
}
}
Here is where I am calling it and having the issue it wont display on the table;
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println("Test Find All Movies");
MovieDAO dao = new MovieDAO();
List<Movie> movies = dao.getAllMovies();
if (movies.isEmpty()) {
System.out.println("List is empty");
} else {
for (Movie m : movies) {
DisplayMovies.setModel(m.toString());
}
}
}

mysql query not executing in java but executing in my SQLYog

can anyone please tell why the following update query which is working perfectly when executed directly from my SQLYog editor, but not executing from java. it is not giving any exception but not updating into the database.
this the update query
UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))
Java code
public static void main(String[] args) throws Exception {
int update = new Dbhandler().update("UPDATE hotel_tables SET hotel_tables.status='reserved' WHERE hotel_tables.section='pub' AND tableno='4' AND ('4' NOT IN (SELECT tableno FROM table_orders WHERE outlet='pub'))");
}
public int update(String Query)throws Exception
{
try
{
cn=getconn();
stmt=(Statement) cn.createStatement();
n=stmt.executeUpdate(Query);
stmt.close();
}
catch(Exception e)
{
e.printStackTrace();
throw(e);
}
finally
{
cn.close();
}
return n;
}
public Connection getconn()
{
try
{
Class.forName(driver).newInstance();
String url="jdbc:mysql://localhost/kot?user=root&password=root";
cn=(Connection) DriverManager.getConnection(url);
}
catch(Exception e)
{
System.out.println("DBHandler ERROR:"+e);
}
return cn;
}
This is how I used to do it before I switched to Spring's JdbcTemplate framework. Maybe this will help. It looks very similar to yours.
public static int runUpdate(String query, DataSource ds, Object... params) throws SQLException {
int rowsAffected = 0;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ds.getConnection();
stmt = conn.prepareStatement(query);
int paramCount = 1;
for (Object param : params) {
stmt.setObject(paramCount++, param);
}
rowsAffected = stmt.executeUpdate();
conn.commit();
} catch (SQLException sqle) {
throw sqle;
//log error
} finally {
closeConnections(conn, stmt, null);
}
return rowsAffected;
}
There are some subtle differences. I do a commit, though autoCommit is the default.
Try like this:
DriverManager.getConnection("jdbc:mysql://localhost:3306/kot","root","root");

Categories