PageRenderTime 547ms CodeModel.GetById 221ms app.highlight 103ms RepoModel.GetById 219ms app.codeStats 0ms

/src/main/java/com/google/ie/business/service/impl/IdeaCommentServiceImpl.java

http://thoughtsite.googlecode.com/
Java | 331 lines | 207 code | 36 blank | 88 comment | 43 complexity | c387ed536b1675e2ffdaecb45f3b4f0c MD5 | raw file
  1/* Copyright 2010 Google Inc.
  2 * 
  3 * Licensed under the Apache License, Version 2.0 (the "License");
  4 * you may not use this file except in compliance with the License.
  5 * You may obtain a copy of the License at
  6 * 
  7 *      http://www.apache.org/licenses/LICENSE-2.0
  8 * 
  9 * Unless required by applicable law or agreed to in writing, software
 10 * distributed under the License is distributed on an "AS IS" BASIS.
 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 * See the License for the specific language governing permissions and
 13 * limitations under the License
 14 */
 15
 16package com.google.ie.business.service.impl;
 17
 18import com.google.ie.business.dao.AdminRequestDao;
 19import com.google.ie.business.dao.CommentDao;
 20import com.google.ie.business.dao.impl.DaoConstants;
 21import com.google.ie.business.domain.AdminRequest;
 22import com.google.ie.business.domain.Comment;
 23import com.google.ie.business.domain.EntityIndex;
 24import com.google.ie.business.domain.IdeaComment;
 25import com.google.ie.business.domain.User;
 26import com.google.ie.business.service.CommentService;
 27import com.google.ie.business.service.EntityIndexService;
 28import com.google.ie.business.service.ServiceConstants;
 29import com.google.ie.business.service.ShardedCounterService;
 30import com.google.ie.common.audit.AuditManager;
 31import com.google.ie.common.constants.IdeaExchangeConstants;
 32import com.google.ie.common.constants.IdeaExchangeErrorCodes;
 33import com.google.ie.common.exception.SystemException;
 34import com.google.ie.common.taskqueue.IndexQueueUpdater;
 35import com.google.ie.dto.RetrievalInfo;
 36
 37import org.apache.commons.lang.StringUtils;
 38import org.apache.log4j.Logger;
 39import org.springframework.beans.factory.annotation.Autowired;
 40import org.springframework.stereotype.Service;
 41import org.springframework.transaction.annotation.Propagation;
 42import org.springframework.transaction.annotation.Transactional;
 43
 44import java.util.Date;
 45import java.util.List;
 46
 47/**
 48 * A service implementation of the CommentService
 49 * 
 50 * @author Sachneet
 51 * 
 52 */
 53@Service
 54public class IdeaCommentServiceImpl implements CommentService {
 55    private static Logger logger = Logger.getLogger(IdeaCommentServiceImpl.class);
 56
 57    private static final String IDEA_KEY = "ideaKey";
 58
 59    @Autowired
 60    private CommentDao commentDao;
 61
 62    @Autowired
 63    private AuditManager auditManager;
 64
 65    @Autowired
 66    private EntityIndexService entityIndexService;
 67
 68    @Autowired
 69    private ShardedCounterService shardedCounterService;
 70
 71    @Autowired
 72    private AdminRequestDao adminRequestDao;
 73
 74    public IdeaCommentServiceImpl() {
 75    }
 76
 77    @Autowired
 78    private IndexQueueUpdater indexQueueUpdater;
 79
 80    @Override
 81    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
 82    public Comment addComment(Comment comment, User user) {
 83        if (comment != null && comment.getText() != null && user != null
 84                        && user.getUserKey() != null) {
 85            comment.setCreatorKey(user.getUserKey());
 86            comment.setCreatedOn(new Date(System.currentTimeMillis()));
 87            comment.setStatus(Comment.STATUS_SAVED);
 88            comment = saveComment(comment);
 89            if (comment != null && comment.getKey() != null) {
 90                // add user points
 91                user = addPointsToUserOnPostComment(user, comment);
 92                getAuditManager().audit(user.getUserKey(), comment.getKey(),
 93                                comment.getClass().getName(),
 94                                ServiceConstants.AUDIT_ACTION_TYPE_SAVE_COMMENT);
 95                logger.info("Comment saved successfully.");
 96            }
 97            return comment;
 98        }
 99        return null;
100    }
101
102    /**
103     * Saved a comment and mark it for indexing.
104     * 
105     * @param comment Comment object to be saved.
106     * @return Saved comment.
107     */
108    @Transactional(readOnly = false, propagation = Propagation.REQUIRED)
109    private Comment saveComment(Comment comment) {
110        comment = getCommentDao().saveComment(comment);
111        /*
112         * Index the entity.Create an EntityIndex object for the entity to be
113         * indexed and then queue the job to task queue
114         */
115        if (comment.getKey() != null) {
116            EntityIndex entityIndex = entityIndexService.createEntityIndex(comment.getKey());
117            getIndexQueueUpdater().indexEntity(entityIndex.getKey());
118        }
119        return comment;
120    }
121
122    @Override
123    public String flagComment(String ideaCommentKey, User user) {
124        String status = IdeaExchangeConstants.FAIL;
125        /* Get description of the Comment */
126        Comment comment = this.getCommentById(ideaCommentKey);
127        if (comment != null && comment.getStatus().equals(IdeaComment.STATUS_FLAGGED)) {
128            status = IdeaExchangeConstants.IDEA_COMMENT_ALLREADY_FLAGED;
129            return status;
130        }
131        AdminRequest adminRequest = new AdminRequest();
132        adminRequest.setEntityKey(ideaCommentKey);
133        adminRequest.setEntityType(IdeaComment.class.getSimpleName());
134        adminRequest.setRequesterkey(user.getUserKey());
135        adminRequest.setRequestType(AdminRequest.REQUEST_OBJECTIONABLE);
136        adminRequest.setCreatedOn(new Date());
137        adminRequest.setStatus(AdminRequest.STATUS_PENDING);
138        if (!StringUtils.isBlank(user.getEmailId())) {
139            adminRequest.setRequesterEmail(user.getEmailId());
140        }
141        if (comment != null && !StringUtils.isBlank(comment.getKey())) {
142            adminRequest.setEntityTitle(getTrimmedComment(comment.getText()));
143            comment.setStatus(Comment.STATUS_FLAGGED);
144            commentDao.saveComment(comment);
145        } else {
146            throw new SystemException(
147                            IdeaExchangeErrorCodes.COMMENT_NULL_EXCEPTION,
148                            "No Comment is associated with the given key");
149        }
150        if (adminRequestDao.saveRequest(adminRequest)) {
151            status = IdeaExchangeConstants.SUCCESS;
152        }
153        return status;
154    }
155
156    /**
157     * Trim the comment text upto 40 characters.
158     * 
159     * @param commentText
160     * @return the trimmed text.
161     */
162    protected String getTrimmedComment(String commentText) {
163        StringBuilder trimcomment = new StringBuilder();
164        if (StringUtils.length(commentText) > 40) {
165            trimcomment.append(commentText.substring(0, 40));
166            trimcomment.append("..");
167        } else {
168            trimcomment.append(commentText);
169        }
170        return trimcomment.toString();
171    }
172
173    @Override
174    public List<Comment> getComments(String ideaKey, RetrievalInfo retrievalInfo) {
175        List<Comment> commentList;
176        if (!StringUtils.isBlank(ideaKey)) {
177            retrievalInfo = prepareRetrievalInfo(retrievalInfo);
178            commentList = getCommentDao().getComments(ideaKey, retrievalInfo, IDEA_KEY);
179            if (commentList != null && commentList.size() > ServiceConstants.ZERO) {
180                return commentList;
181            }
182            logger.info("Comment List is null : There is no comment on the given Idea.");
183        }
184        logger.warn("Idea key is null or has whitespace only");
185        return null;
186    }
187
188    /**
189     * Prepares the {@link RetrievalInfo} object with values to be used as query
190     * parameters.
191     * Checks the received RetrievalInfo object attributes for valid
192     * data.Updates the attributes if they contain garbage values.If the
193     * received {@link RetrievalInfo} object is null,sets it to a new instance
194     * with its attributes set to default values.
195     * 
196     * @param retrievalInfo the {@link RetrievalInfo} object containing the
197     *        values to be used as query parameters
198     * @return the {@link RetrievalInfo} object containing the query parameters
199     */
200
201    private RetrievalInfo prepareRetrievalInfo(RetrievalInfo retrievalInfo) {
202        if (retrievalInfo == null) {
203            retrievalInfo = new RetrievalInfo();
204            retrievalInfo.setStartIndex(ServiceConstants.ZERO);
205            retrievalInfo.setNoOfRecords(ServiceConstants.IDEA_COMMENT_LIST_DEFAULT_SIZE);
206            retrievalInfo.setOrderType(ServiceConstants.DEFAULT_IDEA_COMMENT_ORDERING_TYPE);
207            retrievalInfo.setOrderBy(ServiceConstants.DEFAULT_IDEA_COMMENT_ORDERING_FIELD);
208        } else {
209            // Handle garbage values if any.
210            String orderOn = retrievalInfo.getOrderBy();
211            String orderByParam = retrievalInfo.getOrderType();
212            if (retrievalInfo.getStartIndex() < ServiceConstants.ZERO)
213                retrievalInfo.setStartIndex(ServiceConstants.ZERO);
214            if (retrievalInfo.getNoOfRecords() <= ServiceConstants.ZERO)
215                retrievalInfo.setNoOfRecords(ServiceConstants.IDEA_COMMENT_LIST_DEFAULT_SIZE);
216            if (orderByParam == null || !((orderByParam.equals(DaoConstants.ORDERING_ASCENDING)
217                            || orderByParam.equals(DaoConstants.ORDERING_DESCENDING))))
218                retrievalInfo.setOrderType(ServiceConstants.DEFAULT_IDEA_COMMENT_ORDERING_TYPE);
219            if (orderOn == null || !(orderOn.equals(ServiceConstants.
220                            IDEA_COMMENT_ORDERING_FIELD_CREATED_ON))) {
221                retrievalInfo.setOrderBy(ServiceConstants.DEFAULT_IDEA_COMMENT_ORDERING_FIELD);
222            }
223        }
224        return retrievalInfo;
225    }
226
227    /**
228     * Update sharded counters for the users reputation point calculation.
229     * 
230     * @param user the User who posted the comment on idea
231     * @param idea The Idea object.
232     * @return the User who posted the comment on idea.
233     */
234    private User addPointsToUserOnPostComment(User user, Comment comment) {
235        int points = 0;
236        if (comment.getKey() != null) {
237            points = IdeaExchangeConstants.REPUTATION_POINTS_COMMENT_POST;
238        }
239        shardedCounterService.updateTotalPoints(user.getUserKey(), points);
240        return user;
241    }
242
243    @Override
244    public void updateComment(Comment comment) {
245        commentDao.saveComment(comment);
246    }
247
248    /**
249     * @param auditManager the auditManager to set
250     */
251    public void setAuditManager(AuditManager auditManager) {
252        this.auditManager = auditManager;
253    }
254
255    /**
256     * @return the auditManager
257     */
258    public AuditManager getAuditManager() {
259        return auditManager;
260    }
261
262    /**
263     * @param commentDao the commentDao to set
264     */
265    public void setCommentDao(CommentDao commentDao) {
266        this.commentDao = commentDao;
267    }
268
269    /**
270     * @return the commentDao
271     */
272    public CommentDao getCommentDao() {
273        return commentDao;
274    }
275
276    @Override
277    public Comment getCommentById(String entityKey) {
278        return commentDao.findEntityByPrimaryKey(IdeaComment.class, entityKey);
279    }
280
281    /**
282     * @return the entityIndexService
283     */
284    public EntityIndexService getEntityIndexService() {
285        return entityIndexService;
286    }
287
288    /**
289     * @param entityIndexService the entityIndexService to set
290     */
291    public void setEntityIndexService(EntityIndexService entityIndexService) {
292        this.entityIndexService = entityIndexService;
293    }
294
295    /**
296     * @return the shardedCounterService
297     */
298    public ShardedCounterService getShardedCounterService() {
299        return shardedCounterService;
300    }
301
302    /**
303     * @param shardedCounterService the shardedCounterService to set
304     */
305    public void setShardedCounterService(ShardedCounterService shardedCounterService) {
306        this.shardedCounterService = shardedCounterService;
307    }
308
309    /**
310     * @return the adminRequestDao
311     */
312    public AdminRequestDao getAdminRequestDao() {
313        return adminRequestDao;
314    }
315
316    /**
317     * @param adminRequestDao the adminRequestDao to set
318     */
319    public void setAdminRequestDao(AdminRequestDao adminRequestDao) {
320        this.adminRequestDao = adminRequestDao;
321    }
322
323    public IndexQueueUpdater getIndexQueueUpdater() {
324        return indexQueueUpdater;
325    }
326
327    public void setIndexQueueUpdater(IndexQueueUpdater indexQueueUpdater) {
328        this.indexQueueUpdater = indexQueueUpdater;
329    }
330}
331