com.eryansky.web.base.UserAction.java Source code

Java tutorial

Introduction

Here is the source code for com.eryansky.web.base.UserAction.java

Source

/**
 *  Copyright (c) 2012-2014 http://www.eryansky.com
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.eryansky.web.base;

import com.eryansky.common.model.Combobox;
import com.eryansky.common.model.Datagrid;
import com.eryansky.common.model.Result;
import com.eryansky.common.model.TreeNode;
import com.eryansky.common.orm.Page;
import com.eryansky.common.orm.PropertyFilter;
import com.eryansky.common.orm.entity.StatusState;
import com.eryansky.common.orm.hibernate.EntityManager;
import com.eryansky.common.utils.StringUtils;
import com.eryansky.common.utils.collections.Collections3;
import com.eryansky.common.utils.encode.Encrypt;
import com.eryansky.common.utils.mapper.JsonMapper;
import com.eryansky.common.web.struts2.StrutsAction;
import com.eryansky.common.web.struts2.utils.Struts2Utils;
import com.eryansky.entity.base.Organ;
import com.eryansky.entity.base.Resource;
import com.eryansky.entity.base.Role;
import com.eryansky.entity.base.User;
import com.eryansky.entity.base.state.SexType;
import com.eryansky.service.base.OrganManager;
import com.eryansky.service.base.ResourceManager;
import com.eryansky.service.base.RoleManager;
import com.eryansky.service.base.UserManager;
import com.eryansky.utils.AppConstants;
import com.eryansky.utils.SelectType;
import com.google.common.collect.Lists;
import org.apache.commons.lang.ArrayUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import javax.transaction.SystemException;
import java.util.List;

/**
 * User? Action.
 * @author &Eryan eryanwcp@gmail.com
 * @date 2013-3-21 ?12:20:13 
 *
 */
@SuppressWarnings("serial")
public class UserAction extends StrutsAction<User> {

    private String upateOperate;// ??? 1: 0:
    private String newPassword;// ?
    /**
     * ? ID
     */
    private Long organId;
    /**
     * ID?
     */
    private List<Long> organIds = Lists.newArrayList();
    /**
     * ? ????
     */
    private String loginNameOrName;
    /**
     * ID
     */
    private Long defaultOrganId;

    @Autowired
    private UserManager userManager;
    @Autowired
    private OrganManager organManager;
    @Autowired
    private RoleManager roleManager;
    @Autowired
    private ResourceManager resourceManager;
    //ID?
    private List<Long> roleIds = Lists.newArrayList();

    //?ID?
    private List<Long> resourceIds = Lists.newArrayList();

    @Override
    public EntityManager<User, Long> getEntityManager() {
        return userManager;
    }

