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.company.flightbooking.controller; import com.company.flightbooking.entities.AccountEntity; import com.company.flightbooking.entities.CustomerEntity; import com.company.flightbooking.repositories.AccountRepository; import com.company.flightbooking.repositories.CustomerRepository; import com.company.flightbooking.repositories.RoleRepository; import com.company.flightbooking.utils.PasswordEncoderGenerator; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.sql.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.support.PagedListHolder; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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.servlet.ModelAndView; /** * * @author Admin */ @Controller @RequestMapping(value = "/admin") public class AdminPageController { @Autowired private AccountRepository accountRepository; @Autowired private RoleRepository roleRepository; @Autowired private CustomerRepository customerRepository; @Autowired private JavaMailSender mailSender; @RequestMapping(produces = "application/x-www-form-urlencoded;charset=UTF-8") public ModelAndView adminPagination(@RequestParam(required = false) Integer page) { ModelAndView mv = new ModelAndView(); List<AccountEntity> accountList = (List<AccountEntity>) accountRepository.findAll(); //Create page holder PagedListHolder<AccountEntity> pageListHolder = new PagedListHolder<>(accountList); //Maximum record per page pageListHolder.setPageSize(20); if (page == null || page < 1 || page > pageListHolder.getPageCount()) { page = 1; pageListHolder.setPage(0); mv.addObject("accounts", pageListHolder.getPageList()); } else { pageListHolder.setPage(page - 1); mv.addObject("accounts", pageListHolder.getPageList()); } mv.addObject("page", page); mv.addObject("maxPage", pageListHolder.getPageCount()); mv.addObject("accountList", accountList); mv.addObject("roleList", roleRepository.findAll()); mv.setViewName("admin"); return mv; } @RequestMapping(value = "/create", method = RequestMethod.POST, produces = "application/x-www-form-urlencoded;charset=UTF-8") public String createAccount(HttpServletRequest req, Model model) { String url = "forward:/admin"; AccountEntity account = new AccountEntity(); account.setUsername(req.getParameter("username")); account.setPassword(PasswordEncoderGenerator.PasswordEncoder(req.getParameter("password"))); account.setEmail(req.getParameter("email")); account.setRole(roleRepository.findOne(Integer.parseInt(req.getParameter("role")))); AccountEntity result = accountRepository.save(account); if (result != null) { model.addAttribute("successMsg", "Create account " + account.getUsername() + " success!"); } else { model.addAttribute("errorMsg", "Create new account got error!"); } return url; } @RequestMapping(value = "/delete/{id}") public String deleteAccount(@PathVariable(name = "id", required = true) int id, Model model) { String url = "forward:/admin"; if (accountRepository.exists(id)) { accountRepository.delete(id); model.addAttribute("successMsg", "Deleted successful!"); } else { model.addAttribute("errorMsg", "Deleted error!"); } return url; } @RequestMapping(value = "/update") public String updateAccount(Model model, HttpServletRequest req) { int id = Integer.parseInt(req.getParameter("id")); AccountEntity accountToUpdate = accountRepository.findOne(id); accountToUpdate.setUsername(req.getParameter("username")); accountToUpdate.setPassword(req.getParameter("password")); accountToUpdate.setEmail(req.getParameter("email")); //get OWNER info CustomerEntity owner = accountToUpdate.getOwner(); if (owner == null) { owner = new CustomerEntity(); owner.setIdentityCode(req.getParameter("identityCode")); } owner.setFirstName(req.getParameter("firstName")); owner.setLastName(req.getParameter("lastName")); owner.setBirthdate(Date.valueOf(req.getParameter("birthdate"))); owner.setTel(req.getParameter("tel")); owner.setAddress(req.getParameter("address")); CustomerEntity addNewCusResult = customerRepository.save(owner); if (addNewCusResult != null) { accountToUpdate.setOwner(owner); } else { model.addAttribute("errorMsg", "Update account got error!"); } //UPDATE AccountEntity result = accountRepository.save(accountToUpdate); if (result != null) { owner.setAccount(result); model.addAttribute("successMsg", "Update account " + result.getUsername() + " success!"); } else { model.addAttribute("errorMsg", "Update account got error!"); } return "forward:/admin"; } @RequestMapping(value = "/setrole") public String setRoleForAccount(Model model, HttpServletRequest req) { int id = Integer.parseInt(req.getParameter("id")); AccountEntity accountToSetRole = accountRepository.findOne(id); accountToSetRole.setRole(roleRepository.findOne(Integer.parseInt(req.getParameter("userRole-" + id)))); AccountEntity result = accountRepository.save(accountToSetRole); if (result != null) { model.addAttribute("successMsg", "Set role for account " + result.getUsername() + " success!"); } else { model.addAttribute("errorMsg", "Set role for account got error!"); } return "forward:/admin"; } //check if username is exist @RequestMapping(value = "/search/username") public @ResponseBody String findbyUsername(@RequestParam(name = "username") String username) { AccountEntity result = null; Boolean response; if (username != null) { result = accountRepository.findByUsername(username); } else { } response = (result == null); return response.toString(); } //check if email is exist @RequestMapping(value = "/search/email") public @ResponseBody String findbyEmail(@RequestParam(name = "email") String email) { AccountEntity result = new AccountEntity(); if (email != null) { result = accountRepository.findByEmail(email); } Map<String, Object> data = new HashMap<>(); return (result == null ? "true" : "false"); } //Check if identitycode is exist @RequestMapping(value = "/search/identitycode") public @ResponseBody String findByIndentityCode(@RequestParam(name = "identityCode") String identityCode) { CustomerEntity result = new CustomerEntity(); if (identityCode != null) { result = customerRepository.findByIdentityCode(identityCode); } return (result == null ? "true" : "false"); } //SEND ACTIVE MAIL TO USER EMAIL @RequestMapping(value = "/sendactivemail") public @ResponseBody String sendActivationMail(@RequestParam(name = "email") String email, HttpServletRequest request) { AccountEntity result = accountRepository.findByEmail(email); String scheme = request.getScheme() + "://"; String serverName = request.getServerName(); String serverPort = (request.getServerPort() == 80) ? "" : ":" + request.getServerPort(); String contextPath = request.getContextPath(); String linkActive = scheme + serverName + serverPort + contextPath + "/active" + "?code=" + result.getPassword(); //Setup email content String subject = "Welcome " + result.getUsername() + " to E-flightTrip"; String message = "Click the this link to active your account " + linkActive; // creates a simple e-mail object SimpleMailMessage mailContent = new SimpleMailMessage(); mailContent.setTo(email); mailContent.setSubject(subject); mailContent.setText(message); //Java mail sender mailSender.send(mailContent); String response = (result != null ? "true" : "false"); return response; } //SEARCH FORM @RequestMapping(value = "/search/usernameoremail", produces = "application/json; charset=utf-8") public @ResponseBody String searchByUsernameOrEmail(@RequestParam(name = "searchValue") String searchValue) { List<AccountEntity> resultList = accountRepository .findByUsernameStartingWithOrEmailStartingWith(searchValue, searchValue); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.excludeFieldsWithoutExposeAnnotation().create(); return gson.toJson(resultList); } @RequestMapping(value = "/search/customerbyidentitycode", produces = "application/json") public @ResponseBody String searchCusByIdentityCode(@RequestParam(name = "searchValue") String searchValue) { CustomerEntity result = customerRepository.findByIdentityCode(searchValue); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.excludeFieldsWithoutExposeAnnotation().create(); return gson.toJson(result); } //UPDATE PAGE @RequestMapping(value = "/update/oneaccount/{id}") public ModelAndView showUpdateOneAccount(@PathVariable int id) { ModelAndView mv = new ModelAndView("updateaccount"); mv.addObject("roles", roleRepository.findAll()); mv.addObject("account", accountRepository.findOne(id)); return mv; } //UPDATE PAGE PERFORM @RequestMapping(value = "/update/oneaccount/perform", method = RequestMethod.POST, produces = "application/x-www-form-urlencoded;charset=UTF-8") public String updateOneAccountPerform(HttpServletRequest req, Model model) { String url = "updateaccount"; //GET ACCOUNT ID int id = Integer.parseInt(req.getParameter("id")); //GET ACCOUNT WANNA UPDATE AccountEntity account = accountRepository.findOne(id); account.setUsername(req.getParameter("username")); account.setPassword(req.getParameter("password")); account.setEmail(req.getParameter("email")); //get OWNER info CustomerEntity owner = account.getOwner(); if (owner == null) { owner = new CustomerEntity(); owner.setIdentityCode(req.getParameter("identityCode")); } owner.setFirstName(req.getParameter("firstName")); owner.setLastName(req.getParameter("lastName")); owner.setBirthdate(Date.valueOf(req.getParameter("birthdate"))); owner.setTel(req.getParameter("tel")); owner.setAddress(req.getParameter("address")); CustomerEntity addNewCusResult = customerRepository.save(owner); if (addNewCusResult != null) { account.setOwner(owner); } else { model.addAttribute("errorMsg", "Update account got error!"); } //UPDATE AccountEntity result = accountRepository.save(account); if (result != null) { owner.setAccount(result); model.addAttribute("successMsg", "Update account " + result.getUsername() + " success!"); url = "forward:/admin"; } else { model.addAttribute("errorMsg", "Update account got error!"); } return url; } }