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

Java tutorial

Introduction

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

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.IncorrectResultSizeDataAccessException;
import org.springframework.jdbc.core.RowMapper;

import com.sfs.beans.UserBean;
import com.sfs.beans.ObjectTypeBean;
import com.sfs.beans.PrivilegesBean;
import com.sfs.dao.UserDAO;
import com.sfs.dao.SFSDaoException;
import com.sfs.whichdoctor.beans.SearchBean;
import com.sfs.whichdoctor.beans.WhichDoctorBean;

/**
 * The Class WhichDoctorDAOImpl.
 */
public class WhichDoctorDAOImpl extends BaseDAOImpl implements WhichDoctorDAO {

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

    /** The user dao. */
    @Resource
    private UserDAO userDAO;

    /**
     * Load.
     *
     * @param guid the guid
     * @param type the type
     *
     * @return the collection< which doctor bean>
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final Collection<WhichDoctorBean> load(final int guid, final String type)
            throws WhichDoctorDaoException {
        if (type == null) {
            throw new NullPointerException("The type parameter cannot be null");
        }

        dataLogger.info("History of GUID: " + guid + " requested");

        String loadSQL = getSQL().getValue("whichdoctor/load/person");

        if (type.compareToIgnoreCase("organisation") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/organisation");
        }
        if (type.compareToIgnoreCase("debit") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/debit");
        }
        if (type.compareToIgnoreCase("credit") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/credit");
        }
        if (type.compareToIgnoreCase("receipt") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/receipt");
        }
        if (type.compareToIgnoreCase("reimbursement") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/reimbursement");
        }
        if (type.compareToIgnoreCase("rotation") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/rotation");
        }
        if (type.compareToIgnoreCase("group") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/group");
        }

        Collection<WhichDoctorBean> history = new ArrayList<WhichDoctorBean>();

        try {
            history = this.getJdbcTemplateReader().query(loadSQL, new Object[] { guid }, new RowMapper() {
                public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                    WhichDoctorBean loadedHistory = loadHistory(rs);
                    loadedHistory.setObjectType(type);

                    return loadedHistory;
                }
            });

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

    /**
     * Load siblings.
     *
     * @param guid the GUID of the object
     * @param type the ObjectType of the object
     *
     * @return TreeMap containing sibling details for the identified object
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final TreeMap<String, TreeMap<Integer, Collection<WhichDoctorBean>>> loadSiblings(final int guid,
            final String type) throws WhichDoctorDaoException {

        if (type == null) {
            throw new NullPointerException("The type parameter cannot be null");
        }

        dataLogger.info("History of GUID: " + guid + " requested");

        // Load siblings
        TreeMap<String, TreeMap<Integer, Collection<WhichDoctorBean>>> siblings = new TreeMap<String, TreeMap<Integer, Collection<WhichDoctorBean>>>();

        TreeMap<Integer, Collection<WhichDoctorBean>> memos = loadSiblingBeans(guid, "memo");
        siblings.put("Memos", memos);

        if (type.compareToIgnoreCase("person") == 0 || type.compareToIgnoreCase("organisation") == 0) {
            siblings.put("Addresses", loadSiblingBeans(guid, "address"));
            siblings.put("Phone Numbers", loadSiblingBeans(guid, "phone"));
            siblings.put("Email Addresses", loadSiblingBeans(guid, "email"));
            siblings.put("Specialties", loadSiblingBeans(guid, "specialty"));
        }
        if (type.compareToIgnoreCase("person") == 0) {
            siblings.put("Membership", loadSiblingBeans(guid, "membership"));
            siblings.put("Workshops", loadSiblingBeans(guid, "workshop"));
            siblings.put("Rotations", loadSiblingBeans(guid, "rotation"));
            siblings.put("Projects", loadSiblingBeans(guid, "project"));
            siblings.put("Exams", loadSiblingBeans(guid, "exam"));
            siblings.put("Qualifications", loadSiblingBeans(guid, "qualification"));
        }
        if (type.compareToIgnoreCase("rotation") == 0) {
            siblings.put("Assessments", loadSiblingBeans(guid, "assessment"));
            siblings.put("Reports", loadSiblingBeans(guid, "report"));
            siblings.put("Accreditations", loadSiblingBeans(guid, "accreditation"));
        }
        if (type.compareToIgnoreCase("reimbursement") == 0) {
            siblings.put("Expense Claims", loadSiblingBeans(guid, "expenseclaim"));
        }
        if (type.compareToIgnoreCase("receipt") == 0) {
            siblings.put("Payments", loadSiblingBeans(guid, "payment"));
        }

        return siblings;
    }

    /**
     * Load sibling beans.
     *
     * @param guid the guid
     * @param type the type
     *
     * @return the tree map< integer, collection< which doctor bean>>
     *
     * @throws WhichDoctorDaoException the whichdoctor dao exception
     */
    @SuppressWarnings("unchecked")
    private TreeMap<Integer, Collection<WhichDoctorBean>> loadSiblingBeans(final int guid, final String type)
            throws WhichDoctorDaoException {

        dataLogger.info("Sibling history of GUID: " + guid + " requested");

        String loadSQL = getSQL().getValue("whichdoctor/load/memo");

        if (type.compareToIgnoreCase("membership") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/membership");
        }
        if (type.compareToIgnoreCase("address") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/address");
        }
        if (type.compareToIgnoreCase("phone") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/phone");
        }
        if (type.compareToIgnoreCase("email") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/email");
        }
        if (type.compareToIgnoreCase("specialty") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/specialty");
        }
        if (type.compareToIgnoreCase("workshop") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/workshop");
        }
        if (type.compareToIgnoreCase("rotation") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/rotationSibling");
        }
        if (type.compareToIgnoreCase("project") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/project");
        }
        if (type.compareToIgnoreCase("exam") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/exam");
        }
        if (type.compareToIgnoreCase("qualification") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/qualification");
        }
        if (type.compareToIgnoreCase("accreditation") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/accreditation");
        }
        if (type.compareToIgnoreCase("assessment") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/assessment");
        }
        if (type.compareToIgnoreCase("report") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/report");
        }
        if (type.compareToIgnoreCase("expenseclaim") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/expenseClaim");
        }
        if (type.compareToIgnoreCase("payment") == 0) {
            loadSQL = getSQL().getValue("whichdoctor/load/payment");
        }

        TreeMap<Integer, Collection<WhichDoctorBean>> siblings = new TreeMap<Integer, Collection<WhichDoctorBean>>();

        try {
            Collection<WhichDoctorBean> siblingCollection = this.getJdbcTemplateReader().query(loadSQL,
                    new Object[] { guid }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            WhichDoctorBean whichdoctorBean = loadHistory(rs);
                            whichdoctorBean.setObjectType(type);

                            return whichdoctorBean;
                        }
                    });

