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

Java tutorial

Introduction

Here is the source code for com.sfs.whichdoctor.dao.SavedSearchDAOImpl.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.UserBean;
import com.sfs.whichdoctor.beans.SearchBean;

import java.sql.ResultSet;
import java.sql.Timestamp;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.StringTokenizer;

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;

/**
 * The Class SavedSearchDAOImpl.
 */
public class SavedSearchDAOImpl extends com.sfs.whichdoctor.dao.BaseDAOImpl implements SavedSearchDAO {

    /** The Constant variableDivider. */
    private static final String VARIABLE_DIVIDER = "_|_";

    /** The Constant DEFAULT_LIMIT. */
    private static final int DEFAULT_LIMIT = 20;

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

    /**
     * Used to get a Collection of SearchBean details for a
     * specified search filter.
     *
     * @param filter the filter
     * @param username or public saved searches
     * @param favourite load favourites or load everything
     * @return the collection
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final Collection<SearchBean> load(final String filter, final String username, final boolean favourite)
            throws WhichDoctorDaoException {

        dataLogger.info("Searches for: " + username + " requested");

        Collection<SearchBean> savedsearches = new ArrayList<SearchBean>();

        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(username);

        StringBuffer loadSearch = new StringBuffer();
        loadSearch.insert(0, this.getSQL().getValue("search/loadUser"));

        if (favourite) {
            loadSearch.append(" AND favourite = true");
        }
        if (StringUtils.isNotBlank(filter)) {
            loadSearch.append(" AND (Name LIKE ? OR Description LIKE ?)");
            parameters.add("%" + filter + "%");
            parameters.add("%" + filter + "%");
        }
        loadSearch.append(" ORDER BY savedsearch.Name");

        try {
            savedsearches = this.getJdbcTemplateReader().query(loadSearch.toString(), parameters.toArray(),
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadSearch(rs);
                        }
                    });

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

    /**
     * Load the saved search.
     *
     * @param filter the filter
     * @return the collection
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final Collection<SearchBean> load(final String filter) throws WhichDoctorDaoException {
        return load(filter, "", "");
    }

    /**
     * Used to get a Collection of SearchBean details for a public.
     *
     * @param filter the filter
     * @param subtype the subtype
     * @param username the username
     * @return the collection
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    @SuppressWarnings("unchecked")
    public final Collection<SearchBean> load(final String filter, final String subtype, final String username)
            throws WhichDoctorDaoException {

        final StringBuffer loadSearch = new StringBuffer();

        ArrayList<Object> parameters = new ArrayList<Object>();

        if (StringUtils.isNotBlank(filter)) {
            loadSearch.append(" AND (savedsearch.Name LIKE ? OR savedsearch.Description LIKE ?)");
            parameters.add("%" + filter + "%");
            parameters.add("%" + filter + "%");
        }
        if (StringUtils.isNotBlank(subtype)) {
            loadSearch.append(" AND Type = ?");
            parameters.add(subtype);
        }
        if (StringUtils.isNotBlank(username)) {
            loadSearch.append(" AND (savedsearch.UserDn = ? OR savedsearch.PublicSearch = true)");
            parameters.add(username);
        } else {
            loadSearch.append(" AND savedsearch.publicSearch = true");
        }

        if (loadSearch.length() > 0) {
            /* Delete the AND from the beginning of the search if defined */
            final int subtract = 5;
            loadSearch.delete(0, subtract);
            loadSearch.insert(0, " WHERE ");
        }
        loadSearch.insert(0, this.getSQL().getValue("search/load"));
        loadSearch.append(" ORDER BY savedsearch.Name");

        dataLogger.info("Retrieving saved public searches");

        Collection<SearchBean> savedsearches = new ArrayList<SearchBean>();

        try {
            savedsearches = this.getJdbcTemplateReader().query(loadSearch.toString(), parameters.toArray(),
                    new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadSearch(rs);
                        }
                    });

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

    /**
     * Used to get a SearchBean for the specified SearchId number.
     *
     * @param searchId the search id
     * @return the search bean
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final SearchBean loadId(final int searchId) throws WhichDoctorDaoException {

        dataLogger.info("Search Id: " + searchId + " requested");

        SearchBean search = null;

        try {
            search = (SearchBean) this.getJdbcTemplateReader().queryForObject(
                    this.getSQL().getValue("search/loadId"), new Object[] { searchId }, new RowMapper() {
                        public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException {
                            return loadSearch(rs);
                        }
                    });

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

        return search;
    }

    /**
     * Creates the saved search.
     *
     * @param search the search
     * @param checkUser the check user
     * @return the int
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final int create(final SearchBean search, final UserBean checkUser) throws WhichDoctorDaoException {

        if (StringUtils.isBlank(search.getName())) {
            throw new WhichDoctorDaoException("Saved search description " + "field cannot be an empty string");
        }
        if (StringUtils.isBlank(search.getType())) {
            throw new WhichDoctorDaoException("Saved search type cannot " + "be an empty string");
        }

        dataLogger.info(checkUser.getDN() + " attempting to create new " + "saved search");

        StringBuffer stbVariables = new StringBuffer();
        Collection<Object> searchParameters = search.getSearchParameters();
        if (searchParameters != null) {
            for (Object parameter : searchParameters) {
                if (stbVariables.length() != 0) {
                    stbVariables.append(VARIABLE_DIVIDER);
                }
                String strParameter = String.valueOf(parameter);
                if (StringUtils.isBlank(strParameter)) {
                    strParameter = " ";
                }
                stbVariables.append(strParameter);
            }
        }
        Timestamp sqlTimeStamp = new Timestamp(Calendar.getInstance().getTimeInMillis());

        ArrayList<Object> parameters = new ArrayList<Object>();
        parameters.add(search.getName());
        parameters.add(search.getType());
        parameters.add(search.getSQLWhereStatement());
        parameters.add(stbVariables.toString());
        parameters.add(search.getOrderColumn());
        parameters.add(search.getOrderColumn2());
        parameters.add(search.getOrderColumn3());
        parameters.add(search.getDisplayOrder());
        parameters.add(checkUser.getDN());
        parameters.add(sqlTimeStamp);
        parameters.add(search.getPublicSearch());
        parameters.add(search.getFavourite());
        parameters.add(search.getDescription());

        int searchId = 0;

        try {
            final int createCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("search/create"),
                    parameters.toArray());

            if (createCount > 0) {
                dataLogger.info("Sccessfully created Search");

                /* Get the last searchId value */
                searchId = this.getJdbcTemplateWriter().queryForInt(this.getSQL().getValue("search/findMax"));

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

    /**
     * Modify the saved search.
     *
     * @param search the search
     * @return true, if successful
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean modify(final SearchBean search) throws WhichDoctorDaoException {

        /* Modify search requires all the neccessary information */
        if (StringUtils.isBlank(search.getName())) {
            throw new WhichDoctorDaoException("Saved search description " + "field cannot be an empty string");
        }
        if (search.getId() == 0) {
            throw new WhichDoctorDaoException("A valid SearchId value is required");
        }

        boolean success = false;

        try {
            final int updateCount = this.getJdbcTemplateWriter().update(this.getSQL().getValue("search/modify"),
                    new Object[] { search.getName(), search.getPublicSearch(), search.getFavourite(),
                            search.getDescription(), search.getId() });

            if (updateCount > 0) {
                dataLogger.info("Sccessfully updated SearchId: " + search.getId());
                success = true;
            }
        } catch (DataAccessException de) {
            dataLogger.error("Error updating search: " + de.getMessage());
            throw new WhichDoctorDaoException("Error updating search: " + de.getMessage());
        }
        return success;
    }

    /**
     * Delete the saved search.
     *
     * @param search the search
     * @return true, if successful
     * @throws WhichDoctorDaoException the which doctor dao exception
     */
    public final boolean delete(final SearchBean search) throws WhichDoctorDaoException {

        if (search.getId() == 0) {
            throw new WhichDoctorDaoException("Search requires a vaild SearchId number");
        }

        boolean success = false;

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

            if (deleteCount > 0) {
                dataLogger.info("Sccessfully deleted SearchId: " + search.getId());
                success = true;
            }
        } catch (DataAccessException de) {
            dataLogger.error("Error deleting search: " + de.getMessage());
            throw new WhichDoctorDaoException("Error deleting search: " + de.getMessage());
        }
        return success;
    }

    /**
     * Load the saved search.
     *
     * @param rs the rs
     * @return the search bean
     * @throws SQLException the sQL exception
     */
    private SearchBean loadSearch(final ResultSet rs) throws SQLException {

        final SearchBean search = new SearchBean();

        dataLogger.debug("Loading search id: " + rs.getInt("SearchId"));

        search.setId(rs.getInt("SearchId"));
        search.setName(rs.getString("Name"));
        search.setDisplayOrder(rs.getInt("DisplayOrder"));
        search.setType(rs.getString("Type"));

        String strVariables = rs.getString("Variables");
        Collection<Object> parameters = new ArrayList<Object>();
        if (strVariables == null) {
            strVariables = "";
        }
        StringTokenizer tokenizer = new StringTokenizer(strVariables, VARIABLE_DIVIDER);
        while (tokenizer.hasMoreTokens()) {
            final String variable = tokenizer.nextToken();
            dataLogger.debug("Adding token: '" + variable + "'");
            parameters.add(variable);
        }

        search.setSQLWhereComponents(rs.getString("SQLString"), "", parameters, search.getSearchDescription());

        search.setOrderColumn(rs.getString("Order1"));
        search.setOrderColumn2(rs.getString("Order2"));
        search.setOrderColumn3(rs.getString("Order3"));

        try {
            search.setCreatedDate(rs.getDate("CreatedDate"));
        } catch (SQLException sqe) {
            dataLogger.debug("Error parsing CreatedDate: " + sqe.getMessage());
        }

        search.setPublicSearch(rs.getBoolean("PublicSearch"));
        search.setFavourite(rs.getBoolean("Favourite"));
        search.setDescription(rs.getString("Description"));
        search.setDN(rs.getString("UserDn"));
        search.setUserName(rs.getString("UserName"));

        search.setSavedSearch(true);
        search.setOrderAscending(true);

        search.setRequestedPage(1);
        search.setLimit(DEFAULT_LIMIT);

        return search;
    }
}