NC6 主辅数量换算的工具类

354 篇文章 102 订阅

主辅数量换算的工具类

package nc.impl.pubitf.rbac;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import nc.bs.businessevent.bd.BDCommonEventUtil;
import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.core.util.ObjectCreator;
import nc.bs.ml.NCLangResOnserver;
import nc.bs.rbac.pubqry.RolePermBaseQuery;
import nc.bs.uap.rbac.profile.SubjectOrgRuleUtil;
import nc.itf.bd.pub.IBDMetaDataIDConstBasic;
import nc.itf.uap.rbac.IUserManage;
import nc.itf.uap.rbac.IUserManageQuery;
import nc.itf.uap.rbac.userpassword.IUserPasswordManage;
import nc.jdbc.framework.SQLParameter;
import nc.jdbc.framework.processor.BeanListProcessor;
import nc.jdbc.framework.processor.ColumnListProcessor;
import nc.jdbc.framework.processor.ResultSetProcessor;
import nc.login.vo.ILoginConstants;
import nc.pubitf.rbac.IUserPubConstants;
import nc.pubitf.rbac.IUserPubService;
import nc.pubitf.rbac.PubServiceSqlUtils;
import nc.vo.bd.pub.IPubEnumConst;
import nc.vo.jcom.lang.StringUtil;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDate;
import nc.vo.pub.lang.UFDateTime;
import nc.vo.sm.UserVO;
import nc.vo.sm.enumfactory.UserIdentityTypeEnumFactory;
import nc.vo.trade.sqlutil.IInSqlBatchCallBack;
import nc.vo.trade.sqlutil.InSqlBatchCaller;
import nc.vo.trade.summarize.Hashlize;
import nc.vo.trade.summarize.IHashKey;
import nc.vo.uap.rbac.ResponsibilityVO;
import nc.vo.uap.rbac.SubjectOrgVO;
import nc.vo.uap.rbac.UserPasswordLogVO;
import nc.vo.uap.rbac.rule.orgrule.IOrgRuleStrategy;
import nc.vo.uap.rbac.rule.orgrule.OrgRuleContext;
import nc.vo.uap.rbac.util.RbacPubUtil;
import nc.vo.uap.rbac.util.RbacSqlUtils;
import nc.vo.uap.rbac.util.RbacUserPwdUtil;
import nc.vo.util.BDPKLockUtil;
import nc.vo.util.SqlWrapper;
import nc.vo.util.innercode.NamedParamUtil;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.iterators.EntrySetMapIterator;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;

public class UserPubServiceImpl implements IUserPubService {

	@Override
	public String queryPsndocByUserid(String cuserid) throws BusinessException {
		IUserManageQuery qryService = (IUserManageQuery) nc.bs.framework.common.NCLocator
				.getInstance().lookup(IUserManageQuery.class.getName());

		return qryService.queryPsndocByUserid(cuserid);
	}

	@Override
	public void updateLockedTag(String cuserid, boolean isLocked)
			throws BusinessException {
		IUserManage manageService = (IUserManage) nc.bs.framework.common.NCLocator
				.getInstance().lookup(IUserManage.class.getName());

		manageService.updateLockedTag(cuserid, isLocked);
	}

