Commits

Juan Carlos Picado Herrera  committed 4e91855 Merge

Merge branch 'dianmorales' of github.com:encuestame/encuestame into juanpicado

  • Participants
  • Parent commits cd45e67, 0c707d7

Comments (0)

Files changed (4)

File encuestame-business/src/main/java/org/encuestame/business/service/FrontEndService.java

-/*
 ************************************************************************************
 * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
 * encuestame Development Team.
 * Licensed under the Apache Software License version 2.0
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to  in writing,  software  distributed
 * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
 * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
 * specific language governing permissions and limitations under the License.
 ************************************************************************************
 */
 * Front End Service.
 * @author Picado, Juan juanATencuestame.org
 * @since Oct 17, 2010 11:29:38 AM
 * @version $Id:$
 */
    /** Front End Service Log. **/
    private Logger log = Logger.getLogger(this.getClass());
    /** Max Results. **/
    private final Integer MAX_RESULTS = 15;
    /** **/
    @Autowired
    private TweetPollService tweetPollService;
    /** {@link PollService} **/
    @Autowired
    private PollService pollService;
    /** {@link SurveyService} **/
    @Autowired
    private SurveyService surveyService;
    /**
     * Search Items By tweetPoll.
     * @param maxResults limit of results to return.
     * @return result of the search.
     * @throws EnMeSearchException search exception.
     */
    public List<TweetPollBean> searchItemsByTweetPoll(
                final String period,
                final Integer start,
                Integer maxResults,
                final HttpServletRequest request)
                throws EnMeSearchException{
        final List<TweetPollBean> results = new ArrayList<TweetPollBean>();
        if(maxResults == null){
            maxResults = this.MAX_RESULTS;
        }
        log.debug("Max Results: "+maxResults);
        log.debug("Period Results: "+period);
        final List<TweetPoll> items = new ArrayList<TweetPoll>();
        if (period == null ) {
            throw new EnMeSearchException("search params required.");
        } else {
            final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
            if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.SEVENDAYS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast7Days(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast30Days(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.ALLTIME)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndAllTime(start, maxResults));
            }
            results.addAll(ConvertDomainBean.convertListToTweetPollBean(items));
            for (TweetPollBean tweetPoll : results) {
                //log.debug("Iterate Home TweetPoll id: "+tweetPoll.getId());
                //log.debug("Iterate Home Tweetpoll Hashtag Size: "+tweetPoll.getHashTags().size());
                tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
                tweetPoll.setTotalComments(this.getTotalCommentsbyType(tweetPoll.getId(), TypeSearchResult.TWEETPOLL));
            }
        }
        log.debug("Search Items by TweetPoll: "+results.size());
        return results;
    }
    /**
     *
     */
    public List<SurveyBean> searchItemsBySurvey(final String period,
            final Integer start, Integer maxResults,
            final HttpServletRequest request) throws EnMeSearchException {
        final List<SurveyBean> results = new ArrayList<SurveyBean>();
        if (maxResults == null) {
            maxResults = this.MAX_RESULTS;
        }
        log.debug("Max Results " + maxResults);
        final List<Survey> items = new ArrayList<Survey>();
        if (period == null) {
            throw new EnMeSearchException("search params required.");
        } else {
            final SearchPeriods periodSelected = SearchPeriods
                    .getPeriodString(period);
            if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
                        maxResults));
            } else if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
                        maxResults));
            } else if (periodSelected.equals(SearchPeriods.SEVENDAYS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast7Days(start,
                        maxResults));
            } else if (periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast30Days(
                        start, maxResults));
            } else if (periodSelected.equals(SearchPeriods.ALLTIME)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndAllTime(start,
                        maxResults));
            }
            log.debug("TweetPoll " + items.size());
            results.addAll(ConvertDomainBean.convertListSurveyToBean(items));
            for (SurveyBean surveyBean : results) {
                surveyBean.setTotalComments(this.getTotalCommentsbyType(surveyBean.getSid(), TypeSearchResult.SURVEY));
            }
        }
        return results;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#getFrontEndItems(java.lang.String, java.lang.Integer, java.lang.Integer, javax.servlet.http.HttpServletRequest)
     */
    public List<HomeBean> getFrontEndItems(final String period,
            final Integer start, Integer maxResults,
            final HttpServletRequest request) throws EnMeSearchException {
        // Sorted list based comparable interface
        final List<HomeBean> allItems = new ArrayList<HomeBean>();
        final List<TweetPollBean> tweetPollItems = this.searchItemsByTweetPoll(
                period, start, maxResults, request);
        log.debug("FrontEnd TweetPoll items size  :" + tweetPollItems.size());
        allItems.addAll(ConvertDomainBean
                .convertTweetPollListToHomeBean(tweetPollItems));
        final List<PollBean> pollItems = this.searchItemsByPoll(period, start,
                maxResults);
        log.debug("FrontEnd Poll items size  :" + pollItems.size());
        allItems.addAll(ConvertDomainBean.convertPollListToHomeBean(pollItems));
        final List<SurveyBean> surveyItems = this.searchItemsBySurvey(period,
                start, maxResults, request);
        log.debug("FrontEnd Survey items size  :" + surveyItems.size());
        allItems.addAll(ConvertDomainBean
                .convertSurveyListToHomeBean(surveyItems));
        log.debug("Home bean list size :" + allItems.size());
        Collections.sort(allItems);
        return allItems;
    }
    /**
     * Search items by poll.
     * @param period
     * @param maxResults
     * @return
     * @throws EnMeSearchException
     */
    public List<PollBean> searchItemsByPoll(
            final String period,
            final Integer start,
            Integer maxResults)
            throws EnMeSearchException{
    final List<PollBean> results = new ArrayList<PollBean>();
    if (maxResults == null) {
        maxResults = this.MAX_RESULTS;
    }
    final List<Poll> items = new ArrayList<Poll>();
    if (period == null ) {
        throw new EnMeSearchException("search params required.");
    } else {
        final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
        if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.SEVENDAYS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast7Days(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast30Days(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.ALLTIME)){
            items.addAll(getFrontEndDao().getPollFrontEndAllTime(start, maxResults));
        }
        log.debug("Poll "+items.size());
        results.addAll(ConvertDomainBean.convertListToPollBean((items)));
        for (PollBean pollbean : results) {
            pollbean.setTotalComments(this.getTotalCommentsbyType(pollbean.getId(), TypeSearchResult.POLL));
        }
    }
    return results;
    }
    /**
     * Get hashTags
     * @param maxResults the max results to display
     * @param start to pagination propose.
     * @return List of {@link HashTagBean}
     */
    public List<HashTagBean> getHashTags(
              Integer maxResults,
              final Integer start,
              final String tagCriteria) {
        final List<HashTagBean> hashBean = new ArrayList<HashTagBean>();
        if (maxResults == null) {
            maxResults = this.MAX_RESULTS;
        }
        final List<HashTag> tags = getHashTagDao().getHashTags(maxResults, start, tagCriteria);
        hashBean.addAll(ConvertDomainBean.convertListHashTagsToBean(tags));
        return hashBean;
    }
    /**
     * Get hashTag item.
     * @param tagName
     * @return
     * @throws EnMeNoResultsFoundException
     */
    public HashTag getHashTagItem(final String tagName) throws EnMeNoResultsFoundException {
        final HashTag tag = getHashTagDao().getHashTagByName(tagName);
        if (tag == null){
            throw new EnMeNoResultsFoundException("hashtag not found");
        }
        return tag;
    }
    /**
     * Get TweetPolls by hashTag id.
     * @param hashTagId
     * @param limit
     * @return
     */
    public List<TweetPollBean> getTweetPollsbyHashTagId(
            final Long hashTagId,
            final Integer limit,
            final String filter,
            final HttpServletRequest request){
        final List<TweetPoll> tweetPolls = getTweetPollDao().getTweetpollByHashTagId(hashTagId, limit, filter);
        log.debug("TweetPoll by HashTagId total size ---> "+tweetPolls.size());
        final List<TweetPollBean> tweetPollBean = ConvertDomainBean.convertListToTweetPollBean(tweetPolls);
        for (TweetPollBean tweetPoll : tweetPollBean) {
            tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
        }
        return tweetPollBean;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#checkPreviousHit(java.lang.String, java.lang.Long, java.lang.String)
     */
    public Boolean checkPreviousHit(final String ipAddress, final Long id, final TypeSearchResult searchHitby){
        boolean hit = false;
        final List<Hit> hitList = getFrontEndDao().getHitsByIpAndType(ipAddress, id, searchHitby);
        try {
            if(hitList.size() == 1){
                if(hitList.get(0).getIpAddress().equals(ipAddress)){
                    hit = true;
                }
             }
            else if(hitList.size() > 1){
                log.error("List cant'be greater than one");
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e);
        }
        return hit;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#registerHit(org.encuestame.persistence.domain.tweetpoll.TweetPoll, org.encuestame.persistence.domain.survey.Poll, org.encuestame.persistence.domain.survey.Survey, org.encuestame.persistence.domain.HashTag, java.lang.String)
     */
    public Boolean registerHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
            final String ip) throws EnMeNoResultsFoundException{
        final Hit hit ;
        Long hitCount = 1L;
        Boolean register = false;
        // HashTag
        if (ip != null){
            if (tag != null){
                hit = this.newHashTagHit(tag, ip);
                hitCount = tag.getHits() + hitCount;
                tag.setHits(hitCount);
                getFrontEndDao().saveOrUpdate(tag);
                register = true;
            }
            else if(tweetPoll != null){
                hit = this.newTweetPollHit(tweetPoll, ip);
                hitCount = tweetPoll.getHits() + hitCount;
                tweetPoll.setHits(hitCount);
                getFrontEndDao().saveOrUpdate(tweetPoll);
                register = true;
            }
            else if(poll != null){
                 hit = this.newPollHit(poll, ip);
                 hitCount = poll.getHits() + hitCount;
                 poll.setHits(hitCount);
                 getFrontEndDao().saveOrUpdate(poll);
                 register = true;
            }
            else if(survey != null ){
                 hit = this.newSurveyHit(survey, ip);
                 hitCount = survey.getHits() + hitCount;
                 survey.setHits(hitCount);
                 getFrontEndDao().saveOrUpdate(survey);
                 register = true;
            }
        }
        return register;
    }
    /**
     * New hit item.
     * @param tweetPoll
     * @param poll
     * @param survey
     * @param tag
     * @param ipAddress
     * @return
     */
    @Transactional(readOnly = false)
    private Hit newHitItem(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
            final String ipAddress) {
        final Hit hitItem = new Hit();
        hitItem.setHitDate(Calendar.getInstance().getTime());
        hitItem.setHashTag(tag);
        hitItem.setIpAddress(ipAddress);
        hitItem.setTweetPoll(tweetPoll);
        hitItem.setPoll(poll);
        hitItem.setSurvey(survey);
        getFrontEndDao().saveOrUpdate(hitItem);
        return hitItem;
    }
    /**
     * New tweet poll hit item.
     * @param tweetPoll
     * @param ipAddress
     * @return
     */
    private Hit newTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
        return this.newHitItem(tweetPoll, null, null, null, ipAddress);
    }
    /**
     * New poll hit item.
     * @param poll
     * @param ipAddress
     * @return
     */
    private Hit newPollHit(final Poll poll, final String ipAddress){
        return this.newHitItem(null, poll, null, null, ipAddress);
    }
    /**
     * New hash tag hit item.
     * @param tag
     * @param ipAddress
     * @return
     */
    private Hit newHashTagHit(final HashTag tag, final String ipAddress){
        return this.newHitItem(null, null, null, tag, ipAddress);
    }
    /**
     * New survey hit item.
     * @param survey
     * @param ipAddress
     * @return
     */
    private Hit newSurveyHit(final Survey survey, final String ipAddress){
        return this.newHitItem(null, null, survey, null, ipAddress);
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#registerAccessRate(org.encuestame.persistence.domain.TypeSearchResult, java.lang.Long, java.lang.String, java.lang.Boolean)
     */
    public AccessRate registerAccessRate(final TypeSearchResult type,
            final Long itemId, final String ipAddress, final Boolean rate)
            throws EnMeExpcetion {
        AccessRate recordAccessRate = new AccessRate();
        if (ipAddress != null) {
            if (type.equals(TypeSearchResult.TWEETPOLL)) {
                // Find tweetPoll by itemId.
                final TweetPoll tweetPoll = this.getTweetPoll(itemId);
                Assert.assertNotNull(tweetPoll);
                // Check if exist a previous tweetpoll access record.
                recordAccessRate = this.checkExistTweetPollPreviousRecord(tweetPoll, ipAddress,
                        rate);
            }
            // Poll Acces rate item.
            if (type.equals(TypeSearchResult.POLL)) {
                // Find poll by itemId.
                final Poll poll = this.getPoll(itemId);
                Assert.assertNotNull(poll);
                // Check if exist a previous poll access record.
                recordAccessRate = this.checkExistPollPreviousRecord(poll, ipAddress,
                        rate);
            }
            // Survey Access rate item.
            if (type.equals(TypeSearchResult.SURVEY)) {
                // Find survey by itemId.
                final Survey survey = this.getSurvey(itemId);
                Assert.assertNotNull(survey);
                // Check if exist a previous survey access record.
                recordAccessRate = this.checkExistSurveyPreviousRecord(survey, ipAddress,
                        rate);
            }
        }
        return recordAccessRate;
    }
    /**
     * Check exist tweetPoll previous record.
     * @param tpoll
     * @param ipAddress
     * @param option
     * @throws EnMeExpcetion
     */
    private AccessRate checkExistTweetPollPreviousRecord(final TweetPoll tpoll,
            final String ipAddress, final Boolean option) throws EnMeExpcetion {
        // Search record by tweetPpll in access Rate domain.
        List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
                tpoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
        final AccessRate accessRate;
        if (rateList.size() > 1) {
            throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
        } else if (rateList.size() == 1) {
            // Get first element from access rate list
            accessRate = rateList.get(0);
            //Check if the option selected is the same that you have registered
            if (accessRate.getRate() == option) {
                log.warn("The option was previously selected " + accessRate.getRate());
            } else {
                // We proceed to update the record in the table access Rate.
                accessRate.setRate(option);
                // Update the value in the fields of TweetPoll
                this.setTweetPollSocialOption(option,
                        tpoll);
                // Save access rate record.
                getFrontEndDao().saveOrUpdate(accessRate);
            }
        } else {
            // Otherwise, create access rate record.
            accessRate = this.newTweetPollAccessRate(tpoll, ipAddress, option);
            // update tweetPoll record.
            this.setTweetPollSocialOption(option,
                    tpoll);
        }
        return accessRate;
    }
    /**
     * Check exist Poll previous record.
     * @param poll
     * @param ipAddress
     * @param option
     * @return
     * @throws EnMeExpcetion
     */
    private AccessRate checkExistPollPreviousRecord(final Poll poll,
            final String ipAddress, final Boolean option) throws EnMeExpcetion {
        // Search record by poll in access Rate domain.
        List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
                poll.getPollId(), TypeSearchResult.POLL);
        final AccessRate accessRate;
        if (rateList.size() > 1) {
            throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
        } else if (rateList.size() == 1) {
            // Get first element from access rate list
            accessRate = rateList.get(0);
            //Check if the option selected is the same that you have registered
            if (accessRate.getRate() == option) {
                log.warn("The option was previously selected " + accessRate.getRate());
            } else {
                // We proceed to update the record in the table access Rate.
                accessRate.setRate(option);
                // Update the value in the fields of TweetPoll
                this.setPollSocialOption(option,
                        poll);
                // Save access rate record.
                getFrontEndDao().saveOrUpdate(accessRate);
            }
        } else {
            // Otherwise, create access rate record.
            accessRate = this.newPollAccessRate(poll, ipAddress, option);
            // update poll record.
             this.setPollSocialOption(option,
                    poll);
        }
        return accessRate;
    }
    /**
     * Check exist Survey previous record.
     * @param survey
     * @param ipAddress
     * @param option
     * @return
     * @throws EnMeExpcetion
     */
    private AccessRate checkExistSurveyPreviousRecord(final Survey survey,
            final String ipAddress, final Boolean option) throws EnMeExpcetion {
        // Search record by survey in access Rate domain.
        List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
                survey.getSid(), TypeSearchResult.SURVEY);
        final AccessRate accessRate;
        if (rateList.size() > 1) {
            throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
        } else if (rateList.size() == 1) {
            // Get first element from access rate list
            accessRate = rateList.get(0);
            //Check if the option selected is the same that you have registered
            if (accessRate.getRate() == option) {
                log.warn("The option was previously selected " + accessRate.getRate());
            } else {
                // We proceed to update the record in the table access Rate.
                accessRate.setRate(option);
                // Update the value in the fields of survey
                this.setSurveySocialOption(option, survey);
                // Save access rate record.
                getFrontEndDao().saveOrUpdate(accessRate);
            }
        } else {
            // Otherwise, create access rate record.
            accessRate = this.newSurveyAccessRate(survey, ipAddress, option);
            // update poll record.
            this.setSurveySocialOption(option,
                    survey);
        }
        return accessRate;
    }
    /**
     * Set tweetpoll social options.
     * @param socialOption
     * @param tpoll
     * @return
     */
    private TweetPoll setTweetPollSocialOption(final Boolean socialOption,
            final TweetPoll tpoll) {
        long valueSocialVote = 1L;
        long optionValue;
        // If the user has voted like.
        if (socialOption) {
            valueSocialVote = tpoll.getLikeVote() + valueSocialVote;
            tpoll.setLikeVote(valueSocialVote);
            optionValue = tpoll.getLikeVote() - valueSocialVote;
            tpoll.setDislikeVote(tpoll.getDislikeVote() == 0 ? 0 : optionValue);
            getTweetPollDao().saveOrUpdate(tpoll);
        } else {
            valueSocialVote = tpoll.getDislikeVote() + valueSocialVote;
            optionValue = tpoll.getLikeVote() - valueSocialVote;
            tpoll.setLikeVote(tpoll.getLikeVote() == 0 ? 0 : optionValue);
            tpoll.setDislikeVote(valueSocialVote);
            getTweetPollDao().saveOrUpdate(tpoll);
        }
        return tpoll;
    }
    /**
     * Set Poll social option.
     * @param socialOption
     * @param poll
     * @return
     */
    private Poll setPollSocialOption(final Boolean socialOption, final Poll poll) {
        long valueSocialVote = 1L;
        long optionValue;
        // If the user has voted like.
        if (socialOption) {
            valueSocialVote = poll.getLikeVote() + valueSocialVote;
            poll.setLikeVote(valueSocialVote);
            optionValue = poll.getLikeVote() - valueSocialVote;
            poll.setDislikeVote(poll.getDislikeVote() == 0 ? 0 : optionValue);
            getTweetPollDao().saveOrUpdate(poll);
        } else {
            valueSocialVote = poll.getDislikeVote() + valueSocialVote;
            optionValue = poll.getLikeVote() - valueSocialVote;
            poll.setLikeVote(poll.getLikeVote() == 0 ? 0 : optionValue);
            poll.setDislikeVote(valueSocialVote);
            getTweetPollDao().saveOrUpdate(poll);
        }
        return poll;
    }
    /**
     * Set Survey social option.
     * @param socialOption
     * @param survey
     * @return
     */
    private Survey setSurveySocialOption(final Boolean socialOption,
            final Survey survey) {
        long valueSocialVote = 1L;
        long optionValue;
        // If the user has voted like.
        if (socialOption) {
            valueSocialVote = survey.getLikeVote() + valueSocialVote;
            survey.setLikeVote(valueSocialVote);
            optionValue = survey.getLikeVote() - valueSocialVote;
            survey.setDislikeVote(survey.getDislikeVote() == 0 ? 0
                    : optionValue);
            getTweetPollDao().saveOrUpdate(survey);
        } else {
            valueSocialVote = survey.getDislikeVote() + valueSocialVote;
            optionValue = survey.getLikeVote() - valueSocialVote;
            survey.setLikeVote(survey.getLikeVote() == 0 ? 0 : optionValue);
            survey.setDislikeVote(valueSocialVote);
            getTweetPollDao().saveOrUpdate(survey);
        }
        return survey;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#getAccessRateItem(java.lang.String, java.lang.Long, org.encuestame.persistence.domain.TypeSearchResult)
     */
    private List<AccessRate> getAccessRateItem(final String ipAddress,
            final Long itemId, final TypeSearchResult searchby)
            throws EnMeExpcetion {
        final List<AccessRate> itemAccessList = getFrontEndDao()
                .getAccessRatebyItem(ipAddress, itemId, searchby);
        return itemAccessList;
    }
    /**
     * New access rate item.
     *
     * @param tweetPoll
     * @param poll
     * @param survey
     * @param ipAddress
     * @param rate
     * @return
     */
    @Transactional(readOnly = false)
    private AccessRate newAccessRateItem(final TweetPoll tweetPoll,
            final Poll poll, final Survey survey, final String ipAddress,
            final Boolean rate) {
        final AccessRate itemRate = new AccessRate();
        itemRate.setTweetPoll(tweetPoll);
        itemRate.setPoll(poll);
        itemRate.setSurvey(survey);
        itemRate.setRate(rate);
        itemRate.setUser(null);
        itemRate.setIpAddress(ipAddress);
        getTweetPollDao().saveOrUpdate(itemRate);
        return itemRate;
    }
    /**
     * New TweetPoll access rate.
     *
     * @param tweetPoll
     * @param ipAddress
     * @param rate
     * @return
     */
    private AccessRate newTweetPollAccessRate(final TweetPoll tweetPoll,
            final String ipAddress, final Boolean rate) {
        return this.newAccessRateItem(tweetPoll, null, null, ipAddress, rate);
    }
    /**
     * New Poll access rate.
     *
     * @param poll
     * @param ipAddress
     * @param rate
     * @return
     */
    private AccessRate newPollAccessRate(final Poll poll,
            final String ipAddress, final Boolean rate) {
        return this.newAccessRateItem(null, poll, null, ipAddress, rate);
    }
    /**
     * New Survey access rate.
     * @param survey
     * @param ipAddress
     * @param rate
     * @return
     */
    private AccessRate newSurveyAccessRate(final Survey survey,
            final String ipAddress, final Boolean rate) {
        return this.newAccessRateItem(null, null, survey, ipAddress, rate);
    }
    /**
     *
     * @param id
     * @return
     * @throws EnMeNoResultsFoundException
     */
    private TweetPoll getTweetPoll(final Long id) throws EnMeNoResultsFoundException{
        return getTweetPollService().getTweetPollById(id);
    }
    private Integer getSocialAccountsLinksByItem(final TweetPoll tpoll, final Survey survey, final Poll poll, final TypeSearchResult itemType){
        final List<TweetPollSavedPublishedStatus> totalAccounts = getTweetPollDao().getLinksByTweetPoll(tpoll, survey, poll, itemType);
        return totalAccounts.size();
    }
    /**
     * Get Relevance value by item.
     * @param likeVote
     * @param dislikeVote
     * @param hits
     * @param totalComments
     * @param totalSocialAccounts
     * @param totalNumberVotes
     * @param totalHashTagHits
     * @return
     */
    private long getRelevanceValue(final long likeVote, final long dislikeVote,
            final long hits, final long totalComments,
            final long totalSocialAccounts, final long totalNumberVotes,
            final long totalHashTagHits) {
        final long relevanceValue = EnMeUtils.calculateRelevance(likeVote,
                dislikeVote, hits, totalComments, totalSocialAccounts,
                totalNumberVotes, totalHashTagHits);
        log.info("*******************************");
        log.info("******* Resume of Process *****");
        log.info("-------------------------------");
        log.info("|  Total like votes : " + likeVote + "            |");
        log.info("|  Total dislike votes : " + dislikeVote + "            |");
        log.info("|  Total hits : " + hits + "            |");
        log.info("|  Total Comments : " + totalComments + "            |");
        log.info("|  Total Social Network : " + totalSocialAccounts + "            |");
        log.info("|  Total Votes : " + totalNumberVotes + "            |");
        log.info("|  Total HashTag hits : " + totalHashTagHits + "            |");
        log.info("-------------------------------");
        log.info("*******************************");
        log.info("************ Finished Start Relevance calculate job **************");
        return relevanceValue;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#processItemstoCalculateRelevance(java.util.List, java.util.List, java.util.List, java.util.Calendar, java.util.Calendar)
     */
    public void processItemstoCalculateRelevance(
            final List<TweetPoll> tweetPollList,
            final List<Poll> pollList,
            final List<Survey> surveyList,
            final Calendar datebefore,
            final Calendar todayDate) {
        long likeVote;
        long dislikeVote;
        long hits;
        long relevance;
        long comments;
        long socialAccounts;
        long numberVotes;
        long hashTagHits;
        for (TweetPoll tweetPoll : tweetPollList) {
            likeVote = tweetPoll.getLikeVote() == null ? 0 : tweetPoll
                    .getLikeVote();
            dislikeVote = tweetPoll.getDislikeVote() == null ? 0
                    : tweetPoll.getDislikeVote();
            hits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
           // final Long userId = tweetPoll.getEditorOwner().getUid();
            socialAccounts = this.getSocialAccountsLinksByItem(tweetPoll, null, null, TypeSearchResult.TWEETPOLL);
            numberVotes = tweetPoll.getNumbervotes();
            comments = getTotalCommentsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
            log.debug("Total comments by TweetPoll ---->" + comments);
            hashTagHits = getFrontEndDao().getTotalHitsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.HASHTAG);
            relevance = this.getRelevanceValue(likeVote, dislikeVote, hits, comments, socialAccounts, numberVotes, hashTagHits);
            tweetPoll.setRelevance(relevance);
            getTweetPollDao().saveOrUpdate(tweetPoll);
        }
        for (Poll poll : pollList) {
            likeVote = poll.getLikeVote() == null ? 0 : poll.getLikeVote();
            dislikeVote = poll.getDislikeVote() == null ? 0 : poll
                    .getDislikeVote();
            hits = poll.getHits() == null ? 0 : poll.getHits();
            socialAccounts = this.getSocialAccountsLinksByItem(null, null,
                    poll, TypeSearchResult.POLL);
            numberVotes = poll.getNumbervotes();
            comments =  getTotalCommentsbyType(poll.getPollId(), TypeSearchResult.POLL);
            log.debug("Total Comments by Poll ---->" + comments);
            hashTagHits = getFrontEndDao().getTotalHitsbyType(poll.getPollId(),
                    TypeSearchResult.HASHTAG);
            relevance = this.getRelevanceValue(likeVote, dislikeVote, hits,
                    comments, socialAccounts, numberVotes, hashTagHits);
            poll.setRelevance(relevance);
            getPollDao().saveOrUpdate(poll);
        }
    }
    /**
     * Get total comments by item type {@link TweetPoll}, {@link Poll} or {@link Survey}.
     * @param itemId
     * @param itemType
     * @return
     */
    private Long getTotalCommentsbyType(final Long itemId, final TypeSearchResult itemType){
        final Long totalComments = getCommentsOperations().getTotalCommentsbyItem(itemId, itemType);
        return totalComments;
    }
    /**
     * Get survey by id.
     * @param id
     * @return
     * @throws EnMeNoResultsFoundException
     */
    private Survey getSurvey(final Long id) throws EnMeNoResultsFoundException{
        return getSurveyService().getSurveyById(id);
    }
    /**
     * Get Poll by id.
     * @param id
     * @return
     * @throws EnMePollNotFoundException
     */
    private Poll getPoll(final Long id) throws EnMePollNotFoundException{
        return getPollService().getPollById(id);
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#getTopRatedProfile(java.lang.Boolean)
     */
    public List<ProfileRatedTopBean> getTopRatedProfile(final Boolean status)
            throws EnMeNoResultsFoundException {
        Long topValue = 0L;
        Long totalTweetPollPublished;
        Long totalPollPublished;
        Long total;
        final List<UserAccount> users = getSecurityService()
                .getUserAccountsAvailable(status);
        final List<ProfileRatedTopBean> profiles = ConvertDomainBean
                .convertUserAccountListToProfileRated(users);
        for (ProfileRatedTopBean profileRatedTopBean : profiles) {
            totalTweetPollPublished = getTweetPollDao().getTotalTweetPoll(
                    getUserAccount(profileRatedTopBean.getUsername()), status);
            totalPollPublished = getPollDao().getTotalPollsbyUser(
                    getUserAccount(profileRatedTopBean.getUsername()), status);
            total = totalTweetPollPublished + totalPollPublished;
            topValue = topValue + total;
            profileRatedTopBean.setTopValue(topValue);
        }
        Collections.sort(profiles);
        return profiles;
    }
    /**
     * @return the tweetPollService
     */
    public TweetPollService getTweetPollService() {
        return tweetPollService;
    }
    /**
     * @param tweetPollService the tweetPollService to set
     */
    public void setTweetPollService(TweetPollService tweetPollService) {
        this.tweetPollService = tweetPollService;
    }
    /**
     * @return the pollService
     */
    public PollService getPollService() {
        return pollService;
    }
    /**
     * @param pollService the pollService to set
     */
    public void setPollService(final PollService pollService) {
        this.pollService = pollService;
    }
    /**
     * @return the surveyService
     */
    public SurveyService getSurveyService() {
        return surveyService;
    }
    /**
     * @param surveyService the surveyService to set
     */
    public void setSurveyService(final SurveyService surveyService) {
        this.surveyService = surveyService;
    }
+/*
 ************************************************************************************
 * Copyright (C) 2001-2011 encuestame: system online surveys Copyright (C) 2011
 * encuestame Development Team.
 * Licensed under the Apache Software License version 2.0
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to  in writing,  software  distributed
 * under the License is distributed  on  an  "AS IS"  BASIS,  WITHOUT  WARRANTIES  OR
 * CONDITIONS OF ANY KIND, either  express  or  implied.  See  the  License  for  the
 * specific language governing permissions and limitations under the License.
 ************************************************************************************
 */
 * Front End Service.
 * @author Picado, Juan juanATencuestame.org
 * @since Oct 17, 2010 11:29:38 AM
 * @version $Id:$
 */
    /** Front End Service Log. **/
    private Logger log = Logger.getLogger(this.getClass());
    /** Max Results. **/
    private final Integer MAX_RESULTS = 15;
    /** **/
    @Autowired
    private TweetPollService tweetPollService;
    /** {@link PollService} **/
    @Autowired
    private PollService pollService;
    /** {@link SurveyService} **/
    @Autowired
    private SurveyService surveyService;
    /** {@link SecurityOperations} **/
    @Autowired
    private SecurityOperations securityService;
    /**
     * Search Items By tweetPoll.
     * @param maxResults limit of results to return.
     * @return result of the search.
     * @throws EnMeSearchException search exception.
     */
    public List<TweetPollBean> searchItemsByTweetPoll(
                final String period,
                final Integer start,
                Integer maxResults,
                final HttpServletRequest request)
                throws EnMeSearchException{
        final List<TweetPollBean> results = new ArrayList<TweetPollBean>();
        if(maxResults == null){
            maxResults = this.MAX_RESULTS;
        }
        log.debug("Max Results: "+maxResults);
        log.debug("Period Results: "+period);
        final List<TweetPoll> items = new ArrayList<TweetPoll>();
        if (period == null ) {
            throw new EnMeSearchException("search params required.");
        } else {
            final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
            if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast24(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.SEVENDAYS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast7Days(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndLast30Days(start, maxResults));
            } else if(periodSelected.equals(SearchPeriods.ALLTIME)) {
                items.addAll(getFrontEndDao().getTweetPollFrontEndAllTime(start, maxResults));
            }
            results.addAll(ConvertDomainBean.convertListToTweetPollBean(items));
            for (TweetPollBean tweetPoll : results) {
                //log.debug("Iterate Home TweetPoll id: "+tweetPoll.getId());
                //log.debug("Iterate Home Tweetpoll Hashtag Size: "+tweetPoll.getHashTags().size());
                tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
                tweetPoll.setTotalComments(this.getTotalCommentsbyType(tweetPoll.getId(), TypeSearchResult.TWEETPOLL));
            }
        }
        log.debug("Search Items by TweetPoll: "+results.size());
        return results;
    }
    /**
     *
     */
    public List<SurveyBean> searchItemsBySurvey(final String period,
            final Integer start, Integer maxResults,
            final HttpServletRequest request) throws EnMeSearchException {
        final List<SurveyBean> results = new ArrayList<SurveyBean>();
        if (maxResults == null) {
            maxResults = this.MAX_RESULTS;
        }
        log.debug("Max Results " + maxResults);
        final List<Survey> items = new ArrayList<Survey>();
        if (period == null) {
            throw new EnMeSearchException("search params required.");
        } else {
            final SearchPeriods periodSelected = SearchPeriods
                    .getPeriodString(period);
            if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
                        maxResults));
            } else if (periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast24(start,
                        maxResults));
            } else if (periodSelected.equals(SearchPeriods.SEVENDAYS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast7Days(start,
                        maxResults));
            } else if (periodSelected.equals(SearchPeriods.THIRTYDAYS)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndLast30Days(
                        start, maxResults));
            } else if (periodSelected.equals(SearchPeriods.ALLTIME)) {
                items.addAll(getFrontEndDao().getSurveyFrontEndAllTime(start,
                        maxResults));
            }
            log.debug("TweetPoll " + items.size());
            results.addAll(ConvertDomainBean.convertListSurveyToBean(items));
            for (SurveyBean surveyBean : results) {
                surveyBean.setTotalComments(this.getTotalCommentsbyType(surveyBean.getSid(), TypeSearchResult.SURVEY));
            }
        }
        return results;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#getFrontEndItems(java.lang.String, java.lang.Integer, java.lang.Integer, javax.servlet.http.HttpServletRequest)
     */
    public List<HomeBean> getFrontEndItems(final String period,
            final Integer start, Integer maxResults,
            final HttpServletRequest request) throws EnMeSearchException {
        // Sorted list based comparable interface
        final List<HomeBean> allItems = new ArrayList<HomeBean>();
        final List<TweetPollBean> tweetPollItems = this.searchItemsByTweetPoll(
                period, start, maxResults, request);
        log.debug("FrontEnd TweetPoll items size  :" + tweetPollItems.size());
        allItems.addAll(ConvertDomainBean
                .convertTweetPollListToHomeBean(tweetPollItems));
        final List<PollBean> pollItems = this.searchItemsByPoll(period, start,
                maxResults);
        log.debug("FrontEnd Poll items size  :" + pollItems.size());
        allItems.addAll(ConvertDomainBean.convertPollListToHomeBean(pollItems));
        final List<SurveyBean> surveyItems = this.searchItemsBySurvey(period,
                start, maxResults, request);
        log.debug("FrontEnd Survey items size  :" + surveyItems.size());
        allItems.addAll(ConvertDomainBean
                .convertSurveyListToHomeBean(surveyItems));
        log.debug("Home bean list size :" + allItems.size());
        Collections.sort(allItems);
        return allItems;
    }
    /**
     * Search items by poll.
     * @param period
     * @param maxResults
     * @return
     * @throws EnMeSearchException
     */
    public List<PollBean> searchItemsByPoll(
            final String period,
            final Integer start,
            Integer maxResults)
            throws EnMeSearchException{
    final List<PollBean> results = new ArrayList<PollBean>();
    if (maxResults == null) {
        maxResults = this.MAX_RESULTS;
    }
    final List<Poll> items = new ArrayList<Poll>();
    if (period == null ) {
        throw new EnMeSearchException("search params required.");
    } else {
        final SearchPeriods periodSelected = SearchPeriods.getPeriodString(period);
        if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.TWENTYFOURHOURS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast24(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.SEVENDAYS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast7Days(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.THIRTYDAYS)){
            items.addAll(getFrontEndDao().getPollFrontEndLast30Days(start, maxResults));
        } else if(periodSelected.equals(SearchPeriods.ALLTIME)){
            items.addAll(getFrontEndDao().getPollFrontEndAllTime(start, maxResults));
        }
        log.debug("Poll "+items.size());
        results.addAll(ConvertDomainBean.convertListToPollBean((items)));
        for (PollBean pollbean : results) {
            pollbean.setTotalComments(this.getTotalCommentsbyType(pollbean.getId(), TypeSearchResult.POLL));
        }
    }
    return results;
    }
    /**
     * Get hashTags
     * @param maxResults the max results to display
     * @param start to pagination propose.
     * @return List of {@link HashTagBean}
     */
    public List<HashTagBean> getHashTags(
              Integer maxResults,
              final Integer start,
              final String tagCriteria) {
        final List<HashTagBean> hashBean = new ArrayList<HashTagBean>();
        if (maxResults == null) {
            maxResults = this.MAX_RESULTS;
        }
        final List<HashTag> tags = getHashTagDao().getHashTags(maxResults, start, tagCriteria);
        hashBean.addAll(ConvertDomainBean.convertListHashTagsToBean(tags));
        return hashBean;
    }
    /**
     * Get hashTag item.
     * @param tagName
     * @return
     * @throws EnMeNoResultsFoundException
     */
    public HashTag getHashTagItem(final String tagName) throws EnMeNoResultsFoundException {
        final HashTag tag = getHashTagDao().getHashTagByName(tagName);
        if (tag == null){
            throw new EnMeNoResultsFoundException("hashtag not found");
        }
        return tag;
    }
    /**
     * Get TweetPolls by hashTag id.
     * @param hashTagId
     * @param limit
     * @return
     */
    public List<TweetPollBean> getTweetPollsbyHashTagId(
            final Long hashTagId,
            final Integer limit,
            final String filter,
            final HttpServletRequest request){
        final List<TweetPoll> tweetPolls = getTweetPollDao().getTweetpollByHashTagId(hashTagId, limit, filter);
        log.debug("TweetPoll by HashTagId total size ---> "+tweetPolls.size());
        final List<TweetPollBean> tweetPollBean = ConvertDomainBean.convertListToTweetPollBean(tweetPolls);
        for (TweetPollBean tweetPoll : tweetPollBean) {
            tweetPoll = convertTweetPollRelativeTime(tweetPoll, request);
        }
        return tweetPollBean;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#checkPreviousHit(java.lang.String, java.lang.Long, java.lang.String)
     */
    public Boolean checkPreviousHit(final String ipAddress, final Long id, final TypeSearchResult searchHitby){
        boolean hit = false;
        final List<Hit> hitList = getFrontEndDao().getHitsByIpAndType(ipAddress, id, searchHitby);
        try {
            if(hitList.size() == 1){
                if(hitList.get(0).getIpAddress().equals(ipAddress)){
                    hit = true;
                }
             }
            else if(hitList.size() > 1){
                log.error("List cant'be greater than one");
            }
        } catch (Exception e) {
            // TODO: handle exception
            log.error(e);
        }
        return hit;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#registerHit(org.encuestame.persistence.domain.tweetpoll.TweetPoll, org.encuestame.persistence.domain.survey.Poll, org.encuestame.persistence.domain.survey.Survey, org.encuestame.persistence.domain.HashTag, java.lang.String)
     */
    public Boolean registerHit(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
            final String ip) throws EnMeNoResultsFoundException{
        final Hit hit ;
        Long hitCount = 1L;
        Boolean register = false;
        // HashTag
        if (ip != null){
            if (tag != null){
                hit = this.newHashTagHit(tag, ip);
                hitCount = tag.getHits() + hitCount;
                tag.setHits(hitCount);
                getFrontEndDao().saveOrUpdate(tag);
                register = true;
            }
            else if(tweetPoll != null){
                hit = this.newTweetPollHit(tweetPoll, ip);
                hitCount = tweetPoll.getHits() + hitCount;
                tweetPoll.setHits(hitCount);
                getFrontEndDao().saveOrUpdate(tweetPoll);
                register = true;
            }
            else if(poll != null){
                 hit = this.newPollHit(poll, ip);
                 hitCount = poll.getHits() + hitCount;
                 poll.setHits(hitCount);
                 getFrontEndDao().saveOrUpdate(poll);
                 register = true;
            }
            else if(survey != null ){
                 hit = this.newSurveyHit(survey, ip);
                 hitCount = survey.getHits() + hitCount;
                 survey.setHits(hitCount);
                 getFrontEndDao().saveOrUpdate(survey);
                 register = true;
            }
        }
        return register;
    }
    /**
     * New hit item.
     * @param tweetPoll
     * @param poll
     * @param survey
     * @param tag
     * @param ipAddress
     * @return
     */
    @Transactional(readOnly = false)
    private Hit newHitItem(final TweetPoll tweetPoll, final Poll poll, final Survey survey, final HashTag tag,
            final String ipAddress) {
        final Hit hitItem = new Hit();
        hitItem.setHitDate(Calendar.getInstance().getTime());
        hitItem.setHashTag(tag);
        hitItem.setIpAddress(ipAddress);
        hitItem.setTweetPoll(tweetPoll);
        hitItem.setPoll(poll);
        hitItem.setSurvey(survey);
        getFrontEndDao().saveOrUpdate(hitItem);
        return hitItem;
    }
    /**
     * New tweet poll hit item.
     * @param tweetPoll
     * @param ipAddress
     * @return
     */
    private Hit newTweetPollHit(final TweetPoll tweetPoll, final String ipAddress){
        return this.newHitItem(tweetPoll, null, null, null, ipAddress);
    }
    /**
     * New poll hit item.
     * @param poll
     * @param ipAddress
     * @return
     */
    private Hit newPollHit(final Poll poll, final String ipAddress){
        return this.newHitItem(null, poll, null, null, ipAddress);
    }
    /**
     * New hash tag hit item.
     * @param tag
     * @param ipAddress
     * @return
     */
    private Hit newHashTagHit(final HashTag tag, final String ipAddress){
        return this.newHitItem(null, null, null, tag, ipAddress);
    }
    /**
     * New survey hit item.
     * @param survey
     * @param ipAddress
     * @return
     */
    private Hit newSurveyHit(final Survey survey, final String ipAddress){
        return this.newHitItem(null, null, survey, null, ipAddress);
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#registerAccessRate(org.encuestame.persistence.domain.TypeSearchResult, java.lang.Long, java.lang.String, java.lang.Boolean)
     */
    public AccessRate registerAccessRate(final TypeSearchResult type,
            final Long itemId, final String ipAddress, final Boolean rate)
            throws EnMeExpcetion {
        AccessRate recordAccessRate = new AccessRate();
        if (ipAddress != null) {
            if (type.equals(TypeSearchResult.TWEETPOLL)) {
                // Find tweetPoll by itemId.
                final TweetPoll tweetPoll = this.getTweetPoll(itemId);
                Assert.assertNotNull(tweetPoll);
                // Check if exist a previous tweetpoll access record.
                recordAccessRate = this.checkExistTweetPollPreviousRecord(tweetPoll, ipAddress,
                        rate);
            }
            // Poll Acces rate item.
            if (type.equals(TypeSearchResult.POLL)) {
                // Find poll by itemId.
                final Poll poll = this.getPoll(itemId);
                Assert.assertNotNull(poll);
                // Check if exist a previous poll access record.
                recordAccessRate = this.checkExistPollPreviousRecord(poll, ipAddress,
                        rate);
            }
            // Survey Access rate item.
            if (type.equals(TypeSearchResult.SURVEY)) {
                // Find survey by itemId.
                final Survey survey = this.getSurvey(itemId);
                Assert.assertNotNull(survey);
                // Check if exist a previous survey access record.
                recordAccessRate = this.checkExistSurveyPreviousRecord(survey, ipAddress,
                        rate);
            }
        }
        return recordAccessRate;
    }
    /**
     * Check exist tweetPoll previous record.
     * @param tpoll
     * @param ipAddress
     * @param option
     * @throws EnMeExpcetion
     */
    private AccessRate checkExistTweetPollPreviousRecord(final TweetPoll tpoll,
            final String ipAddress, final Boolean option) throws EnMeExpcetion {
        // Search record by tweetPpll in access Rate domain.
        List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
                tpoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
        final AccessRate accessRate;
        if (rateList.size() > 1) {
            throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
        } else if (rateList.size() == 1) {
            // Get first element from access rate list
            accessRate = rateList.get(0);
            //Check if the option selected is the same that you have registered
            if (accessRate.getRate() == option) {
                log.warn("The option was previously selected " + accessRate.getRate());
            } else {
                // We proceed to update the record in the table access Rate.
                accessRate.setRate(option);
                // Update the value in the fields of TweetPoll
                this.setTweetPollSocialOption(option,
                        tpoll);
                // Save access rate record.
                getFrontEndDao().saveOrUpdate(accessRate);
            }
        } else {
            // Otherwise, create access rate record.
            accessRate = this.newTweetPollAccessRate(tpoll, ipAddress, option);
            // update tweetPoll record.
            this.setTweetPollSocialOption(option,
                    tpoll);
        }
        return accessRate;
    }
    /**
     * Check exist Poll previous record.
     * @param poll
     * @param ipAddress
     * @param option
     * @return
     * @throws EnMeExpcetion
     */
    private AccessRate checkExistPollPreviousRecord(final Poll poll,
            final String ipAddress, final Boolean option) throws EnMeExpcetion {
        // Search record by poll in access Rate domain.
        List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
                poll.getPollId(), TypeSearchResult.POLL);
        final AccessRate accessRate;
        if (rateList.size() > 1) {
            throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
        } else if (rateList.size() == 1) {
            // Get first element from access rate list
            accessRate = rateList.get(0);
            //Check if the option selected is the same that you have registered
            if (accessRate.getRate() == option) {
                log.warn("The option was previously selected " + accessRate.getRate());
            } else {
                // We proceed to update the record in the table access Rate.
                accessRate.setRate(option);
                // Update the value in the fields of TweetPoll
                this.setPollSocialOption(option,
                        poll);
                // Save access rate record.
                getFrontEndDao().saveOrUpdate(accessRate);
            }
        } else {
            // Otherwise, create access rate record.
            accessRate = this.newPollAccessRate(poll, ipAddress, option);
            // update poll record.
             this.setPollSocialOption(option,
                    poll);
        }
        return accessRate;
    }
    /**
     * Check exist Survey previous record.
     * @param survey
     * @param ipAddress
     * @param option
     * @return
     * @throws EnMeExpcetion
     */
    private AccessRate checkExistSurveyPreviousRecord(final Survey survey,
            final String ipAddress, final Boolean option) throws EnMeExpcetion {
        // Search record by survey in access Rate domain.
        List<AccessRate> rateList = this.getAccessRateItem(ipAddress,
                survey.getSid(), TypeSearchResult.SURVEY);
        final AccessRate accessRate;
        if (rateList.size() > 1) {
            throw new EnMeExpcetion("Access rate list found coudn't be greater than one ");
        } else if (rateList.size() == 1) {
            // Get first element from access rate list
            accessRate = rateList.get(0);
            //Check if the option selected is the same that you have registered
            if (accessRate.getRate() == option) {
                log.warn("The option was previously selected " + accessRate.getRate());
            } else {
                // We proceed to update the record in the table access Rate.
                accessRate.setRate(option);
                // Update the value in the fields of survey
                this.setSurveySocialOption(option, survey);
                // Save access rate record.
                getFrontEndDao().saveOrUpdate(accessRate);
            }
        } else {
            // Otherwise, create access rate record.
            accessRate = this.newSurveyAccessRate(survey, ipAddress, option);
            // update poll record.
            this.setSurveySocialOption(option,
                    survey);
        }
        return accessRate;
    }
    /**
     * Set tweetpoll social options.
     * @param socialOption
     * @param tpoll
     * @return
     */
    private TweetPoll setTweetPollSocialOption(final Boolean socialOption,
            final TweetPoll tpoll) {
        long valueSocialVote = 1L;
        long optionValue;
        // If the user has voted like.
        if (socialOption) {
            valueSocialVote = tpoll.getLikeVote() + valueSocialVote;
            tpoll.setLikeVote(valueSocialVote);
            optionValue = tpoll.getLikeVote() - valueSocialVote;
            tpoll.setDislikeVote(tpoll.getDislikeVote() == 0 ? 0 : optionValue);
            getTweetPollDao().saveOrUpdate(tpoll);
        } else {
            valueSocialVote = tpoll.getDislikeVote() + valueSocialVote;
            optionValue = tpoll.getLikeVote() - valueSocialVote;
            tpoll.setLikeVote(tpoll.getLikeVote() == 0 ? 0 : optionValue);
            tpoll.setDislikeVote(valueSocialVote);
            getTweetPollDao().saveOrUpdate(tpoll);
        }
        return tpoll;
    }
    /**
     * Set Poll social option.
     * @param socialOption
     * @param poll
     * @return
     */
    private Poll setPollSocialOption(final Boolean socialOption, final Poll poll) {
        long valueSocialVote = 1L;
        long optionValue;
        // If the user has voted like.
        if (socialOption) {
            valueSocialVote = poll.getLikeVote() + valueSocialVote;
            poll.setLikeVote(valueSocialVote);
            optionValue = poll.getLikeVote() - valueSocialVote;
            poll.setDislikeVote(poll.getDislikeVote() == 0 ? 0 : optionValue);
            getTweetPollDao().saveOrUpdate(poll);
        } else {
            valueSocialVote = poll.getDislikeVote() + valueSocialVote;
            optionValue = poll.getLikeVote() - valueSocialVote;
            poll.setLikeVote(poll.getLikeVote() == 0 ? 0 : optionValue);
            poll.setDislikeVote(valueSocialVote);
            getTweetPollDao().saveOrUpdate(poll);
        }
        return poll;
    }
    /**
     * Set Survey social option.
     * @param socialOption
     * @param survey
     * @return
     */
    private Survey setSurveySocialOption(final Boolean socialOption,
            final Survey survey) {
        long valueSocialVote = 1L;
        long optionValue;
        // If the user has voted like.
        if (socialOption) {
            valueSocialVote = survey.getLikeVote() + valueSocialVote;
            survey.setLikeVote(valueSocialVote);
            optionValue = survey.getLikeVote() - valueSocialVote;
            survey.setDislikeVote(survey.getDislikeVote() == 0 ? 0
                    : optionValue);
            getTweetPollDao().saveOrUpdate(survey);
        } else {
            valueSocialVote = survey.getDislikeVote() + valueSocialVote;
            optionValue = survey.getLikeVote() - valueSocialVote;
            survey.setLikeVote(survey.getLikeVote() == 0 ? 0 : optionValue);
            survey.setDislikeVote(valueSocialVote);
            getTweetPollDao().saveOrUpdate(survey);
        }
        return survey;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#getAccessRateItem(java.lang.String, java.lang.Long, org.encuestame.persistence.domain.TypeSearchResult)
     */
    private List<AccessRate> getAccessRateItem(final String ipAddress,
            final Long itemId, final TypeSearchResult searchby)
            throws EnMeExpcetion {
        final List<AccessRate> itemAccessList = getFrontEndDao()
                .getAccessRatebyItem(ipAddress, itemId, searchby);
        return itemAccessList;
    }
    /**
     * New access rate item.
     *
     * @param tweetPoll
     * @param poll
     * @param survey
     * @param ipAddress
     * @param rate
     * @return
     */
    @Transactional(readOnly = false)
    private AccessRate newAccessRateItem(final TweetPoll tweetPoll,
            final Poll poll, final Survey survey, final String ipAddress,
            final Boolean rate) {
        final AccessRate itemRate = new AccessRate();
        itemRate.setTweetPoll(tweetPoll);
        itemRate.setPoll(poll);
        itemRate.setSurvey(survey);
        itemRate.setRate(rate);
        itemRate.setUser(null);
        itemRate.setIpAddress(ipAddress);
        getTweetPollDao().saveOrUpdate(itemRate);
        return itemRate;
    }
    /**
     * New TweetPoll access rate.
     *
     * @param tweetPoll
     * @param ipAddress
     * @param rate
     * @return
     */
    private AccessRate newTweetPollAccessRate(final TweetPoll tweetPoll,
            final String ipAddress, final Boolean rate) {
        return this.newAccessRateItem(tweetPoll, null, null, ipAddress, rate);
    }
    /**
     * New Poll access rate.
     *
     * @param poll
     * @param ipAddress
     * @param rate
     * @return
     */
    private AccessRate newPollAccessRate(final Poll poll,
            final String ipAddress, final Boolean rate) {
        return this.newAccessRateItem(null, poll, null, ipAddress, rate);
    }
    /**
     * New Survey access rate.
     * @param survey
     * @param ipAddress
     * @param rate
     * @return
     */
    private AccessRate newSurveyAccessRate(final Survey survey,
            final String ipAddress, final Boolean rate) {
        return this.newAccessRateItem(null, null, survey, ipAddress, rate);
    }
    /**
     *
     * @param id
     * @return
     * @throws EnMeNoResultsFoundException
     */
    private TweetPoll getTweetPoll(final Long id) throws EnMeNoResultsFoundException{
        return getTweetPollService().getTweetPollById(id);
    }
    private Integer getSocialAccountsLinksByItem(final TweetPoll tpoll, final Survey survey, final Poll poll, final TypeSearchResult itemType){
        final List<TweetPollSavedPublishedStatus> totalAccounts = getTweetPollDao().getLinksByTweetPoll(tpoll, survey, poll, itemType);
        return totalAccounts.size();
    }
    /**
     * Get Relevance value by item.
     * @param likeVote
     * @param dislikeVote
     * @param hits
     * @param totalComments
     * @param totalSocialAccounts
     * @param totalNumberVotes
     * @param totalHashTagHits
     * @return
     */
    private long getRelevanceValue(final long likeVote, final long dislikeVote,
            final long hits, final long totalComments,
            final long totalSocialAccounts, final long totalNumberVotes,
            final long totalHashTagHits) {
        final long relevanceValue = EnMeUtils.calculateRelevance(likeVote,
                dislikeVote, hits, totalComments, totalSocialAccounts,
                totalNumberVotes, totalHashTagHits);
        log.info("*******************************");
        log.info("******* Resume of Process *****");
        log.info("-------------------------------");
        log.info("|  Total like votes : " + likeVote + "            |");
        log.info("|  Total dislike votes : " + dislikeVote + "            |");
        log.info("|  Total hits : " + hits + "            |");
        log.info("|  Total Comments : " + totalComments + "            |");
        log.info("|  Total Social Network : " + totalSocialAccounts + "            |");
        log.info("|  Total Votes : " + totalNumberVotes + "            |");
        log.info("|  Total HashTag hits : " + totalHashTagHits + "            |");
        log.info("-------------------------------");
        log.info("*******************************");
        log.info("************ Finished Start Relevance calculate job **************");
        return relevanceValue;
    }
    /*
     * (non-Javadoc)
     * @see org.encuestame.core.service.imp.IFrontEndService#processItemstoCalculateRelevance(java.util.List, java.util.List, java.util.List, java.util.Calendar, java.util.Calendar)
     */
    public void processItemstoCalculateRelevance(
            final List<TweetPoll> tweetPollList,
            final List<Poll> pollList,
            final List<Survey> surveyList,
            final Calendar datebefore,
            final Calendar todayDate) {
        long likeVote;
        long dislikeVote;
        long hits;
        long relevance;
        long comments;
        long socialAccounts;
        long numberVotes;
        long hashTagHits;
        for (TweetPoll tweetPoll : tweetPollList) {
            likeVote = tweetPoll.getLikeVote() == null ? 0 : tweetPoll
                    .getLikeVote();
            dislikeVote = tweetPoll.getDislikeVote() == null ? 0
                    : tweetPoll.getDislikeVote();
            hits = tweetPoll.getHits() == null ? 0 : tweetPoll.getHits();
           // final Long userId = tweetPoll.getEditorOwner().getUid();
            socialAccounts = this.getSocialAccountsLinksByItem(tweetPoll, null, null, TypeSearchResult.TWEETPOLL);
            numberVotes = tweetPoll.getNumbervotes();
            comments = getTotalCommentsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.TWEETPOLL);
            log.debug("Total comments by TweetPoll ---->" + comments);
            hashTagHits = getFrontEndDao().getTotalHitsbyType(tweetPoll.getTweetPollId(), TypeSearchResult.HASHTAG);
            relevance = this.getRelevanceValue(likeVote, dislikeVote, hits, comments, socialAccounts, numberVotes, hashTagHits);
            tweetPoll.setRelevance(relevance);
            getTweetPollDao().saveOrUpdate(tweetPoll);
        }
        for (Poll poll : pollList) {
            likeVote = poll.getLikeVote() == null ? 0 : poll.getLikeVote();
            dislikeVote = poll.getDislikeVote() == null ? 0 : poll
                    .getDislikeVote();
            hits = poll.getHits() == null ? 0 : poll.getHits();
            socialAccounts = this.getSocialAccountsLinksByItem(null, null,
                    poll, TypeSearchResult.POLL);
            numberVotes = poll.getNumbervotes();
            comments =  getTotalCommentsbyType(poll.getPollId(), TypeSearchResult.POLL);
            log.debug("Total Comments by Poll ---->" + comments);
            hashTagHits = getFrontEndDao().getTotalHitsbyType(poll.getPollId(),