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.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.modules.sys._enum.OrganType; import com.eryansky.modules.sys._enum.SexType; import com.eryansky.modules.sys.entity.Organ; import com.eryansky.modules.sys.entity.User; import com.eryansky.utils.CacheConstants; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; 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.*; /** * Organ? Service. * @author &Eryan eryanwcp@gmail.com * @date 2013-09-09 ?21:26:46 */ @Service public class OrganManager extends EntityManager<Organ, String> { private static final String ICON_ORGAN_ROOT = "eu-icon-organ-root"; private static final String ICON_USER_RED = "eu-icon-user_red"; private static final String ICON_USER = "eu-icon-user"; private static final String ICON_GROUP = "eu-icon-group"; @Autowired private UserManager userManager; private HibernateDao<Organ, String> organDao;// DAO???. /** * sessionFactory?DAO???. */ @Autowired public void setSessionFactory(final SessionFactory sessionFactory) { organDao = new HibernateDao<Organ, String>(sessionFactory, Organ.class); } @Override protected HibernateDao<Organ, String> getEntityDao() { return organDao; } /** * ?. */ @CacheEvict(value = { CacheConstants.ORGAN_USER_TREE_CACHE }, allEntries = true) public void saveOrUpdate(Organ entity) throws DaoException, SystemException, ServiceException { logger.debug(":{}"); Assert.notNull(entity, "?[entity]!"); organDao.saveOrUpdate(entity); } /** * ?. */ @CacheEvict(value = { CacheConstants.ORGAN_USER_TREE_CACHE }, allEntries = true) public void merge(Organ entity) throws DaoException, SystemException, ServiceException { Assert.notNull(entity, "?[entity]!"); organDao.merge(entity); } @CacheEvict(value = { CacheConstants.ORGAN_USER_TREE_CACHE }, allEntries = true) @Override public void saveEntity(Organ entity) throws DaoException, SystemException, ServiceException { super.saveEntity(entity); } /** * (?ID). * * @param id * ID */ @CacheEvict(value = { CacheConstants.ORGAN_USER_TREE_CACHE }, allEntries = true) public void deleteById(final String id) { getEntityDao().delete(id); } /** * . */ @CacheEvict(value = { CacheConstants.ORGAN_USER_TREE_CACHE }, allEntries = true) public void deleteByIds(List<String> ids) throws DaoException, SystemException, ServiceException { super.deleteByIds(ids); } public List<Organ> findAllNormal() { StringBuffer hql = new StringBuffer(); Parameter parameter = new Parameter(StatusState.NORMAL.getValue()); hql.append(" from Organ o where o.status = :p1 order by o.orderNo asc"); List<Organ> list = getEntityDao().find(hql.toString(), parameter); return list; } /** * * @param organIds ?ID * @param query * @return */ public List<Organ> findWithInclude(List<String> organIds, String query, List<Integer> organTypes) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue()); StringBuffer hql = new StringBuffer(); hql.append("from Organ o where o.status = :p1 "); if (Collections3.isEmpty(organIds) && StringUtils.isBlank(query)) { hql.append(" and 1 <> 1 "); } else if (Collections3.isNotEmpty(organIds) && StringUtils.isNotBlank(query)) { hql.append(" and (o.id in (:organIds) or o.name like :query )"); parameter.put("organIds", organIds); parameter.put("query", "%" + query + "%"); } else { if (Collections3.isNotEmpty(organIds)) { hql.append(" and o.id in (:organIds)"); parameter.put("organIds", organIds); } else if (StringUtils.isNotBlank(query)) { hql.append(" and o.name like :query "); parameter.put("query", "%" + query + "%"); } } if (Collections3.isNotEmpty(organTypes)) { hql.append(" and o.type in (:organTypes)"); parameter.put("organTypes", organTypes); } hql.append(" order by o.orderNo asc"); return getEntityDao().find(hql.toString(), parameter); } /** * * @param organIds ?ID * @param query * @return */ public List<Organ> findDepartmensWithInclude(List<String> organIds, String query) { List<Integer> organTypes = new ArrayList<Integer>(1); organTypes.add(OrganType.department.getValue()); return findWithInclude(organIds, query, organTypes); } /** * * @return */ public List<TreeNode> findOrganTree() { return findOrganTree(null, null); } /** * * @param parentId null * @return */ @Cacheable(value = CacheConstants.ORGAN_USER_TREE_CACHE, condition = "#cacheable == true") public List<TreeNode> findOrganTree(String parentId, boolean cacheable) { return findOrganTree(parentId, null); } public List<TreeNode> findOrganTree(String parentId, boolean cacheable, boolean cascade) { return findOrganUserTree(parentId, null, false, null, cascade); } /** * * @param parentId null * @param excludeOrganId ID * @return */ public List<TreeNode> findOrganTree(String parentId, String excludeOrganId) { return findOrganUserTree(parentId, excludeOrganId, false, null, true); } /** * * @param parentId null * @param addUser ? * @return */ public List<TreeNode> findOrganUserTree(String parentId, boolean addUser, boolean cascade) { return findOrganUserTree(parentId, null, addUser, null, cascade); } /** * * @param parentId null * @param checkedUserIds * @return */ public List<TreeNode> findOrganUserTree(String parentId, List<String> checkedUserIds, boolean cascade) { return findOrganUserTree(parentId, null, true, checkedUserIds, cascade); } /** * * @param parentId null * @param excludeOrganId ID * @param addUser ? * @param checkedUserIds addUsertrue * @param cascade ? * @return */ public List<TreeNode> findOrganUserTree(String parentId, String excludeOrganId, boolean addUser, List<String> checkedUserIds, boolean cascade) { List<Organ> organs = null; if (parentId == null) { if (cascade) { organs = this.findAllNormal(); } else { organs = this.findRoots(); } } else { if (cascade) { organs = this.findOwnerAndChildsOrgans(parentId); } else { organs = this.loadById(parentId).getSubOrgans(); } } List<TreeNode> tempTreeNodes = Lists.newArrayList(); Map<String, TreeNode> tempMap = Maps.newLinkedHashMap(); Iterator<Organ> iterator = organs.iterator(); while (iterator.hasNext()) { Organ organ = iterator.next(); if (StringUtils.isNotBlank(excludeOrganId) && organ.getId().equals(excludeOrganId)) { continue; } // if (StringUtils.isNotBlank(excludeOrganId) && organ.getParentIds() != null && organ.getParentIds().contains(excludeOrganId)) { continue; } TreeNode treeNode = this.organToTreeNode(organ); if (addUser) { List<User> organUsers = organ.getDefautUsers(); if (Collections3.isNotEmpty(organUsers)) { for (User organUser : organUsers) { TreeNode userTreeNode = userToTreeNode(organUser); if (Collections3.isNotEmpty(checkedUserIds)) { if (checkedUserIds.contains(userTreeNode.getId())) { userTreeNode.setChecked(true); } } treeNode.addChild(userTreeNode); } } } tempTreeNodes.add(treeNode); tempMap.put(organ.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; } /** * TreeNode * @param organ * @return */ public TreeNode organToTreeNode(Organ organ) { TreeNode treeNode = new TreeNode(organ.getId(), organ.getName()); if (StringUtils.isBlank(organ.get_parentId())) { treeNode.setIconCls(ICON_ORGAN_ROOT); } else { treeNode.setIconCls(ICON_GROUP); } treeNode.setState(organ.getState()); treeNode.setpId(organ.get_parentId()); treeNode.addAttributes("code", organ.getCode()); treeNode.addAttributes("sysCode", organ.getSysCode()); treeNode.addAttributes("type", organ.getType()); treeNode.addAttributes("nType", "o");// return treeNode; } /** * TreeNode * @param user * @return */ public TreeNode userToTreeNode(User user) { TreeNode treeNode = new TreeNode(user.getId(), user.getName()); if (SexType.girl.getValue().equals(user.getSex())) { treeNode.setIconCls(ICON_USER_RED); } else { treeNode.setIconCls(ICON_USER); } treeNode.addAttributes("nType", "u");// treeNode.addAttributes("loginName", user.getLoginName());// return treeNode; } /** * * @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; } /** * ?ID */ public void syncAllParentIds() { List<Organ> rootOrgans = this.findRoots(); updateParentIds(rootOrgans); } /** * * @param organs */ private void updateParentIds(List<Organ> organs) { for (Organ organ : organs) { organ.syncParentIds2(); this.update(organ); updateParentIds(organ.getSubOrgans()); } } /** * * ??Organ. * * @param sysCode * ? * @return */ public Organ getBySysCode(String sysCode) { if (StringUtils.isBlank(sysCode)) { return null; } Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), sysCode); StringBuffer hql = new StringBuffer(); hql.append("from Organ o where o.status = :p1 and o.sysCode = :p2"); Query query = getEntityDao().createQuery(hql.toString(), parameter); query.setMaxResults(1); List<Organ> list = query.list(); return list.isEmpty() ? null : list.get(0); } /** * * ??Organ. * * @param code * ? * @return */ public Organ getByCode(String code) { if (StringUtils.isBlank(code)) { return null; } Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), code); StringBuffer hql = new StringBuffer(); hql.append("from Organ o where o.status = :p1 and o.code = :p2"); Query query = getEntityDao().createQuery(hql.toString(), parameter); query.setMaxResults(1); List<Organ> list = query.list(); return list.isEmpty() ? null : list.get(0); } /** * * @return */ public List<Organ> findRoots() { return findByParent(null, null); } /** * * ?ID Organ. <br> * orderNo asc,id asc?. * * @param parentId * ID(?null) * @return */ public List<Organ> findByParent(String parentId) { return findByParent(parentId, null); } /** * * ?ID Organ. <br> * orderNo asc,id asc?. * * @param parentId * ID(?null) * @param status * ?? @see com.eryansky.common.orm.entity.StatusState * <br>statusnull :StatusState.NORMAL.getValue() * @return */ @SuppressWarnings("unchecked") public List<Organ> findByParent(String parentId, String status) { // if (status == null) { status = StatusState.NORMAL.getValue(); } StringBuilder sb = new StringBuilder(); Parameter parameter = new Parameter(); sb.append("from Organ o where o.status = :status "); parameter.put("status", status); sb.append(" and o.parent"); if (parentId == null) { sb.append(" is null "); } else { sb.append(".id = :parentId "); parameter.put("parentId", parentId); } sb.append(" order by o.orderNo asc"); List<Organ> list = organDao.find(sb.toString(), parameter); return list; } /** * ? * @param parentId * @param status * @return */ public List<Organ> findDataByParent(String parentId, List<String> status) { // if (Collections3.isEmpty(status)) { status = new ArrayList<String>(3); status.add(StatusState.NORMAL.getValue()); status.add(StatusState.LOCK.getValue()); status.add(StatusState.AUDIT.getValue()); } StringBuilder sb = new StringBuilder(); Parameter parameter = new Parameter(); sb.append("from Organ o where o.status in (:status) "); parameter.put("status", status); sb.append(" and o.parent"); if (StringUtils.isBlank(parentId)) { sb.append(" is null "); } else { sb.append(".id = :parentId "); parameter.put("parentId", parentId); } sb.append(" order by o.orderNo asc"); List<Organ> list = organDao.find(sb.toString(), parameter); return list; } /** * ?. * * @return ? */ public Integer getMaxSort() throws DaoException, SystemException, ServiceException { Iterator<?> iterator = organDao.createQuery("select max(o.orderNo) from Organ o ").iterate(); Integer max = 0; while (iterator.hasNext()) { max = (Integer) iterator.next(); if (max == null) { max = 0; } } return max; } /** * ?ID * @param organIds ID? * @return */ public List<Organ> findOrgansByIds(List<String> organIds) { Parameter parameter = new Parameter(organIds); return getEntityDao().find("from Organ o where o.id in :p1", parameter); } /** * ?ID * @param organId * @return */ public List<String> findOrganUserIds(String organId) { Parameter parameter = new Parameter(organId, StatusState.NORMAL.getValue()); StringBuilder hql = new StringBuilder(); hql.append( "select u.id from User u where u.defaultOrganId in (select o.id from Organ o where o.id = :p1) and u.status = :p2"); return getEntityDao().find(hql.toString(), parameter); } /** * ?? * @param id ID * @return */ public List<Organ> findChildsOrgans(String id) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue()); Organ organ = this.loadById(id); StringBuilder hql = new StringBuilder(); hql.append("from Organ o where o.status = :p1 "); if (organ != null) { hql.append(" and o.parentIds like :parentIds "); parameter.put("parentIds", "%," + id + ",%"); } hql.append(" order by o.orderNo asc"); List<Organ> list = organDao.find(hql.toString(), parameter); return list; } /** * ?? * @param id ID * @return */ public List<String> findChildsOrganIds(String id) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue()); Organ organ = this.loadById(id); StringBuilder hql = new StringBuilder(); hql.append("select o.id from Organ o where o.status = :p1 "); if (organ != null) { hql.append(" and o.parentIds like :parentIds "); parameter.put("parentIds", "%," + id + ",%"); } hql.append(" order by o.orderNo asc"); List<String> list = organDao.find(hql.toString(), parameter); return list; } /** * ?? * @param id ID * @return */ public List<Organ> findOwnerAndChildsOrgans(String id) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), id); Organ organ = this.loadById(id); StringBuilder hql = new StringBuilder(); hql.append("from Organ o where o.status = :p1 and (o.id = :p2 "); if (organ != null) { hql.append(" or o.parentIds like :parentIds "); parameter.put("parentIds", "%," + id + ",%"); } hql.append(" ) "); hql.append(" order by o.orderNo asc"); List<Organ> list = organDao.find(hql.toString(), parameter); return list; } /** * ?? * @param id ID * @return */ public List<String> findOwnerAndChildsOrganIds(String id) { Parameter parameter = new Parameter(StatusState.NORMAL.getValue(), id); Organ organ = this.loadById(id); StringBuilder hql = new StringBuilder(); hql.append("select o.id from Organ o where o.status = :p1 and (o.id = :p2 "); if (organ != null) { hql.append(" or o.parentIds like :parentIds "); parameter.put("parentIds", "%," + id + ",%"); } hql.append(" ) "); hql.append(" order by o.orderNo asc"); List<String> list = organDao.find(hql.toString(), parameter); return list; } /** * ???? * @param anyOrganId / ID * @return */ public List<Organ> findOrganChildsDepartmentOrgans(String anyOrganId) { if (StringUtils.isBlank(anyOrganId)) { return null; } Organ organ = this.loadById(anyOrganId); if (organ == null) { return null; } return findChildsDepartmentOrgans(organ.getCompanyId()); } /** * ???? * @param anyOrganId / ID * @return */ public List<String> findOrganChildsDepartmentOrganIds(String anyOrganId) { if (StringUtils.isBlank(anyOrganId)) { return null; } Organ organ = this.loadById(anyOrganId); if (organ == null) { return null; } return findChildsDepartmentOrganIds(organ.getCompanyId()); } /** * ???? * @param id ID * @return */ public List<Organ> findChildsDepartmentOrgans(String id) { List<Organ> organs = findChildsOrgans(id); List<Organ> list = Lists.newArrayList(); for (Organ organ : organs) { if (OrganType.department.getValue().equals(organ.getType()) && organ.getCompanyId().equals(id)) { list.add(organ); } } return list; } /** * ???? * @param id ID * @return */ public List<String> findChildsDepartmentOrganIds(String id) { List<Organ> organs = findChildsOrgans(id); List<String> list = Lists.newArrayList(); for (Organ organ : organs) { if (OrganType.department.getValue().equals(organ.getType()) && organ.getCompanyId().equals(id)) { list.add(organ.getId()); } } return list; } /** * ???? * @param anyOrganId / ID * @return */ public List<Organ> findOrganChildsOfficeOrgans(String anyOrganId) { if (StringUtils.isBlank(anyOrganId)) { return null; } Organ organ = this.loadById(anyOrganId); if (organ == null) { return null; } return findChildsDepartmentOrgans(organ.getOfficeId()); } /** * ???? * @param anyOrganId / ID * @return */ public List<String> findOrganChildsOfficeOrganIds(String anyOrganId) { if (StringUtils.isBlank(anyOrganId)) { return null; } Organ organ = this.loadById(anyOrganId); if (organ == null) { return null; } return findChildsDepartmentOrganIds(organ.getOfficeId()); } /** * ???? * @param id ID * @return */ public List<Organ> findChildsOfficeOrgans(String id) { List<Organ> organs = findChildsOrgans(id); List<Organ> list = Lists.newArrayList(); for (Organ organ : organs) { if (organ.getOfficeId().equals(id)) { list.add(organ); } } return list; } /** * ???? * @param id ID * @return */ public List<String> findChildsOfficeOrganIds(String id) { List<Organ> organs = findChildsOrgans(id); List<String> list = Lists.newArrayList(); for (Organ organ : organs) { if (organ.getOfficeId().equals(id)) { list.add(organ.getId()); } } return list; } /** * * * @param unionUsers * @return */ public List<TreeNode> getOrganUserTreeDataFast(Set<String> unionUsers) throws ServiceException { int maxGrade = 0; Map<Integer, Set<Organ>> organMap = Maps.newHashMap();// Map<String, List<User>> userMap = Maps.newHashMap();// ID if (Collections3.isNotEmpty(unionUsers)) { for (String userId : unionUsers) { User user = userManager.loadById(userId); Organ userOrgan = user.getOffice(); if (userOrgan == null) { throw new ServiceException(user.getName() + "."); } Set<Organ> organs = organMap.get(userOrgan.getGrade()); if (Collections3.isEmpty(organs)) { organs = Sets.newHashSet(); } organs.add(userOrgan); organMap.put(userOrgan.getGrade(), organs); List<User> users = userMap.get(userOrgan.getId()); if (Collections3.isEmpty(users)) { users = Lists.newArrayList(); } users.add(user); userMap.put(userOrgan.getId(), users); if (maxGrade < userOrgan.getGrade()) { maxGrade = userOrgan.getGrade(); } } } List<Integer> gradeKeys = Lists.newArrayList(organMap.keySet()); Collections.sort(gradeKeys); List<TreeNode> treeNodes = Lists.newArrayList(); for (Integer grade : gradeKeys) { Set<Organ> organs = organMap.get(grade); for (Organ rs : organs) { TreeNode organTreeNode = new TreeNode(rs.getId().toString(), rs.getName()); Map<String, Object> attributes = Maps.newHashMap(); attributes.put("nType", "o"); attributes.put("type", rs.getType()); attributes.put("sysCode", rs.getSysCode()); organTreeNode.setAttributes(attributes); organTreeNode.setIconCls(ICON_GROUP); List<User> userList = userMap.get(rs.getId()); Collections.sort(userList, new Comparator<User>() { @Override public int compare(User u1, User u2) { if (u1.getOrderNo() > u2.getOrderNo()) { return 1; } else if (u1.getOrderNo() < u2.getOrderNo()) { return -1; } else { return 0; } } }); if (Collections3.isNotEmpty(userList)) { for (User user : userList) { TreeNode userNode = new TreeNode(user.getId().toString(), user.getName()); Map<String, Object> userAttributes = Maps.newHashMap(); userAttributes.put("nType", "u"); userNode.setAttributes(userAttributes); if (SexType.girl.getValue().equals(user.getSex())) { userNode.setIconCls(ICON_USER_RED); } else { userNode.setIconCls(ICON_USER); } organTreeNode.addChild(userNode); } } treeNodes.add(organTreeNode); } } return treeNodes; } /** * ?? * * @param organUserTree * @param unionUsers * ? * @return */ private void iteratTree(List<TreeNode> newTree, List<TreeNode> organUserTree, Set<String> unionUsers) { for (TreeNode treeNode : organUserTree) { if ("u".equals(treeNode.getAttributes().get("nType"))) { // ?? if (unionUsers.contains(treeNode.getId())) { // ??ID newTree.add(treeNode); // ? } } else {// ? List<TreeNode> childrens = treeNode.getChildren(); if (Collections3.isNotEmpty(childrens)) { // ?? List<TreeNode> newNode = Lists.newArrayList(); iteratTree(newNode, childrens, unionUsers); // ?? if (Collections3.isNotEmpty(newNode)) { treeNode.setChildren(newNode); newTree.add(treeNode); // } } } } } }