	@Override
	public UserVO queryUserVOByPsnDocID(String pkPsndoc)
			throws BusinessException {
		IUserManageQuery qryService = (IUserManageQuery) nc.bs.framework.common.NCLocator
				.getInstance().lookup(IUserManageQuery.class.getName());

		return qryService.queryUserVOByPsnDocID(pkPsndoc);
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserVO[] queryUserVOsByPsnDocID(String pk_psndoc, String pk_group)
			throws BusinessException {
		String condition = "base_doc_type = ? and pk_base_doc = ? ";
		SQLParameter p = new SQLParameter();
		p.addParam(UserIdentityTypeEnumFactory.TYPE_PERSON);
		p.addParam(pk_psndoc);

		if (StringUtils.isNotBlank(pk_group)) {
			condition += " and pk_group = ?";
			p.addParam(pk_group);
		}

		BaseDAO dao = new BaseDAO();
		Collection<UserVO> c = dao.retrieveByClause(UserVO.class, condition, p);

		return CollectionUtils.isEmpty(c) ? null : c.toArray(new UserVO[0]);
	}

	@SuppressWarnings("unchecked")
	@Override
	public HashMap<String, UserVO[]> batchQueryUserVOsByPsnDocID(
			String[] psndocPks, final String pk_group) throws BusinessException {
		if (ArrayUtils.isEmpty(psndocPks))
			return null;

		try {
			InSqlBatchCaller caller = new InSqlBatchCaller(psndocPks);
			List<UserVO> userResultList = (List<UserVO>) caller
					.execute(new IInSqlBatchCallBack() {
						List<UserVO> userResultList = new ArrayList<UserVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							String condition = " base_doc_type = ? ";
							SQLParameter p = new SQLParameter();
							p.addParam(UserIdentityTypeEnumFactory.TYPE_PERSON);

							if (StringUtils.isNotBlank(pk_group)) {
								condition += " and pk_group = ?";
								p.addParam(pk_group);
							}

							condition += " and pk_base_doc in " + inSql;

							BaseDAO dao = new BaseDAO();
							Collection<UserVO> tempResult = dao
									.retrieveByClause(UserVO.class, condition,
											p);

							if (CollectionUtils.isNotEmpty(tempResult))
								userResultList.addAll(tempResult);

							return userResultList;
						}

					});

			HashMap<String, UserVO[]> psndoc_users_map = new HashMap<String, UserVO[]>();

			if (CollectionUtils.isNotEmpty(userResultList)) {
				HashMap<String, List<UserVO>> psndoc_userList_map = Hashlize
						.hashlizeVOs(userResultList.toArray(new UserVO[0]),
								new IHashKey() {
									@Override
									public String getKey(Object o) {
										UserVO user = (UserVO) o;
										return user.getPk_base_doc();
									}

								});

				EntrySetMapIterator mapIterator = new EntrySetMapIterator(
						psndoc_userList_map);
				while (mapIterator.hasNext()) {
					String psndoc = (String) mapIterator.next();
					List<UserVO> userList = (List<UserVO>) mapIterator
							.getValue();

					psndoc_users_map.put(psndoc,
							userList.toArray(new UserVO[0]));
				}
			}

			return psndoc_users_map;

		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}

	}