    /**
     * 
     * @return
     * @throws Exception
     */
    public String userDatagrid() throws Exception {
        try {
            Page<User> p = userManager.getUsersByQuery(organId, loginNameOrName, page, rows, sort, order);
            Datagrid<User> dg = new Datagrid<User>(p.getTotalCount(), p.getResult());
            Struts2Utils.renderJson(dg);
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    /**
     * combogrid
     * @return
     * @throws Exception
     */
    public String combogridAll() throws Exception {
        try {
            List<PropertyFilter> filters = Lists.newArrayList();
            filters.add(new PropertyFilter("EQI_status", StatusState.normal.getValue().toString()));
            List<User> users = userManager.find(filters, "id", "asc");
            Datagrid<User> dg = new Datagrid<User>(users.size(), users);
            Struts2Utils.renderJson(dg);
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    /**
     * combogrid
     * @return
     * @throws Exception
     */
    public String combogrid() throws Exception {
        try {
            Criterion statusCriterion = Restrictions.eq("status", StatusState.normal.getValue());
            Criterion[] criterions = new Criterion[0];
            criterions = (Criterion[]) ArrayUtils.add(criterions, 0, statusCriterion);
            Criterion criterion = null;
            if (!Collections3.isEmpty(ids)) {
                //in?
                Criterion inCriterion = Restrictions.in("id", ids);

                if (StringUtils.isNotBlank(loginNameOrName)) {
                    Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName,
                            MatchMode.ANYWHERE);
                    Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
                    Criterion criterion1 = Restrictions.or(loginNameCriterion, nameCriterion);
                    criterion = Restrictions.or(inCriterion, criterion1);
                } else {
                    criterion = inCriterion;
                }
                //??
                criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
            } else {
                if (StringUtils.isNotBlank(loginNameOrName)) {
                    Criterion loginNameCriterion = Restrictions.like("loginName", loginNameOrName,
                            MatchMode.ANYWHERE);
                    Criterion nameCriterion = Restrictions.like("name", loginNameOrName, MatchMode.ANYWHERE);
                    criterion = Restrictions.or(loginNameCriterion, nameCriterion);
                    //??
                    criterions = (Criterion[]) ArrayUtils.add(criterions, 0, criterion);
                }
            }

            //
            Page<User> p = new Page<User>(rows);//
            p = userManager.findByCriteria(p, criterions);
            Datagrid<User> dg = new Datagrid<User>(p.getTotalCount(), p.getResult());
            Struts2Utils.renderJson(dg);
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    /**
     * .
     */
    @Override
    public String remove() throws Exception {
        Result result;
        try {
            userManager.deleteByIds(ids);
            result = Result.successResult();
            logger.debug(result.toString());
            Struts2Utils.renderJson(result);
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    /**
    * ?.
    */
    @Override
    public String save() throws Exception {
        Result result = null;
        try {
            // ????
            User user = userManager.getUserByLoginName(model.getLoginName());
            if (user != null && !user.getId().equals(model.getId())) {
                result = new Result(Result.WARN, "??[" + model.getLoginName() + "],!",
                        "loginName");
                logger.debug(result.toString());
                Struts2Utils.renderText(result);
                return null;
            }

            if (model.getId() == null) {// 
                model.setPassword(Encrypt.e(model.getPassword()));
            } else {// 
                User superUser = userManager.getSuperUser();
                User sessionUser = userManager.getCurrentUser();
                if (!sessionUser.getId().equals(superUser.getId())) {
                    throw new SystemException("??!");
                }
            }
            userManager.saveEntity(model);
            result = Result.successResult();
            logger.debug(result.toString());
            Struts2Utils.renderText(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return null;
    }

    /**
     * ??.
     */
    public String password() throws Exception {
        return "password";

    }

    //updateUserPassword()?
    public void prepareUpdateUserPassword() throws Exception {
        model = new User();
        model.setId(super.id);
    }

    /**
     * ?.
     * <br>?upateOperate ??"1" ???"0".
     * @see UserAction.prepareUpdateUserPassword()
     */
    public String updateUserPassword() throws Exception {
        Result result;
        try {
            if (!StringUtils.isEmpty(upateOperate)) {
                User user = userManager.loadById(model.getId());
                if (user != null) {
                    boolean isCheck = true;
                    //??
                    if (AppConstants.USER_UPDATE_PASSWORD_YES.equals(upateOperate)) {
                        String originalPassword = user.getPassword(); //??
                        String pagePassword = model.getPassword(); //??
                        if (!originalPassword.equals(Encrypt.e(pagePassword))) {
                            isCheck = false;
                        }
                    }
                    //???
                    if (AppConstants.USER_UPDATE_PASSWORD_NO.equals(upateOperate)) {
                        isCheck = true;
                    }
                    if (isCheck) {
                        user.setPassword(Encrypt.e(newPassword));
                        userManager.saveEntity(user);
                        result = Result.successResult();
                    } else {
                        result = new Result(Result.WARN, "?.", "password");
                    }
                } else {
                    result = new Result(Result.ERROR, "?.", null);
                }
            } else {
                result = Result.errorResult();
                logger.warn("?,?[upateOperate].");
            }
            logger.debug(result.toString());
            Struts2Utils.renderText(result);
        } catch (Exception e) {
            throw e;
        }
        return null;
    }

    /**
     * ?.
     */
    public String role() throws Exception {
        return "role";
    }

    //updateUserRole()?
    public void prepareUpdateUserRole() throws Exception {
        super.prepareModel();
    }

    /**
     * .
     */
    public void updateUserRole() throws Exception {
        Result result = null;
        try {
            List<Role> rs = Lists.newArrayList();
            for (Long id : roleIds) {
                Role role = roleManager.loadById(id);
                rs.add(role);
            }
            model.setRoles(rs);
            userManager.saveEntity(model);
            result = Result.successResult();
            Struts2Utils.renderText(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * ?.
     */
    public String organ() throws Exception {
        super.prepareModel();
        //?
        List<Combobox> defaultOrganCombobox = Lists.newArrayList();
        if (model.getId() != null) {
            List<Organ> organs = model.getOrgans();
            Combobox combobox;
            if (!Collections3.isEmpty(organs)) {
                for (Organ organ : organs) {
                    combobox = new Combobox(organ.getId().toString(), organ.getName());
                    defaultOrganCombobox.add(combobox);
                }
            }
        }
        String defaultOrganComboboxData = JsonMapper.nonDefaultMapper().toJson(defaultOrganCombobox);
        logger.debug(defaultOrganComboboxData);
        Struts2Utils.getRequest().setAttribute("defaultOrganComboboxData", defaultOrganComboboxData);
        return "organ";
    }

    //updateUserOrgan()?
    public void prepareUpdateUserOrgan() throws Exception {
        super.prepareModel();
    }

    /**
     * .
     */
    public void updateUserOrgan() throws Exception {
        Result result = null;
        try {
            //
            model.setOrgans(null);
            List<Organ> organs = Lists.newArrayList();
            for (Long organId : organIds) {
                Organ organ = organManager.loadById(organId);
                organs.add(organ);
            }
            model.setOrgans(organs);

            //
            model.setDefaultOrgan(null);
            Organ defaultOrgan = null;
            if (defaultOrganId != null) {
                defaultOrgan = organManager.loadById(model.getDefaultOrganId());
            }
            model.setDefaultOrgan(defaultOrgan);

            userManager.saveEntity(model);
            result = Result.successResult();
            Struts2Utils.renderText(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * ??.
     */
    public String resource() throws Exception {
        List<TreeNode> treeNodes = Lists.newArrayList();
        try {
            treeNodes = resourceManager.getResourceTree(null, true);
            String resourceComboboxData = JsonMapper.nonDefaultMapper().toJson(treeNodes);
            logger.debug(resourceComboboxData);
            Struts2Utils.getRequest().setAttribute("resourceComboboxData", resourceComboboxData);
        } catch (Exception e) {
            throw e;
        }
        return "resource";
    }

    //updateUserResource()?
    public void prepareUpdateUserResource() throws Exception {
        super.prepareModel();
    }

    /**
     * ?.
     */
    public void updateUserResource() throws Exception {
        Result result = null;
        try {
            List<Resource> rs = Lists.newArrayList();
            for (Long id : resourceIds) {
                Resource resource = resourceManager.loadById(id);
                rs.add(resource);
            }
            model.setResources(rs);
            userManager.saveEntity(model);
            result = Result.successResult();
            Struts2Utils.renderText(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }

    }

    /**
     * 
     * @throws Exception
     */
    public void sexTypeCombobox() throws Exception {
        try {
            List<Combobox> cList = Lists.newArrayList();

            //combobox  "------"?"------"
            if (!StringUtils.isBlank(selectType)) {
                SelectType s = SelectType.getSelectTypeValue(selectType);
                if (s != null) {
                    Combobox selectCombobox = new Combobox("", s.getDescription());
                    cList.add(selectCombobox);
                }
            }
            SexType[] _enums = SexType.values();
            for (int i = 0; i < _enums.length; i++) {
                Combobox combobox = new Combobox(_enums[i].getValue().toString(), _enums[i].getDescription());
                cList.add(combobox);
            }
            Struts2Utils.renderJson(cList);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public void setNewPassword(String newPassword) {
        this.newPassword = newPassword;
    }

    public void setUpateOperate(String upateOperate) {
        this.upateOperate = upateOperate;
    }

    public void setRoleIds(List<Long> roleIds) {
        this.roleIds = roleIds;
    }

    public void setResourceIds(List<Long> resourceIds) {
        this.resourceIds = resourceIds;
    }

    public void setOrganId(Long organId) {
        this.organId = organId;
    }

    public void setLoginNameOrName(String loginNameOrName) {
        this.loginNameOrName = loginNameOrName;
    }

    public void setDefaultOrganId(Long defaultOrganId) {
        this.defaultOrganId = defaultOrganId;
    }

    public void setOrganIds(List<Long> organIds) {
        this.organIds = organIds;
    }
}