Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.askme.controller.app; import com.askme.model.*; import com.askme.service.*; import com.askme.util.Const; import com.askme.util.StringUtil; import com.askme.validator.PasswordValidator; import java.beans.PropertyEditorSupport; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; /** * * @author Admin */ @Controller public class AppController { @Autowired UserService userService; @Autowired QuestionService questionService; @Autowired AnswerService answerService; @Autowired CategoryService categoryService; @Autowired TagService tagService; @Autowired VoteService voteService; @Autowired PasswordValidator passwordValidator; @RequestMapping(value = "/", method = RequestMethod.GET) public String home(ModelMap model) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); // Main data List<Question> lastQuestions = questionService.findLast(1, 10); List<Question> topViewsQuestions = questionService.findTopViews(1, 10); List<Question> noAnswersQuestions = questionService.findNoAnswers(1, 10); model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("lastQuestions", lastQuestions); model.addAttribute("topViewsQuestions", topViewsQuestions); model.addAttribute("noAnswersQuestions", noAnswersQuestions); return "home"; } @RequestMapping(value = "/loadMoreLast", method = RequestMethod.GET) public ModelAndView loadMoreLast(Model model, @RequestParam int page) { if (page != 1) { page = (page - 1) * Const.QUESTION_PER_PAGE + 1; } List<Question> questions = questionService.findLast(page, Const.QUESTION_PER_PAGE); model.addAttribute("questions", questions); return new ModelAndView("questions_fragment"); } @RequestMapping(value = "/loadMoreTopViews", method = RequestMethod.GET) public ModelAndView loadMoreTopViews(Model model, @RequestParam int page) { if (page != 1) { page = (page - 1) * Const.QUESTION_PER_PAGE + 1; } List<Question> questions = questionService.findTopViews(page, Const.QUESTION_PER_PAGE); model.addAttribute("questions", questions); return new ModelAndView("questions_fragment"); } @RequestMapping(value = "/loadMoreNoAnswers", method = RequestMethod.GET) public ModelAndView loadMoreNoAnswers(Model model, @RequestParam int page) { if (page != 1) { page = (page - 1) * Const.QUESTION_PER_PAGE + 1; } List<Question> questions = questionService.findNoAnswers(page, Const.QUESTION_PER_PAGE); model.addAttribute("questions", questions); return new ModelAndView("questions_fragment"); } @RequestMapping(value = "/category/{slug}-{id}.html", method = RequestMethod.GET) public String category(ModelMap model, @PathVariable String slug, @PathVariable int id) { // Check category exist List<Category> categories = categoryService.findAll(); Category currentCategory = null; for (Category category : categories) { if (category.getId() == id) { currentCategory = category; break; } } if (currentCategory == null) { return "redirect:/404"; } // Header and sidebar data List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); // Main data List<Question> questions = questionService.findByCategory(id, 1, 10); model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("questions", questions); model.addAttribute("currentCategory", currentCategory); return "category"; } @RequestMapping(value = "/loadMoreByCategory", method = RequestMethod.GET) public ModelAndView loadMoreByCategory(Model model, @RequestParam int id, @RequestParam int page) { if (page != 1) { page = (page - 1) * Const.QUESTION_PER_PAGE + 1; } List<Question> questions = questionService.findByCategory(id, page, Const.QUESTION_PER_PAGE); model.addAttribute("questions", questions); return new ModelAndView("questions_fragment"); } @RequestMapping(value = "/tag/{name}", method = RequestMethod.GET) public String tag(ModelMap model, @PathVariable String name) { // Check tag exist List<Tag> tags = tagService.findAll(); Tag currentTag = null; for (Tag tag : tags) { if (tag.getName().equals(name)) { currentTag = tag; } } if (currentTag == null) { return "redirect:/404"; } // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); // Main data List<Question> questions = questionService.findByTag(name, 1, 10); model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("questions", questions); model.addAttribute("currentTag", currentTag); return "tag"; } @RequestMapping(value = "/loadMoreByTag", method = RequestMethod.GET) public ModelAndView loadMoreByTag(Model model, @RequestParam String name, @RequestParam int page) { if (page != 1) { page = (page - 1) * Const.QUESTION_PER_PAGE + 1; } List<Question> questions = questionService.findByTag(name, page, Const.QUESTION_PER_PAGE); model.addAttribute("questions", questions); return new ModelAndView("questions_fragment"); } @RequestMapping(value = "/search", method = RequestMethod.GET) public String search(ModelMap model, @RequestParam String keyword) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); // Main data List<Question> questions = questionService.search(keyword, 1, 10); model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("questions", questions); return "search"; } @RequestMapping(value = "/loadMoreSearch", method = RequestMethod.GET) public ModelAndView loadMoreSearch(Model model, @RequestParam String keyword, @RequestParam int page) { if (page != 1) { page = (page - 1) * Const.QUESTION_PER_PAGE + 1; } List<Question> questions = questionService.search(keyword, page, Const.QUESTION_PER_PAGE); model.addAttribute("questions", questions); return new ModelAndView("questions_fragment"); } @RequestMapping(value = "/question/ask", method = RequestMethod.GET) public String getAskQuestion(ModelMap model) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<Tag> tags = tagService.findAll(); // Main data Question question = new Question(); model.addAttribute("categories", categories); model.addAttribute("tags", tags); model.addAttribute("question", question); return "question_form"; } @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Category.class, "category", new PropertyEditorSupport() { @Override public void setAsText(String text) { Category category = categoryService.findById(Integer.parseInt(text)); setValue(category); } }); binder.registerCustomEditor(Set.class, "tags", new CustomCollectionEditor(Set.class) { @Override protected Object convertElement(Object element) { Integer id = Integer.parseInt((String) element); return tagService.findById(id); } }); } @RequestMapping(value = "/question/ask", method = RequestMethod.POST) public String postAskQuestion(@Valid Question question, BindingResult result, ModelMap model, RedirectAttributes redirect) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<Tag> tags = tagService.findAll(); model.addAttribute("categories", categories); model.addAttribute("tags", tags); if (result.hasErrors()) { System.out.println(result.getAllErrors()); return "question_form"; } question.setSlug(StringUtil.slugify(question.getTitle())); question.setCreatedAt(new Date()); question.setUpdatedAt(new Date()); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User currentUser = ((CustomUserDetails) principal).getUser(); question.setUser(currentUser); questionService.save(question); redirect.addFlashAttribute("success", "Cu h?i ca bn c to thnh cng!"); return "redirect:/question/ask"; } @RequestMapping(value = "/question/{slug}-{id}.html", method = RequestMethod.GET) public String showQuestion(ModelMap model, @PathVariable String slug, @PathVariable int id) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); // Main data Question question = questionService.findById(id); if (question == null) { return "redirect:/404"; } questionService.upViews(question); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof CustomUserDetails) { Answer answer = new Answer(); model.addAttribute("answer", answer); } model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("question", question); return "app_question_detail"; } @RequestMapping(value = "/question/{id}/answer/post", method = RequestMethod.POST) public String postAnswer(ModelMap model, @PathVariable int id, @Valid Answer answer, BindingResult result, RedirectAttributes redirect) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); Question question = questionService.findById(id); model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("question", question); if (result.hasErrors()) { redirect.addFlashAttribute("error", "Vui lng nhp ni dung cu tr l?i"); } else { answer.setCreatedAt(new Date()); answer.setQuestion(question); Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); User currentUser = ((CustomUserDetails) principal).getUser(); answer.setUser(currentUser); answerService.save(answer); redirect.addFlashAttribute("success", "Tr l?i ca bn c gi!"); } return "redirect:/question/" + question.getSlug() + "-" + question.getId() + ".html"; } @RequestMapping(value = "/answer/vote", method = RequestMethod.GET) public @ResponseBody int vote(@RequestParam Integer answerId, @RequestParam String action) { Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof CustomUserDetails) { Answer answer = answerService.findById(answerId); User currentUser = ((CustomUserDetails) principal).getUser(); Vote vote = voteService.find(answer, currentUser); if (action.equals("like")) { // Like if (vote == null) { vote = new Vote(answer, currentUser, 1); voteService.save(vote); answerService.upVotes(answer); return 1; } else { if (vote.getAction() == 0) { vote.setAction(1); voteService.update(vote); answerService.upVotes(answer); return 1; } else { return 3; } } } else { // Dislike if (vote == null) { vote = new Vote(answer, currentUser, 0); voteService.save(vote); answerService.downVotes(answer); return 1; } else { if (vote.getAction() == 1) { vote.setAction(0); voteService.update(vote); answerService.downVotes(answer); return 1; } else { return 3; } } } } else { return 2; } } @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) public String userProfile(ModelMap model, @PathVariable int id) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); // Main data User user = userService.findProfile(id); if (user == null) { return "redirect:/404"; } model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("user", user); return "app_user_profile"; } @RequestMapping(value = "/user/{id}/change-profile.html", method = RequestMethod.GET) public String getChangeProfile(ModelMap model, @PathVariable int id) { // Check logged in Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof CustomUserDetails) { User currentUser = ((CustomUserDetails) principal).getUser(); if (currentUser.getId() == id) { // Header and sidebar data List<Category> categories = categoryService.findAll(); List<User> topUsers = userService.findTopPoint(5); List<Tag> tags = tagService.findAll(); User user = userService.findById(id); model.addAttribute("categories", categories); model.addAttribute("topUsers", topUsers); model.addAttribute("tags", tags); model.addAttribute("user", user); return "change_profile"; } } return "redirect:/404"; } @RequestMapping(value = "/user/changeProfile", method = RequestMethod.POST) public String postChangeProfile(@Valid User user, BindingResult result, ModelMap model, RedirectAttributes redirect, HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) { passwordValidator.validate(user, result); if (result.hasErrors()) { System.out.println(result.getAllErrors()); return "change_profile"; } // Upload avatar if (file != null) { try { InputStream inputStream = file.getInputStream(); if (inputStream == null) { System.out.println("File inputstream is null"); } String path = request.getServletContext().getRealPath("/") + "public/avatar/"; FileUtils.forceMkdir(new File(path)); File upload = new File(path + file.getOriginalFilename()); file.transferTo(upload); user.setAvatar(file.getOriginalFilename()); IOUtils.closeQuietly(inputStream); } catch (IOException ex) { System.out.println("Error saving uploaded file"); } } userService.update(user); redirect.addFlashAttribute("success", "Cp nht profile thnh cng"); return "redirect:/login"; } }