com.lushapp.modules.sys.service.UserManager.java Source code

Java tutorial

Introduction

Here is the source code for com.lushapp.modules.sys.service.UserManager.java

Source

/**
 *  Copyright (c) 2014 http://www.lushapp.wang
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.lushapp.modules.sys.service;

import com.google.common.collect.Lists;
import com.lushapp.common.exception.DaoException;
import com.lushapp.common.exception.ServiceException;
import com.lushapp.common.exception.SystemException;
import com.lushapp.common.orm.Page;
import com.lushapp.common.orm.PropertyFilter;
import com.lushapp.common.orm.entity.StatusState;
import com.lushapp.common.orm.hibernate.EntityManager;
import com.lushapp.common.orm.hibernate.HibernateDao;
import com.lushapp.common.utils.StringUtils;
import com.lushapp.common.utils.collections.Collections3;
import com.lushapp.core.security.SecurityUtils;
import com.lushapp.core.security.SessionInfo;
import com.lushapp.modules.sys.entity.Organ;
import com.lushapp.modules.sys.entity.Role;
import com.lushapp.modules.sys.entity.User;
import com.lushapp.utils.CacheConstants;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * ?User Service.
 * @author honey.zhao@aliyun.com  
 * @date 2014-10-20 ?11:22:13 
 *
 */
@Service
public class UserManager extends EntityManager<User, Long> {

    private HibernateDao<User, Long> userDao;

