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

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.dao.ItemDAOImpl.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 com.sfs.beans.ObjectTypeBean;
import com.sfs.beans.PrivilegesBean;
import com.sfs.beans.UserBean;
import com.sfs.whichdoctor.beans.IsbTransactionBean;
import com.sfs.whichdoctor.beans.ItemBean;

import java.sql.Date;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Locale;
import java.util.TreeMap;

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;

/**
 * The Class ItemDAOImpl.
 *
 * @author David Harrison
 */
public class ItemDAOImpl extends WhichDoctorBaseDAOImpl implements ItemDAO {

    /** The Constant BASE_TIME. */
    private static final long BASE_TIME = 9000000000000000L;

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

    /** The person dao. */
    @Resource
    private PersonDAO personDAO;

    /** The isb transaction dao. */
    @Resource
    private IsbTransactionDAO isbTransactionDAO;

    /**
     * Load an ordered map of ItemBeans for the supplied group GUID details.
     *
     * @param guid the guid
     * @param fullResults the full results
     * @param itemTypeVal the item type value
     * @param groupClassVal the group class
     *
     * @return the tree map< string, item bean>
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final TreeMap<String, ItemBean> load(final int guid, final boolean fullResults, final String itemTypeVal,
            final String groupClassVal) throws WhichDoctorDaoException {
        return load(guid, fullResults, itemTypeVal, groupClassVal, 0, null, null);
    }

    /**
     * Used to get a TreeMap of ItemBean details for a specified GUID number.
     *
     * @param guid the guid
     * @param fullResults the full results
     * @param itemTypeVal the item type value
     * @param groupClassVal the group class value
     * @param object2GUID the object2 guid
     * @param startDate the start date
     * @param endDate the end date
     *
     * @return the tree map< string, item bean>
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final TreeMap<String, ItemBean> load(final int guid, final boolean fullResults, final String itemTypeVal,
            final String groupClassVal, final int object2GUID, final String startDate, final String endDate)
            throws WhichDoctorDaoException {

        TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>();

        String itemType = "Group";
        String groupClass = "Members";
        if (itemTypeVal != null) {
            itemType = itemTypeVal;
        }
        if (groupClass != null) {
            groupClass = groupClassVal;
        }

        if (StringUtils.equalsIgnoreCase(itemType, "Employer")
                || StringUtils.equalsIgnoreCase(itemType, "Employee")) {
            itemType = "Employment";
        }

        java.util.Date dtStartDate = null;
        java.util.Date dtEndDate = null;
        DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
        try {
            dtStartDate = df.parse(startDate);
        } catch (Exception e) {
            dataLogger.debug("Error parsing start date: " + e.getMessage());
        }
        try {
            dtEndDate = df.parse(endDate);
        } catch (Exception e) {
            dataLogger.debug("Error parsing end date: " + e.getMessage());
        }
        if (dtStartDate != null && dtEndDate != null && dtStartDate.compareTo(dtEndDate) > 0) {
            /* Start date is greater than end date, switch around */
            java.util.Date tempStartDate = dtStartDate;
            dtStartDate = dtEndDate;
            dtEndDate = tempStartDate;
        }

        StringBuffer loadItems = new StringBuffer();
        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(guid);
        parameters.add(itemType);

        loadItems.append(getLoadSQL(groupClass));

        if (StringUtils.equalsIgnoreCase(groupClass, "Employers")) {
            loadItems.append(" AND items.Object2GUID = ? AND itemtype.Class = ?");
        } else {
            loadItems.append(" AND items.Object1GUID = ? AND itemtype.Class = ?");
        }
        if (object2GUID > 0) {
            loadItems.append(" AND items.Object2GUID = ?");
            parameters.add(object2GUID);
        }

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

        Collection<ItemBean> itemCollection = new ArrayList<ItemBean>();
        try {
            itemCollection = this.getJdbcTemplateReader().query(loadItems.toString(), parameters.toArray(),
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadItem(rs);
                        }
                    });

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

        for (ItemBean item : itemCollection) {
            if (item.display(dtStartDate, dtEndDate)) {
                items.put(item.getOrderIndex(), item);
            }
        }

        return items;
    }

    /**
     * Load the ItemBean for the supplied ItemId.
     *
     * @param itemId the item id
     * @param groupClassVal the group class value
     *
     * @return the item bean
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final ItemBean load(final int itemId, final String groupClassVal) throws WhichDoctorDaoException {

        String groupClass = "Members";
        if (groupClassVal != null) {
            groupClass = groupClassVal;
        }

        ItemBean item = null;

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

        final String loadSQL = getLoadSQL(groupClass) + " AND items.ItemId = ?";

        try {
            item = (ItemBean) this.getJdbcTemplateReader().queryForObject(loadSQL, new Object[] { itemId },
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadItem(rs);
                        }
                    });

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

    /**
     * Load the referenced ItemBean for the supplied ReferenceGUID/Object1GUID pair.
     *
     * @param referenceGUID the reference id
     * @param object1GUID the object1 guid
     * @param groupClassVal the group class value
     *
     * @return the item bean
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final ItemBean loadReference(final int referenceGUID, final int object1GUID, final String groupClassVal)
            throws WhichDoctorDaoException {

        String groupClass = "Members";
        if (groupClassVal != null) {
            groupClass = groupClassVal;
        }

        ItemBean item = null;

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

        final String loadSql = getLoadSQL(groupClass) + " AND items.ReferenceGUID = ? AND items.Object1GUID = ?";

        try {
            item = (ItemBean) this.getJdbcTemplateReader().queryForObject(loadSql,
                    new Object[] { referenceGUID, object1GUID }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadItem(rs);
                        }
                    });

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

    /**
     * Creates the ItemBean.
     *
     * @param item the item
     * @param checkUser the check user
     * @param privileges the privileges
     * @param isbMapping the ISB mapping of the parent group - if null then none at all
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int create(final ItemBean item, final UserBean checkUser, final PrivilegesBean privileges,
            final String isbMapping) throws WhichDoctorDaoException {

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

    /**
     * Modify the ItemBean.
     *
     * @param item the item
     * @param checkUser the check user
     * @param privileges the privileges
     * @param isbMapping the ISB mapping of the parent group - if null then none at all
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int modify(final ItemBean item, final UserBean checkUser, final PrivilegesBean privileges,
            final String isbMapping) throws WhichDoctorDaoException {

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

    /**
     * Delete the ItemBean.
     *
     * @param item the item
     * @param checkUser the check user
     * @param privileges the privileges
     * @param isbMapping the ISB mapping - if null then none at all
     *
     * @return true, if successful
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean delete(final ItemBean item, final UserBean checkUser, final PrivilegesBean privileges,
            final String isbMapping) throws WhichDoctorDaoException {

        boolean success = false;

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

    /**
     * Save.
     *
     * @param item the item
     * @param checkUser the check user
     * @param privileges the privileges
     * @param action the action
     * @param isbMapping the ISB mapping of the parent group - if null then none at all
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    private int save(final ItemBean item, final UserBean checkUser, final PrivilegesBean privileges,
            final String action, final String isbMapping) throws WhichDoctorDaoException {

        /* Check required information within item bean is present */
        if (item.getObject1GUID() == 0) {
            throw new WhichDoctorDaoException("Item requires a valid Object1GUID");
        }
        if (item.getObject2GUID() == 0) {
            throw new WhichDoctorDaoException("Item requires a valid Object2GUID");
        }
        if (item.getPermission() == null) {
            throw new WhichDoctorDaoException("The item's permission cannot be null");
        }
        if (StringUtils.isBlank(item.getPermission())) {
            throw new WhichDoctorDaoException("The item's permssion cannot be set to nothing");
        }
        if (!privileges.getPrivilege(checkUser, item.getPermission(), action)) {
            throw new WhichDoctorDaoException(
                    "Insufficient user credentials to " + action + " item (" + item.getPermission() + ")");
        }

        int itemTypeId = 0;
        try {
            String dbItemType = item.getItemType();
            if (StringUtils.equalsIgnoreCase(item.getItemType(), "Employee")
                    || StringUtils.equalsIgnoreCase(item.getItemType(), "Employer")) {
                dbItemType = "Employment";
            }
            ObjectTypeBean object = this.getObjectTypeDAO().load("Item Type", "", dbItemType);
            itemTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error loading objecttype for item type: " + e.getMessage());
            throw new WhichDoctorDaoException("Item requires a valid type");
        }

        int itemId = 0;

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());
        Date startDate = null;
        Date endDate = null;
        if (item.getStartDate() != null) {
            startDate = new Date(item.getStartDate().getTime());
        }
        if (item.getEndDate() != null) {
            endDate = new Date(item.getEndDate().getTime());
        }

        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(item.getObject1GUID());
        parameters.add(item.getObject2GUID());
        parameters.add(item.getReferenceGUID());
        parameters.add(item.getTitle());
        parameters.add(item.getComment());
        parameters.add(item.getWeighting());
        parameters.add(startDate);
        parameters.add(endDate);
        parameters.add(itemTypeId);
        parameters.add(item.getActive());
        parameters.add(sqlTimeStamp);
        parameters.add(checkUser.getDN());
        parameters.add(item.getLogMessage(action));

        IsbTransactionBean isbTransaction = null;
        if (isbMapping != null) {
            /* The item has an ISB mapping - begin the ISB transaction */
            isbTransaction = this.isbTransactionDAO.begin(item.getObject2GUID());
        }

        String sqlType = "item";
        if (StringUtils.equalsIgnoreCase(item.getItemType(), "Candidate")) {
            sqlType = "candidate";
        }
        if (StringUtils.equalsIgnoreCase(item.getItemType(), "Vote")) {
            sqlType = "vote";
        }
        try {
            Integer[] result = this.performUpdate(sqlType, item.getGUID(), parameters, "Item", checkUser, action);
            /* Set the returned guid and id values */
            item.setGUID(result[0]);
            itemId = result[1];
        } catch (Exception e) {
            dataLogger.error("Error processing item record: " + e.getMessage());
            throw new WhichDoctorDaoException("Error processing item record: " + e.getMessage());
        }

        if (itemId > 0) {
            /* Update the indexes */
            updateIndexes(item.getObject2GUID(), item.getItemType());

            if (isbTransaction != null) {
                // Commit the transaction to the ISB
                this.isbTransactionDAO.commit(isbTransaction);
            }
        }

        return itemId;
    }

    /**
     * Load item.
     *
     * @param rs the rs
     *
     * @return the item bean
     *
     * @throws SQLException the SQL exception
     */
    private ItemBean loadItem(final ResultSet rs) throws SQLException {

        ItemBean item = new ItemBean();

        item.setId(rs.getInt("ItemId"));
        item.setGUID(rs.getInt("GUID"));
        item.setObject1GUID(rs.getInt("Object1GUID"));
        item.setObject2GUID(rs.getInt("Object2GUID"));
        item.setReferenceGUID(rs.getInt("ReferenceGUID"));
        item.setName(rs.getString("Name"));
        item.setTitle(rs.getString("Title"));
        item.setComment(rs.getString("Comment"));
        item.setItemType(rs.getString("ItemType"));
        item.setWeighting(rs.getInt("Weighting"));
        try {
            item.setStartDate(rs.getDate("StartDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error parsing StartDate: " + sqe.getMessage());
        }
        try {
            item.setEndDate(rs.getDate("EndDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error parsing EndDate: " + sqe.getMessage());
        }
        item.setPermission(rs.getString("Permission"));

        item.setActive(rs.getBoolean("Active"));
        item.setCreatedBy(rs.getString("CreatedBy"));
        try {
            item.setCreatedDate(rs.getDate("Created"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error parsing CreatedDate: " + sqe.getMessage());
        }

        if (StringUtils.equalsIgnoreCase(item.getItemType(), "Employment")) {
            // Order by employment date
            String start = "";
            if (item.getStartDate() != null) {
                Long time = BASE_TIME - item.getStartDate().getTime();
                start = String.valueOf(time);
            }
            item.setOrderIndex(start + rs.getString("OrderIndex"), rs.getRow());
        } else {
            item.setOrderIndex(rs.getString("OrderIndex"), rs.getRow());
        }

        return item;
    }

    /**
     * Gets the load sql.
     *
     * @param groupClass the group class
     *
     * @return the load sql
     */
    private String getLoadSQL(final String groupClass) {

        String loadSQL = getSQL().getValue("item/loadPerson");

        if (StringUtils.equalsIgnoreCase(groupClass, "Organisations")) {
            loadSQL = this.getSQL().getValue("item/loadOrganisation");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Debits")) {
            loadSQL = getSQL().getValue("item/loadDebit");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Credits")) {
            loadSQL = getSQL().getValue("item/loadCredit");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Reimbursements")) {
            loadSQL = getSQL().getValue("item/loadReimbursement");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Receipts")) {
            loadSQL = getSQL().getValue("item/loadReceipt");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Rotations")) {
            loadSQL = getSQL().getValue("item/loadRotation");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Mentors")) {
            loadSQL = getSQL().getValue("item/loadMentor");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Employees")) {
            loadSQL = getSQL().getValue("item/loadEmployee");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Employers")) {
            loadSQL = getSQL().getValue("item/loadEmployer");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Candidates")) {
            loadSQL = getSQL().getValue("item/loadCandidate");
        }
        if (StringUtils.equalsIgnoreCase(groupClass, "Votes")) {
            loadSQL = getSQL().getValue("item/loadVote");
        }

        return loadSQL;
    }

    /**
     * Update indexes.
     *
     * @param object2GUID the object2 guid
     * @param itemType the item type
     */
    private void updateIndexes(final int object2GUID, final String itemType) {

        dataLogger.debug("Updating search indexes for an item of type: " + itemType);

        if (itemType.compareToIgnoreCase("Employee") == 0 || itemType.compareToIgnoreCase("Employer") == 0
                || itemType.compareToIgnoreCase("Employment") == 0) {

            try {
                this.personDAO.updateRegion(object2GUID);
            } catch (Exception e) {
                dataLogger.error("Error updating region for person (" + object2GUID + "): " + e.getMessage());
            }
        }
    }
}