com.sfs.whichdoctor.dao.SupervisorDAOImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.dao.SupervisorDAOImpl.java

Source

/*******************************************************************************
 * Copyright (c) 2009 David Harrison.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Contributors:
 *     David Harrison - initial API and implementation
 ******************************************************************************/
package com.sfs.whichdoctor.dao;

import com.sfs.beans.BuilderBean;
import com.sfs.beans.ObjectTypeBean;
import com.sfs.beans.PrivilegesBean;
import com.sfs.beans.UserBean;
import com.sfs.whichdoctor.beans.PersonBean;
import com.sfs.whichdoctor.beans.SupervisorBean;

import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeMap;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;

/**
 * The Class SupervisorDAOImpl.
 *
 * @author David Harrison
 */
public class SupervisorDAOImpl extends WhichDoctorBaseDAOImpl implements SupervisorDAO {

    /** The data logger. */
    private static Logger dataLogger = Logger.getLogger(SupervisorDAOImpl.class);

    /** The person dao. */
    @Resource
    private PersonDAO personDAO;

    /**
     * Used to get a Collection of SupervisorBeans for a specified GUID.
     *
     * @param guid the guid
     * @param loadDetails the load details
     *
     * @return the collection< supervisor bean>
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final Collection<SupervisorBean> load(final int guid, final BuilderBean loadDetails)
            throws WhichDoctorDaoException {

        dataLogger.info("Supervisors for GUID: " + guid + " requested");

        final String loadSupervisors = getSQL().getValue("supervisor/load")
                + " WHERE supervisors.Active = true AND supervisors.ReferenceGUID = ?"
                + " ORDER BY supervisors.OrderId ASC, relationshiptype.Class ASC,"
                + " relationshiptype.Name ASC, people.LastName ASC";

        Collection<SupervisorBean> supervisors = new ArrayList<SupervisorBean>();

        try {
            supervisors = this.getJdbcTemplateReader().query(loadSupervisors, new Object[] { guid },
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadSupervisor(rs, loadDetails);
                        }
                    });

        } catch (IncorrectResultSizeDataAccessException ie) {
            dataLogger.debug("No results found for search: " + ie.getMessage());
        }
        return supervisors;
    }

    /**
     * Used to get a SupervisorBean for a specified supervisor Id.
     *
     * @param supervisorId the supervisor id
     *
     * @return the supervisor bean
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final SupervisorBean load(final int supervisorId) throws WhichDoctorDaoException {

        dataLogger.info("SupervisorId: " + supervisorId + " requested");

        final String loadSupervisorId = getSQL().getValue("supervisor/load")
                + " WHERE supervisors.SupervisorId = ?";

        SupervisorBean supervisor = null;

        final BuilderBean loadDetails = new BuilderBean();
        loadDetails.setParameter("SUPERVISOR_PERSONOBJ", true);

        try {
            supervisor = (SupervisorBean) this.getJdbcTemplateReader().queryForObject(loadSupervisorId,
                    new Object[] { supervisorId }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadSupervisor(rs, loadDetails);
                        }
                    });

        } catch (IncorrectResultSizeDataAccessException ie) {
            dataLogger.debug("No results found for search: " + ie.getMessage());
        }
        return supervisor;
    }

    /**
     * Used to get a SupervisorBean for a related rotation or organisation based
     * on the supplied hierarchy, relationship class and division parameters.
     *
     * @param referenceGUID - the GUID of the rotation or organisation
     * @param hierarchy - the hierarchy value (must be greater than zero)
     * @param relationshipClass - the relationship class
     * @param division - the training division
     *
     * @return - The identified supervisor. A null object is returned if no
     * supervisor is found, or if the hierarchy = 0 and/or the division
     * is null/empty string.
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final SupervisorBean load(final int referenceGUID, final int hierarchy, final String relationshipClass,
            final String division) throws WhichDoctorDaoException {

        dataLogger.info("Supervisor for reference GUID: " + referenceGUID + ", hierarchy: " + hierarchy
                + ", relationship class: " + relationshipClass + ", division: " + division);

        SupervisorBean supervisor = null;

        if (referenceGUID > 0 && hierarchy > 0 && StringUtils.isNotBlank(relationshipClass)
                && StringUtils.isNotBlank(division)) {

            final String loadSupervisorId = getSQL().getValue("supervisor/load")
                    + " WHERE supervisors.Active = true AND" + " supervisors.ReferenceGUID = ? AND"
                    + " relationshiptype.Value <= ? AND" + " relationshiptype.Class = ? AND"
                    + " relationshiptype.Security = ?" + " ORDER BY relationshiptype.Value LIMIT 1";

            final BuilderBean loadDetails = new BuilderBean();
            loadDetails.setParameter("SUPERVISOR_PERSONOBJ", true);

            try {
                supervisor = (SupervisorBean) this.getJdbcTemplateReader().queryForObject(loadSupervisorId,
                        new Object[] { referenceGUID, hierarchy, relationshipClass, division }, new RowMapper() {
                            public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                                return loadSupervisor(rs, loadDetails);
                            }
                        });

            } catch (IncorrectResultSizeDataAccessException ie) {
                dataLogger.debug("No results found for search: " + ie.getMessage());
            }
        }
        return supervisor;
    }

    /**
     * Used to get a SupervisorBean for a specified supervisor GUID.
     *
     * @param guid the guid
     *
     * @return the supervisor bean
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final SupervisorBean loadGUID(final int guid) throws WhichDoctorDaoException {

        dataLogger.info("Supervisor GUID: " + guid + " requested");

        final String loadSupervisorId = getSQL().getValue("supervisor/load")
                + " WHERE supervisors.Active = true AND supervisors.GUID = ?";

        SupervisorBean supervisor = null;

        final BuilderBean loadDetails = new BuilderBean();
        loadDetails.setParameter("SUPERVISOR_PERSONOBJ", true);

        try {
            supervisor = (SupervisorBean) this.getJdbcTemplateReader().queryForObject(loadSupervisorId,
                    new Object[] { guid }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadSupervisor(rs, loadDetails);
                        }
                    });

        } catch (IncorrectResultSizeDataAccessException ie) {
            dataLogger.debug("No results found for search: " + ie.getMessage());
        }
        return supervisor;
    }

    /**
     * Update the SupervisorBean.
     *
     * @param referenceGUID the reference guid
     * @param action the action
     * @param updatedSupervisors the updated supervisors
     * @param personGUID the person guid
     * @param checkUser the check user
     * @param privileges the privileges
     */
    public final void update(final int referenceGUID, final String action,
            final Collection<SupervisorBean> updatedSupervisors, final int personGUID, final UserBean checkUser,
            final PrivilegesBean privileges) {

        Collection<SupervisorBean> existingSupervisors = new ArrayList<SupervisorBean>();
        /* Load the existing supervisors for this referenceGUID */
        try {
            existingSupervisors = this.load(referenceGUID, new BuilderBean());
        } catch (Exception e) {
            dataLogger.error("Error loading existing supervisors to update: " + e.getMessage());
        }

        HashMap<Integer, SupervisorBean> supervisorMap = new HashMap<Integer, SupervisorBean>();
        HashMap<Integer, Integer> processedGUIDs = new HashMap<Integer, Integer>();

        for (SupervisorBean supervisor : existingSupervisors) {
            supervisorMap.put(supervisor.getGUID(), supervisor);
        }

        Collection<SupervisorBean> updatedOrderedSupervisors = orderedSupervisors(updatedSupervisors);

        if (!StringUtils.equalsIgnoreCase(action, "delete")) {
            // If the action is delete then do not bother iterating through the
            // supervisor array as we want to delete all the supervisors.
            for (SupervisorBean supervisor : updatedOrderedSupervisors) {

                supervisor.setReferenceGUID(referenceGUID);

                if (supervisorMap.containsKey(supervisor.getGUID())) {

                    // This updated supervisor exists in the updated list - update
                    try {
                        SupervisorBean existingSupervisor = supervisorMap.get(supervisor.getGUID());
                        if (existingSupervisor.compare(supervisor)) {
                            // The supervisor has been modified - edit the record
                            this.modify(supervisor, checkUser, privileges);
                        }
                    } catch (Exception e) {
                        dataLogger.error("Error updating supervisor: " + e.getMessage());
                    }
                } else {
                    // The updated supervisor does not exist - this is a create
                    try {
                        this.create(supervisor, checkUser, privileges);
                    } catch (Exception e) {
                        dataLogger.error("Error creating supervisor: " + e.getMessage());
                    }
                }
                processedGUIDs.put(supervisor.getGUID(), supervisor.getGUID());
            }
        }

        // Now iterate through the existingGUIDs
        for (Integer supervisorGUID : supervisorMap.keySet()) {
            if (!processedGUIDs.containsKey(supervisorGUID)) {
                // The processedGUID map does not contain this GUID - delete
                SupervisorBean supervisor = null;
                try {
                    dataLogger.debug("Loading GUID: " + supervisorGUID);
                    supervisor = this.loadGUID(supervisorGUID);
                } catch (Exception e) {
                    dataLogger.error("Error loading supervisor to delete: " + e.getMessage());
                }
                if (supervisor != null) {
                    try {
                        this.delete(supervisor, checkUser, privileges);
                    } catch (Exception e) {
                        dataLogger.error("Error deleting supervisor: " + e.getMessage());
                    }
                } else {
                    dataLogger.error("The null supervisor could not be deleted");
                }
            }
        }
    }

