Java tutorial
/** * Copyright (c) 2012-2014 http://www.eryansky.com * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.eryansky.modules.sys.service; import com.eryansky.common.exception.DaoException; import com.eryansky.common.exception.ServiceException; import com.eryansky.common.exception.SystemException; import com.eryansky.common.model.Menu; import com.eryansky.common.model.TreeNode; import com.eryansky.common.orm.entity.StatusState; import com.eryansky.common.orm.hibernate.EntityManager; import com.eryansky.common.orm.hibernate.HibernateDao; import com.eryansky.common.orm.hibernate.Parameter; import com.eryansky.common.utils.StringUtils; import com.eryansky.common.utils.collections.Collections3; import com.eryansky.core.security.SecurityUtils; import com.eryansky.modules.sys._enum.ResourceType; import com.eryansky.modules.sys.entity.Resource; import com.eryansky.utils.CacheConstants; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.apache.commons.lang3.Validate; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import java.util.*; /** * ?Resource? Service. * <br>? ??? * @author &Eryan eryanwcp@gmail.com * @date 2012-10-11 ?4:26:46 */ @Service public class ResourceManager extends EntityManager<Resource, String> { @Autowired private UserManager userManager; private HibernateDao<Resource, String> resourceDao;// DAO???. /** * sessionFactory?DAO???. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { resourceDao = new HibernateDao<Resource, String>(sessionFactory, Resource.class); } @Override protected HibernateDao<Resource, String> getEntityDao() { return resourceDao; } /** * ?. */ // @CacheEvict(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE, CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }, allEntries = true) public void saveOrUpdate(Resource entity) throws DaoException, SystemException, ServiceException { logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + "," + CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + "," + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE); Assert.notNull(entity, "?[entity]!"); resourceDao.saveOrUpdate(entity); } /** * ?. */ // @CacheEvict(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE, CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }, allEntries = true) public void merge(Resource entity) throws DaoException, SystemException, ServiceException { logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + "," + CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + "," + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE); Assert.notNull(entity, "?[entity]!"); resourceDao.merge(entity); } @CacheEvict(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE, CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }, allEntries = true) @Override public void saveEntity(Resource entity) throws DaoException, SystemException, ServiceException { logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + "," + CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + "," + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE); super.saveEntity(entity); } /** * ??. * <br/>??? ??? * @param entity ? * @throws DaoException * @throws SystemException * @throws ServiceException */ @CacheEvict(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE, CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }, allEntries = true) public void saveResource(Resource entity) throws DaoException, SystemException, ServiceException { logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + "," + CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + "," + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE); Assert.notNull(entity, "?[entity]!"); this.saveEntity(entity); if (entity.getType() != null && ResourceType.function.getValue().equals(entity.getType())) { List<Resource> ownerAndChilds = this.findOwnerAndChilds(entity.getId()); Iterator<Resource> iterator = ownerAndChilds.iterator(); while (iterator.hasNext()) { Resource subResource = iterator.next(); subResource.setType(ResourceType.function.getValue()); this.update(subResource); } } } /** * . */ // @CacheEvict(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE, CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE, CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }, allEntries = true) public void deleteByIds(List<String> ids) throws DaoException, SystemException, ServiceException { logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + "," + CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + "," + CacheConstants.RESOURCE_USER_MENU_TREE_CACHE); if (!Collections3.isEmpty(ids)) { for (String id : ids) { Resource resource = getEntityDao().load(id); resource.setRoles(null); resource.setUsers(null); this.delete(resource); } } else { logger.warn("?[ids]."); } } /** * ?? * @param id * @return */ public List<Resource> findOwnerAndChilds(String id) { return this.findOwnerAndChilds(id, null); } /** * ??? * @param id * @param resourceTypes ? null, {@link ResourceType} * @return */ public List<Resource> findOwnerAndChilds(String id, List<Integer> resourceTypes) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), id); Resource resource = this.loadById(id); StringBuilder hql = new StringBuilder(); hql.append("from Resource r where r.status = :p1 and (r.id = :p2 "); if (resource != null) { hql.append(" or r.parentIds like :parentIds "); parameter.put("parentIds", "%," + id + ",%"); } hql.append(" ) "); if (resourceTypes != null) { hql.append(" and r.type in (:resourceTypes)"); parameter.put("resourceTypes", resourceTypes); } hql.append(" order by r.orderNo asc"); List<Resource> list = getEntityDao().find(hql.toString(), parameter); return list; } /** * ?? * @param id * @return */ public List<Resource> findChilds(String id) { return this.findChilds(id, null); } /** * ? ? * @param id ID * @param status null :StatusState.NORMAL.getValue() {@link StatusState} * @return */ public List<Resource> findChilds(String id, String status) { // if (status == null) { status = StatusState.NORMAL.getValue(); } StringBuilder sb = new StringBuilder(); Parameter parameter = new Parameter(); sb.append("from Resource r where r.status = :status "); parameter.put("status", status); sb.append(" and r.parent"); if (id == null) { sb.append(" is null "); } else { sb.append(".id = :parentId "); parameter.put("parentId", id); } sb.append(" order by r.orderNo asc"); List<Resource> list = getEntityDao().find(sb.toString(), parameter); return list; } /** * ???? * @param resourceCode ?? * @return */ public Resource getByCode(String resourceCode) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), resourceCode); StringBuffer hql = new StringBuffer(); hql.append("from Resource r where r.status = :p1 and r.code = :p2 "); Query query = getEntityDao().createQuery(hql.toString(), parameter); query.setMaxResults(1); List<Resource> list = query.list(); return list.isEmpty() ? null : list.get(0); } /** * ??? * @param userId ID * @return */ public List<Resource> findAppAndMenuResourcesByUserId(String userId) { List<Integer> resourceTypes = Lists.newArrayList(); resourceTypes.add(ResourceType.app.getValue()); resourceTypes.add(ResourceType.menu.getValue()); return findResourcesByUserId(userId, resourceTypes); } /** * ??? * @param userId ID * @return */ public List<Resource> findAppResourcesByUserId(String userId) { List<Integer> resourceTypes = Lists.newArrayList(); resourceTypes.add(ResourceType.app.getValue()); return findResourcesByUserId(userId, resourceTypes); } /** * ??? * @param userId ID * @return */ public List<Resource> findMenuResourcesByUserId(String userId) { List<Integer> resourceTypes = Lists.newArrayList(); resourceTypes.add(ResourceType.menu.getValue()); return findResourcesByUserId(userId, resourceTypes); } /** * ? * @param userId ID * @return */ public List<Resource> findResourcesByUserId(String userId) { return findResourcesByUserId(userId, null); } /** * ? * @param userId ID * @param resourceTypes ? null, {@link ResourceType} * @return */ public List<Resource> findResourcesByUserId(String userId, List<Integer> resourceTypes) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), userId); StringBuffer hql = new StringBuffer(); hql.append("select r from Resource r left join r.users u where r.status = :p1 and u.id = :p2 "); if (resourceTypes != null) { hql.append(" and r.type in (:resourceTypes)"); parameter.put("resourceTypes", resourceTypes); } hql.append(" or r.id in ("); hql.append( "select urrs.id from User u left join u.roles urs left join urs.resources urrs where urrs.status = :p1 and u.id = :p2 "); if (resourceTypes != null) { hql.append(" and urrs.type in (:resourceTypes)"); parameter.put("resourceTypes", resourceTypes); } hql.append(" order by urrs.orderNo asc"); hql.append(" )"); hql.append(" order by r.orderNo asc"); Query query = getEntityDao().distinct(getEntityDao().createQuery(hql.toString(), parameter)); List<Resource> list = query.list(); // Collections.sort(list, new Comparator<Resource>() { // @Override // public int compare(Resource o1, Resource o2) { // if (o1.getOrderNo() != null && o2.getOrderNo() != null) { // return o1.getOrderNo().compareTo(o2.getOrderNo()); // } // return 0; // } // }); return list; } /** * ?? ?? * @param userId ID * @return */ @Cacheable(value = { CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }) public List<TreeNode> findNavTreeNodeWithPermissions(String userId) { List<Resource> list = null; if (SecurityUtils.isUserAdmin(userId)) {// list = this.findAppAndMenuResources(); } else { list = this.findAppAndMenuResourcesByUserId(userId); } logger.debug(":{}", CacheConstants.RESOURCE_USER_MENU_TREE_CACHE + " ?userId=" + userId); return resourcesToTreeNode(list); } /** * ?? * @param userId ID * @return */ public List<Menu> findNavMenuWithPermissions(String userId) { List<Resource> list = null; if (SecurityUtils.isUserAdmin(userId)) {// list = this.findAppAndMenuResources(); } else { list = this.findAppAndMenuResourcesByUserId(userId); } return resourcesToMenu(list); } /** * ?ID???? * @param userId ID * @return */ @Cacheable(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE }) public List<TreeNode> findTreeNodeResourcesWithPermissions(String userId) { List<Resource> list = null; if (SecurityUtils.isUserAdmin(userId)) {// list = this.findResources(null); } else { list = this.findResourcesByUserId(userId, null); } logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + " ?userId=" + userId); return resourcesToTreeNode(list); } /** * ? ?? * @param userId ID * @return */ public List<Resource> findAppResourcesWithPermissions(String userId) { List<Resource> list = null; if (SecurityUtils.isUserAdmin(userId)) {// list = this.findAppResources(); } else { list = this.findAppResourcesByUserId(userId); } return list; } /** * ??? * @return */ public List<Resource> findAppAndMenuResources() { List<Integer> resourceTypes = Lists.newArrayList(); resourceTypes.add(ResourceType.app.getValue()); resourceTypes.add(ResourceType.menu.getValue()); return findResources(resourceTypes); } /** * ??? * @return */ public List<Resource> findAppResources() { List<Integer> resourceTypes = Lists.newArrayList(); resourceTypes.add(ResourceType.app.getValue()); return findResources(resourceTypes); } /** * ??? * @return */ public List<Resource> findMenuResources() { List<Integer> resourceTypes = Lists.newArrayList(); resourceTypes.add(ResourceType.menu.getValue()); return findResources(resourceTypes); } /** * ? * @return */ public List<Resource> findResources() { return findResources(null, null); } /** * ? * @param resourceTypes ? null, {@link ResourceType} * @return */ public List<Resource> findResources(List<Integer> resourceTypes) { return findResources(resourceTypes, null); } /** * ? * @param resourceTypes ? null, {@link ResourceType} * @param excludeResourceId ?ID * @return */ public List<Resource> findResources(List<Integer> resourceTypes, String excludeResourceId) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue()); StringBuffer hql = new StringBuffer(); hql.append("from Resource r where r.status = :p1 "); if (excludeResourceId != null) { hql.append(" and r.id <> :excludeReourceId"); parameter.put("excludeReourceId", excludeResourceId); } if (resourceTypes != null) { hql.append(" and r.type in (:resourceTypes)"); parameter.put("resourceTypes", resourceTypes); } hql.append(" order by r.orderNo asc"); return getEntityDao().find(hql.toString(), parameter); } /** * ? * @return */ public List<TreeNode> findTreeNodeResources() { List<Resource> list = this.findResources(null); return resourcesToTreeNode(list); } /** * ? * @param excludeResourceId ??ID ? * @return */ public List<TreeNode> findTreeNodeResourcesWithExclude(String excludeResourceId) { List<Resource> list = this.findResources(null, excludeResourceId); return resourcesToTreeNode(list); } /** * ???TreeNode * @param resources * @return */ private List<TreeNode> resourcesToTreeNode(List<Resource> resources) { List<TreeNode> tempTreeNodes = Lists.newArrayList(); if (Collections3.isEmpty(resources)) { return tempTreeNodes; } Map<String, TreeNode> tempMap = Maps.newLinkedHashMap(); Iterator<Resource> iterator = resources.iterator(); while (iterator.hasNext()) { Resource resource = iterator.next(); TreeNode treeNode = this.resourceToTreeNode(resource); tempTreeNodes.add(treeNode); tempMap.put(resource.getId(), treeNode); } Set<String> keyIds = tempMap.keySet(); Iterator<String> iteratorKey = keyIds.iterator(); while (iteratorKey.hasNext()) { TreeNode treeNode = tempMap.get(iteratorKey.next()); if (StringUtils.isNotBlank(treeNode.getpId())) { TreeNode pTreeNode = getParentTreeNode(treeNode.getpId(), tempTreeNodes); if (pTreeNode != null) { pTreeNode.addChild(treeNode); iteratorKey.remove(); } } } List<TreeNode> result = Lists.newArrayList(); keyIds = tempMap.keySet(); iteratorKey = keyIds.iterator(); while (iteratorKey.hasNext()) { TreeNode treeNode = tempMap.get(iteratorKey.next()); result.add(treeNode); } return result; } /** * * @param resources * @return */ private List<Menu> resourcesToMenu(List<Resource> resources) { List<Menu> tempMenus = Lists.newArrayList(); if (Collections3.isEmpty(resources)) { return tempMenus; } Map<String, Menu> tempMap = Maps.newHashMap(); Iterator<Resource> iterator = resources.iterator(); while (iterator.hasNext()) { Resource resource = iterator.next(); Menu menu = this.resourceToMenu(resource); tempMenus.add(menu); tempMap.put(resource.getId(), menu); } Set<String> keyIds = tempMap.keySet(); Iterator<String> iteratorKey = keyIds.iterator(); while (iteratorKey.hasNext()) { Menu menu = tempMap.get(iteratorKey.next()); if (StringUtils.isNotBlank(menu.getpId())) { Menu parentMenu = getParentMenu(menu.getpId(), tempMenus); if (parentMenu != null) { parentMenu.addChild(menu); iteratorKey.remove(); } } } List<Menu> result = Lists.newArrayList(); keyIds = tempMap.keySet(); iteratorKey = keyIds.iterator(); while (iteratorKey.hasNext()) { Menu menu = tempMap.get(iteratorKey.next()); result.add(menu); } return result; } /** * * @param parentId * @param treeNodes * @return */ private TreeNode getParentTreeNode(String parentId, List<TreeNode> treeNodes) { TreeNode t = null; for (TreeNode treeNode : treeNodes) { if (parentId.equals(treeNode.getId())) { t = treeNode; break; } } return t; } /** * * @param parentId * @param menus * @return */ private Menu getParentMenu(String parentId, List<Menu> menus) { Menu t = null; for (Menu menu : menus) { if (parentId.equals(menu.getId())) { t = menu; break; } } return t; } /** * ?TreeNode * @param resource ? * @return */ private TreeNode resourceToTreeNode(Resource resource) { TreeNode treeNode = new TreeNode(resource.getId(), resource.getName(), resource.getIconCls()); treeNode.setpId(resource.get_parentId()); treeNode.addAttributes("url", resource.getUrl()); treeNode.addAttributes("markUrl", resource.getMarkUrl()); treeNode.addAttributes("code", resource.getCode()); treeNode.addAttributes("type", resource.getType()); return treeNode; } /** * ?Menu * @param resource ? * @return */ private Menu resourceToMenu(Resource resource) { Assert.notNull(resource, "?resource?"); Menu menu = new Menu(resource.getId(), resource.getName()); menu.setpId(resource.get_parentId()); menu.setHref(resource.getUrl()); menu.addAttributes("type", resource.getType()); return menu; } /** * ?. * * @return ? */ public Integer getMaxSort() throws DaoException, SystemException, ServiceException { Iterator<?> iterator = resourceDao.createQuery("select max(m.orderNo)from Resource m ").iterate(); Integer max = 0; while (iterator.hasNext()) { // Object[] row = (Object[]) iterator.next(); max = (Integer) iterator.next(); if (max == null) { max = 0; } } return max; } /** * ?????? * @param userId ID * @param resourceCode ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public boolean isUserPermittedResourceCode(String userId, String resourceCode) throws DaoException, SystemException, ServiceException { Assert.notNull(userId, "?[userId]!"); Assert.notNull(resourceCode, "?[resourceCode]!"); List<Resource> list = this.findResourcesByUserId(userId); boolean flag = false; for (Resource resource : list) { if (resource != null && StringUtils.isNotBlank(resource.getCode()) && resource.getCode().equalsIgnoreCase(resourceCode)) { flag = true; break; } } return flag; } /** * ????url * @param requestUrl URL? * @param userId ID * @return */ @Cacheable(value = { CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE }) public boolean isAuthorityWithPermissions(String requestUrl, String userId) throws DaoException, SystemException, ServiceException { //? ?? if (SecurityUtils.isUserAdmin(userId)) { return true; } //URL?? boolean isInterceptorUrl = this.isInterceptorUrl(requestUrl); if (isInterceptorUrl) { //??Lo List<String> userAuthoritys = this.getUserAuthoritysByUserId(userId); for (String markUrl : userAuthoritys) { String[] markUrls = markUrl.split(";"); for (int i = 0; i < markUrls.length; i++) { if (StringUtils.isNotBlank(markUrls[i]) && StringUtils.simpleWildcardMatch(markUrls[i], requestUrl)) { return true; } } } return false; } logger.debug(":{}", CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE + "?requestUrl=" + requestUrl + ",userId=" + userId); return true; } /** * ?url * @return */ public List<String> getAllInterceptorUrls() throws DaoException, SystemException, ServiceException { List<String> markUrls = Lists.newArrayList(); //? List<Resource> resources = this.findResources(); for (Resource resource : resources) { if (StringUtils.isNotBlank(resource.getMarkUrl())) { markUrls.add(resource.getMarkUrl()); } } return markUrls; } /** * ?URL? * @param requestUrl URL? * @return */ public boolean isInterceptorUrl(String requestUrl) throws DaoException, SystemException, ServiceException { List<String> markUrlList = this.getAllInterceptorUrls(); for (String markUrl : markUrlList) { String[] markUrls = markUrl.split(";"); for (int i = 0; i < markUrls.length; i++) { if (StringUtils.isNotBlank(markUrls[i]) && StringUtils.simpleWildcardMatch(markUrls[i], requestUrl)) { return true; } } } return false; } /** * ?IDURL?? * @param userId ID * @return List<String> markUrl? */ public List<String> getUserAuthoritysByUserId(String userId) throws DaoException, SystemException, ServiceException { List<String> userAuthoritys = Lists.newArrayList(); List<TreeNode> treeNodes = this.findTreeNodeResourcesWithPermissions(userId); for (TreeNode node : treeNodes) { Object obj = node.getAttributes().get("markUrl"); if (obj != null) { String markUrl = (String) obj; if (StringUtils.isNotBlank(markUrl)) { userAuthoritys.add(markUrl); } } } return userAuthoritys; } /** ??? **/ /** * ? * * @param code ? * @param name ??? * @param parentCode ? * @param status ?? ? {@link StatusState} * @return */ public void iSynchronous(Integer resourceType, String code, String name, String parentCode, String status) throws DaoException, SystemException, ServiceException { Validate.notNull(code, "?[code]?null"); if (status == null) { status = StatusState.NORMAL.getValue(); } Resource parentResource = null; if (StringUtils.isNotBlank(parentCode)) { parentResource = this.iGetReource(resourceType, parentCode, status); if (parentResource == null) { throw new SystemException("[" + parentCode + "]?."); } } Resource resource = null; if (StringUtils.isNotBlank(code)) { resource = this.iGetReource(resourceType, code, status); } if (resource == null) { resource = new Resource(); } resource.setStatus(status); resource.setName(name); resource.setCode(code); resource.setType(resourceType); resource.setParent(parentResource); this.saveOrUpdate(resource); } /** * ? * @param resourceType ? * @param code ?? */ public void iDeleteResource(Integer resourceType, String code) { Resource resource = iGetReource(resourceType, code, null); if (resource == null) { throw new SystemException("?[" + code + "]?."); } List<String> ids = Lists.newArrayList(); ids.add(resource.getId()); this.deleteByIds(ids); } /** * * @param resourceType ? * @param code ?? * @param status * @return */ public Resource iGetReource(Integer resourceType, String code, String status) { Validate.notNull(code, "?[code]?null"); Parameter parameter = new Parameter(code); StringBuffer hql = new StringBuffer(); hql.append("from Resource r where r.code = :p1 "); if (resourceType != null) { hql.append(" and r.type = :type"); parameter.put("type", resourceType); } if (status != null) { hql.append(" and r.status = :status "); parameter.put("status", status); } List<Resource> list = getEntityDao().find(hql.toString(), parameter); return list.isEmpty() ? null : list.get(0); } /** * ?? * * @return */ public List<Resource> iGetResources(Integer resourceType) { Parameter parameter = new Parameter(); StringBuffer hql = new StringBuffer(); hql.append("from Resource r where 1=1"); if (resourceType != null) { hql.append(" and r.type = :type"); parameter.put("type", resourceType); } List<Resource> list = getEntityDao().find(hql.toString(), parameter); return list; } /** ??? **/ }