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