    /**
     * Creates the SupervisorBean.
     *
     * @param supervisor the supervisor
     * @param checkUser the check user
     * @param privileges the privileges
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int create(final SupervisorBean supervisor, final UserBean checkUser,
            final PrivilegesBean privileges) throws WhichDoctorDaoException {

        supervisor.setActive(true);
        return save(supervisor, checkUser, privileges, "create");
    }

    /**
     * Modify the SupervisorBean.
     *
     * @param supervisor the supervisor
     * @param checkUser the check user
     * @param privileges the privileges
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int modify(final SupervisorBean supervisor, final UserBean checkUser,
            final PrivilegesBean privileges) throws WhichDoctorDaoException {

        supervisor.setActive(true);
        return save(supervisor, checkUser, privileges, "modify");
    }

    /**
     * Delete the SupervisorBean.
     *
     * @param supervisor the supervisor
     * @param checkUser the check user
     * @param privileges the privileges
     *
     * @return true, if successful
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean delete(final SupervisorBean supervisor, final UserBean checkUser,
            final PrivilegesBean privileges) throws WhichDoctorDaoException {

        boolean success = false;

        supervisor.setActive(false);
        int deleteId = save(supervisor, checkUser, privileges, "delete");
        if (deleteId > 0) {
            success = true;
        }
        return success;
    }

    /**
     * Save.
     *
     * @param supervisor the supervisor
     * @param checkUser the check user
     * @param privileges the privileges
     * @param action the action
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    private int save(final SupervisorBean supervisor, final UserBean checkUser, final PrivilegesBean privileges,
            final String action) throws WhichDoctorDaoException {

        /* Check required information within supervisor bean is present */
        if (StringUtils.isBlank(supervisor.getRelationshipClass())) {
            throw new WhichDoctorDaoException("A relationship class needs to " + "be defined");
        }
        if (StringUtils.isBlank(supervisor.getRelationshipType())) {
            throw new WhichDoctorDaoException("A relationship type needs to " + "be defined");
        }
        if (supervisor.getReferenceGUID() == 0) {
            throw new WhichDoctorDaoException("Supervisor requires a valid " + "Reference GUID number");
        }
        if (supervisor.getPerson() == null || supervisor.getPerson().getGUID() == 0) {
            throw new WhichDoctorDaoException("Supervisor requires a valid " + "person object");
        }
        if (!privileges.getPrivilege(checkUser, "supervisors", action)) {
            throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " supervisor entry");
        }

        int relationshipTypeId = 0, supervisorTypeId = 0;
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Relationship Type",
                    supervisor.getRelationshipType(), supervisor.getRelationshipClass());
            relationshipTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error loading objecttype for relationship type: " + e.getMessage());
        }
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Supervisor Type", "",
                    supervisor.getSupervisorClass());
            supervisorTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error loading objecttype for supervisor type: " + e.getMessage());
        }

        int supervisorId = 0;

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(supervisor.getReferenceGUID());
        parameters.add(supervisor.getPersonGUID());
        parameters.add(supervisor.getOrderId());
        parameters.add(relationshipTypeId);
        parameters.add(supervisorTypeId);
        parameters.add(supervisor.getActive());
        parameters.add(sqlTimeStamp);
        parameters.add(checkUser.getDN());
        parameters.add(supervisor.getLogMessage(action));

        try {
            Integer[] result = this.performUpdate("supervisor", supervisor.getGUID(), parameters, "Supervisor",
                    checkUser, action);
            /* Set the returned guid and id values */
            supervisor.setGUID(result[0]);
            supervisorId = result[1];
        } catch (Exception e) {
            dataLogger.error("Error processing supervisor record: " + e.getMessage());
            throw new WhichDoctorDaoException("Error processing supervisor: " + e.getMessage());
        }
        return supervisorId;
    }

    /**
     * Ordered supervisors.
     *
     * @param supervisors the supervisors
     *
     * @return the collection< supervisor bean>
     */
    private Collection<SupervisorBean> orderedSupervisors(final Collection<SupervisorBean> supervisors) {
        final Collection<SupervisorBean> ordered = new ArrayList<SupervisorBean>();

        TreeMap<String, SupervisorBean> orderMap = new TreeMap<String, SupervisorBean>();

        if (supervisors != null) {
            for (SupervisorBean supervisor : supervisors) {
                final String key = supervisor.getOrderId() + "_" + supervisor.getGUID();
                orderMap.put(key, supervisor);
            }
        }

        int orderId = 1;

        for (String key : orderMap.keySet()) {
            SupervisorBean supervisor = orderMap.get(key);

            supervisor.setOrderId(orderId);
            ordered.add(supervisor);

            orderId++;
        }
        return ordered;
    }

    /**
     * Load supervisor.
     *
     * @param rs the rs
     * @param loadDetails the load details
     *
     * @return the supervisor bean
     *
     * @throws SQLException the SQL exception
     */
    private SupervisorBean loadSupervisor(final ResultSet rs, final BuilderBean loadDetails) throws SQLException {
        SupervisorBean supervisor = new SupervisorBean();

        supervisor.setId(rs.getInt("SupervisorId"));
        supervisor.setGUID(rs.getInt("GUID"));
        supervisor.setReferenceGUID(rs.getInt("ReferenceGUID"));
        supervisor.setOrderId(rs.getInt("OrderId"));
        supervisor.setRelationshipClass(rs.getString("RelationshipClass"));
        supervisor.setRelationshipType(rs.getString("RelationshipType"));
        supervisor.setRelationshipAbbreviation(rs.getString("RelationshipAbbreviation"));
        supervisor.setSupervisorClass(rs.getString("SupervisorClass"));
        supervisor.setPersonGUID(rs.getInt("PersonGUID"));

        if (loadDetails.getBoolean("SUPERVISOR_PERSONOBJ")) {
            try {
                PersonBean person = this.personDAO.loadGUID(supervisor.getPersonGUID(), loadDetails);
                supervisor.setPerson(person);
            } catch (Exception e) {
                dataLogger.error("Error loading person for supervisor: " + e.getMessage());
            }
        }

        supervisor.setActive(rs.getBoolean("Active"));
        try {
            supervisor.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error setting CreatedDate: " + sqe.getMessage());
        }
        supervisor.setCreatedBy(rs.getString("CreatedBy"));
        try {
            supervisor.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error setting ModifiedDate: " + sqe.getMessage());
        }
        supervisor.setModifiedBy(rs.getString("ModifiedBy"));

        return supervisor;
    }
}