Java tutorial
/** * Copyright (c) 2012-2014 http://www.eryansky.com * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.eryansky.service.base; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import com.eryansky.common.model.Menu; import com.eryansky.common.utils.StringUtils; import com.eryansky.entity.base.Resource; import com.eryansky.entity.base.state.ResourceType; import org.apache.commons.collections.ListUtils; 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 com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.eryansky.common.exception.DaoException; import com.eryansky.common.exception.ServiceException; import com.eryansky.common.exception.SystemException; import com.eryansky.common.model.TreeNode; import com.eryansky.common.orm.hibernate.EntityManager; import com.eryansky.common.orm.hibernate.HibernateDao; import com.eryansky.common.utils.collections.Collections3; import com.eryansky.entity.base.User; import com.eryansky.common.orm.entity.StatusState; import com.eryansky.utils.CacheConstants; /** * ?Resource? Service. * <br>? ??? * @author &Eryan eryanwcp@gmail.com * @date 2012-10-11 ?4:26:46 */ @Service public class ResourceManager extends EntityManager<Resource, Long> { @Autowired private UserManager userManager; private HibernateDao<Resource, Long> resourceDao;// DAO???. /** * sessionFactory?DAO???. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { resourceDao = new HibernateDao<Resource, Long>(sessionFactory, Resource.class); } @Override protected HibernateDao<Resource, Long> 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> subResources = entity.getSubResources(); while (!Collections3.isEmpty(subResources)) { Iterator<Resource> iterator = subResources.iterator(); while (iterator.hasNext()) { Resource subResource = iterator.next(); subResource.setType(ResourceType.function.getValue()); iterator.remove(); subResources = ListUtils.union(subResources, subResource.getSubResources()); super.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<Long> 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 (Long id : ids) { Resource resource = getEntityDao().load(id); resource.setRoles(null); resource.setUsers(null); getEntityDao().delete(resource); } } else { logger.warn("?[ids]."); } } /** * ???? * @param resourceCode ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public Resource getResourceByCode(String resourceCode) throws DaoException, SystemException, ServiceException { return getEntityDao().findUniqueBy("code", resourceCode); } /** * ?????? * @param userId ID * @param resourceCode ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public boolean isUserPermittedResourceCode(Long userId, String resourceCode) throws DaoException, SystemException, ServiceException { Assert.notNull(userId, "?[userId]!"); Assert.notNull(resourceCode, "?[resourceCode]!"); List<Resource> list = this.getResourcesByUserId(userId); boolean flag = false; for (Resource resource : list) { if (resource != null && StringUtils.isNotBlank(resource.getCode()) && resource.getCode().equalsIgnoreCase(resourceCode)) { flag = true; } } return flag; } /** * ??(????). * @param userId ID * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ @Cacheable(value = { CacheConstants.RESOURCE_USER_MENU_TREE_CACHE }, key = "#userId +'getNavMenuTreeByUserId'") public List<TreeNode> getNavMenuTreeByUserId(Long userId) throws DaoException, SystemException, ServiceException { List<TreeNode> nodes = Lists.newArrayList(); List<Resource> userResources = Lists.newArrayList(); User user = userManager.loadById(userId); User superUser = userManager.getSuperUser(); boolean isSuperUser = false; //?? if (user != null && superUser != null && user.getId() == superUser.getId()) {// isSuperUser = true; userResources = this.getByParentId(null, StatusState.normal.getValue()); } else if (user != null) { userResources = this.getResourcesByUserId(userId); } for (Resource resource : userResources) { if (isSuperUser) { TreeNode node = this.resourceToTreeNode(resource, ResourceType.menu.getValue(), true); if (node != null) { nodes.add(node); } } else { if (resource != null && resource.getParentResource() == null) { TreeNode node = this.resourceToTreeNode(userResources, resource, ResourceType.menu.getValue(), true); if (node != null) { nodes.add(node); } } } } logger.debug(":{}", CacheConstants.RESOURCE_USER_MENU_TREE_CACHE + " ?userId=" + userId); return nodes; } public List<Resource> getResourcesByUserId(Long userId) throws DaoException, SystemException, ServiceException { Assert.notNull(userId, "userId?"); //?? List<Resource> roleResources = resourceDao.distinct(resourceDao.createQuery( "select ms from User u left join u.roles rs left join rs.resources ms where u.id= ? order by ms.orderNo asc", userId)).list(); //?? User user = userManager.loadById(userId); List<Resource> userResources = user.getResources(); System.out.println(userResources.size()); System.out.println(roleResources.size()); List<Resource> rs = Collections3.aggregate(roleResources, userResources); return rs; } public List<Resource> getResourcesByUserId(Long userId, Resource parentResource) throws DaoException, SystemException, ServiceException { List<Resource> list = new ArrayList<Resource>(); List<Resource> resources = this.getResourcesByUserId(userId); if (null == parentResource) { for (Resource resource : resources) { if (resource != null && resource.getParentResource() == null && StatusState.normal.getValue().equals(resource.getStatus())) { list.add(resource); } } } else { for (Resource resource : resources) { if (resource != null && resource.getParentResource() != null && resource.getParentResource().getId().equals(parentResource.getId()) && StatusState.normal.getValue().equals(resource.getStatus())) { list.add(resource); } } } return list; } /** * ?ID????. * @param userId ID * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ // @Cacheable(value = { CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE }, key = "#userId +'getResourceTreeByUserId'") public List<TreeNode> getResourceTreeByUserId(Long userId) throws DaoException, SystemException, ServiceException { // Assert.notNull(userId, "?[userId]!"); List<TreeNode> nodes = Lists.newArrayList(); List<Resource> userResources = Lists.newArrayList(); User user = userManager.loadById(userId); User superUser = userManager.getSuperUser(); boolean isSuperUser = false; //?? if (user != null && superUser != null && user.getId() == superUser.getId()) {// userResources = this.getByParentId(null, StatusState.normal.getValue()); } else if (user != null) { userResources = this.getResourcesByUserId(userId); } for (Resource resource : userResources) { if (isSuperUser) { TreeNode node = this.resourceToTreeNode(resource, null, true); if (node != null) { nodes.add(node); } } else { TreeNode node = this.resourceToTreeNode(userResources, resource, null, true); if (node != null) { nodes.add(node); } } } logger.debug(":{}", CacheConstants.RESOURCE_USER_RESOURCE_TREE_CACHE + " ?userId=" + userId); return nodes; } /** * ResourceTreeNode * @param resource ? * @param resourceType ? * @param isCascade ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ private TreeNode resourceToTreeNode(Resource resource, Integer resourceType, boolean isCascade) throws DaoException, SystemException, ServiceException { if (resourceType != null) { if (!resourceType.equals(resource.getType())) { return null; } } TreeNode treeNode = new TreeNode(resource.getId().toString(), resource.getName(), resource.getIconCls()); // url Map<String, Object> attributes = Maps.newHashMap(); attributes.put("url", resource.getUrl()); attributes.put("markUrl", resource.getMarkUrl()); attributes.put("code", resource.getCode()); attributes.put("type", resource.getType()); treeNode.setAttributes(attributes); if (isCascade) { List<TreeNode> childrenTreeNodes = Lists.newArrayList(); for (Resource subResource : resource.getSubResources()) { TreeNode node = resourceToTreeNode(subResource, resourceType, isCascade); if (node != null) { childrenTreeNodes.add(node); } } treeNode.setChildren(childrenTreeNodes); } return treeNode; } /** * ResourceTreeNode * @param repositoryResources ? * @param resource ? * @param resourceType ? * @param isCascade ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ private TreeNode resourceToTreeNode(List<Resource> repositoryResources, Resource resource, Integer resourceType, boolean isCascade) throws DaoException, SystemException, ServiceException { if (resource == null || !repositoryResources.contains(resource)) { return null; } if (resourceType != null) { if (!resourceType.equals(resource.getType())) { return null; } } TreeNode treeNode = new TreeNode(resource.getId().toString(), resource.getName(), resource.getIconCls()); // url Map<String, Object> attributes = Maps.newHashMap(); attributes.put("url", resource.getUrl()); attributes.put("markUrl", resource.getMarkUrl()); attributes.put("code", resource.getCode()); attributes.put("type", resource.getType()); treeNode.setAttributes(attributes); if (isCascade) { List<TreeNode> childrenTreeNodes = Lists.newArrayList(); for (Resource subResource : resource.getSubResources()) { TreeNode node = resourceToTreeNode(repositoryResources, subResource, resourceType, isCascade); if (node != null) { childrenTreeNodes.add(node); } } treeNode.setChildren(childrenTreeNodes); } return treeNode; } /** * ResourceEasy UI Menu * @param resource * @param isCascade ???? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public Menu resourceToMenu(Resource resource, boolean isCascade) throws DaoException, SystemException, ServiceException { Assert.notNull(resource, "?resource?"); if (ResourceType.menu.getValue().equals(resource.getType())) { Menu menu = new Menu(); menu.setId(resource.getId().toString()); menu.setText(resource.getName()); menu.setHref(resource.getUrl()); if (isCascade) { List<Menu> childrenMenus = Lists.newArrayList(); for (Resource subResource : resource.getSubResources()) { if (ResourceType.menu.getValue().equals(subResource.getType())) { childrenMenus.add(resourceToMenu(subResource, true)); } } menu.setChildren(childrenMenus); } return menu; } return null; } public List<Menu> getAppMenusByUserId(Long userId) { List<Menu> menus = Lists.newArrayList(); List<Resource> resources = Lists.newArrayList(); User user = userManager.loadById(userId); User superUser = userManager.getSuperUser(); if (user != null && superUser != null && user.getId() == superUser.getId()) {// resources = super.getAll(); } else if (user != null) { resources = getResourcesByUserId(userId); } for (Resource resource : resources) { if (StringUtils.isNotBlank(resource.getUrl())) { if (ResourceType.menu.getValue().equals(resource.getType())) { Menu menu = new Menu(); menu.setId(resource.getId().toString()); menu.setText(resource.getName()); menu.setHref(resource.getUrl()); menus.add(menu); } } } return menus; } /** * ??. * @param userId ID */ public List<Menu> getMenusByUserId(Long userId) { List<Menu> menus = Lists.newArrayList(); List<Resource> rootResources = Lists.newArrayList(); User user = userManager.loadById(userId); User superUser = userManager.getSuperUser(); if (user != null && superUser != null && user.getId() == superUser.getId()) {// rootResources = getByParentId(null, StatusState.normal.getValue()); } else if (user != null) { rootResources = getResourcesByUserId(userId, null); //???? Iterator<Resource> iterator = rootResources.iterator(); while (iterator.hasNext()) { if (!ResourceType.menu.getValue().equals(iterator.next().getType())) { iterator.remove(); } } } for (Resource parentResource : rootResources) { Menu menu = resourceToMenu(parentResource, true); if (menu != null) { menus.add(menu); } } return menus; } /** * * @param entity * @param id * @param isCascade ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public TreeNode getTreeNode(Resource entity, Long id, boolean isCascade) throws DaoException, SystemException, ServiceException { TreeNode node = this.resourceToTreeNode(entity, null, true); List<Resource> subResources = this.getByParentId(entity.getId(), StatusState.normal.getValue()); if (subResources.size() > 0) { if (isCascade) {// ? List<TreeNode> children = Lists.newArrayList(); for (Resource d : subResources) { boolean isInclude = true;// ?? TreeNode treeNode = null; treeNode = getTreeNode(d, id, true); // if (id != null) { if (!d.getId().equals(id)) { treeNode = getTreeNode(d, id, true); } else { isInclude = false; } } else { treeNode = getTreeNode(d, id, true); } if (isInclude) { children.add(treeNode); node.setState(TreeNode.STATE_CLOASED); } else { node.setState(TreeNode.STATE_OPEN); } } node.setChildren(children); } } return node; } /** * ?????. * @param excludeResourceId ??ID ? * @param isCascade ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public List<TreeNode> getResourceTree(Long excludeResourceId, boolean isCascade) throws DaoException, SystemException, ServiceException { List<TreeNode> treeNodes = Lists.newArrayList(); // ? List<Resource> resources = getByParentId(null, StatusState.normal.getValue()); for (Resource rs : resources) { TreeNode rootNode = getTreeNode(rs, excludeResourceId, isCascade); treeNodes.add(rootNode); } return treeNodes; } /** * * ?nameResource. * * @param name * ??? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public Resource getByName(String name) throws DaoException, SystemException, ServiceException { if (StringUtils.isBlank(name)) { return null; } name = StringUtils.strip(name);// return resourceDao.findUniqueBy("name", name); } /** * * ??Resource. * * @param code * ?? * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ public Resource getByCode(String code) throws DaoException, SystemException, ServiceException { if (StringUtils.isBlank(code)) { return null; } return resourceDao.findUniqueBy("code", code); } /** * * ?ID Resource. <br> * orderNo asc,id asc?. * * @param parentId * ID(?null?) * @param status * ?? @see com.eryansky.common.orm.entity.StatusState * <br>statusnull :StatusState.normal.getValue() * @return * @throws DaoException * @throws SystemException * @throws ServiceException */ @SuppressWarnings("unchecked") public List<Resource> getByParentId(Long parentId, Integer status) throws DaoException, SystemException, ServiceException { // if (status == null) { status = StatusState.normal.getValue(); } StringBuilder sb = new StringBuilder(); Object[] objs; sb.append("from Resource r where r.status = ? "); sb.append(" and r.parentResource.id "); if (parentId == null) { sb.append(" is null "); objs = new Object[] { status }; } else { sb.append(" = ? "); objs = new Object[] { status, parentId }; } sb.append(" order by r.orderNo asc,r.id asc"); List<Resource> list = resourceDao.createQuery(sb.toString(), objs).list(); return list; } /** * ????url * @param requestUrl URL? * @param userId ID * @return */ @Cacheable(value = { CacheConstants.RESOURCE_USER_AUTHORITY_URLS_CACHE }, key = "#requestUrl + #userId +'isAuthority'") public boolean isAuthority(String requestUrl, Long userId) throws DaoException, SystemException, ServiceException { //? ?? if (userManager.getSuperUser().getId().equals(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.findBy("NEI_status",StatusState.delete.getValue()); List<Resource> resources = this.getAll(); 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(Long userId) throws DaoException, SystemException, ServiceException { List<String> userAuthoritys = Lists.newArrayList(); List<TreeNode> treeNodes = this.getResourceTreeByUserId(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); } } // List<TreeNode> childrenNodes = node.getChildren(); for (TreeNode childrenNode : childrenNodes) { Object childrenObj = childrenNode.getAttributes().get("markUrl"); if (childrenObj != null) { String markUrl = (String) childrenObj; if (StringUtils.isNotBlank(markUrl)) { userAuthoritys.add(markUrl); } } } } return userAuthoritys; } /** * ?. * * @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; } }