	@Override
	public UserPasswordLogVO[] queryUserPasswordLog(String cuserid)
			throws BusinessException {

		String condition = "cuserid = ?";
		SQLParameter p = new SQLParameter();
		p.addParam(cuserid);

		return queryUserPasswordLogByDefCond(condition, p);
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserPasswordLogVO[] queryUserPasswordLogByDefCond(
			String defCondition, SQLParameter sp) throws BusinessException {
		BaseDAO dao = new BaseDAO();
		List<UserPasswordLogVO> list = (List<UserPasswordLogVO>) dao
				.retrieveByClause(UserPasswordLogVO.class, defCondition, sp);
		return list == null ? null : (UserPasswordLogVO[]) list
				.toArray(new UserPasswordLogVO[list.size()]);
	}

	@Override
	public int checkUserPwd(String usercode, String password)
			throws BusinessException {
		IUserManageQuery qryService = (IUserManageQuery) nc.bs.framework.common.NCLocator
				.getInstance().lookup(IUserManageQuery.class.getName());

		String dsName = InvocationInfoProxy.getInstance().getUserDataSource();
		UserVO user = qryService.findUserByCode(usercode, dsName);
		if (user == null)
			return ILoginConstants.USER_NAME_WRONG;

		if (!RbacUserPwdUtil.checkUserPassword(user, password))
			return ILoginConstants.USER_NAME_RIGHT_PWD_WRONG;

		return checkUser(user, new UFDate());

	}

	private int checkUser(UserVO user, UFDate today) {

		if (user.getAbledate() != null && today.before(user.getAbledate())) {
			return ILoginConstants.USER_BEFORE_EFFECT;
		}
		if (user.getDisabledate() != null && today.after(user.getDisabledate())) {
			return ILoginConstants.USER_AFTER_EXPIRED;
		}
		if (user.getEnablestate() != null
				&& user.getEnablestate() != IPubEnumConst.ENABLESTATE_ENABLE) {
			if (user.getEnablestate() == IPubEnumConst.ENABLESTATE_DISABLE) {
				return ILoginConstants.USER_DISABLE;
			} else {
				return ILoginConstants.USER_UNENABLE;
			}
		}
		return ILoginConstants.USER_IDENTITY_LEGAL;
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean checkUserUnique(String usercode) throws BusinessException {
		String usercode_q = StringUtils.upperCase(usercode);

		String condition = " user_code_q = ?";

		SQLParameter sp = new SQLParameter();
		sp.addParam(usercode_q);

		BaseDAO dao = new BaseDAO();
		Collection<UserVO> user = dao.retrieveByClause(UserVO.class, condition,
				sp);

		return CollectionUtils.isEmpty(user);
	}

	@Override
	public ResponsibilityVO[] getRespsRelatedWithUserAndPermOrgs(
			final String cuserid, String[] orgPKs) throws BusinessException {
		if (StringUtils.isEmpty(cuserid) || ArrayUtils.isEmpty(orgPKs))
			return null;
		orgPKs=getRolesHasPermOrgs(cuserid, orgPKs);
		HashSet<String> rolePKResult = fetchRolesHasOrgPerm(cuserid, orgPKs);

//		String pk_group = InvocationInfoProxy.getInstance().getGroupId();
//		Map<String, List<String>> roleWithRuleOrgs=getRuleOrgs(cuserid, pk_group);
//		if(roleWithRuleOrgs!=null){
//			for(String role:roleWithRuleOrgs.keySet()){
//				for(String org:orgPKs){
//					if(roleWithRuleOrgs.get(role)!=null&&roleWithRuleOrgs.get(role).contains(org)){
//						rolePKResult.add(role);
//						break;
//					}
//				}
//			}
//		}
		if (CollectionUtils.isEmpty(rolePKResult))
			return null;

		List<ResponsibilityVO> respResultList = fetchResponsibilityRelateRoles(rolePKResult);

		return CollectionUtils.isEmpty(respResultList) ? null : respResultList
				.toArray(new ResponsibilityVO[0]);
	}
	@SuppressWarnings("unchecked")
	private String[]getRolesHasPermOrgs(String cuserid,String[]orgPKs) throws BusinessException{
		if(orgPKs==null||orgPKs.length==0){
			return orgPKs;
		}
		List<String> rolePKResult =new ArrayList<String>();
		rolePKResult.addAll(Arrays.asList(orgPKs));
		String pk_group = InvocationInfoProxy.getInstance().getGroupId();
		Map<String, Map<String, Set<String>>> roleWithRuleOrgs=getRuleOrgs(cuserid,pk_group);
		if(roleWithRuleOrgs!=null){
			for(String role:roleWithRuleOrgs.keySet()){
				for(String org:orgPKs){
					rolePKResult.add(org);
					Map<String, Set<String>>ruleOrgs=roleWithRuleOrgs.get(role);
					if(!ruleOrgs.isEmpty()){
						for(String ruleid:ruleOrgs.keySet()){
							if(ruleOrgs.get(ruleid).contains(org)){
								rolePKResult.add(ruleid);
								break;
							}
						}
					}
				}
			}
		}
		return rolePKResult.toArray(new String[0]);
	}
	
	//*******************************************START********************************************
	/**
	 * 规则计算出的组织
	 * @param cuserid
	 * @param pk_group
	 * @return
	 * @throws BusinessException
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Map<String, Set<String>>>getRuleOrgs(String cuserid, String pk_group) throws BusinessException { 
		BaseDAO dao = new BaseDAO();
		String sql = RbacSqlUtils.QUERY_ALLORGRULES_USERPERM_SQL;

		SqlWrapper wrapper = new SqlWrapper(sql);
		wrapper.bind("cuserid", cuserid);
		wrapper.bind("nowtime", new UFDateTime());
		wrapper.bind("pk_group", pk_group);
		Map<String, Set<String>> result =new HashMap<String, Set<String>>();
		Map<String, SubjectOrgVO> Subjects =new HashMap<String, SubjectOrgVO>();
		List<SubjectOrgVO> retList  = (List<SubjectOrgVO>)dao.executeQuery(wrapper.getSql(), wrapper.getSqlParameter(), 
				new BeanListProcessor(SubjectOrgVO.class));

		processSubjectAndOrgRelation(result, retList, Subjects);
		
		Map<String, Map<String, Set<String>>> ret = new HashMap<String, Map<String, Set<String>>>();
		sql = "select pk_rule,ruleclass from sm_rule";
		Map<String, String> ruleTypeMap = (Map<String, String>) dao.executeQuery(sql, new ResultSetProcessor() {
			@Override
			public Object handleResultSet(ResultSet rs) throws SQLException {
				Map<String, String> rules = new HashMap<String, String>();
				while (rs.next()) {
				
					String pk = rs.getString("pk_rule");
					String ruleclass = rs.getString("ruleclass");
					if(!rules.containsKey(pk))
					{
						rules.put(pk, ruleclass);
					}
				} 
				return rules;
			}
		});

		if (ruleTypeMap == null) {
			return null;
		}
		
		IUserManageQuery umq = (IUserManageQuery) NCLocator.getInstance().lookup(IUserManageQuery.class.getName());
		UserVO userVO = umq.getUser(cuserid);
		if (userVO == null) {
			return null;
		}
		
		Map<String, List<String>> ruleOrgs = new HashMap<String, List<String>>();
		Map<String, String> ruleTS = new HashMap<String, String>();
		Set<String> subjects = result.keySet();
		for (String subject : subjects) {
			Set<String> orgids = result.get(subject);
			if (orgids == null ) {
				continue;
			}
			for (String id : orgids.toArray(new String[0])) {
				if (SubjectOrgRuleUtil.isRule(id)) {
					if (!ret.containsKey(subject)){
						ret.put(subject, new HashMap<String, Set<String>>());
					}
					Map<String, Set<String>> orgsBySubject = ret.get(subject);
					String subjectID = SubjectOrgRuleUtil.getRuleIdbySetKey(id);
					SubjectOrgVO ruleSubVO=Subjects.get(subjectID);
					String ruleId = ruleSubVO.getPk_org();
//					if (!ruleTS.containsKey(ruleId)) {
						String ruleClass = ruleTypeMap.get(ruleId);
						List<String> tempOrgs = this.queryAssignedRuleOrgs(ruleClass, userVO,  ruleId,ruleSubVO.getRulepar());
						ruleOrgs.put(ruleId, tempOrgs);
//					}

					String ts = ruleTS.get(ruleId);
					String key = ruleId;
					
					if (!orgsBySubject.containsKey(key)) {
						orgsBySubject.put(key, new HashSet<String>());
					}
					if(ruleOrgs.get(ruleId) != null) {
						orgsBySubject.get(key).addAll(ruleOrgs.get(ruleId));
					}
				}
			}
		}
		return ret;
	}
	
	private void processSubjectAndOrgRelation(
			Map<String, Set<String>> result, List<SubjectOrgVO> retList,
			Map<String, SubjectOrgVO> subjects) {
		for(SubjectOrgVO vo:retList){
			if (StringUtils.isNotEmpty(vo.getSubjectid())) {
				Set<String> orgPksSet = result.get(vo.getSubjectid());
				if (orgPksSet == null) {
					orgPksSet = new HashSet<String>();
				}
				if(!StringUtil.isEmptyWithTrim(vo.getPk_org())) {
					if (!StringUtils.equalsIgnoreCase(vo.getIsrule(), "Y") ? true : false) {
						orgPksSet.add(vo.getPk_org());
					}
					else {
						orgPksSet.add(SubjectOrgRuleUtil.getSetKey(vo.getPk_subject_org()));
						 subjects.put(vo.getPk_subject_org(), vo);
					}
				}
				
				result.put(vo.getSubjectid(), orgPksSet);
			}
		}
		
	}
	private List<String> queryAssignedRuleOrgs(String ruleClass, UserVO userVO, String ruleId, String rulepar) throws BusinessException {
		IOrgRuleStrategy strategy;
		try {
			strategy = (IOrgRuleStrategy) ObjectCreator.newInstance(ruleClass);
		}
		catch (Exception e) {
			return null;
		}
		OrgRuleContext orgRuleContext = new OrgRuleContext();
		orgRuleContext.setUservo(userVO);
		if(!StringUtil.isEmptyWithTrim(rulepar)){
			strategy.setPar(rulepar);
		}
		List<String> tempOrgs = strategy.getOrgs(orgRuleContext);
		return tempOrgs;
	}
	//**************************************END*************************************************
	@SuppressWarnings("unchecked")
	private HashSet<String> fetchRolesHasOrgPerm(final String cuserid,
			String[] orgPKs) throws BusinessException {
		try {
			InSqlBatchCaller roleCaller = new InSqlBatchCaller(orgPKs);
			HashSet<String> rolePKResult = (HashSet<String>) roleCaller
					.execute(new IInSqlBatchCallBack() {
						HashSet<String> rolePKResult = new HashSet<String>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {

							NamedParamUtil npu = new NamedParamUtil();
							npu.addNamedParam("orgPKs", inSql);

							String queryRoleSql = npu
									.format(PubServiceSqlUtils.USER_OWNED_ROLESWITHORGS);
							SqlWrapper sw = new SqlWrapper(queryRoleSql);
							sw.bind("cuserid", cuserid);
							sw.bind("nowtime", new UFDate());

							BaseDAO dao = new BaseDAO();
							List<String> rolePKList = (List<String>) dao
									.executeQuery(sw.getSql(),
											sw.getSqlParameter(),
											new ColumnListProcessor());

							if (CollectionUtils.isNotEmpty(rolePKList))
								rolePKResult.addAll(rolePKList);

							return rolePKResult;
						}

					});
			return rolePKResult;
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	private List<ResponsibilityVO> fetchResponsibilityRelateRoles(
			HashSet<String> rolePKResult) throws BusinessException {
		try {
			String[] rolePKs = rolePKResult.toArray(new String[0]);

			InSqlBatchCaller respCaller = new InSqlBatchCaller(rolePKs);
			List<ResponsibilityVO> respResultList = (List<ResponsibilityVO>) respCaller
					.execute(new IInSqlBatchCallBack() {
						List<ResponsibilityVO> respResultList = new ArrayList<ResponsibilityVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							NamedParamUtil npu = new NamedParamUtil();
							npu.reset();
							npu.addNamedParam("rolePKs", inSql);

							BaseDAO dao = new BaseDAO();
							List<ResponsibilityVO> respList = (List<ResponsibilityVO>) dao
									.retrieveByClause(
											ResponsibilityVO.class,
											npu.format(PubServiceSqlUtils.RESP_OWNEDBY_ROLES_COND));

							if (CollectionUtils.isNotEmpty(respList))
								respResultList.addAll(respList);

							return respResultList;
						}
					});
			return respResultList;
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}
	}

	@Override
	public UserVO[] getUsersOwnedRespAndOrgsPerm(String[] respPKs,
			final String[] orgPKs) throws BusinessException {
		if (ArrayUtils.isEmpty(respPKs))
			return null;
		
		List<String> roleResult = RolePermBaseQuery
				.fetchRolePKlistByRespAndOrg(respPKs, orgPKs);

		if (CollectionUtils.isEmpty(roleResult))
			roleResult = new ArrayList<String>();

		final String[] rolePKs = roleResult.toArray(new String[0]);

		List<UserVO> userResult = getUserListByRoles(rolePKs);
		if(userResult==null){
			userResult=new ArrayList<UserVO>();
		}
		
		//TODO
		//加入组织规则计算出的用户
		List<String> allRoleResult = RolePermBaseQuery
				.fetchRolePKlistByRespAndOrg(respPKs, null);
		final String[] allRolePKs = allRoleResult.toArray(new String[0]);

		List<UserVO> allUserResult = getUserListByRoles(allRolePKs);
		String pk_group = InvocationInfoProxy.getInstance().getGroupId();
		
		if(!CollectionUtils.isEmpty(allUserResult)&&!CollectionUtils.isEmpty(userResult)){
			allUserResult.removeAll(userResult);
		}
		if(!CollectionUtils.isEmpty(allUserResult)){
			for(UserVO user:allUserResult){
				Map<String, Map<String, Set<String>>> roleWithRuleOrgs=getRuleOrgs(user.getCuserid(),pk_group);	
				if(roleWithRuleOrgs!=null){
					a:for(String role:roleWithRuleOrgs.keySet()){
						for(String org:orgPKs){
							Map<String, Set<String>>ruleOrgs=roleWithRuleOrgs.get(role);
							if(!ruleOrgs.isEmpty()){
								for(String ruleid:ruleOrgs.keySet()){
									if(ruleOrgs.get(ruleid).contains(org)){
											userResult.add(user);
										break a;
									}
								}
							}
						}
					}
				}
			}
		}
		
		UserVO[] uo = queryUserWithInOrgPermission(orgPKs);
		UserVO[] ur = queryUserWithInRespPermission(respPKs);

		Map<String, UserVO> m2 = new HashMap<String, UserVO>();
		Map<String, UserVO> m3 = new HashMap<String, UserVO>();
		if (uo != null) {
			for (UserVO u : uo)
				m2.put(u.getCuserid(), u);
		}
		if (ur != null) {
			for (UserVO u : ur)
				if (m2.containsKey(u.getCuserid()))
					m3.put(u.getCuserid(), u);
		}
		if (userResult != null) {
			for (UserVO u : userResult)
				m3.put(u.getCuserid(), u);
		}
		return CollectionUtils.isEmpty(m3.keySet()) ? null : m3.values()
				.toArray(new UserVO[0]);
	}

	@Override
	public UserVO[] getUsersOwnedRespPerm(String[] respPKs)
			throws BusinessException {
		if (ArrayUtils.isEmpty(respPKs))
			return null;

		List<String> roleResult = RolePermBaseQuery
				.queryRolePKlistByInRespAndInOrg(respPKs, null);

		if (CollectionUtils.isEmpty(roleResult))
			roleResult = new ArrayList<String>();

		final String[] rolePKs = roleResult.toArray(new String[0]);

		List<UserVO> userResult = getUserListByRoles(rolePKs);

		UserVO[] ur = queryUserWithInRespPermission(respPKs);

		Map<String, UserVO> userMap = new HashMap<String, UserVO>();

		if (ur != null) {
			for (UserVO u : ur)
				userMap.put(u.getCuserid(), u);
		}

		if (userResult != null) {
			for (UserVO u : userResult)
				userMap.put(u.getCuserid(), u);
		}
		return CollectionUtils.isEmpty(userMap.keySet()) ? null : userMap
				.values().toArray(new UserVO[0]);
	}

	@SuppressWarnings("unchecked")
	private UserVO[] queryUserWithInOrgPermission(String... orgPKs)
			throws BusinessException {
		if (ArrayUtils.isEmpty(orgPKs))
			return null;

		try {
			InSqlBatchCaller caller = new InSqlBatchCaller(orgPKs);
			List<UserVO> resultList = (List<UserVO>) caller
					.execute(new IInSqlBatchCallBack() {
						List<UserVO> resultList = new ArrayList<UserVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							String pk_group = InvocationInfoProxy.getInstance()
									.getGroupId();
							NamedParamUtil npu = new NamedParamUtil();
							npu.addNamedParam("pk_group", pk_group);
							npu.addNamedParam("orgs", inSql);

							String condition = npu
									.format(PubServiceSqlUtils.USERS_WITHIN_ORGPERM_CONDITION);

							BaseDAO dao = new BaseDAO();

							List<UserVO> userList = (List<UserVO>) dao
									.retrieveByClause(UserVO.class, condition);

							if (CollectionUtils.isNotEmpty(userList))
								resultList.addAll(userList);

							return resultList;
						}
					});

			return CollectionUtils.isEmpty(resultList) ? null : resultList
					.toArray(new UserVO[0]);
		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}

	@SuppressWarnings("unchecked")
	private UserVO[] queryUserWithInRespPermission(String... respPKs)
			throws BusinessException {
		if (ArrayUtils.isEmpty(respPKs))
			return null;

		try {
			InSqlBatchCaller caller = new InSqlBatchCaller(respPKs);
			List<UserVO> resultList = (List<UserVO>) caller
					.execute(new IInSqlBatchCallBack() {
						List<UserVO> resultList = new ArrayList<UserVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							String pk_group = InvocationInfoProxy.getInstance()
									.getGroupId();
							NamedParamUtil npu = new NamedParamUtil();
							npu.addNamedParam("pk_group", pk_group);
							npu.addNamedParam("resps", inSql);

							String condition = npu
									.format(PubServiceSqlUtils.USERS_WITHIN_RESPPERM_CONDITION);

							BaseDAO dao = new BaseDAO();

							List<UserVO> userList = (List<UserVO>) dao
									.retrieveByClause(UserVO.class, condition);

							if (CollectionUtils.isNotEmpty(userList))
								resultList.addAll(userList);

							return resultList;
						}
					});

			return CollectionUtils.isEmpty(resultList) ? null : resultList
					.toArray(new UserVO[0]);
		} catch (Exception e) {
			throw new BusinessException(e);
		}
	}

	@SuppressWarnings("unchecked")
	private List<UserVO> getUserListByRoles(final String[] rolePKs)
			throws BusinessException {
		try {
			InSqlBatchCaller userCaller = new InSqlBatchCaller(rolePKs);
			List<UserVO> userResult = (List<UserVO>) userCaller
					.execute(new IInSqlBatchCallBack() {
						List<UserVO> userResult = new ArrayList<UserVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							NamedParamUtil npu = new NamedParamUtil();
							npu.addNamedParam("rolePKs", inSql);
							npu.addNamedParam("nowtime", new UFDate());

							BaseDAO dao = new BaseDAO();
							List<UserVO> userList = (List<UserVO>) dao.retrieveByClause(
									UserVO.class,
									npu.format(PubServiceSqlUtils.OWNED_ROLESPERM_USERS_COND));

							if (CollectionUtils.isNotEmpty(userList))
								userResult.addAll(userList);

							return userResult;
						}

					});
			return userResult;
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserVO[] getUsersByPKs(String[] userPKs) throws BusinessException {
		if (ArrayUtils.isEmpty(userPKs))
			return null;

		InSqlBatchCaller caller = new InSqlBatchCaller(userPKs);
		try {
			List<UserVO> userList = (List<UserVO>) caller
					.execute(new IInSqlBatchCallBack() {
						List<UserVO> userResult = new ArrayList<UserVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							String cond = UserVO.CUSERID + " in " + inSql;
							BaseDAO dao = new BaseDAO();
							Collection<UserVO> userColl = dao.retrieveByClause(
									UserVO.class, cond);

							userResult.addAll(userColl);

							return userResult;
						}

					});

			return CollectionUtils.isEmpty(userList) ? null : userList
					.toArray(new UserVO[0]);
		} catch (SQLException e) {
			throw new BusinessException(e.getMessage());
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public Map<String, UserVO> getUsersRelatedWithCustomer(String[] userPKs)
			throws BusinessException {

		try {
			List<UserVO> userList = null;

			if (ArrayUtils.isEmpty(userPKs)) {
				String cond = " base_doc_type = ? and pk_base_doc != '~' ";
				SQLParameter sp = new SQLParameter();
				sp.addParam(UserIdentityTypeEnumFactory.TYPE_CUSTOMER);

				BaseDAO dao = new BaseDAO();
				userList = (List<UserVO>) dao.retrieveByClause(UserVO.class,
						cond, sp);

			} else {
				InSqlBatchCaller caller = new InSqlBatchCaller(userPKs);
				userList = (List<UserVO>) caller
						.execute(new IInSqlBatchCallBack() {
							List<UserVO> userResult = new ArrayList<UserVO>();

							@Override
							public Object doWithInSql(String inSql)
									throws BusinessException, SQLException {
								String cond = " base_doc_type = ? and pk_base_doc != '~' and "
										+ UserVO.CUSERID + " in " + inSql;
								SQLParameter sp = new SQLParameter();
								sp.addParam(UserIdentityTypeEnumFactory.TYPE_CUSTOMER);

								BaseDAO dao = new BaseDAO();
								Collection<UserVO> userColl = dao
										.retrieveByClause(UserVO.class, cond,
												sp);

								userResult.addAll(userColl);

								return userResult;
							}

						});
			}

			Map<String, UserVO> pk_user_map = null;
			if (CollectionUtils.isNotEmpty(userList))
				pk_user_map = RbacPubUtil.getHashMapVO(userList
						.toArray(new UserVO[0]));

			return pk_user_map;
		} catch (SQLException e) {
			throw new BusinessException(e.getMessage());
		}
	}

	@Override
	public boolean resetUserPassWord(String cuserid) throws BusinessException {
		try {
			IUserPasswordManage upwdManage = NCLocator.getInstance().lookup(
					IUserPasswordManage.class);
			upwdManage.resetUserPassWord(cuserid);

			return true;
		} catch (Exception ex) {
			return false;
		}
	}

	@Override
	public void updateUserPassWord(String cuserid, String oldPwd, String newPwd)
			throws BusinessException {
		if (StringUtils.isBlank(oldPwd))
			throw new BusinessException(
					IUserPubConstants.getOldPasswordNullMsg());
		if (StringUtils.isBlank(newPwd))
			throw new BusinessException(
					IUserPubConstants.getNewPasswordNullMsg());
		if (StringUtils.equals(oldPwd, newPwd))
			throw new BusinessException(
					IUserPubConstants.getNewAndOldPAsswordNotSameMsg());

		IUserManageQuery userQry = NCLocator.getInstance().lookup(
				IUserManageQuery.class);
		UserVO oldUser = userQry.getUser(cuserid);

		// 旧密码加密并与之前 用户当前密码比较 进行校验
		if (!RbacUserPwdUtil.checkUserPassword(oldUser, oldPwd))
			throw new BusinessException(
					IUserPubConstants.getOldPasswordErrorMsg());

		IUserPasswordManage upwdManage = NCLocator.getInstance().lookup(
				IUserPasswordManage.class);
		upwdManage.changeUserPassWord(oldUser, newPwd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public UserVO[] queryUsersOwnedOrgPermission(String... orgPKs)
			throws BusinessException {
		if (ArrayUtils.isEmpty(orgPKs))
			return null;

		if (orgPKs.length == 1) {
			BaseDAO dao = new BaseDAO();
			SqlWrapper sw = new SqlWrapper(
					PubServiceSqlUtils.USERS_OWNED_SINGLEORG_COND);
			sw.bind("pk_org", orgPKs[0]);
			sw.bind("nowtime", new UFDateTime());

			Collection<UserVO> userColl = dao.retrieveByClause(UserVO.class,
					sw.getSql(), sw.getSqlParameter());

			return CollectionUtils.isEmpty(userColl) ? null : userColl
					.toArray(new UserVO[0]);
		} else {

			String pk_group = InvocationInfoProxy.getInstance().getGroupId();

			List<UserVO> userResult = getUserListByGroupAndOrgs(pk_group,
					orgPKs);

			return CollectionUtils.isEmpty(userResult) ? null : userResult
					.toArray(new UserVO[0]);
		}
	}

	@SuppressWarnings("unchecked")
	private List<UserVO> getUserListByGroupAndOrgs(final String pk_group,
			String... orgPKs) throws BusinessException {
		try {
			InSqlBatchCaller userCaller = new InSqlBatchCaller(orgPKs);
			List<UserVO> userResult = (List<UserVO>) userCaller
					.execute(new IInSqlBatchCallBack() {
						List<UserVO> userResult = new ArrayList<UserVO>();

						@Override
						public Object doWithInSql(String inSql)
								throws BusinessException, SQLException {
							NamedParamUtil npu = new NamedParamUtil();
							npu.addNamedParam("pk_group", pk_group);
							npu.addNamedParam("orgs", inSql);

							String userOwnPermCond = npu
									.format(PubServiceSqlUtils.USERS_OWNED_MANYORG_COND);

							SqlWrapper sw = new SqlWrapper(userOwnPermCond);
							sw.bind("nowtime", new UFDateTime());

							BaseDAO dao = new BaseDAO();
							List<UserVO> userList = (List<UserVO>) dao
									.retrieveByClause(UserVO.class,
											sw.getSql(), sw.getSqlParameter());
							if (CollectionUtils.isNotEmpty(userList))
								userResult.addAll(userList);

							return userResult;
						}

					});
			return userResult;
		} catch (Exception ex) {
			throw new BusinessException(ex.getMessage());
		}
	}

	/**
	 * @author liuxing0
	 */
	@Override
	public void updateUserEmail(String cuserid, String email, String password)
			throws BusinessException {
		BaseDAO dao = new BaseDAO();
		UserVO userVO = (UserVO) dao.retrieveByPK(UserVO.class, cuserid);
		BDPKLockUtil.lockSuperVO(userVO);
		validate(userVO, email, password);

		UserVO newVO = (UserVO) userVO.clone();
		newVO.setEmail(email);
		// 事件前通知
		BDCommonEventUtil eventUtil = new BDCommonEventUtil(
				IBDMetaDataIDConstBasic.USER);
		eventUtil.setOldObjs(new Object[] { userVO });
		eventUtil.dispatchUpdateBeforeEvent(new Object[] { newVO });
		// 数据库更新
		dao.updateVO(newVO);
		newVO = (UserVO) dao.retrieveByPK(UserVO.class, newVO.getPrimaryKey());
		// 事件后通知
		eventUtil.setOldObjs(new Object[] { userVO });
		eventUtil.dispatchUpdateBeforeEvent(new Object[] { newVO });
	}

	private void validate(UserVO userVO, String email, String password)
			throws BusinessException {
		checkPassword(password, userVO);
		checkEmailForm(email);
	}

	private void checkPassword(String password, UserVO userVO)
			throws BusinessException {
		if (!(userVO.getUser_password().equals(password))) {
			throw new BusinessException(NCLangResOnserver.getInstance()
					.getStrByID("sfapp", "MailBingPage-00011")/* 您输入的密码不正确 */,
					IUserPubConstants.PASSWORG_ERROR_CODE);
		}
	}

	private void checkEmailForm(String email) throws BusinessException {
		boolean flag = false;
		try {
			String check = "^([a-z0-9A-Z]+[_-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
			Pattern regex = Pattern.compile(check);
			Matcher matcher = regex.matcher(email);
			flag = matcher.matches();
		} catch (Exception e) {
			flag = false;
		}
		if (!flag) {
			throw new BusinessException(
					NCLangResOnserver.getInstance().getStrByID("sfapp",
							"MailBingPage-00012") /* 您输入的有邮箱不正确 */,
					IUserPubConstants.EMAIL_FORM_ERROR_CODE);
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值