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

Java tutorial

Introduction

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

Source

/*******************************************************************************
 * Copyright (c) 2011 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.AssessmentBean;
import com.sfs.whichdoctor.beans.RotationBean;

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

import javax.annotation.Resource;

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

/**
 * The Class AssessmentDAOImpl.
 */
public class AssessmentDAOImpl extends WhichDoctorBaseDAOImpl implements AssessmentDAO {

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

    /** The rotation dao. */
    @Resource
    private RotationDAO rotationDAO;

    /** The training status dao. */
    @Resource
    private TrainingStatusDAO trainingStatusDAO;

    /**
     * Load the assessment bean.
     *
     * @param guid the guid
     * @return the collection
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public Collection<AssessmentBean> load(final int guid) throws WhichDoctorDaoException {

        Collection<AssessmentBean> assessment = new ArrayList<AssessmentBean>();

        final String loadSQL = this.getSQL().getValue("assessment/load")
                + " AND assessment.Active = true AND assessment.ReferenceGUID = ? "
                + "ORDER BY assessmenttype.Abbreviation, assessment.SpecialtyType";

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

        } catch (IncorrectResultSizeDataAccessException ie) {
            // No results found for this search
        }
        return assessment;
    }

    /**
     * Load the assessment bean.
     *
     * @param assessmentId the assessment id
     * @param loadDetails the load details
     * @return the assessment bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public AssessmentBean load(final int assessmentId, final BuilderBean loadDetails)
            throws WhichDoctorDaoException {

        AssessmentBean assessment = null;

        final String loadSQL = getSQL().getValue("assessment/load") + " AND assessment.AssessmentId = ?";

        try {
            assessment = (AssessmentBean) this.getJdbcTemplateReader().queryForObject(loadSQL,
                    new Object[] { assessmentId }, new RowMapper() {
                        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                            return loadAssessmentBean(rs, loadDetails);
                        }
                    });

        } catch (IncorrectResultSizeDataAccessException ie) {
            // No results found for this search
        }
        return assessment;
    }

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

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

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

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

    /**
     * Delete the assessment.
     *
     * @param assessment the assessment
     * @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 AssessmentBean assessment, final UserBean checkUser,
            final PrivilegesBean privileges) throws WhichDoctorDaoException {
        boolean success = false;

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

    /**
     * Recalculate years of training for all rotations.
     *
     */
    public final void recalculateAllYearsOfTraining() throws WhichDoctorDaoException {

        Collection<RotationBean> rotations = rotationDAO.loadActiveRotations();

        for (RotationBean rotation : rotations) {
            try {
                this.recalculateYearsOfTraining(rotation);
                dataLogger.error("Recalculated year of training for rotation GUID: " + rotation.getGUID());
            } catch (WhichDoctorDaoException wde) {
                dataLogger.error("Error recalculating year of training for rotation GUID " + rotation.getGUID()
                        + ": " + wde.getMessage());
            }
        }
        dataLogger.error("All years of training recalculated");
    }