            for (WhichDoctorBean whichdoctorBean : siblingCollection) {

                Collection<WhichDoctorBean> history = new ArrayList<WhichDoctorBean>();
                if (siblings.containsKey(whichdoctorBean.getGUID())) {
                    history = siblings.get(whichdoctorBean.getGUID());
                }
                history.add(whichdoctorBean);

                siblings.put(whichdoctorBean.getGUID(), history);
            }

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

    /**
     * Load.
     *
     * @param guid the guid
     *
     * @return the which doctor bean
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final WhichDoctorBean load(final int guid) throws WhichDoctorDaoException {
        dataLogger.info("Loading GUID: " + guid);

        WhichDoctorBean whichdoctorBean = null;

        try {
            whichdoctorBean = (WhichDoctorBean) this.getJdbcTemplateReader().queryForObject(
                    getSQL().getValue("whichdoctor/load/guid"), new Object[] { guid }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadBean(rs);
                        }
                    });

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

    /**
     * create inserts a guid entry and sets the created date and user dn.
     *
     * @param user the user
     * @param objectType the object type
     *
     * @return the int
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int create(final UserBean user, final String objectType) throws WhichDoctorDaoException {
        // Create GUID entry for global tracking
        if (user.getDN() == null) {
            throw new WhichDoctorDaoException("Valid User DN required");
        }

        int guid = 0;

        int objectTypeId = 0;
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("WhichDoctor", "", objectType);
            objectTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error identifying object type for new GUID: " + e.getMessage());
            throw new WhichDoctorDaoException("Error identifying object type for new GUID");
        }

        try {
            this.userDAO.cache(user);
        } catch (SFSDaoException sfde) {
            dataLogger.error("Error proxying user details: " + sfde.getMessage());
        }

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        final int createCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("whichdoctor/create"),
                new Object[] { objectTypeId, user.getDN(), sqlTimeStamp });

        if (createCount > 0) {
            guid = this.getJdbcTemplateWriter().queryForInt(this.getSQL().getValue("whichdoctor/loadLast"));
        }

        return guid;
    }

    /**
     * update sets the modified date and modified user dn for a GUID entry.
     *
     * @param guid the guid
     * @param objectType the object type
     * @param user the user
     *
     * @return true, if update
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean update(final int guid, final String objectType, final UserBean user)
            throws WhichDoctorDaoException {

        if (user == null) {
            throw new WhichDoctorDaoException("The user object cannot be null");
        }
        if (user.getDN() == null) {
            throw new WhichDoctorDaoException("Valid User DN required");
        }
        if (objectType == null) {
            throw new WhichDoctorDaoException("ObjectType cannot be null");
        }
        if (guid == 0) {
            throw new WhichDoctorDaoException("Valid GUID required");
        }

        int objectTypeId = 0;
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("WhichDoctor", "", objectType);
            objectTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error identifying object type for new GUID: " + e.getMessage());
            throw new WhichDoctorDaoException("Error identifying object type for new GUID");
        }

        boolean success = false;

        dataLogger.warn(user.getDN() + " updating GUID: " + guid);

        try {
            this.userDAO.cache(user);
        } catch (SFSDaoException sfde) {
            dataLogger.error("Error proxying user details: " + sfde.getMessage());
        }

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        final int updateCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("whichdoctor/modify"),
                new Object[] { objectTypeId, user.getDN(), sqlTimeStamp, null, null, guid });

        if (updateCount > 0) {
            dataLogger.info(user.getDN() + " successfully modified GUID: " + guid);
            success = true;
        }
        return success;
    }

    /**
     * delete sets the deleted date and deleted userid for a GUID entry.
     *
     * @param guid the guid
     * @param objectType the object type
     * @param user the user
     *
     * @return boolean success or fail
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean delete(final int guid, final String objectType, final UserBean user)
            throws WhichDoctorDaoException {

        if (user == null) {
            throw new WhichDoctorDaoException("The user object cannot be null");
        }
        if (user.getDN() == null) {
            throw new WhichDoctorDaoException("Valid User DN required");
        }
        if (guid == 0) {
            throw new WhichDoctorDaoException("Valid GUID required");
        }

        int objectTypeId = 0;
        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("WhichDoctor", "", objectType);
            objectTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error identifying object type for new GUID: " + e.getMessage());
            throw new WhichDoctorDaoException("Error identifying object type for new GUID");
        }

        boolean success = false;

        dataLogger.warn(user.getDN() + " deleted GUID: " + guid);

        try {
            this.userDAO.cache(user);
        } catch (SFSDaoException sfde) {
            dataLogger.error("Error proxying user details: " + sfde.getMessage());
        }

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        final int deleteCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("whichdoctor/delete"),
                new Object[] { objectTypeId, user.getDN(), sqlTimeStamp, guid });

        if (deleteCount > 0) {
            dataLogger.info(user.getDN() + " successfully deleted GUID: " + guid);
            success = true;
        }
        return success;
    }

    /**
     * export sets the export date and export userid for a GUID entry.
     *
     * @param search the search
     * @param user the user
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final void export(final SearchBean search, final UserBean user) throws WhichDoctorDaoException {

        if (user == null) {
            throw new WhichDoctorDaoException("The user object cannot be null");
        }
        if (user.getDN() == null) {
            throw new WhichDoctorDaoException("Valid User DN required");
        }

        String exportSQL = "";
        if (search.getType().compareToIgnoreCase("person") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/person") + search.getSQLArrayStatement("people.GUID");
        }
        if (search.getType().compareToIgnoreCase("organisation") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/organisation")
                    + search.getSQLArrayStatement("organisation.GUID");
        }
        if (search.getType().compareToIgnoreCase("debit") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/debit") + search.getSQLArrayStatement("invoice.GUID");
        }
        if (search.getType().compareToIgnoreCase("credit") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/credit") + search.getSQLArrayStatement("credit.GUID");
        }
        if (search.getType().compareToIgnoreCase("receipt") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/receipt")
                    + search.getSQLArrayStatement("receipt.GUID");
        }
        if (search.getType().compareToIgnoreCase("reimbursement") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/reimbursement")
                    + search.getSQLArrayStatement("reimbursement.GUID");
        }
        if (search.getType().compareToIgnoreCase("rotation") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/rotation")
                    + search.getSQLArrayStatement("rotation.GUID");
        }
        if (search.getType().compareToIgnoreCase("group") == 0) {
            exportSQL = getSQL().getValue("whichdoctor/export/group") + search.getSQLArrayStatement("groups.GUID");
        }

        dataLogger.debug("ExportSQL: " + exportSQL);

        try {
            this.userDAO.cache(user);
        } catch (SFSDaoException sfde) {
            dataLogger.error("Error proxying user details: " + sfde.getMessage());
        }

        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        ArrayList<Object> variables = (ArrayList<Object>) search.getSearchArray();
        if (variables == null) {
            variables = new ArrayList<Object>();
        }
        variables.add(0, user.getDN());
        variables.add(1, sqlTimeStamp);
        Object[] sqlVariables = variables.toArray();

        this.getJdbcTemplateWriter().update(exportSQL, sqlVariables);

    }

    /**
     * Update record.
     *
     * @param guid the guid
     * @param objectType the object type
     * @param checkUser the check user
     * @param action the action
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final void updateRecord(final int guid, final String objectType, final UserBean checkUser,
            final String action) throws WhichDoctorDaoException {
        try {
            if (action.compareTo("create") != 0) {
                if (action.compareTo("delete") == 0) {
                    try {
                        this.delete(guid, objectType, checkUser);
                    } catch (Exception e) {
                        throw new WhichDoctorDaoException(
                                "Unable to update deletion time for GUID: " + guid + ", " + e.getMessage());
                    }
                } else {
                    try {
                        this.update(guid, objectType, checkUser);
                    } catch (Exception e) {
                        throw new WhichDoctorDaoException(
                                "Unable to update modification time for GUID: " + guid + ", " + e.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            throw new WhichDoctorDaoException("Error updating GUID record: " + e.getMessage());
        }
    }

    /**
     * Renames the identified DN within the datastore to the new DN.
     *
     * @param originalDN the original dn
     * @param newDN the new dn
     * @param checkUser the check user
     * @param privileges the privileges
     *
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final void renameDN(final String originalDN, final String newDN, final UserBean checkUser,
            final PrivilegesBean privileges) throws WhichDoctorDaoException {
        if (originalDN == null) {
            throw new WhichDoctorDaoException("The original User DN cannot be null");
        }
        if (originalDN.compareTo("") == 0) {
            throw new WhichDoctorDaoException("The original User DN cannot be an empty string");
        }
        if (newDN == null) {
            throw new WhichDoctorDaoException("The User DN cannot be null");
        }
        if (newDN.compareTo("") == 0) {
            throw new WhichDoctorDaoException("The User DN cannot be an empty string");
        }
        if (!privileges.getPrivilege(checkUser, "systemAdmin", "modify")) {
            throw new WhichDoctorDaoException("Insufficient user credentials to rename user DN");
        }

        /** Loop through the SQLBean values and execute relevant updates **/

