dbaccess.servlets.ModifyServlet.java Source code

Java tutorial

Introduction

Here is the source code for dbaccess.servlets.ModifyServlet.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package dbaccess.servlets;

import dbaccess.persistence.DBHelper;
import dbaccess.beans.BookData;
import dbaccess.persistence.Book;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.servlet.RequestDispatcher;
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 org.apache.commons.beanutils.BeanUtils;

/**
 *
 * @author ashdarji
 */
@WebServlet(name = "ModifyServlet", urlPatterns = { "/ModifyServlet" })
public class ModifyServlet extends HttpServlet {
    @PersistenceContext(unitName = "Store2PU")
    private EntityManager em;
    @Resource
    private javax.transaction.UserTransaction utx;

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // extract request parameters to a book data bean using
        // apache BeanUtils
        BookData bookData = new BookData();
        try {
            BeanUtils.populate(bookData, request.getParameterMap());
            String nextPage = null;

            // set up the bean as request parameter
            request.setAttribute("bookData", bookData);

            // ADD A BOOK
            if (request.getParameter("add") != null) {
                if (bookData.isComplete()) {
                    if (DBHelper.addBook(em, utx, bookData)) {
                        nextPage = "/index.jsp";
                    } else {
                        nextPage = "/failedAdd.jsp";
                    }
                } else {
                    nextPage = "/failedAdd.jsp";
                }
            }
            // DELETE A BOOK
            else if (request.getParameter("delete") != null) {
                if (DBHelper.deleteBook(em, utx, bookData)) {
                    nextPage = "/index.jsp";
                } else {
                    nextPage = "/failedDelete.jsp";
                }

            }
            // GO TO KIDS PAGE
            else if (request.getParameter("kidspage") != null) {
                if (DBHelper.getAllKidsBookIDS(em) != null) {
                    nextPage = "/KidsBooksPage";
                } else {
                    nextPage = "/emptyDatabaseError.jsp";
                }
            }

            // GO TO TECH PAGE
            else if (request.getParameter("techpage") != null) {
                if (DBHelper.getAllTechBookIDS(em) != null) {
                    nextPage = "/TechBooksPage";
                } else {
                    nextPage = "/emptyDatabaseError.jsp";
                }
            }

            // SHOW RESULTS in table, if any
            fillTable(em, request, nextPage);

            RequestDispatcher dispatcher = request.getRequestDispatcher(nextPage);
            dispatcher.forward(request, response);
        } catch (IllegalAccessException | InvocationTargetException | ServletException | IOException ex) {
        }

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    /**
     * Find a book by id and check if any that the other fields are valid
     */
    private List<Book> getBookById(EntityManager em, BookData bookData) {
        Book book = DBHelper.findBook(em, bookData.getId());
        if (book == null) {
            return null;
        } else if (book.matches(bookData)) {
            ArrayList<Book> result = new ArrayList<>();
            result.add(book);
            return result;
        }
        return null;
    }

    private List<Book> checkResults(List<Book> allresults, BookData bookData) {
        ArrayList<Book> results = new ArrayList<>();
        for (Book book : allresults) {
            if (book.matches(bookData))
                results.add(book);
        }
        if (results.isEmpty()) {
            return null;
        } else {
            return results;
        }
    }

    private void fillTable(EntityManager em, HttpServletRequest request, String nextPage) {
        List<Book> results = null;
        results = DBHelper.getBooks(em);
        if (results != null) {
            // books have been found
            request.setAttribute("results", results);
            nextPage = "/index.jsp";
        } else {

            nextPage = "/updateError.jsp";
        }
    }

    public void persist(Object object) {
        try {
            utx.begin();
            em.persist(object);
            utx.commit();
        } catch (Exception e) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
            throw new RuntimeException(e);
        }
    }

}