    /**
     * Recalculate the years of training for the supplied rotation.
     *
     * @param rotation the rotation
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final void recalculateYearsOfTraining(final RotationBean rotation) throws WhichDoctorDaoException {

        Collection<AssessmentBean> assessments = this.load(rotation.getGUID());

        for (AssessmentBean assessment : assessments) {

            int yearOfTraining = calculateYearOfTraining(rotation.getPersonId(), rotation.getRotationType(),
                    rotation.getStartDate(), assessment.getCommitteeSpecialty());

            this.getJdbcTemplateWriter().update(getSQL().getValue("assessment/updateYearOfTraining"),
                    new Object[] { yearOfTraining, assessment.getGUID() });
        }
    }

    /**
     * Save the assessment.
     *
     * @param assessment the assessment
     * @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 AssessmentBean assessment, final UserBean checkUser, final PrivilegesBean privileges,
            final String action) throws WhichDoctorDaoException {

        // Assessment requires all the essential information is supplied

        if (StringUtils.isBlank(assessment.getAssessmentType())) {
            throw new WhichDoctorDaoException("Assessment type cannot be an empty string");
        }
        if (assessment.getRotation() == null) {
            throw new NullPointerException("Assessment must be " + "associated to a rotation");
        }
        if (!privileges.getPrivilege(checkUser, "assessments", action)) {
            throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " assessment");
        }

        RotationBean rotation = rotationDAO.loadGUID(assessment.getRotation().getGUID());

        if (rotation == null) {
            throw new WhichDoctorDaoException("A valid rotation is required");
        }

        int assessmentId = 0, assessmentTypeId = 0, statusId = 0, approvedId = 0, trainingProgramId = 0;

        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Assessment Type", "",
                    assessment.getAssessmentType());
            assessmentTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.info("Error loading objecttype for assessment type: " + e.getMessage());
        }
        if (assessment.getStatus() != null) {
            try {
                ObjectTypeBean object = this.getObjectTypeDAO().load("Rotation Status",
                        assessment.getStatusReason(), assessment.getStatus());
                statusId = object.getObjectTypeId();
            } catch (Exception e) {
                dataLogger.error("Error loading objecttype for rotation status: " + e.getMessage());
            }
        }
        if (assessment.getCommitteeSpecialty() != null) {
            final String abbreviation = assessment.getCommitteeSpecialtyAbbreviation();

            if (StringUtils.isNotBlank(abbreviation)) {
                try {
                    ObjectTypeBean object = this.getObjectTypeDAO().load("Accredited Specialty", "",
                            assessment.getCommitteeSpecialty());
                    assessment.setCommitteeSpecialtyAbbreviation(object.getAbbreviation());
                } catch (Exception e) {
                    dataLogger.error("Error loading abbreviation for accredited " + "specialty: " + e.getMessage());
                }
            }
        }
        if (assessment.getApproved() != null) {
            try {
                ObjectTypeBean object = this.getObjectTypeDAO().load("Rotation Approval",
                        assessment.getApprovedCondition(), assessment.getApproved());
                approvedId = object.getObjectTypeId();
            } catch (Exception e) {
                dataLogger.error("Error loading objecttype for rotation " + "approval status: " + e.getMessage());
            }
        }
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Training Program",
                    assessment.getTrainingProgram(), assessment.getTrainingOrganisation());
            trainingProgramId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error loading objecttype for training program: " + e.getMessage());
        }

        int yearOfTraining = 1;
        try {
            yearOfTraining = calculateYearOfTraining(rotation.getPersonId(), rotation.getRotationType(),
                    rotation.getStartDate(), assessment.getCommitteeSpecialty());
        } catch (WhichDoctorDaoException wde) {
            dataLogger.error("Error calculating year of training: " + wde.getMessage());
        }

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

        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(assessment.getRotation().getGUID());
        parameters.add(assessmentTypeId);
        parameters.add(trainingProgramId);
        parameters.add(assessment.getCommitteeSpecialty());
        parameters.add(assessment.getCommitteeSpecialtyAbbreviation());
        parameters.add(yearOfTraining);
        parameters.add(approvedId);
        parameters.add(statusId);
        parameters.add(assessment.getApplicationComment());
        parameters.add(assessment.getAccreditationComment());
        parameters.add(assessment.getActive());
        parameters.add(sqlTimeStamp);
        parameters.add(checkUser.getDN());
        parameters.add(assessment.getLogMessage(action));

        try {
            Integer[] result = this.performUpdate("assessment", assessment.getGUID(), parameters, "assessment",
                    checkUser, action);
            /* Set the returned guid and id values */
            assessment.setGUID(result[0]);
            assessmentId = result[1];

