Java tutorial
/******************************************************************************* * Copyright (c) 2012 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.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.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TreeSet; 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; 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.ReportBean; import com.sfs.whichdoctor.beans.RotationBean; /** * The Class ReportDAOImpl. */ public class ReportDAOImpl extends WhichDoctorBaseDAOImpl implements ReportDAO { /** The data logger. */ private static Logger dataLogger = Logger.getLogger(ReportDAOImpl.class); /** The person dao. */ @Resource private PersonDAO personDAO; /** The rotation dao. */ @Resource private RotationDAO rotationDAO; /** The training status dao. */ @Resource private TrainingStatusDAO trainingStatusDAO; /** The reports to create. */ private Map<String, Collection<ReportBean>> reportsToCreate; /** * Sets the reports to create. * * @param reportMap the report map */ public void setReportsToCreate(final Map<String, Collection<ReportBean>> reportMap) { this.reportsToCreate = reportMap; } /** * Used to get an Collection of ReportBeans 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<ReportBean> load(final int guid, final boolean fullResults) throws WhichDoctorDaoException { dataLogger.info("Reports for GUID: " + guid + " requested"); final String loadReport = getSQL().getValue("report/load") + " WHERE report.Active = true AND report.ReferenceGUID = ?" + " ORDER BY reporttype.Value, report.AuthorOrder"; Collection<ReportBean> reports = new ArrayList<ReportBean>(); try { reports = this.getJdbcTemplateReader().query(loadReport, new Object[] { guid }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadReport(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } return reports; } /** * Used to get a ReportBean for a specified reportId. * * @param reportId the report id * @return the report bean * @throws WhichDoctorDaoException the which doctor dao exception */ @SuppressWarnings("unchecked") public final ReportBean load(final int reportId) throws WhichDoctorDaoException { dataLogger.info("reportId: " + reportId + " requested"); final String loadId = getSQL().getValue("report/load") + " WHERE report.reportId = ?"; ReportBean report = null; try { report = (ReportBean) this.getJdbcTemplateReader().queryForObject(loadId, new Object[] { reportId }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadReport(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } return report; } /** * Creates the report bean. * * @param report the report * @param checkUser the check user * @param privileges the privileges * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int create(final ReportBean report, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { report.setActive(true); return save(report, checkUser, privileges, "create"); } /** * Modify the report bean. * * @param report the report * @param checkUser the check user * @param privileges the privileges * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int modify(final ReportBean report, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { report.setActive(true); return save(report, checkUser, privileges, "modify"); } /** * Delete the report bean. * * @param report the report * @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 ReportBean report, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { boolean success = false; report.setActive(false); int deleteId = save(report, checkUser, privileges, "delete"); if (deleteId > 0) { success = true; } return success; } /** * Gets the reports to create once the rotation is created. * * @param rotationType the rotation type * @return the reports to create */ public final Collection<ReportBean> getReportsToCreate(final String rotationType) { Collection<ReportBean> reports = new ArrayList<ReportBean>(); if (this.reportsToCreate == null) { this.reportsToCreate = new HashMap<String, Collection<ReportBean>>(); } if (this.reportsToCreate.containsKey(rotationType)) { reports = this.reportsToCreate.get(rotationType); } return reports; } /** * Save the report bean. * * @param report the report * @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 ReportBean report, final UserBean checkUser, final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException { /* Check required information within reportbean is present */ if (report.getReferenceGUID() == 0) { throw new WhichDoctorDaoException("Report requires a valid Reference GUID number"); } if (!privileges.getPrivilege(checkUser, "rotations", "modify")) { throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " report entry"); } int personGUID = 0; try { RotationBean rotation = this.rotationDAO.loadGUID(report.getReferenceGUID()); if (rotation != null) { personGUID = rotation.getPersonId(); } } catch (WhichDoctorDaoException wde) { dataLogger.error("Error loading rotation for report: " + wde.getMessage()); } if (personGUID == 0) { throw new WhichDoctorDaoException("The report is not associated with a valid rotation/person"); } int reportTypeId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Report Type", report.getReportStatus(), report.getReportType()); reportTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for report type: " + e.getMessage()); throw new WhichDoctorDaoException("The report requires a valid report type"); } int reportId = 0; Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); String authors = buildAuthors(report.getAuthors()); String authorOrder = buildAuthorOrder(report.getAuthors()); ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(report.getReferenceGUID()); parameters.add(reportTypeId); parameters.add(report.getMemo()); parameters.add(authors); parameters.add(authorOrder); parameters.add(report.getActive()); parameters.add(sqlTimeStamp); parameters.add(checkUser.getDN()); parameters.add(report.getLogMessage(action)); try { Integer[] result = this.performUpdate("report", report.getGUID(), parameters, "report", checkUser, action); /* Set the returned guid and id values */ report.setGUID(result[0]); reportId = result[1]; if (reportId > 0) { this.trainingStatusDAO.calculate(personGUID); } } catch (Exception e) { dataLogger.error("Error processing report record: " + e.getMessage()); throw new WhichDoctorDaoException("Error processing report record: " + e.getMessage()); } return reportId; } /** * Builds the author string. * * @param authors the authors * @return the string */ private String buildAuthors(final List<PersonBean> authors) { StringBuilder sb = new StringBuilder(); if (authors != null) { for (PersonBean person : authors) { if (sb.length() > 0) { sb.append(","); } sb.append(person.getGUID()); } } return sb.toString(); } /** * Builds the author order string. * * @param authors the authors * @return the string */ private String buildAuthorOrder(final List<PersonBean> authors) { StringBuilder sb = new StringBuilder(); TreeSet<String> order = new TreeSet<String>(); if (authors != null) { for (PersonBean person : authors) { order.add(person.getLastName() + "," + person.getFirstName()); } } for (String item : order) { if (sb.length() > 0) { sb.append("-"); } sb.append(item); } return sb.toString(); } /** * Load the report bean from the result set. * * @param rs the rs * @return the report bean * @throws SQLException the sQL exception */ private ReportBean loadReport(final ResultSet rs) throws SQLException { ReportBean report = new ReportBean(); report.setId(rs.getInt("ReportId")); report.setGUID(rs.getInt("GUID")); report.setReferenceGUID(rs.getInt("ReferenceGUID")); report.setReportType(rs.getString("ReportType")); report.setReportStatus(rs.getString("ReportStatus")); report.setReportGrouping(rs.getString("ReportGrouping")); report.setReportOrder(rs.getInt("ReportOrder")); report.setYear(rs.getInt("ReportYear")); report.setMemo(rs.getString("Memo")); if (StringUtils.equalsIgnoreCase(rs.getString("ReportPublish"), "yes")) { report.setReportPublish(true); } String authors = rs.getString("Authors"); if (StringUtils.isNotBlank(authors)) { StringTokenizer st = new StringTokenizer(authors, ","); while (st.hasMoreTokens()) { String strGUID = st.nextToken(); try { int guid = Integer.parseInt(strGUID); PersonBean person = personDAO.loadGUID(guid); if (person != null) { report.addAuthor(person); } } catch (Exception e) { dataLogger.error("Could not load PersonBean for report"); } } } report.setActive(rs.getBoolean("Active")); try { report.setCreatedDate(rs.getTimestamp("CreatedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage()); } report.setCreatedBy(rs.getString("CreatedBy")); try { report.setModifiedDate(rs.getTimestamp("ModifiedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage()); } report.setModifiedBy(rs.getString("ModifiedBy")); try { report.setExportedDate(rs.getTimestamp("ExportedDate")); } catch (SQLException sqe) { dataLogger.debug("Error reading ExportedDate: " + sqe.getMessage()); } report.setExportedBy(rs.getString("ExportedBy")); // Load user details from DB UserBean user = new UserBean(); user.setDN(rs.getString("CreatedBy")); user.setPreferredName(rs.getString("CreatedFirstName")); user.setLastName(rs.getString("CreatedLastName")); report.setCreatedUser(user); UserBean modified = new UserBean(); modified.setDN(rs.getString("ModifiedBy")); modified.setPreferredName(rs.getString("ModifiedFirstName")); modified.setLastName(rs.getString("ModifiedLastName")); report.setModifiedUser(modified); UserBean export = new UserBean(); export.setDN(rs.getString("ExportedBy")); export.setPreferredName(rs.getString("ExportedFirstName")); export.setLastName(rs.getString("ExportedLastName")); report.setExportedUser(export); return report; } }