        String[] types = { "update", "replace", "delete" };
        final int maxCount = 100;

        for (String type : types) {
            for (int i = 0; i < maxCount; i++) {
                String sql = null;
                try {
                    final String sqlIndex = "whichdoctor/renameDn/" + type + i;
                    dataLogger.debug("SQL Index: " + sqlIndex);
                    sql = this.getSQL().getValue(sqlIndex);
                    dataLogger.debug(StringUtils.capitalize(type) + " SQL: " + sql);
                } catch (Exception e) {
                    sql = null;
                }

                ArrayList<String> variables = new ArrayList<String>();

                if (StringUtils.equals(type, "update")) {
                    variables.add(newDN);
                    variables.add(originalDN);
                }
                if (StringUtils.equals(type, "replace")) {
                    variables.add(originalDN);
                    variables.add(newDN);
                }
                if (StringUtils.equals(type, "delete")) {
                    variables.add(originalDN);
                }

                if (StringUtils.isNotBlank(sql)) {
                    try {
                        this.getJdbcTemplateWriter().update(sql, variables.toArray());
                    } catch (DataAccessException dae) {
                        dataLogger.error("Error renaming User DN: " + dae.getMessage());
                    }
                }
            }
        }
    }

    /**
     * Load history.
     *
     * @param rs the rs
     *
     * @return the which doctor bean
     *
     * @throws SQLException the SQL exception
     */
    private WhichDoctorBean loadHistory(final ResultSet rs) throws SQLException {

        WhichDoctorBean whichdoctor = new WhichDoctorBean();

        whichdoctor.setGUID(rs.getInt("GUID"));
        whichdoctor.setId(rs.getInt("Id"));
        whichdoctor.setDescription(rs.getString("Description"));
        try {
            whichdoctor.setEntryCreatedDate(rs.getTimestamp("Created"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error setting Created date: " + sqe.getMessage());
        }

        whichdoctor.setLogMessage(rs.getString("LogMessage"));
        whichdoctor.setActive(rs.getBoolean("Active"));

        UserBean user = new UserBean();
        user.setDN(rs.getString("CreatedBy"));
        user.setPreferredName(rs.getString("PreferredName"));
        user.setLastName(rs.getString("LastName"));
        whichdoctor.setEntryCreatedUser(user);

        return whichdoctor;
    }

    private WhichDoctorBean loadBean(final ResultSet rs) throws SQLException {

        final WhichDoctorBean loadedBean = new WhichDoctorBean();

        loadedBean.setGUID(rs.getInt("GUID"));
        loadedBean.setObjectType(rs.getString("ObjectType"));
        try {
            loadedBean.setCreatedDate(rs.getTimestamp("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading CreatedDate: " + sqe.getMessage());
        }
        loadedBean.setCreatedBy(rs.getString("CreatedBy"));
        try {
            loadedBean.setModifiedDate(rs.getTimestamp("ModifiedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error reading ModifiedDate: " + sqe.getMessage());
        }
        loadedBean.setModifiedBy(rs.getString("ModifiedBy"));

        return loadedBean;
    }
}