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

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.dao.TagDAOImpl.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.Collection;
import java.util.Calendar;

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.DataFilter;
import com.sfs.beans.ObjectTypeBean;
import com.sfs.beans.PrivilegesBean;
import com.sfs.beans.UserBean;
import com.sfs.dao.UserDAO;
import com.sfs.dao.SFSDaoException;
import com.sfs.whichdoctor.beans.TagBean;

/**
 * The Class TagDAOImpl.
 */
public class TagDAOImpl extends BaseDAOImpl implements TagDAO {

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

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

    /**
     * Used to get a Collection of TagBeans for a specified GUID.
     *
     * @param guid the guid
     * @param username the username
     * @param fullResults the full results
     * @return the collection
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final Collection<TagBean> load(final int guid, final String username, final boolean fullResults)
            throws WhichDoctorDaoException {

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

        Collection<TagBean> tags = new ArrayList<TagBean>();

        String loadTags = this.getSQL().getValue("tag/loadAnonymous");

        Collection<Object> parameters = new ArrayList<Object>();
        parameters.add(guid);
        parameters.add("Private");

        if (StringUtils.isNotEmpty(username)) {
            loadTags = this.getSQL().getValue("tag/loadAuthenticated");
            parameters.add("Private");
            parameters.add(username);
        }

        try {
            tags = this.getJdbcTemplateReader().query(loadTags, parameters.toArray(), new RowMapper() {
                public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                    return loadTag(rs, fullResults);
                }
            });

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

    /**
     * Used to get a TagBean based on its ID.
     *
     * @param tagId the tag id
     * @return the tag bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final TagBean load(final int tagId) throws WhichDoctorDaoException {

        dataLogger.info("TagId: " + tagId + " requested");

        final String loadTag = getSQL().getValue("tag/loadId");

        TagBean tag = null;
        try {
            tag = (TagBean) this.getJdbcTemplateReader().queryForObject(loadTag, new Object[] { tagId },
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadTag(rs, true);
                        }
                    });

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

    /**
     * Used to get an ArrayList of TagBeans for a specified search term.
     *
     * @param tagName the tag name
     * @return the collection
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final Collection<TagBean> autocomplete(final String tagName) throws WhichDoctorDaoException {

        if (tagName == null) {
            throw new WhichDoctorDaoException("Tag search term cannot be null");
        }

        Collection<TagBean> tags = new ArrayList<TagBean>();

        /* Only perform a search if there is more than two characters to search on */
        if (tagName.length() > 2) {

            dataLogger.info("Performing tag search for '" + tagName + "'");

            final String loadTags = getSQL().getValue("tag/autocomplete");

            try {
                tags = this.getJdbcTemplateReader().query(loadTags, new Object[] { "%" + tagName + "%" },
                        new RowMapper() {
                            public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                                TagBean tag = new TagBean();
                                tag.setTagName(rs.getString("TagName"));
                                return tag;
                            }
                        });

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

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

        if (tag.getGUID() == 0) {
            throw new WhichDoctorDaoException("Tag must have a GUID > 0");
        }
        if (StringUtils.isBlank(tag.getTagName())) {
            throw new WhichDoctorDaoException("Tag cannot be an empty string");
        }
        if (StringUtils.isBlank(tag.getSecurity())) {
            throw new WhichDoctorDaoException("A security level must be set for the tag");
        }
        if (!this.uniqueTest(tag)) {
            /* The tag submitted is not unique */
            throw new WhichDoctorDaoException("Sorry a tag of these " + "characteristics already exists");
        }

        boolean allowCreate = privileges.getPrivilege(checkUser, tag.getSecurity(), "modify");
        /* If the tag is of type private default to allow */
        if (StringUtils.equalsIgnoreCase(tag.getTagType(), "Private")) {
            allowCreate = true;
        }
        if (!allowCreate) {
            throw new WhichDoctorDaoException("Sorry, you do not have the required privileges to create this tag");
        }

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

        int tagId = 0;

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

        int updateCount = 0;

        try {
            updateCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("tag/create"),
                    new Object[] { tag.getGUID(), objectTypeId, DataFilter.capitaliseFirst(tag.getTagName()),
                            sqlTimeStamp, checkUser.getDN() });

        } catch (DataAccessException de) {
            dataLogger.error("Error creating tag: " + de.getMessage());
            throw new WhichDoctorDaoException("Error creating tag: " + de.getMessage());
        }

        if (updateCount > 0) {
            dataLogger.info(checkUser.getDN() + " successfully created tag");

            final String findMaxSQL = getSQL().getValue("tag/findMax");

            tagId = this.getJdbcTemplateWriter().queryForInt(findMaxSQL);
        }

