control.dao.StaffDAO.java Source code

Java tutorial

Introduction

Here is the source code for control.dao.StaffDAO.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 control.dao;

import control.tools.MD5;
import java.util.List;
import model.LoginCode;
import prj2.lw.bean.StaffBean;
import static model.LoginCode.CodeList;
import model.entity.Staff;
import control.dco.StaffDCO;
import java.util.Collection;
import java.util.Iterator;
import java.util.ArrayList;
import model.entity.Role;
import org.hibernate.Criteria;
import org.hibernate.FetchMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author Wing
 */
public class StaffDAO {

    StaffDCO dco = new StaffDCO();

    //Search Staff list
    public List<Object> getStaffList(String key, int type, int page) {
        int firstResult = (page - 1) * 20;
        int totalSize;
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        List<Object> resultSet = new ArrayList<>();
        boolean searchByFirstName = true;
        try {
            session.beginTransaction();
            //            Query qr =session.createQuery("from "
            //                    +Staff.class.getName() 
            //                    + " s left join fetch s.roleCollection");
            //            session.createQuery(")
            Criteria crit = session.createCriteria(Staff.class);
            crit.setFetchMode("roleCollection", FetchMode.SELECT);
            crit.addOrder(Order.asc("id"));
            crit.setProjection(Projections.projectionList().add(Projections.property("id"))
                    .add(Projections.property("userName")).add(Projections.property("firstName"))
                    .add(Projections.property("lastName")).add(Projections.property("phone"))
                    .add(Projections.property("email")).add(Projections.property("status")));

            switch (type) {
            case 0:
                break;

            case 1:
                crit.add(Restrictions.ilike("userName", "%" + key + "%"));
                break;

            case 2:
                while (true) {
                    if (searchByFirstName) {
                        crit.add(Restrictions.ilike("firstName", "%" + key + "%"));
                        searchByFirstName = crit.list().isEmpty();
                        if (searchByFirstName) {
                            break;
                        }
                    } else {
                        crit.add(Restrictions.ilike("lastName", "%" + key + "%"));
                        break;
                    }
                }
                break;

            case 3:
                crit.add(Restrictions.ilike("phone", "%" + key + "%"));
                break;

            case 4:
                crit.add(Restrictions.ilike("email", "%" + key + "%"));
                break;

            case 5:
                crit.add(Restrictions.ilike("adress", "%" + key + "%"));
                break;
            }

            totalSize = crit.list().size();
            crit.setFirstResult(firstResult);
            crit.setMaxResults(20);
            resultSet = crit.list();
            resultSet.add(totalSize);
            return resultSet == null ? new ArrayList<>() : resultSet;
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    public long countEmployees() {
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.setProjection(Projections.rowCount());
            return (long) crit.uniqueResult();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    public Staff getEmployeeInfo(int id) {
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        Staff entity = new Staff();
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.add(Restrictions.eq("id", id));
            entity = (Staff) crit.uniqueResult();
            return entity == null ? new Staff() : entity;
        } catch (Exception e) {
            e.printStackTrace();
            return new Staff();
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    //    public List<StaffBean> searchByDate(Date date) {
    //        List<Staff> res = null;
    //        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
    //        try {
    //            session.beginTransaction();
    //            Criteria crit = session.createCriteria(Staff.class);
    //            crit.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
    //            crit.add(Restrictions.eq("birthDay", date));
    //            res = crit.list();
    //            return dco.toStaffBeanCollect(res);
    //        } catch (Exception e) {
    //            System.out.println("Error at ");
    //            return null;
    //        } finally {
    //            if (session.getTransaction().isActive()) {
    //                session.getTransaction().commit();
    //            }
    //        }
    //    }
    public boolean createUser(StaffBean bean) {
        Staff entity = null;
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        entity = dco.toEntity(bean);
        try {
            session.beginTransaction();
            session.save(entity);
            return true;
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            return false;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    // update only Staff's Personal info
    public boolean updatePersonalInfo(StaffBean bean) {
        Staff staff = null;
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.add(Restrictions.eq("id", bean.getId()));
            staff = (Staff) crit.uniqueResult();
            staff = dco.toEntity(bean);
            session.update(staff);
            return true;
        } catch (HibernateException e) {
            session.getTransaction().rollback();
            return false;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    public String getUserName(String userName) {
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        Object obj = null;
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            //            ProjectionList prl = Projections.projectionList();
            //            prl.add(Projections.property("userName"));
            crit.setProjection(Projections.property("userName"));
            //            crit.setProjection(prl);
            crit.add(Restrictions.eq("userName", userName));
            obj = crit.uniqueResult();
            return (obj != null) ? obj.toString() : null;
        } catch (Exception e) {
            //log here
            return null;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    //get Staff's info to Login
    public Staff login(String username, String encode) {
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        Staff staff = null;
        String logincode = null;
        String pattern = null;

        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.add(Restrictions.eq("userName", username));
            //            Hibernate.initialize("roleCollection");
            staff = (Staff) crit.uniqueResult();
            if (staff == null) {
                return null;
            } else {
                for (LoginCode c : CodeList) {
                    if (c.getUsername().equals(username)) {
                        logincode = c.getLogincode();
                        break;
                    }
                }
                pattern = MD5.encode(staff.getPassword() + logincode);
                System.out.println("here is pattern:\t" + pattern);
                System.out.println("here is encode:\t" + encode);
                return (encode.equals(pattern)) ? staff : null;
            }
        } catch (Exception e) {
            //Log here
            e.printStackTrace();
            return null;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    public boolean changeRole(int id, int[] role) {
        Staff staff = null;
        Collection<Role> roleCol = null;
        Collection<Role> newRolCol = new ArrayList<>();
        int roleSize = 0;
        Role newRole = null;
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.add(Restrictions.eq("id", id));
            staff = (Staff) crit.uniqueResult();
            roleCol = staff.getRoleCollection();
            if (role == null) {
                for (Role value : roleCol) {
                    session.delete(value);
                }
                staff.setRoleCollection(null);
            } else {
                for (Iterator<Role> r = roleCol.iterator(); r.hasNext();) {
                    Role value = r.next();
                    roleSize = role.length;
                    for (int i = 0; i < roleSize; i++) {
                        if (value.getRoleType() == role[i]) {
                            newRolCol.add(value);
                            r.remove();
                            role[i] = -1;
                            break;
                        }
                    }
                }
                for (Role r : roleCol) {
                    session.delete(r);
                }
                for (int i : role) {
                    if (i != -1) {
                        newRole = new Role(null, i);
                        newRole.setStaffId(staff);
                        newRolCol.add(newRole);
                    }
                }

                staff.setRoleCollection(newRolCol);
            }
            session.update(staff);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
            return false;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    public boolean changeStatus(int id, int status) {
        Staff staff = null;
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.add(Restrictions.eq("id", id));
            staff = (Staff) crit.uniqueResult();
            staff.setStatus(status);
            session.update(staff);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
            return false;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }

    private boolean checkAdmin(int id) {
        Session session = utils.HibernateUtils.getSessionFactory().getCurrentSession();
        Staff staff = null;
        Collection<Role> roleCol = null;
        try {
            session.beginTransaction();
            Criteria crit = session.createCriteria(Staff.class);
            crit.add(Restrictions.eq("id", id));
            staff = (Staff) crit.uniqueResult();
            roleCol = staff.getRoleCollection();
            for (Role role : roleCol) {
                if (role.getRoleType() == 2) {
                    return true;
                }
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (session.getTransaction().isActive()) {
                session.getTransaction().commit();
            }
        }
    }
}