com.aistor.modules.sys.web.UserController.java Source code

Java tutorial

Introduction

Here is the source code for com.aistor.modules.sys.web.UserController.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/Dopas/dopas">Dopas</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.aistor.modules.sys.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
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.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.aistor.common.beanvalidator.BeanValidators;
import com.aistor.common.config.Global;
import com.aistor.common.persistence.Page;
import com.aistor.common.utils.DateUtils;
import com.aistor.common.utils.excel.ExportExcel;
import com.aistor.common.utils.excel.ImportExcel;
import com.aistor.common.web.BaseController;
import com.aistor.modules.sys.entity.User;
import com.aistor.modules.sys.service.SystemService;
import com.aistor.modules.sys.utils.UserUtils;

/**
 * Controller
 * @author Zaric
 * @version 2013-3-23
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/sys/user")
public class UserController extends BaseController {

    @Autowired
    private SystemService systemService;

    @ModelAttribute
    public User get(@RequestParam(required = false) Long id) {
        if (id != null) {
            return systemService.getUser(id);
        } else {
            return new User();
        }
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = { "list", "" })
    public String list(User user, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<User> page = systemService.findUser(new Page<User>(request, response), user);
        model.addAttribute("page", page);
        return "modules/sys/userList";
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "form")
    public String form(User user, Model model) {
        if (user.getArea() == null) {
            user.setArea(UserUtils.getUser().getArea());
        }
        if (user.getOffice() == null) {
            user.setOffice(UserUtils.getUser().getOffice());
        }
        model.addAttribute("user", user);
        model.addAttribute("allRoles", systemService.findAllRole());
        return "modules/sys/userForm";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "save")
    public String save(User user, String oldLoginName, String newPassword, Model model,
            RedirectAttributes redirectAttributes) {
        // ????
        if (StringUtils.isNotBlank(newPassword)) {
            user.setPassword(SystemService.entryptPassword(newPassword));
        }
        if (!beanValidator(model, user)) {
            return form(user, model);
        }
        if (!"true".equals(checkLoginName(oldLoginName, user.getLoginName()))) {
            addMessage(model, "?'" + user.getLoginName() + "'??");
            return form(user, model);
        }
        systemService.saveUser(user);
        addMessage(redirectAttributes, "?'" + user.getLoginName() + "'?");
        return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "delete")
    public String delete(Long id, RedirectAttributes redirectAttributes) {
        if (User.isAdmin(id)) {
            addMessage(redirectAttributes, ", ????");
        } else {
            systemService.deleteUser(id);
            addMessage(redirectAttributes, "?");
        }
        return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "export", method = RequestMethod.POST)
    public String exportFile(User user, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        try {
            String fileName = "?" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            Page<User> page = systemService.findUser(new Page<User>(request, response, -1), user);
            new ExportExcel("?", User.class).setDataList(page.getList()).write(response, fileName)
                    .dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "??" + e.getMessage());
        }
        return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
    }

    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "import", method = RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
        try {
            int successNum = 0;
            int failureNum = 0;
            StringBuilder failureMsg = new StringBuilder();
            ImportExcel ei = new ImportExcel(file, 1, 0);
            List<User> list = ei.getDataList(User.class);
            for (User user : list) {
                try {
                    if ("true".equals(checkLoginName("", user.getLoginName()))) {
                        user.setPassword(SystemService.entryptPassword("123456"));
                        BeanValidators.validateWithException(validator, user);
                        systemService.saveUser(user);
                        successNum++;
                    } else {
                        failureMsg.append("<br/>?? " + user.getLoginName() + " ; ");
                        failureNum++;
                    }
                } catch (ConstraintViolationException ex) {
                    failureMsg.append("<br/>?? " + user.getLoginName() + " ");
                    List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                    for (String message : messageList) {
                        failureMsg.append(message + "; ");
                        failureNum++;
                    }
                } catch (Exception ex) {
                    failureMsg
                            .append("<br/>?? " + user.getLoginName() + " " + ex.getMessage());
                }
            }
            if (failureNum > 0) {
                failureMsg.insert(0, " " + failureNum + " ??");
            }
            addMessage(redirectAttributes, "? " + successNum + " ?" + failureMsg);
        } catch (Exception e) {
            addMessage(redirectAttributes, "??" + e.getMessage());
        }
        return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
    }

    @RequiresPermissions("sys:user:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
        try {
            String fileName = "??.xlsx";
            List<User> list = Lists.newArrayList();
            list.add(UserUtils.getUser());
            new ExportExcel("?", User.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "???" + e.getMessage());
        }
        return "redirect:" + Global.ADMIN_PATH + "/sys/user/?repage";
    }

    @ResponseBody
    @RequiresPermissions("sys:user:edit")
    @RequestMapping(value = "checkLoginName")
    public String checkLoginName(String oldLoginName, String loginName) {
        if (loginName != null && loginName.equals(oldLoginName)) {
            return "true";
        } else if (loginName != null && systemService.getUserByLoginName(loginName) == null) {
            return "true";
        }
        return "false";
    }

    @RequiresUser
    @RequestMapping(value = "info")
    public String info(User user, Model model) {
        User currentUser = UserUtils.getUser();
        if (StringUtils.isNotBlank(user.getName())) {
            currentUser.setEmail(user.getEmail());
            currentUser.setPhone(user.getPhone());
            currentUser.setMobile(user.getMobile());
            currentUser.setRemarks(user.getRemarks());
            systemService.saveUser(currentUser);
            currentUser = UserUtils.getUser();
            model.addAttribute("message", "???");
        }
        model.addAttribute("user", currentUser);
        return "modules/sys/userInfo";
    }

    @RequiresUser
    @RequestMapping(value = "modifyPwd")
    public String modifyPwd(String oldPassword, String newPassword, Model model) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) {
            if (SystemService.validatePassword(oldPassword, user.getPassword())) {
                systemService.updatePasswordById(user.getId(), user.getLoginName(), newPassword);
                model.addAttribute("message", "??");
            } else {
                model.addAttribute("message", "??");
            }
        }
        model.addAttribute("user", user);
        return "modules/sys/userModifyPwd";
    }

    //   @InitBinder
    //   public void initBinder(WebDataBinder b) {
    //      b.registerCustomEditor(List.class, "roleList", new PropertyEditorSupport(){
    //         @Autowired
    //         private SystemService systemService;
    //         @Override
    //         public void setAsText(String text) throws IllegalArgumentException {
    //            String[] ids = StringUtils.split(text, ",");
    //            List<Role> roles = new ArrayList<Role>();
    //            for (String id : ids) {
    //               Role role = systemService.getRole(Long.valueOf(id));
    //               roles.add(role);
    //            }
    //            setValue(roles);
    //         }
    //         @Override
    //         public String getAsText() {
    //            return Collections3.extractToString((List) getValue(), "id", ",");
    //         }
    //      });
    //   }
}