    @Autowired
    private OrganManager organManager;
    @Autowired
    private RoleManager roleManager;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        userDao = new HibernateDao<User, Long>(sessionFactory, User.class);
    }

    @Override
    protected HibernateDao<User, Long> getEntityDao() {
        return userDao;
    }

    /**
     * .
     * <br> ???? ??.
     */
    @CacheEvict(value = { CacheConstants.ROLE_ALL_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE,
            CacheConstants.RESOURCE_USER_MENU_TREE_CACHE,
            CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE }, allEntries = true)
    public void saveOrUpdate(User entity) throws DaoException, SystemException, ServiceException {
        logger.debug(":{}",
                CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + ","
                        + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE + ","
                        + CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE);
        userDao.saveOrUpdate(entity);
    }

    /**
     * .
     * <br> ???? ??.
     */
    @CacheEvict(value = { CacheConstants.ROLE_ALL_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE,
            CacheConstants.RESOURCE_USER_MENU_TREE_CACHE,
            CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE }, allEntries = true)
    public void merge(User entity) throws DaoException, SystemException, ServiceException {
        logger.debug(":{}",
                CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + ","
                        + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE + ","
                        + CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE);
        userDao.merge(entity);
    }

    /**
     * .
     * <br> ???? ??.
     */
    @CacheEvict(value = { CacheConstants.ROLE_ALL_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE,
            CacheConstants.RESOURCE_USER_MENU_TREE_CACHE,
            CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE }, allEntries = true)
    @Override
    public void saveEntity(User entity) throws DaoException, SystemException, ServiceException {
        logger.debug(":{}",
                CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + ","
                        + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE + ","
                        + CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE);
        super.saveEntity(entity);
    }

    /**
    * .
    */
    @CacheEvict(value = { CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE,
            CacheConstants.RESOURCE_USER_MENU_TREE_CACHE,
            CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE }, allEntries = true)
    public void deleteByIds(List<Long> ids) throws DaoException, SystemException, ServiceException {
        logger.debug(":{}",
                CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + ","
                        + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE + ","
                        + CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE);
        if (!Collections3.isEmpty(ids)) {
            for (Long id : ids) {
                User superUser = this.getSuperUser();
                if (id.equals(superUser.getId())) {
                    throw new SystemException("??!");
                }
                User user = userDao.get(id);
                if (user != null) {
                    //?
                    user.setDefaultOrgan(null);
                    user.setOrgans(null);
                    user.setRoles(null);
                    user.setResources(null);
                    //
                    //?(? ?)
                    //               user.setStatus(StatusState.delete.getValue());
                    //? ?
                    userDao.delete(user);
                }
            }
        } else {
            logger.warn("?[ids].");
        }
    }

    /**
     * ?.
     * @return
     * @throws com.lushapp.common.exception.DaoException
     * @throws com.lushapp.common.exception.SystemException
     * @throws com.lushapp.common.exception.ServiceException
     */
    public User getCurrentUser() throws DaoException, SystemException, ServiceException {
        SessionInfo sessionInfo = SecurityUtils.getCurrentSessionInfo();
        User user = getEntityDao().load(sessionInfo.getUserId());
        return user;
    }

    /**
     * .
     *
     * @return
     * @throws com.lushapp.common.exception.DaoException
     * @throws com.lushapp.common.exception.SystemException
     * @throws com.lushapp.common.exception.ServiceException
     */
    public User getSuperUser() throws DaoException, SystemException, ServiceException {
        User superUser = userDao.load(1l);//ID1
        if (superUser == null) {
            throw new SystemException(".");
        }
        return superUser;
    }

    /**
     * ?????.
     * <br/>
     * @param loginName
     *            ??
     * @param password
     *            ?
     * @return
     * @throws com.lushapp.common.exception.DaoException
     * @throws com.lushapp.common.exception.SystemException
     * @throws com.lushapp.common.exception.ServiceException
     */
    @SuppressWarnings("unchecked")
    public User getUserByLP(String loginName, String password)
            throws DaoException, SystemException, ServiceException {
        Assert.notNull(loginName, "?[loginName]!");
        Assert.notNull(password, "?[password]!");
        List<User> list = userDao
                .createQuery("from User u where u.loginName = ? and u.password = ? and u.status <> ?",
                        new Object[] { loginName, password, StatusState.delete.getValue() })
                .list();
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * ?ID.
     *
     * @param roleids
     * @return
     * @throws com.lushapp.common.exception.DaoException
     * @throws com.lushapp.common.exception.SystemException
     * @throws com.lushapp.common.exception.ServiceException
     */
    @SuppressWarnings("unchecked")
    public List<User> getRoleIds(String roleids) throws DaoException, SystemException, ServiceException {
        StringBuffer sb = new StringBuffer();
        sb.append("from User u where u.roleids ");
        List<User> list = new ArrayList<User>();
        if (roleids == null) {
            sb.append(" is null order by u.id asc");
            list = userDao.createQuery(sb.toString()).list();
        } else {
            sb.append(" = ? order by u.id asc");
            list = userDao.createQuery(sb.toString(), new Object[] { roleids }).list();
        }
        return list;
    }

    /**
     * ???.
     * <br>
     * @param loginName ??
     * @return
     * @throws com.lushapp.common.exception.DaoException
     * @throws com.lushapp.common.exception.SystemException
     * @throws com.lushapp.common.exception.ServiceException
     */
    @SuppressWarnings("unchecked")
    public User getUserByLoginName(String loginName) throws DaoException, SystemException, ServiceException {
        Assert.notNull(loginName, "?[loginName]!");
        Assert.notNull(loginName, "?[status]!");
        List<User> list = userDao.createQuery("from User u where u.loginName = ? and u.status <> ?",
                new Object[] { loginName, StatusState.delete.getValue() }).list();
        return list.isEmpty() ? null : list.get(0);
    }

    /**
     * ?
     * @return
     */
    public List<User> getAllNormal() {
        List<PropertyFilter> filters = Lists.newArrayList();
        filters.add(new PropertyFilter("EQI_status", StatusState.normal.getValue().toString()));
        return getEntityDao().find(filters, "id", "asc");
    }

    /**
     * ?Id?????
     * @param organId ID
     * @param loginNameOrName ????
     * @param page 
     * @param rows ?
     * @param sort ?
     * @param order ?? ?:'asc',??:'desc'
     * @return
     */
    public Page<User> getUsersByQuery(Long organId, String loginNameOrName, int page, int rows, String sort,
            String order) {
        //??
        if (organId == null && StringUtils.isBlank(loginNameOrName)) {
            return super.find(page, rows, null, null, new ArrayList<PropertyFilter>());
        }
        List<Object> params = Lists.newArrayList();
        StringBuilder hql = new StringBuilder();
        hql.append("from User u where u.status <> ? ");
        params.add(StatusState.delete.getValue());
        if (organId != null) {
            Organ organ = organManager.loadById(organId);
            hql.append("and ? in elements(u.organs) ");
            params.add(organ);
        }
        if (StringUtils.isNotBlank(loginNameOrName)) {
            hql.append("and (u.loginName like ? or u.name like ?) ");
            params.add("%" + loginNameOrName + "%");
            params.add("%" + loginNameOrName + "%");
        }
        //
        Page<User> p = new Page<User>(rows);
        p.setPageNo(page);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            p.setOrder(order);
            p.setOrderBy(sort);
        } else {
            p.setOrder(Page.ASC);
            p.setOrderBy("id");
        }
        logger.debug(hql.toString());
        Page<User> userPage = userDao.findPage(p, hql.toString(), params.toArray());
        return userPage;
    }

    /**
     * ?Id?????
     * @param inUserIds id?
     * @param loginNameOrName ????
     * @param page 
     * @param rows ?
     * @param sort ?
     * @param order ?? ?:'asc',??:'desc'
     * @return
     */
    public Page<User> getUsersByQuery(List<Long> inUserIds, String loginNameOrName, int page, int rows, String sort,
            String order) {
        List<Object> params = Lists.newArrayList();
        StringBuilder hql = new StringBuilder();
        hql.append("from User u where 1=1 ");
        if (!Collections3.isEmpty(inUserIds)) {
            hql.append("and (u.id in (:ids) ");
            if (StringUtils.isNotBlank(loginNameOrName)) {
                hql.append("or u.loginName like ? or u.name like ? ) ");
                params.add("%" + loginNameOrName + "%");
                params.add("%" + loginNameOrName + "%");
            }
        } else {
            if (StringUtils.isNotBlank(loginNameOrName)) {
                hql.append("and (u.loginName like ? or u.name like ?) ");
                params.add("%" + loginNameOrName + "%");
                params.add("%" + loginNameOrName + "%");
            }
        }

        hql.append("and u.status = ? ");
        params.add(StatusState.normal.getValue());
        //
        Page<User> p = new Page<User>(rows);
        p.setPageNo(page);
        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            p.setOrder(order);
            p.setOrderBy(sort);
        } else {
            p.setOrder(Page.ASC);
            p.setOrderBy("id");
        }
        Query q = userDao.createQuery(hql.toString(), params.toArray());
        if (!Collections3.isEmpty(inUserIds)) {
            q.setParameterList("ids", inUserIds);
        }

        if (p.isAutoCount()) {
            long totalCount = getEntityDao().countHqlResult(hql.toString(), params.toArray());
            p.setTotalCount(totalCount);
        }

        getEntityDao().setPageParameterToQuery(q, p);

        List result = q.list();
        p.setResult(result);
        return p;
    }

    /**
     *
     * @param organId ID
     * @param roleId ID
     * @param loginNameOrName ????
     * @param sort
     * @param order
     * @return
     */
    public List<User> getUsersByOrgOrRole(Long organId, Long roleId, String loginNameOrName, String sort,
            String order) {
        List<Object> params = Lists.newArrayList();
        StringBuilder hql = new StringBuilder();
        hql.append("from User u where u.status = ? ");
        params.add(StatusState.normal.getValue());
        if (organId != null) {
            Organ organ = organManager.loadById(organId);
            hql.append("and ? in elements(u.organs) ");
            params.add(organ);
        }
        if (roleId != null) {
            Role role = roleManager.loadById(roleId);
            hql.append("and ? in elements(u.roles) ");
            params.add(role);
        }
        if (StringUtils.isNotBlank(loginNameOrName)) {
            hql.append("and  (u.name like ? or loginName like ?) ");
            params.add("%" + loginNameOrName + "%");
            params.add("%" + loginNameOrName + "%");
        }
        List<User> users = userDao.find(hql.toString(), params.toArray());
        return users;
    }

    /**
     * ?
     * @param organId
     * @return
     */
    public List<User> getUsersByOrganId(Long organId) {
        Assert.notNull(organId, "?[organId]!");
        Organ organ = organManager.loadById(organId);
        if (organ == null) {
            throw new ServiceException("[" + organId + "]?.");
        }
        List<User> users = organ.getUsers();
        return users;
    }
}