        return tagId;
    }

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

        if (tag.getId() == 0) {
            throw new WhichDoctorDaoException("Tag must have a valid id");
        }
        if (tag.getGUID() == 0) {
            throw new WhichDoctorDaoException("Tag must have a GUID > 0");
        }
        if (StringUtils.isBlank(tag.getTagName())) {
            throw new WhichDoctorDaoException("Tag cannot be an empty string");
        }
        if (!this.uniqueTest(tag)) {
            /* The tag submitted is not unique */
            throw new WhichDoctorDaoException("Sorry a tag of these " + "characteristics already exists");
        }

        int objectTypeId = 0;

        try {
            ObjectTypeBean object = this.getObjectTypeDAO().load("Tag Type", "", tag.getTagType());
            objectTypeId = object.getObjectTypeId();
        } catch (Exception e) {
            dataLogger.error("Error identifying object type for tag: " + e.getMessage());
            throw new WhichDoctorDaoException("Error identifying object type for tag");
        }

        boolean allowModify = privileges.getPrivilege(checkUser, tag.getSecurity(), "modify");
        /* If the tag is of type private default to allow */
        if (StringUtils.equalsIgnoreCase(tag.getTagType(), "Private")) {
            allowModify = true;
        }
        if (!allowModify) {
            throw new WhichDoctorDaoException("Sorry, you do not have the required privileges to modify this tag");
        }

        int tagId = 0;

        dataLogger.info(checkUser.getDN() + " attempting to modify tag");

        try {
            final Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

            final int updateCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("tag/modify"),
                    new Object[] { tag.getGUID(), objectTypeId, DataFilter.capitaliseFirst(tag.getTagName()),
                            sqlTimeStamp, checkUser.getDN(), tag.getId() });

            if (updateCount > 0) {
                dataLogger.info(checkUser.getDN() + " successfully modified tag");
                tagId = tag.getId();
            } else {
                dataLogger.error(checkUser.getUserName() + ": could not modify tag");
                throw new WhichDoctorDaoException("Failed to modify tag entry");
            }

        } catch (DataAccessException de) {
            dataLogger.error("Error modifying tag: " + de.getMessage());
            throw new WhichDoctorDaoException("Error modifying tag: " + de.getMessage());
        }
        return tagId;
    }

    /**
     * Deletes the tag bean.
     *
     * @param tag the tag
     * @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 TagBean tag, final UserBean checkUser, final PrivilegesBean privileges)
            throws WhichDoctorDaoException {

        if (tag.getId() == 0) {
            throw new WhichDoctorDaoException("Tag must have a valid id");
        }
        if (StringUtils.isBlank(tag.getSecurity())) {
            throw new WhichDoctorDaoException("A security level must be set for the tag");
        }

        boolean allowDelete = privileges.getPrivilege(checkUser, tag.getSecurity(), "modify");
        // If the tag is of type private default to allow if owned by checkuser
        if (StringUtils.equalsIgnoreCase(tag.getTagType(), "Private")
                && StringUtils.equalsIgnoreCase(checkUser.getDN(), tag.getCreatedBy())) {
            allowDelete = true;
        }
        if (!allowDelete) {
            throw new WhichDoctorDaoException("Sorry, you do not have the required privileges to delete this tag");
        }

        boolean success = false;

        try {
            final int deleteCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("tag/delete"),
                    new Object[] { tag.getId() });

            if (deleteCount > 0) {
                dataLogger.info(checkUser.getDN() + " successfully deleted tag");
                success = true;
            } else {
                dataLogger.error(checkUser.getUserName() + ": could not delete tag");
                throw new WhichDoctorDaoException("Failed to delete tag entry");
            }

        } catch (DataAccessException de) {
            dataLogger.error("Error deleting tag: " + de.getMessage());
            throw new WhichDoctorDaoException("Error deleting tag: " + de.getMessage());
        }
        return success;
    }

    /**
     * Used to test if a tag is unique or not.
     *
     * @param tag the tag
     * @return true, if successful
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    private boolean uniqueTest(final TagBean tag) throws WhichDoctorDaoException {

        boolean unique = true;

        dataLogger.info("Unique tag test requested");

        String searchSQL = getSQL().getValue("tag/unique");

        Collection<Object> parameters = new ArrayList<Object>();
        parameters.add(tag.getGUID());
        parameters.add(tag.getTagName());
        parameters.add(tag.getTagType());

        if (StringUtils.equalsIgnoreCase(tag.getTagType(), "Private")) {
            searchSQL += " AND tags.CreatedBy = ?";
            /* Set the username test condition */
            parameters.add(tag.getCreatedBy());
        }

        Collection<TagBean> tags = new ArrayList<TagBean>();
        try {
            tags = this.getJdbcTemplateReader().query(searchSQL, parameters.toArray(), new RowMapper() {
                public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                    final TagBean tag = new TagBean();
                    tag.setId(rs.getInt("TagId"));
                    return tag;
                }
            });

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

        if (tags.size() > 0) {
            /* A tag already exists with this name */
            unique = false;
        }
        return unique;
    }

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

        final TagBean tag = new TagBean();

        tag.setId(rs.getInt("TagId"));
        tag.setGUID(rs.getInt("GUID"));
        tag.setTagName(rs.getString("TagName"));
        tag.setTagType(rs.getString("TagType"));

        if (fullResults) {
            try {
                tag.setCreatedDate(rs.getTimestamp("CreatedDate"));
            } catch (SQLException sqe) {
                dataLogger.debug("Error parsing tag creation date: " + sqe.getMessage());
            }
            tag.setCreatedBy(rs.getString("CreatedBy"));

            if (StringUtils.isNotBlank(tag.getCreatedBy())) {
                try {
                    tag.setCreatedUser(this.userDAO.loadCached(tag.getCreatedBy()));
                } catch (SFSDaoException sfde) {
                    dataLogger.debug("Error loading tag creator: " + sfde.getMessage());
                }
            }
        }
        return tag;
    }
}