controllers.ProcessController.java Source code

Java tutorial

Introduction

Here is the source code for controllers.ProcessController.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 controllers;

import JsonObjects.Depart;
import JsonObjects.Record;
import JsonObjects.Staff;
import com.google.gson.Gson;
import dao.DepartsDAO;
import dao.Mailer;
import dao.RecordsDAO;
import dao.StaffsDAO;
import dao.UsersDAO;
import entities.ChangePasswordToken;
import entities.Departs;
import entities.Records;
import entities.Staffs;
import entities.Users;
import hibernate.HibernateUtil;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Phan Ba Hai
 */
@Controller
@RequestMapping(method = RequestMethod.POST)
public class ProcessController {

    List<ChangePasswordToken> list = new ArrayList<>();

    @Autowired
    ServletContext context;
    @Autowired
    Mailer mailer;

    @RequestMapping(value = "login", params = "btnLogin")
    public String login(ModelMap model, @RequestParam("username") String username,
            @RequestParam("password") String password, HttpSession session) {
        UsersDAO userDAO = new UsersDAO();
        if (userDAO.checkPassword(username, password)) {
            Users users = userDAO.getUserLogin(username);
            session.setAttribute("username", users.getUsername());
            session.setAttribute("fullName", users.getFullname());
            return "redirect:/index.htm";
        } else {
            model.addAttribute("message", "Username or password invaild! Please try agian");
            return "login";
        }
    }

    @RequestMapping("login/forgot")
    public String forgot(@RequestParam("email") String email, ModelMap model) throws Exception {
        String username = "";
        ChangePasswordToken token = new ChangePasswordToken(UUID.randomUUID(), email);
        list.add(token);

        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.getTransaction().begin();
            Query query = session.createQuery("FROM Staffs WHERE email = :email");
            query.setString("email", email);
            Staffs staff = (Staffs) query.uniqueResult();
            username = staff.getName();
            session.getTransaction().commit();
        } catch (Exception e) {
            model.addAttribute("message", "Email not found! Please try agian");
            session.getTransaction().rollback();
            return "forgot-password";
        }

        String url = "http://green.sakadream.me/login/reset.htm?token=" + token.getToken().toString() + "&email="
                + token.getEmail();

        String body = "Dear " + username + "!" + "<br>" + "You received this email because you forgot your password"
                + "<br>" + "Please click this link to change your password: " + url + "<br>" + "Thank you!" + "<br>"
                + "Administrator of Green Ltd - Ba Hai Phan";