            if (assessmentId > 0) {
                // Recalculate the person's training status.
                this.trainingStatusDAO.calculate(rotation.getPersonId());
            }
        } catch (Exception e) {
            dataLogger.error("Error processing assessment record: " + e.getMessage());
            throw new WhichDoctorDaoException("Error processing assessment record: " + e.getMessage());
        }
        return assessmentId;
    }

    /**
     * Calculate the year of training.
     *
     * @param rotationGUID the rotation guid
     * @param committeeSpecialty the committee specialty
     * @return the int
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    private int calculateYearOfTraining(final int personGUID, final String rotationType,
            final Date rotationStartDate, final String committeeSpecialty) throws WhichDoctorDaoException {

        if (personGUID == 0) {
            throw new WhichDoctorDaoException("A valid person is required");
        }
        if (StringUtils.isBlank(rotationType)) {
            throw new WhichDoctorDaoException("A valid rotation type is required");
        }
        if (rotationStartDate == null) {
            throw new WhichDoctorDaoException("The valid start date is required");
        }
        if (StringUtils.isBlank(committeeSpecialty)) {
            throw new WhichDoctorDaoException("A valid committee specialty is required");
        }

        int priorWeeksCertified = 0;

        // Load the weeks of certified accreditation
        try {
            priorWeeksCertified = this.getJdbcTemplateReader().queryForInt(
                    getSQL().getValue("assessment/calculateYearOfTraining"),
                    new Object[] { rotationType, personGUID, rotationStartDate, committeeSpecialty, "default" });
        } catch (IncorrectResultSizeDataAccessException ie) {
            // No results found for this search
        }

        return (priorWeeksCertified / 52) + 1;
    }

    /**
     * Load assessment bean.
     *
     * @param rs the rs
     * @param loadDetails the load details
     * @return the assessment bean
     * @throws SQLException the sQL exception
     */
    private AssessmentBean loadAssessmentBean(final ResultSet rs, final BuilderBean loadDetails)
            throws SQLException {

        AssessmentBean assessment = new AssessmentBean();

        /* Create resource bean and fill with dataset info */
        assessment.setId(rs.getInt("AssessmentId"));
        assessment.setGUID(rs.getInt("GUID"));
        assessment.setAssessmentType(rs.getString("AssessmentType"));

        /* Set assessment details */
        assessment.setTrainingOrganisation(rs.getString("TrainingOrganisation"));
        assessment.setTrainingProgram(rs.getString("TrainingProgram"));
        assessment.setTrainingProgramISBMapping(rs.getString("TrainingProgramISBMapping"));
        assessment.setCommitteeSpecialty(rs.getString("SpecialtyType"));
        assessment.setCommitteeSpecialtyAbbreviation(rs.getString("SpecialtyTypeAbbreviation"));
        assessment.setYearOfTraining(rs.getInt("YearOfTraining"));

        assessment.setStatus(rs.getString("FeedbackStatus"));
        assessment.setStatusReason(rs.getString("StatusReason"));
        assessment.setApproved(rs.getString("Approved"));
        assessment.setApprovedCondition(rs.getString("ApprovedCondition"));
        assessment.setApplicationComment(rs.getString("ApplicationComment"));
        assessment.setAccreditationComment(rs.getString("AccreditationComment"));

        RotationBean rotation = new RotationBean();
        rotation.setGUID(rs.getInt("ReferenceGUID"));
        assessment.setRotation(rotation);

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

        /* Load user details */
        if (loadDetails.getBoolean("CREATED")) {
            try {
                UserBean user = new UserBean();
                user.setDN(rs.getString("CreatedBy"));
                user.setPreferredName(rs.getString("CreatedFirstName"));
                user.setLastName(rs.getString("CreatedLastName"));
                assessment.setCreatedUser(user);
            } catch (SQLException sqe) {
                dataLogger.debug("Error loading created user details: " + sqe.getMessage());
            }
        }
        if (loadDetails.getBoolean("MODIFIED")) {
            try {
                UserBean user = new UserBean();
                user.setDN(rs.getString("ModifiedBy"));
                user.setPreferredName(rs.getString("ModifiedFirstName"));
                user.setLastName(rs.getString("ModifiedLastName"));
                assessment.setModifiedUser(user);
            } catch (SQLException sqe) {
                dataLogger.debug("Error loading modified user details: " + sqe.getMessage());
            }
        }

        return assessment;
    }
}