Java tutorial
/******************************************************************************* * 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.util.ArrayList; import java.util.Collection; import java.util.TreeMap; import java.sql.ResultSet; import java.sql.SQLException; import javax.annotation.Resource; import com.sfs.beans.BuilderBean; import com.sfs.beans.UserBean; import com.sfs.beans.PrivilegesBean; import com.sfs.whichdoctor.beans.GroupBean; import com.sfs.whichdoctor.beans.VoteBean; import com.sfs.whichdoctor.beans.ItemBean; import com.sfs.whichdoctor.beans.PersonBean; import com.sfs.whichdoctor.beans.SearchBean; import com.sfs.whichdoctor.beans.SearchResultsBean; import com.sfs.whichdoctor.search.SearchDAO; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.dao.IncorrectResultSizeDataAccessException; import org.springframework.jdbc.core.RowMapper; /** * The Class VoteDAOImpl. * * @author David Harrison */ public class VoteDAOImpl extends BaseDAOImpl implements VoteDAO { /** The data logger. */ private static Logger dataLogger = Logger.getLogger(VoteDAOImpl.class); /** The search dao. */ @Resource private SearchDAO searchDAO; /** The group dao. */ @Resource private GroupDAO groupDAO; /** The item dao. */ @Resource private ItemDAO itemDAO; /** * This method loads the votes cast by a particular group of people It is * built on top of the items functionality, the significant difference being * only one vote can be cast by each person in the group. * * @param groupGUID the group guid * * @return the tree map< integer, vote bean> * * @throws WhichDoctorDaoException the which doctor dao exception */ public final TreeMap<Integer, VoteBean> load(final int groupGUID) throws WhichDoctorDaoException { if (groupGUID == 0) { throw new WhichDoctorDaoException("Sorry a group guid greater than 0 is required"); } int year = 0; /* Load the group to get its year */ try { GroupBean group = this.groupDAO.loadGUID(groupGUID); year = group.getYear(); } catch (Exception e) { dataLogger.error("Error loading group associated with votes: " + e.getMessage()); } TreeMap<Integer, Integer> eligibleVotes = new TreeMap<Integer, Integer>(); TreeMap<Integer, VoteBean> votesCast = new TreeMap<Integer, VoteBean>(); try { eligibleVotes = loadEligible(groupGUID); } catch (Exception e) { throw new WhichDoctorDaoException("Error loading eligible votes: " + e.getMessage()); } // Load the vote items for the submitted group GUID TreeMap<String, ItemBean> items = new TreeMap<String, ItemBean>(); try { items = this.itemDAO.load(groupGUID, true, "Vote", "Votes"); } catch (Exception e) { dataLogger.error("Error loading votes cast: " + e.getMessage()); } if (items != null) { for (ItemBean item : items.values()) { // Get the unique vote id for each person // Add each vote to the votesCast map VoteBean vote = new VoteBean(); vote.setVoteNumber(PersonBean.getVoteNumber(item.getObject2GUID(), year)); vote.setGroupGUID(item.getObject1GUID()); if (eligibleVotes.containsKey(vote.getVoteNumber())) { // Set the basic details related to this vote and add it to // the treemap vote.setId(item.getId()); vote.setGUID(item.getGUID()); vote.setCandidateGUID(item.getWeighting()); vote.setPermission(item.getPermission()); vote.setActive(item.getActive()); vote.setCreatedBy(item.getCreatedBy()); vote.setCreatedDate(item.getCreatedDate()); vote.setCreatedUser(item.getCreatedUser()); vote.setModifiedBy(item.getModifiedBy()); vote.setModifiedDate(item.getModifiedDate()); vote.setModifiedUser(item.getModifiedUser()); // Add this to the vote treemap if this person is allowed to // vote votesCast.put(vote.getVoteNumber(), vote); } } } return votesCast; } /** * Loads an array of groups based on the submitted voteNumber and year. * * @param voteNumber the vote number * @param year the year * * @return the collection< group bean> * * @throws WhichDoctorDaoException the which doctor dao exception */ @SuppressWarnings("unchecked") public final Collection<GroupBean> findElections(final int voteNumber, final int year) throws WhichDoctorDaoException { if (year == 0) { throw new WhichDoctorDaoException("Sorry a valid year is required"); } Collection<GroupBean> elections = new ArrayList<GroupBean>(); dataLogger.info("Loading elections for: " + voteNumber + "/" + year); /* Identify the referenceGUID from the vote number and year */ int referenceGUID = PersonBean.getVoterGUID(voteNumber, year); TreeMap<Integer, Integer> electionList = new TreeMap<Integer, Integer>(); try { Collection<Integer> guids = this.getJdbcTemplateReader().query( this.getSQL().getValue("vote/findPossibleElections"), new Object[] { year, referenceGUID }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return rs.getInt("GUID"); } }); for (Integer guid : guids) { electionList.put(guid, guid); } } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } try { Collection<Integer> guids = this.getJdbcTemplateReader().query( this.getSQL().getValue("vote/findVotedElections"), new Object[] { year, referenceGUID }, new RowMapper() { public Object mapRow(final ResultSet rs, final int rowNum) throws SQLException { return rs.getInt("GUID"); } }); for (Integer guid : guids) { if (electionList.containsKey(guid)) { // This election has been voted for already, remove it from the list electionList.remove(guid); } } } catch (IncorrectResultSizeDataAccessException ie) { dataLogger.debug("No results found for this search: " + ie.getMessage()); } if (electionList.size() > 0) { // An unvoted election exists in the map, perform a group search to load it Collection<Object> guidCollection = new ArrayList<Object>(); for (Integer groupGUID : electionList.keySet()) { guidCollection.add(groupGUID); } try { SearchBean search = this.searchDAO.initiate("group", null); search.setLimit(0); search.setOrderColumn("groups.Weighting"); search.setOrderColumn2("groups.Name"); search.setSearchArray(guidCollection, "Unvoted list of elections"); BuilderBean loadDetails = new BuilderBean(); loadDetails.setParameter("CANDIDATES", true); SearchResultsBean results = this.searchDAO.search(search, loadDetails); if (results != null) { // Add each group to the election array for (Object result : results.getSearchResults()) { GroupBean election = (GroupBean) result; elections.add(election); } } } catch (Exception e) { dataLogger.error("Error performing election search: " + e.getMessage()); throw new WhichDoctorDaoException("Error performing election search: " + e.getMessage()); } } return elections; } /** * This method loads the eligible votes for a particular group of people It * is built on top of the items functionality, the significant difference * being only one vote can be cast by each person in the group. * * @param groupGUID the group guid * * @return the tree map< integer, integer> * * @throws WhichDoctorDaoException the which doctor dao exception */ public final TreeMap<Integer, Integer> loadEligible(final int groupGUID) throws WhichDoctorDaoException { if (groupGUID == 0) { throw new WhichDoctorDaoException("Sorry a group guid greater than 0 is required"); } TreeMap<Integer, Integer> eligibleVotes = new TreeMap<Integer, Integer>(); /* * Load the group with its items to build a map of which members are * allowed to vote */ try { BuilderBean loadDetails = new BuilderBean(); loadDetails.setParameter("ITEMS", true); GroupBean group = this.groupDAO.loadGUID(groupGUID, loadDetails); TreeMap<String, ItemBean> items = group.getItems(); if (items != null) { for (ItemBean item : items.values()) { int voterId = PersonBean.getVoteNumber(item.getObject2GUID(), group.getYear()); eligibleVotes.put(voterId, voterId); } } } catch (Exception e) { dataLogger.error("Error loading group: " + e.getMessage()); } return eligibleVotes; } /** * This method creates a new vote It acts as a wrapper around the ItemDAO * functionality. * * @param vote the vote * @param checkUser the check user * @param privileges the privileges * * @return the int * * @throws WhichDoctorDaoException the which doctor dao exception */ public final int create(final VoteBean vote, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { /* Check that the vote belongs to a valid election */ GroupBean group; try { group = this.groupDAO.loadGUID(vote.getGroupGUID()); } catch (Exception e) { dataLogger.error("Error loading election: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading election: " + e.getMessage()); } if (group == null || !StringUtils.equalsIgnoreCase(group.getType(), "Election")) { throw new WhichDoctorDaoException("Sorry a valid election relating to this vote could not be found"); } /* Check to see if the person who this vote belongs to is in the group */ TreeMap<Integer, Integer> eligibleVotes = new TreeMap<Integer, Integer>(); /* * Load the group with its items to build a map of which members are * allowed to vote */ try { eligibleVotes = loadEligible(vote.getGroupGUID()); } catch (Exception e) { throw new WhichDoctorDaoException("Error loading eligible votes: " + e.getMessage()); } if (!eligibleVotes.containsKey(vote.getVoteNumber())) { throw new WhichDoctorDaoException("Sorry this vote is not eligible for this election"); } /* Check if this vote has already been recorded */ TreeMap<Integer, VoteBean> castVotes = new TreeMap<Integer, VoteBean>(); try { castVotes = this.load(vote.getGroupGUID()); } catch (Exception e) { dataLogger.error("Error loading cast votes: " + e.getMessage()); } if (castVotes.containsKey(vote.getVoteNumber())) { throw new WhichDoctorDaoException("This vote has already been recorded for this election"); } ItemBean item = new ItemBean(); item.setObject1GUID(vote.getGroupGUID()); item.setObject2GUID(PersonBean.getVoterGUID(vote.getVoteNumber(), group.getYear())); item.setWeighting(vote.getCandidateGUID()); item.setItemType("Vote"); item.setPermission("groups"); return this.itemDAO.create(item, checkUser, privileges, null); } /** * This method deletes a cast vote based on its GUID. * * @param vote the vote * @param checkUser the check user * @param privileges the privileges * * @return true, if delete * * @throws WhichDoctorDaoException the which doctor dao exception */ public final boolean delete(final VoteBean vote, final UserBean checkUser, final PrivilegesBean privileges) throws WhichDoctorDaoException { /* Check that the vote belongs to a valid election */ GroupBean group = new GroupBean(); try { group = this.groupDAO.loadGUID(vote.getGroupGUID()); } catch (Exception e) { dataLogger.error("Error loading election: " + e.getMessage()); throw new WhichDoctorDaoException("Error loading election: " + e.getMessage()); } if (group.getType().compareTo("Election") != 0) { throw new WhichDoctorDaoException("Sorry a valid election relating to this vote could not be found"); } // Check if this vote has been recorded TreeMap<Integer, VoteBean> castVotes = new TreeMap<Integer, VoteBean>(); try { castVotes = this.load(vote.getGroupGUID()); } catch (Exception e) { dataLogger.error("Error loading cast votes: " + e.getMessage()); } if (!castVotes.containsKey(vote.getVoteNumber())) { throw new WhichDoctorDaoException("Sorry, this vote has not been recorded"); } ItemBean item = new ItemBean(); item.setId(vote.getId()); item.setGUID(vote.getGUID()); item.setObject1GUID(vote.getGroupGUID()); item.setWeighting(vote.getCandidateGUID()); item.setObject2GUID(PersonBean.getVoteNumber(vote.getVoteNumber(), group.getYear())); item.setItemType("Vote"); item.setPermission("groups"); return this.itemDAO.delete(item, checkUser, privileges, null); } }