        mailer.send("accfordownapp@gmail.com", email, "Reset Password - Green Ltd", body);
        model.addAttribute("message", "Mail sended! Please check your inbox or junk");
        return "forgot-password";
    }

    @RequestMapping(value = "login/reset", method = RequestMethod.GET)
    public String reset(ModelMap model, @RequestParam("token") String UUID, @RequestParam("email") String email) {
        for (ChangePasswordToken token : list) {
            if (token.getToken().toString().equals(UUID) & token.getEmail().equals(email)) {
                String username = "";
                String fullname = "";
                Session session = HibernateUtil.getSessionFactory().openSession();
                try {
                    session.getTransaction().begin();
                    Query query = session.createQuery("FROM Staffs WHERE email = :email");
                    query.setString("email", email);
                    Staffs staff = (Staffs) query.uniqueResult();
                    fullname = staff.getName();
                    session.getTransaction().commit();
                } catch (Exception e) {
                    session.getTransaction().rollback();
                }
                try {
                    session.getTransaction().begin();
                    Query query = session.createQuery("FROM Users WHERE fullname = :fullname");
                    query.setString("fullname", fullname);
                    Users user = (Users) query.uniqueResult();
                    username = user.getUsername();
                    session.getTransaction().commit();
                } catch (Exception e) {
                    session.getTransaction().rollback();
                }
                model.addAttribute("username", username);
                model.addAttribute("token", token.getToken().toString());
                return "reset-password";
            }
        }
        model.addAttribute("message",
                "This link was used, please go to login page and click forgot password link agian");
        return "reset-message";
    }

    @RequestMapping(value = "login/resetProcessing", method = RequestMethod.POST)
    public String submitReset(ModelMap model, @RequestParam("password") String password,
            @RequestParam("comfirm") String comfirmPassword, @RequestParam("username") String username,
            @RequestParam("token") String tokenString) {
        String oldPassword = "";
        Users user = new Users();
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.getTransaction().begin();
            Query query = session.createQuery("FROM Users WHERE username = :username");
            query.setString("username", username);
            user = (Users) query.uniqueResult();
            oldPassword = user.getPassword();
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        }
        if (!password.equals(comfirmPassword)) {
            model.addAttribute("message", "Comfirm password not match! Please try again!");
            model.addAttribute("username", username);
            model.addAttribute("token", tokenString);
            return "reset-password";
        } else if (oldPassword.equals(comfirmPassword)) {
            model.addAttribute("message", "The new password is same with the old one! Please try agian!");
            model.addAttribute("username", username);
            model.addAttribute("token", tokenString);
            return "reset-password";
        } else {
            UsersDAO usersDAO = new UsersDAO();
            usersDAO.changePassword(user, password);
            model.addAttribute("message", "Reset password complete!");
            for (ChangePasswordToken token : list) {
                if (token.getToken().toString().equals(tokenString)) {
                    token.setToken(new UUID(0, 0));
                    token.setEmail("");
                }
            }
            return "reset-message";
        }
    }

    @RequestMapping("management/departs/add")
    public ModelAndView addDepart(@RequestParam("name") String name) {
        DepartsDAO departsDAO = new DepartsDAO();
        departsDAO.addDepart(name);
        return new ModelAndView("redirect:../departs.htm");
    }

    @RequestMapping(value = "management/departs/ajax", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getDepart(@RequestBody String req) {
        String id = req.substring(req.indexOf("=") + 1);
        DepartsDAO departsDAO = new DepartsDAO();
        Gson gson = new Gson();
        Departs d = departsDAO.getDepart(id);
        Depart depart = new Depart(d.getId(), d.getName());
        return gson.toJson(depart);
    }

    @RequestMapping("management/departs/edit")
    public ModelAndView deleteDepart(@RequestParam("depart-id") String id,
            @RequestParam("depart-name") String name) {
        DepartsDAO departsDAO = new DepartsDAO();
        departsDAO.editDepart(id, name);
        return new ModelAndView("redirect:../departs.htm");
    }

    @RequestMapping("management/departs/delete")
    public ModelAndView deleteDepart(@RequestParam("depart-id") String id) {
        DepartsDAO departsDAO = new DepartsDAO();
        departsDAO.deleteDepart(id);
        return new ModelAndView("redirect:../departs.htm");
    }

    @RequestMapping("management/staffs/add")
    public ModelAndView staffs(@RequestParam("name") String name, @RequestParam("gender") String genderString,
            @RequestParam("birthday") String birthdayString, @RequestParam("avatar") MultipartFile avatar,
            @RequestParam("email") String email, @RequestParam("phone") String phone,
            @RequestParam("salary") String salaryString, @RequestParam("notes") String notes,
            @RequestParam("depart") String departId) throws IOException {
        String avatarFileName = "default-avatar.png";
        if (!avatar.isEmpty()) {
            String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename());
            avatar.transferTo(new File(avatarPath));
            avatarFileName = new File(avatarPath).getName();
        }
        StaffsDAO staffsDAO = new StaffsDAO();
        staffsDAO.addStaff(name, genderString, birthdayString, avatarFileName, email, phone, salaryString, notes,
                departId);
        return new ModelAndView("redirect:../staffs.htm");
    }

    @RequestMapping(value = "management/staffs/ajax", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getStaff(@RequestBody String req) {
        String id = req.substring(req.indexOf("=") + 1);
        StaffsDAO staffsDAO = new StaffsDAO();
        Gson gson = new Gson();
        Staffs s = staffsDAO.getStaff(id);
        Staff staff = new Staff(s.getId(), s.getDeparts().getName(), s.getName(), s.isGender(), s.getBirthday(),
                s.getPhoto(), s.getEmail(), s.getPhone(), s.getSalary(), s.getNotes());
        return gson.toJson(staff);
    }

    @RequestMapping("management/staffs/delete")
    public ModelAndView deleteStaff(@RequestParam("id") String id) {
        StaffsDAO staffsDAO = new StaffsDAO();
        staffsDAO.deleteStaff(id);
        return new ModelAndView("redirect:../staffs.htm");
    }

    @RequestMapping("management/staffs/edit")
    public ModelAndView editStaff(@RequestParam("id") String id, @RequestParam("name") String name,
            @RequestParam("gender") String genderString, @RequestParam("birthday") String birthdayString,
            @RequestParam("avatar") MultipartFile avatar, @RequestParam("email") String email,
            @RequestParam("phone") String phone, @RequestParam("salary") String salaryString,
            @RequestParam("note") String notes, @RequestParam("depart") String departId) throws IOException {
        String avatarFileName = "";
        if (!avatar.isEmpty()) {
            String avatarPath = context.getRealPath("/resources/images/" + avatar.getOriginalFilename());
            avatar.transferTo(new File(avatarPath));
            avatarFileName = new File(avatarPath).getName();
        }
        StaffsDAO staffsDAO = new StaffsDAO();
        staffsDAO.editStaff(id, name, genderString, birthdayString, avatarFileName, email, phone, salaryString,
                notes, departId);
        return new ModelAndView("redirect:../staffs.htm");
    }

    @RequestMapping(value = "record/ajaxDeparts", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getStaffsByDepart(@RequestBody String req) {
        String id = req.substring(req.indexOf("=") + 1);
        StaffsDAO staffsDAO = new StaffsDAO();
        List<Staffs> staffsList = staffsDAO.getStaffsByDepart(id);
        List<Staff> list = new ArrayList<>();
        for (Staffs s : staffsList) {
            list.add(new Staff(s.getId(), s.getDeparts().getName(), s.getName(), s.isGender(), s.getBirthday(),
                    s.getPhoto(), s.getEmail(), s.getPhone(), s.getSalary(), s.getNotes()));
        }
        Gson gson = new Gson();
        return gson.toJson(list);
    }

    @RequestMapping(value = "record/ajax", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String getRecord(@RequestBody String req) {
        String id = req.substring(req.indexOf("=") + 1);
        RecordsDAO recordsDAO = new RecordsDAO();
        Gson gson = new Gson();
        Records r = recordsDAO.getRecord(id);
        return gson.toJson(
                new Record(r.getId(), r.getStaffs().getName(), r.getType().getId(), r.getReason(), r.getDate()));
    }

    @RequestMapping("record/add")
    public ModelAndView addRecord(@RequestParam("type") String typeId, @RequestParam("reason") String reason,
            @RequestParam("date") String dateString, @RequestParam("staff") String staffId) {
        RecordsDAO recordsDAO = new RecordsDAO();
        recordsDAO.addRecord(typeId, reason, dateString, staffId);
        return new ModelAndView("redirect:../record.htm");
    }

    @RequestMapping("record/edit")
    public ModelAndView editRecord(@RequestParam("id") String id, @RequestParam("type") String typeId,
            @RequestParam("reason") String reason, @RequestParam("date") String date) throws ParseException {
        RecordsDAO recordsDAO = new RecordsDAO();
        recordsDAO.editRecord(id, typeId, reason, date);
        return new ModelAndView("redirect:../record.htm");
    }

    @RequestMapping("record/delete")
    public ModelAndView deleteRecord(@RequestParam("id") String id) {
        RecordsDAO recordsDAO = new RecordsDAO();
        recordsDAO.deleteRecord(id);
        return new ModelAndView("redirect:../record.htm");
    }

    public boolean checkSession(HttpSession session) {
        return (session == null) ? true : false;
    }
}