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

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.dao.MemoDAOImpl.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 java.sql.Date;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Calendar;

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.MemoBean;

/**
 * The Class MemoDAOImpl.
 */
public class MemoDAOImpl extends WhichDoctorBaseDAOImpl implements MemoDAO {

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

    /**
     * Used to get a Collection of MemoBean details 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<MemoBean> load(final int guid, final boolean fullResults)
            throws WhichDoctorDaoException {

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

        final String loadMemo = getSQL().getValue("memo/load")
                + " WHERE memo.ReferenceGUID = ? AND memo.Active = true"
                + " ORDER BY memo.Priority ASC, guid.CreatedDate DESC";

        Collection<MemoBean> memos = new ArrayList<MemoBean>();

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

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

    /**
     * Load the MemoBean.
     *
     * @param memoId the memo id
     * @return the memo bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final MemoBean load(final int memoId) throws WhichDoctorDaoException {

        dataLogger.info("Getting memoId:" + memoId);

        final String loadMemoId = getSQL().getValue("memo/load") + " WHERE memo.MemoId = ?";

        MemoBean memo = null;

        try {
            memo = (MemoBean) this.getJdbcTemplateReader().queryForObject(loadMemoId, new Object[] { memoId },
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadMemo(rs, true);
                        }
                    });

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

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

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

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

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

    /**
     * Delete the MemoBean.
     *
     * @param memo the memo
     * @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 MemoBean memo, final UserBean checkUser, final PrivilegesBean privileges)
            throws WhichDoctorDaoException {

        boolean success = false;

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

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

        /* Check required information within Memo bean is present */
        if (StringUtils.isBlank(memo.getMessage())) {
            throw new WhichDoctorDaoException("The memo message cannot be an empty string");
        }
        if (memo.getReferenceGUID() == 0) {
            throw new WhichDoctorDaoException("The memo requires a valid Reference GUID number");
        }
        if (!privileges.getPrivilege(checkUser, "memos", action)) {
            throw new WhichDoctorDaoException("Insufficient user credentials to create new memo entry");
        }

        // Get MemoTypeId
        int memoTypeId = 0;
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Memo Type", memo.getType(), memo.getObjectType());
            memoTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error loading objecttype for memo: " + e.getMessage());
            throw new WhichDoctorDaoException("The memo requires a valid type: " + e.getMessage());
        }

        int memoId = 0;

        final Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
        Date expiresDate = null;
        if (memo.getExpires() != null) {
            expiresDate = new Date(memo.getExpires().getTime());
        }

        final ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(memo.getReferenceGUID());
        parameters.add(memoTypeId);
        parameters.add(memo.getPriority());
        parameters.add(memo.getMessage());
        parameters.add(expiresDate);
        parameters.add(memo.getActive());
        parameters.add(sqlTimeStamp);
        parameters.add(checkUser.getDN());
        parameters.add(memo.getLogMessage(action));

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

        return memoId;
    }

    /**
     * Load the MemoBean.
     *
     * @param rs the rs
     * @param fullResults the full results
     * @return the memo bean
     * @throws SQLException the sQL exception
     */
    private MemoBean loadMemo(final ResultSet rs, final boolean fullResults) throws SQLException {

        final MemoBean memo = new MemoBean();

        memo.setId(rs.getInt("MemoId"));
        memo.setGUID(rs.getInt("GUID"));
        memo.setReferenceGUID(rs.getInt("ReferenceGUID"));
        memo.setType(rs.getString("Type"));
        memo.setObjectType(rs.getString("ObjectType"));
        memo.setSecurity(rs.getString("Security"));
        memo.setPriority(rs.getInt("Priority"));
        if (fullResults) {
            memo.setMessage(rs.getString("Message"));
        }
        try {
            memo.setExpires(rs.getDate("Expires"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error loading Expires: " + sqe.getMessage());
        }

        memo.setActive(rs.getBoolean("Active"));
        try {
            memo.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
        }
        memo.setCreatedBy(rs.getString("CreatedBy"));
        try {
            memo.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
        }
        memo.setModifiedBy(rs.getString("ModifiedBy"));
        try {
            memo.setExportedDate(rs.getTimestamp("ExportedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ExportedDate: " + sqe.getMessage());
        }
        memo.setExportedBy(rs.getString("ExportedBy"));

        if (fullResults) {
            /* Set the user details objects */
            UserBean user = new UserBean();
            user.setDN(rs.getString("CreatedBy"));
            user.setPreferredName(rs.getString("CreatedFirstName"));
            user.setLastName(rs.getString("CreatedLastName"));
            memo.setCreatedUser(user);

            UserBean modified = new UserBean();
            modified.setDN(rs.getString("ModifiedBy"));
            modified.setPreferredName(rs.getString("ModifiedFirstName"));
            modified.setLastName(rs.getString("ModifiedLastName"));
            memo.setModifiedUser(modified);
        }

        return memo;
    }
}