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.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; 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.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.EmailBean; import com.sfs.whichdoctor.beans.IsbTransactionBean; /** * The Class EmailDAOImpl. */ public class EmailDAOImpl extends WhichDoctorBaseDAOImpl implements EmailDAO { /** The data logger. */ private static Logger dataLogger = Logger.getLogger(EmailDAOImpl.class); /** The isb transaction dao. */ @Resource private IsbTransactionDAO isbTransactionDAO; /** * Used to get an Collection of EmailBean objects for a * specified GUID number. * * @param guid the guid * @param allAddresses the all addresses * @param emailClass the email class * @param emailType the email type * @return the collection * @throws WhichDoctorDaoException the which doctor dao exception */ @SuppressWarnings("unchecked") public final Collection<EmailBean> load(final int guid, final boolean allAddresses, final String emailClass, final String emailType) throws WhichDoctorDaoException { dataLogger.info("Email Addresses for GUID: " + guid + " requested"); // Do check whether required results are light (only primary) // or full(all email addresses) boolean specificAddress = false; String sql = getSQL().getValue("email/load") + " WHERE email.ReferenceGUID = ? AND email.Active = true"; Collection<Object> variables = new ArrayList<Object>(); /* The GUID value is the first variable */ variables.add(guid); if (emailClass != null) { if (emailClass.compareTo("") != 0 && emailClass.compareTo("Preferred") != 0) { sql += " AND emailtype.Class = ?"; variables.add(emailClass); specificAddress = true; } } if (emailType != null) { if (emailType.compareTo("") != 0 && emailType.compareTo("Preferred") != 0) { sql += " AND emailtype.Name = ?"; variables.add(emailType); specificAddress = true; } } sql += " ORDER BY PrimaryEmail DESC"; if (!allAddresses) { sql += " LIMIT 1"; } Collection<EmailBean> emailAddresses = new ArrayList<EmailBean>(); try { emailAddresses = this.getJdbcTemplateReader().query(sql, variables.toArray(), new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadEmail(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for search: " + ie.getMessage()); } if (specificAddress && emailAddresses.size() == 0) { /** * Specific email type defined but no result found * Try getting a more generic email address */ if (emailType != null) { if (emailType.compareTo("") != 0) { emailAddresses = load(guid, allAddresses, emailClass, null); } } if (emailAddresses.size() == 0) { if (emailClass != null) { if (emailClass.compareTo("") != 0) { emailAddresses = load(guid, allAddresses, null, null); } } } } return emailAddresses; } /** * Load an EmailBean based on its id. * * @param emailId the email id * @return the email bean * @throws WhichDoctorDaoException the which doctor dao exception */ public final EmailBean load(final int emailId) throws WhichDoctorDaoException { dataLogger.info("Getting emailId:" + emailId); final String loadId = getSQL().getValue("email/load") + " " + getSQL().getValue("email/whereId"); EmailBean email = null; try { email = (EmailBean) this.getJdbcTemplateReader().queryForObject(loadId, new Object[] { emailId }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadEmail(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for search: " + ie.getMessage()); } return email; } /** * Load the EmailBeans that have the supplied domain name. * * @param domainName the address domain name * @return the collection of EmailBeans * @throws WhichDoctorDaoException the which doctor dao exception */ @SuppressWarnings("unchecked") public final Collection<EmailBean> loadDomain(final String domainName) throws WhichDoctorDaoException { final String loadDomain = getSQL().getValue("email/load") + " " + getSQL().getValue("email/whereDomain"); String domainSearch = ""; if (StringUtils.isNotBlank(domainName)) { domainSearch = "%@" + domainName; } Collection<EmailBean> emailAddresses = new ArrayList<EmailBean>(); if (StringUtils.isNotBlank(domainSearch)) { try { emailAddresses = this.getJdbcTemplateReader().query(loadDomain, new Object[] { domainSearch, true }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return loadEmail(rs); } }); } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for search: " + ie.getMessage()); } } return emailAddresses; } /** * Creates the EmailBean. * * @param email the email * @param checkUser the check user * @param privileges the privileges * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int create(final EmailBean email, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { email.setActive(true); return save(email, checkUser, privileges, "create"); } /** * Modify the EmailBean. * * @param email the email * @param checkUser the check user * @param privileges the privileges * @return the int * @throws WhichDoctorDaoException the which doctor dao exception */ public final int modify(final EmailBean email, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { email.setActive(true); return save(email, checkUser, privileges, "modify"); } /** * Delete the EmailBean. * * @param email the email * @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 EmailBean email, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { boolean success = false; email.setActive(false); int emailId = save(email, checkUser, privileges, "delete"); if (emailId > 0) { success = true; } return success; } /** * Save the EmailBean. * * @param email the email * @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 EmailBean email, final UserBean checkUser, final PrivilegesBean privileges, final String action) throws WhichDoctorDaoException { /* Check required information within email bean is present */ if (email.getContactClass() == null) { throw new WhichDoctorDaoException("Contact class field cannot be null"); } if (email.getContactClass().compareTo("") == 0) { throw new WhichDoctorDaoException("Contact class field cannot be an empty string"); } if (email.getContactType() == null) { throw new WhichDoctorDaoException("Contact type field cannot be null"); } if (email.getContactType().compareTo("") == 0) { throw new WhichDoctorDaoException("Contact type field cannot be an empty string"); } if (email.getEmail() == null) { throw new WhichDoctorDaoException("Email address field cannot be null"); } if (email.getEmail().compareTo("") == 0) { throw new WhichDoctorDaoException("Email address field cannot be an empty string"); } if (email.getReferenceGUID() == 0) { throw new WhichDoctorDaoException("Email requires a valid Reference GUID number"); } if (!privileges.getPrivilege(checkUser, "emails", action)) { throw new WhichDoctorDaoException("Insufficient user credentials to " + action + " email address"); } int emailTypeId = 0; try { ObjectTypeBean object = this.getObjectTypeDAO().load("Email Type", email.getContactType(), email.getContactClass()); emailTypeId = object.getObjectTypeId(); } catch (Exception e) { dataLogger.error("Error loading objecttype for email type: " + e.getMessage()); throw new WhichDoctorDaoException("Email type not found"); } int emailId = 0; Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis()); ArrayList<Object> parameters = new ArrayList<Object>(); parameters.add(email.getReferenceGUID()); parameters.add(emailTypeId); parameters.add(email.getDescription()); parameters.add(email.getEmail()); parameters.add(email.getPrimary()); parameters.add(email.getEmailQuestions()); parameters.add(email.getReturnedMail()); parameters.add(email.getRequestNoMail()); parameters.add(email.getActive()); parameters.add(sqlTimeStamp); parameters.add(checkUser.getDN()); parameters.add(email.getLogMessage(action)); /* Begin the ISB transaction */ IsbTransactionBean isbTransaction = this.isbTransactionDAO.begin(email.getReferenceGUID()); try { Integer[] result = this.performUpdate("email", email.getGUID(), parameters, "Email", checkUser, action); /* Set the returned guid and id values */ email.setGUID(result[0]); emailId = result[1]; } catch (Exception e) { dataLogger.error("Error processing email record: " + e.getMessage()); throw new WhichDoctorDaoException("Error processing email record: " + e.getMessage()); } if (emailId > 0) { // Update person city/region/primary address // details to reflect modification updatePrimary(email, action); /* Commit the ISB transaction */ this.isbTransactionDAO.commit(isbTransaction); } return emailId; } /** * If the EmailBean is primary ensure no other primary * entry exists for the ReferenceGUID. * * @param email the email * @param action the action * @throws WhichDoctorDaoException the which doctor dao exception */ private void updatePrimary(final EmailBean email, final String action) throws WhichDoctorDaoException { if (email.getPrimary()) { if (action.compareTo("delete") != 0) { /* Find old primary address and turn off flag */ this.getJdbcTemplateWriter().update(this.getSQL().getValue("email/updatePrimary"), new Object[] { false, email.getReferenceGUID(), email.getGUID(), true }); } } } /** * Load the EmailBean from the database. * * @param rs the rs * @return the email bean * @throws SQLException the sQL exception */ private EmailBean loadEmail(final ResultSet rs) throws SQLException { EmailBean emailAddress = new EmailBean(); emailAddress.setId(rs.getInt("EmailId")); emailAddress.setGUID(rs.getInt("GUID")); emailAddress.setReferenceGUID(rs.getInt("ReferenceGUID")); emailAddress.setContactClass(rs.getString("ContactClass")); emailAddress.setContactType(rs.getString("ContactType")); emailAddress.setDescription(rs.getString("Description")); emailAddress.setEmail(rs.getString("Email")); emailAddress.setEmailQuestions(rs.getBoolean("EmailQuestions")); emailAddress.setReturnedMail(rs.getBoolean("ReturnedMail")); emailAddress.setRequestNoMail(rs.getBoolean("RequestNoMail")); emailAddress.setPrimary(rs.getBoolean("PrimaryEmail")); emailAddress.setActive(rs.getBoolean("Active")); try { emailAddress.setCreatedDate(rs.getTimestamp("CreatedDate")); } catch (SQLException sqe) { dataLogger.debug("Error loading CreatedDate: " + sqe.getMessage()); } emailAddress.setCreatedBy(rs.getString("CreatedBy")); try { emailAddress.setModifiedDate(rs.getTimestamp("ModifiedDate")); } catch (SQLException sqe) { dataLogger.debug("Error loading ModifiedDate: " + sqe.getMessage()); } emailAddress.setModifiedBy(rs.getString("ModifiedBy")); try { emailAddress.setExportedDate(rs.getTimestamp("ExportedDate")); } catch (SQLException sqe) { dataLogger.debug("Error loading ExportedDate: " + sqe.getMessage()); } emailAddress.setExportedBy(rs.getString("ExportedBy")); return emailAddress; } }