Java tutorial
/******************************************************************************* * 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 java.sql.Date; 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 javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Required; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.RowMapper; import com.sfs.beans.ObjectTypeBean; import com.sfs.beans.PrivilegesBean; import com.sfs.beans.UserBean; import com.sfs.whichdoctor.beans.ExamBean; /** * The Class ExamDAOImpl. */ public class ExamDAOImpl extends WhichDoctorBaseDAOImpl implements ExamDAO { /** The Constant the days in a year. */ private static final int DAYS_IN_YEAR = 365; /** The data logger. */ private static Logger dataLogger = Logger.getLogger(ExamDAOImpl.class); /** The exam deadline. */ private int examDeadline; /** The membership dao. */ @Resource private MembershipDAO membershipDAO; /** The training status dao. */ @Resource private TrainingStatusDAO trainingStatusDAO; /** * Sets the exam deadline. * * @param examDeadlineVal the new exam deadline */ @Required public final void setExamDeadline(final int examDeadlineVal) { this.examDeadline = examDeadlineVal; } /** * Gets the exam deadline. * * @return the exam deadline */ public final int getExamDeadline() { return this.examDeadline; } /** * Used to get a Collection of ExamBeans for a specified GUID number. * * @param guid the guid * @param fullResults the full results * @return the collection * @throws WhichDoctorDaoException the which doctor dao exception */ @SuppressWarnings("unchecked") public final Collection<ExamBean> load(final int guid, final boolean fullResults) throws WhichDoctorDaoException { dataLogger.info("Exams for GUID: " + guid + " requested"); final String loadExam = getSQL().getValue("exam/load") + " WHERE exam.Active = true AND exam.ReferenceGUID = ?" + " ORDER BY exam.DateSat"; Collection<ExamBean> exams = new ArrayList<ExamBean>(); try { exams = this.getJdbcTemplateReader().query(loadExam, new Object[] { guid }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadExam(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results for this search: " + ie.getMessage()); } return exams; } /** * Used to get an ExamBean for a specified examId number. * * @param examId the exam id * @return the exam bean * @throws WhichDoctorDaoException the which doctor dao exception */ @SuppressWarnings("unchecked") public final ExamBean load(final int examId) throws WhichDoctorDaoException { dataLogger.info("ExamId: " + examId + " requested"); final String loadSQL = getSQL().getValue("exam/load") + " WHERE exam.ExamId = ?"; ExamBean exam = null; try { exam = (ExamBean) this.getJdbcTemplateReader().queryForObject(loadSQL, new Object[] { examId }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadExam(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results for this search: " + ie.getMessage()); } return exam; } /** * Calculate exam deadline. * * @param exams the exams * @return the date */ public final java.util.Date calculateExamDeadline(final Collection<ExamBean> exams) { java.util.Date identifiedExamDeadline = null; if (exams != null && this.examDeadline > 0) { boolean examPassed = false; for (ExamBean exam : exams) { if (!examPassed && exam != null) { if (StringUtils.equalsIgnoreCase(exam.getType(), "Written Exam") && StringUtils.equalsIgnoreCase(exam.getStatus(), "Passed")) { /* Written exam passed - set exam deadline */ Calendar calendar = Calendar.getInstance(); calendar.setTime(exam.getDateSat()); calendar.add(Calendar.DATE, this.examDeadline); identifiedExamDeadline = calendar.getTime(); } else { if (StringUtils.equalsIgnoreCase(exam.getStatus(), "Passed")) { // Non-written exam passed - set exam passed examPassed = true; identifiedExamDeadline = null; } if (StringUtils.equalsIgnoreCase(exam.getStatus(), "Deferred")) { // Non-written exam deferred - redefine exam deadline Calendar calendar = Calendar.getInstance(); calendar.setTime(identifiedExamDeadline); calendar.add(Calendar.DATE, DAYS_IN_YEAR); identifiedExamDeadline = calendar.getTime(); } } } } } return identifiedExamDeadline; } /** * Creates the exam bean. * * @param exam the exam * @param checkUser the check user * @param privileges the privileges * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int create(final ExamBean exam, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { exam.setActive(true); return save(exam, checkUser, privileges, "create"); } /** * Modify the exam bean. * * @param exam the exam * @param checkUser the check user * @param privileges the privileges * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int modify(final ExamBean exam, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { exam.setActive(true); return save(exam, checkUser, privileges, "modify"); } /** * Delete the exam bean. * * @param exam the exam * @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 ExamBean exam, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { boolean success = false; exam.setActive(false); int examId = save(exam, checkUser, privileges, "delete"); if (examId > 0) { success = true; } return success; } /** * Save. * * @param exam the exam * @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 ExamBean exam, final UserBean checkUser, final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException { /* Check required information within Memo bean is present */ if (exam.getDateSat() == null) { throw new NullPointerException("Exam requires a valid date"); } if (exam.getType() == null) { throw new NullPointerException("Exam type cannot be null"); } if (exam.getType().compareTo("") == 0) { throw new WhichDoctorDaoException("Exam type cannot be an empty string"); } if (exam.getReferenceGUID() == 0) { throw new WhichDoctorDaoException("Exam requires a valid Reference GUID number"); } if (!privileges.getPrivilege(checkUser, "exams", action)) { throw new WhichDoctorDaoException("Insufficient user credentials to create new exam entry"); } int examTypeId = 0, examStatusId = 0, specialtyTypeId = 0, examId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Exam Type", "", exam.getType()); examTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for exam type: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading objecttype for exam type: " + e.getMessage()); } try { ObjectTypeBean object = this.getObjectTypeDAO().load("Exam Status", exam.getType(), exam.getStatusLevel(), exam.getStatus()); examStatusId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for exam status: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading objecttype for exam status: " + e.getMessage()); } try { ObjectTypeBean object = this.getObjectTypeDAO().load("Training Program", exam.getTrainingProgram(), exam.getTrainingOrganisation()); specialtyTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.info("Error loading objecttype for specialty: " + e.getMessage()); } Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); Date dateSat = null; if (exam.getDateSat() != null) { dateSat = new Date(exam.getDateSat().getTime()); } ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(exam.getReferenceGUID()); parameters.add(examTypeId); parameters.add(specialtyTypeId); parameters.add(examStatusId); parameters.add(exam.getLocation()); parameters.add(exam.getAwardedMarks()); parameters.add(exam.getTotalMarks()); parameters.add(dateSat); parameters.add(exam.getActive()); parameters.add(sqlTimeStamp); parameters.add(checkUser.getDN()); parameters.add(exam.getLogMessage(action)); try { Integer[] result = this.performUpdate("exam", exam.getGUID(), parameters, "Exam", checkUser, action); /* Set the returned guid and id values */ exam.setGUID(result[0]); examId = result[1]; } catch (Exception e) { dataLogger.error("Error processing exam record: " + e.getMessage()); throw new WhichDoctorDaoException("Error processing exam record: " + e.getMessage()); } if (examId > 0) { /* Record created - perform training update */ this.membershipDAO.updateTrainingStatus(exam.getReferenceGUID(), checkUser, privileges); this.trainingStatusDAO.calculate(exam.getReferenceGUID()); } return examId; } /** * Load exam. * * @param rs the rs * @return the exam bean * @throws SQLException the sQL exception */ private ExamBean loadExam(final ResultSet rs) throws SQLException { ExamBean exam = new ExamBean(); exam.setId(rs.getInt("ExamId")); exam.setGUID(rs.getInt("GUID")); exam.setReferenceGUID(rs.getInt("ReferenceGUID")); exam.setType(rs.getString("Type")); exam.setTrainingOrganisation(rs.getString("TrainingOrganisation")); exam.setTrainingProgram(rs.getString("TrainingProgram")); exam.setStatus(rs.getString("Status")); exam.setStatusLevel(rs.getString("StatusLevel")); try { exam.setDateSat(rs.getDate("DateSat")); } catch (SQLException sqe) { dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage()); } exam.setLocation(rs.getString("Location")); exam.setAwardedMarks(rs.getInt("AwardedMarks")); exam.setTotalMarks(rs.getInt("TotalMarks")); exam.setActive(rs.getBoolean("Active")); try { exam.setCreatedDate(rs.getTimestamp("CreatedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage()); } exam.setCreatedBy(rs.getString("CreatedBy")); try { exam.setModifiedDate(rs.getTimestamp("ModifiedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage()); } exam.setModifiedBy(rs.getString("ModifiedBy")); try { exam.setExportedDate(rs.getTimestamp("ExportedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading ExportedDate: " + sqe.getMessage()); } exam.setExportedBy(rs.getString("ExportedBy")); return exam; } }