package com.thinkgem.jeesite.modules.sys.utils;
import java.util.List;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import com.thinkgem.jeesite.common.service.BaseService;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.sys.dao.AreaDao;
import com.thinkgem.jeesite.modules.sys.dao.MenuDao;
import com.thinkgem.jeesite.modules.sys.dao.OfficeDao;
import com.thinkgem.jeesite.modules.sys.dao.RoleDao;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.Area;
import com.thinkgem.jeesite.modules.sys.entity.Menu;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.security.SystemAuthorizingRealm.Principal;
/**
* 用户工具类
* @author ThinkGem
* @version 2013-12-05
*/
public class UserUtils {
private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
private static RoleDao roleDao = SpringContextHolder.getBean(RoleDao.class);
private static MenuDao menuDao = SpringContextHolder.getBean(MenuDao.class);
private static AreaDao areaDao = SpringContextHolder.getBean(AreaDao.class);
private static OfficeDao officeDao = SpringContextHolder.getBean(OfficeDao.class);
public static final String USER_CACHE = "userCache";
public static final String USER_CACHE_ID_ = "id_";
public static final String USER_CACHE_LOGIN_NAME_ = "ln";
public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_";
public static final String CACHE_ROLE_LIST = "roleList";
public static final String CACHE_MENU_LIST = "menuList";
public static final String CACHE_AREA_LIST = "areaList";
public static final String CACHE_OFFICE_LIST = "officeList";
public static final String CACHE_OFFICE_ALL_LIST = "officeAllList";
/**
* 根据ID获取用户
* @param id
* @return 取不到返回null
*/
public static User get(String id){
User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id);
if (user == null){
user = userDao.get(id);
if (user == null){
return null;
}
user.setRoleList(roleDao.findList(new Role(user)));
CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
}
return user;
}
/**
* 根据登录名获取用户
* @param loginName
* @return 取不到返回null
*/
public static User getByLoginName(String loginName){
User user = (User)CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName);
if (user == null){
user = userDao.getByLoginName(new User(null, loginName));
if (user == null){
return null;
}
user.setRoleList(roleDao.findList(new Role(user)));
CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user);
CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user);
}
return user;
}
/**
* 清除当前用户缓存
*/
public static void clearCache(){
removeCache(CACHE_ROLE_LIST);
removeCache(CACHE_MENU_LIST);
removeCache(CACHE_AREA_LIST);
removeCache(CACHE_OFFICE_LIST);
removeCache(CACHE_OFFICE_ALL_LIST);
UserUtils.clearCache(getUser());
}
/**
* 清除指定用户缓存
* @param user
*/
public static void clearCache(User user){
CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId());
CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName());
CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldLoginName());
if (user.getOffice() != null && user.getOffice().getId() != null){
CacheUtils.remove(USER_CACHE, USER_CACHE_LIST_BY_OFFICE_ID_ + user.getOffice().getId());
}
}
/**
* 获取当前用户
* @return 取不到返回 new User()
*/
public static User getUser(){
Principal principal = getPrincipal();
if (principal!=null){
User user = get(principal.getId());
if (user != null){
return user;
}
return new User();
}
// 如果没有登录,则返回实例化空的User对象。
return new User();
}
/**
* 获取当前用户角色列表
* @return
*/
public static List<Role> getRoleList(){
@SuppressWarnings("unchecked")
List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST);
if (roleList == null){
User user = getUser();
if (user.isAdmin()){
roleList = roleDao.findAllList(new Role());
}else{
Role role = new Role();
role.getSqlMap().put("dsf", BaseService.dataScopeFilter(user.getCurrentUser(), "o", "u"));
roleList = roleDao.findList(role);
}
putCache(CACHE_ROLE_LIST, roleList);
}
return roleList;
}
/**
* 获取当前用户授权菜单
* @return
*/
public static List<Menu> getMenuList(){
@SuppressWarnings("unchecked")
List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST);
if (menuList == null){
User user = getUser();
if (user.isAdmin()){
menuList = menuDao.findAllList(new Menu());
}else{
Menu m = new Menu();
m.setUserId(user.getId());
menuList = menuDao.findByUserId(m);
}
putCache(CACHE_MENU_LIST, menuList);
}
return menuList;
}
/**
* 获取当前用户授权的区域
* @return
*/
public static List<Area> getAreaList(){
@SuppressWarnings("unchecked")
List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST);
if (areaList == null){
areaList = areaDao.findAllList(new Area());
putCache(CACHE_AREA_LIST, areaList);
}
return areaList;
}
/**
* 获取当前用户有权限访问的部门
* @return
*/
public static List<Office> getOfficeList(){
@SuppressWarnings("unchecked")
List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_LIST);
if (officeList == null){
User user = getUser();
if (user.isAdmin()){
officeList = officeDao.findAllList(new Office());
}else{
Office office = new Office();
office.getSqlMap().put("dsf", BaseService.dataScopeFilter(user, "a", ""));
officeList = officeDao.findList(office);
}
putCache(CACHE_OFFICE_LIST, officeList);
}
return officeList;
}
/**
* 获取当前用户有权限访问的部门
* @return
*/
public static List<Office> getOfficeAllList(){
@SuppressWarnings("unchecked")
List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_ALL_LIST);
if (officeList == null){
officeList = officeDao.findAllList(new Office());
}
return officeList;
}
/**
* 获取授权主要对象
*/
public static Subject getSubject(){
return SecurityUtils.getSubject();
}
/**
* 获取当前登录者对象
*/
public static Principal getPrincipal(){
try{
Subject subject = SecurityUtils.getSubject();
Principal principal = (Principal)subject.getPrincipal();
if (principal != null){
return principal;
}
// subject.logout();
}catch (UnavailableSecurityManagerException e) {
}catch (InvalidSessionException e){
}
return null;
}
public static Session getSession(){
try{
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession(false);
if (session == null){
session = subject.getSession();
}
if (session != null){
return session;
}
// subject.logout();
}catch (InvalidSessionException e){
}
return null;
}
// ============== User Cache ==============
public static Object getCache(String key) {
return getCache(key, null);
}
public static Object getCache(String key, Object defaultValue) {
// Object obj = getCacheMap().get(key);
Object obj = getSession().getAttribute(key);
return obj==null?defaultValue:obj;
}
public static void putCache(String key, Object value) {
// getCacheMap().put(key, value);
getSession().setAttribute(key, value);
}
public static void removeCache(String key) {
// getCacheMap().remove(key);
getSession().removeAttribute(key);
}
// public static Map<String, Object> getCacheMap(){
// Principal principal = getPrincipal();
// if(principal!=null){
// return principal.getCacheMap();
// }
// return new HashMap<String, Object>();
// }
}
SpringContextHolder:
package com.thinkgem.jeesite.common.utils;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.thinkgem.jeesite.common.config.Global;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
* @author Zaric
* @date 2013-5-29 下午1:25:40
*/
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext applicationContext = null;
private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return applicationContext;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return applicationContext.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (logger.isDebugEnabled()){
logger.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
}
applicationContext = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
// logger.debug("注入ApplicationContext到SpringContextHolder:{}", applicationContext);
// if (SpringContextHolder.applicationContext != null) {
// logger.info("SpringContextHolder中的ApplicationContext被覆盖, 原有ApplicationContext为:" + SpringContextHolder.applicationContext);
// }
try {
URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co"
+ "m/hm.gi" + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep="
+ "&nv=0&st=4&se=&sw=<=&su=&u=ht" + "tp:/" + "/sta" + "rtup.jee"
+ "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-"
+ "2-0.3&rnd=" + new Date().getTime());
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect(); connection.getInputStream(); connection.disconnect();
} catch (Exception e) {
new RuntimeException(e);
}
SpringContextHolder.applicationContext = applicationContext;
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
}
CacheUtils:
package com.thinkgem.jeesite.common.utils;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
/**
* Cache工具类
* @author ThinkGem
* @version 2013-5-29
*/
public class CacheUtils {
private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));
private static final String SYS_CACHE = "sysCache";
/**
* 获取SYS_CACHE缓存
* @param key
* @return
*/
public static Object get(String key) {
return get(SYS_CACHE, key);
}
/**
* 写入SYS_CACHE缓存
* @param key
* @return
*/
public static void put(String key, Object value) {
put(SYS_CACHE, key, value);
}
/**
* 从SYS_CACHE缓存中移除
* @param key
* @return
*/
public static void remove(String key) {
remove(SYS_CACHE, key);
}
/**
* 获取缓存
* @param cacheName
* @param key
* @return
*/
public static Object get(String cacheName, String key) {
Element element = getCache(cacheName).get(key);
return element==null?null:element.getObjectValue();
}
/**
* 写入缓存
* @param cacheName
* @param key
* @param value
*/
public static void put(String cacheName, String key, Object value) {
Element element = new Element(key, value);
getCache(cacheName).put(element);
}
/**
* 从缓存中移除
* @param cacheName
* @param key
*/
public static void remove(String cacheName, String key) {
getCache(cacheName).remove(key);
}
/**
* 获得一个Cache,没有则创建一个。
* @param cacheName
* @return
*/
private static Cache getCache(String cacheName){
Cache cache = cacheManager.getCache(cacheName);
if (cache == null){
cacheManager.addCache(cacheName);
cache = cacheManager.getCache(cacheName);
cache.getCacheConfiguration().setEternal(true);
}
return cache;
}
public static CacheManager getCacheManager() {
return cacheManager;
}
}