PageRenderTime 65ms CodeModel.GetById 21ms app.highlight 38ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/google/ie/web/controller/ProjectCommentController.java

http://thoughtsite.googlecode.com/
Java | 282 lines | 174 code | 23 blank | 85 comment | 21 complexity | cae69ace07600be9188dead44f73fee5 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.web.controller;
 17
 18import static com.google.ie.web.controller.WebConstants.ERROR;
 19import static com.google.ie.web.controller.WebConstants.FLAG;
 20import static com.google.ie.web.controller.WebConstants.SUCCESS;
 21import static com.google.ie.web.controller.WebConstants.VIEW_STATUS;
 22
 23import com.google.ie.business.domain.Comment;
 24import com.google.ie.business.domain.Idea;
 25import com.google.ie.business.domain.ProjectComment;
 26import com.google.ie.business.domain.User;
 27import com.google.ie.business.service.CommentService;
 28import com.google.ie.business.service.UserService;
 29import com.google.ie.common.constants.IdeaExchangeConstants;
 30import com.google.ie.common.editor.StringEditor;
 31import com.google.ie.common.util.ReCaptchaUtility;
 32import com.google.ie.common.validation.CommentValidator;
 33import com.google.ie.dto.CommentDetail;
 34import com.google.ie.dto.RetrievalInfo;
 35import com.google.ie.dto.ViewStatus;
 36
 37import org.apache.log4j.Logger;
 38import org.springframework.beans.factory.annotation.Autowired;
 39import org.springframework.beans.factory.annotation.Qualifier;
 40import org.springframework.beans.propertyeditors.CustomBooleanEditor;
 41import org.springframework.stereotype.Controller;
 42import org.springframework.validation.BindingResult;
 43import org.springframework.validation.FieldError;
 44import org.springframework.web.bind.WebDataBinder;
 45import org.springframework.web.bind.annotation.InitBinder;
 46import org.springframework.web.bind.annotation.ModelAttribute;
 47import org.springframework.web.bind.annotation.PathVariable;
 48import org.springframework.web.bind.annotation.RequestMapping;
 49import org.springframework.web.bind.annotation.RequestMethod;
 50import org.springframework.web.bind.annotation.RequestParam;
 51import org.springframework.web.bind.annotation.SessionAttributes;
 52
 53import java.io.IOException;
 54import java.util.ArrayList;
 55import java.util.HashMap;
 56import java.util.Iterator;
 57import java.util.List;
 58import java.util.Map;
 59
 60import javax.servlet.http.HttpServletRequest;
 61import javax.servlet.http.HttpSession;
 62
 63/**
 64 * A controller that handles request for comments.
 65 * 
 66 * @author asirohi
 67 * 
 68 */
 69@Controller
 70@RequestMapping("/projectComments")
 71@SessionAttributes("user")
 72public class ProjectCommentController {
 73    private static Logger logger = Logger.getLogger(ProjectCommentController.class);
 74    @Autowired
 75    @Qualifier("projectCommentServiceImpl")
 76    private CommentService commentService;
 77    @Autowired
 78    private UserService userService;
 79    @Autowired
 80    private ReCaptchaUtility reCaptchaUtility;
 81    @Autowired
 82    private CommentValidator commentValidator;
 83
 84    /**
 85     * Handles request to add comment on a Project.
 86     * 
 87     * @param projectComment key of the Project on which the comment is to be
 88     *        added.
 89     * @param user the User object
 90     * @throws IOException
 91     */
 92    @RequestMapping(value = "/postProjectComments", method = RequestMethod.POST)
 93    public void postCommentOnProject(HttpServletRequest request,
 94                    @ModelAttribute ProjectComment projectComment,
 95                    BindingResult result, Map<String, Object> map,
 96                    @RequestParam String recaptchaChallengeField,
 97                    @RequestParam String recaptchaResponseField, HttpSession session)
 98                    throws IOException {
 99        ViewStatus viewStatus = new ViewStatus();
100        Boolean captchaValidation = reCaptchaUtility.verifyCaptcha(request.getRemoteAddr(),
101                        recaptchaChallengeField,
102                        recaptchaResponseField);
103        /* call CommentValidator to validate input ProjectComment object */
104        getCommentValidator().validate(projectComment, result);
105        if (result.hasErrors() || !captchaValidation) {
106            logger.warn("Comment object has " + result.getErrorCount() + " validation errors");
107            viewStatus.setStatus(WebConstants.ERROR);
108            /* Add a message if the captcha validation fails */
109            if (!captchaValidation) {
110                viewStatus.addMessage(WebConstants.CAPTCHA, WebConstants.CAPTCHA_MISMATCH);
111            }
112            /* Iterate the errors and add a message for each error */
113            for (Iterator<FieldError> iterator = result.getFieldErrors().iterator(); iterator
114                            .hasNext();) {
115                FieldError fieldError = iterator.next();
116                viewStatus.addMessage(fieldError.getField(), fieldError.getDefaultMessage());
117                logger.warn("Error found in field: " + fieldError.getField() + " Message :"
118                                + fieldError.getDefaultMessage());
119            }
120
121        } else {
122            User user = (User) session.getAttribute(WebConstants.USER);
123            Comment comment = commentService.addComment(projectComment, user);
124            if (comment != null) {
125                viewStatus.setStatus(WebConstants.SUCCESS);
126                viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_SUCCESSFULL);
127            } else {
128                viewStatus.setStatus(WebConstants.ERROR);
129                viewStatus.addMessage(WebConstants.COMMENTS, WebConstants.COMMENT_FAILED);
130            }
131        }
132        map.remove("projectComment");
133        map.put(WebConstants.VIEW_STATUS, viewStatus);
134    }
135
136    /**
137     * Handle request to get lists of the comments on Idea with the given key.
138     * 
139     * @param ideaKey the key of the {@link Idea} object
140     * @param retrievalInfo the {@link RetrievalInfo} object
141     * @param map data map for the view status
142     */
143    @RequestMapping("listProjectComments/{projectKey}")
144    public void listProjectComments(@PathVariable String projectKey,
145                    @ModelAttribute RetrievalInfo retrievalInfo, Map<String, Object> map) {
146
147        /* Fetch the parameters as sent in the request */
148        long startIndex = retrievalInfo.getStartIndex();
149        long noOfRecordsRequested = retrievalInfo.getNoOfRecords();
150        /* Get the comment list */
151        List<ProjectComment> comments = commentService.getComments(projectKey, retrievalInfo);
152        List<CommentDetail> commentDetailList = getDetailedCommentsForProject(comments);
153        /* Map of data to be inserted into the view status object */
154        HashMap<String, Object> parameters = new HashMap<String, Object>();
155        /* Map containing the previous and next index values */
156        HashMap<String, Long> pagingMap = new HashMap<String, Long>();
157        /*
158         * If the size of the list is greater than the no. of records requested
159         * ,set the parameter 'next' to be used as start index for the next
160         * page retrieval.
161         */
162        if (commentDetailList != null && commentDetailList.size() > noOfRecordsRequested) {
163            pagingMap.put(WebConstants.NEXT, startIndex + noOfRecordsRequested);
164        } else {
165            /*
166             * If the list size is not greater than the number requested set
167             * the 'next' parameter to minus one
168             */
169            pagingMap.put(WebConstants.NEXT, (long) WebConstants.MINUS_ONE);
170        }
171        /*
172         * Set the parameter 'previous' to be used as the start index for the
173         * previous page retrieval
174         */
175        pagingMap.put(WebConstants.PREVIOUS, startIndex - noOfRecordsRequested);
176        /* Add the map containing the paging values to the map of parameters */
177        parameters.put(WebConstants.PAGING, pagingMap);
178
179        ViewStatus viewStatus = ViewStatus.createTheViewStatus(commentDetailList,
180                        WebConstants.COMMENTS, parameters);
181        map.put(WebConstants.VIEW_STATUS, viewStatus);
182
183    }
184
185    /**
186     * Flag the comment abusive
187     * 
188     * @param commentKey the key of the {@link Comment} to be flagged abusive
189     * @param user the {@link User} initiating the flagging
190     * @param model the data map
191     * @return the resource to which the request should be forwarded
192     */
193    @RequestMapping("flag/abuse/{commentKey}")
194    public String flagComment(@PathVariable String commentKey,
195                    HttpSession session,
196                    Map<String, Object> model) {
197        ViewStatus viewStatus = new ViewStatus();
198
199        User user = (User) session.getAttribute(WebConstants.USER);
200        /* Flag the comment */
201        String resultStatus = commentService.flagComment(commentKey, user);
202        if (resultStatus.equalsIgnoreCase(IdeaExchangeConstants.SUCCESS)) {
203            viewStatus.setStatus(SUCCESS);
204            viewStatus.addMessage(FLAG,
205                            WebConstants.COMMENT_FLAGGING_SUCCESSFULL);
206        } else if (resultStatus.equalsIgnoreCase(IdeaExchangeConstants.FAIL)) {
207            viewStatus.setStatus(ERROR);
208            viewStatus.addMessage(FLAG,
209                            WebConstants.FLAGGING_FAILED);
210        } else {
211            viewStatus.setStatus(ERROR);
212            viewStatus.addMessage(FLAG,
213                            resultStatus);
214        }
215        model.put(VIEW_STATUS, viewStatus);
216        return "projects/show";
217    }
218
219    /**
220     * Convert idea Comment to comment detail.
221     * 
222     * @param projectComments the list of {@link ProjectComment} objects
223     * @return list of {@link CommentDetail} objects
224     */
225    private List<CommentDetail> getDetailedCommentsForProject(List<ProjectComment> projectComments) {
226        List<CommentDetail> commentDetailList = new ArrayList<CommentDetail>();
227        User user = null;
228        CommentDetail commentDetail = null;
229        if (projectComments != null && projectComments.size() > WebConstants.ZERO) {
230            for (ProjectComment comment : projectComments) {
231                /* Fetch the owner of the comment */
232                user = userService.getUserByPrimaryKey(comment.getCreatorKey());
233                commentDetail = new CommentDetail();
234                comment.setCommentTextAsString(comment.getText());
235                commentDetail.setComment(comment);
236                commentDetail.setUser(user);
237                /* Add the object to list */
238                commentDetailList.add(commentDetail);
239            }
240            if (commentDetailList.size() > WebConstants.ZERO) {
241                return commentDetailList;
242            }
243        }
244        return null;
245    }
246
247    /**
248     * Register custom binders for Spring. Needed to run on app engine
249     * 
250     * @param binder the {@link WebDataBinder} object
251     * 
252     */
253    @InitBinder
254    public void initBinder(WebDataBinder binder) {
255        binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true));
256        binder.registerCustomEditor(String.class, new StringEditor(true));
257    }
258
259    /**
260     * @param userService the userService to set
261     */
262    public void setUserService(UserService userService) {
263        this.userService = userService;
264    }
265
266    /**
267     * @return the userService
268     */
269    public UserService getUserService() {
270        return userService;
271    }
272
273    public CommentValidator getCommentValidator() {
274        return commentValidator;
275    }
276
277    public void setCommentValidator(CommentValidator commentValidator) {
278        this.commentValidator = commentValidator;
279    }
280
281}
282