Compare commits

...

5 Commits

10 changed files with 803 additions and 3 deletions

View File

@ -162,4 +162,16 @@ public class SysUserController {
ExcelUtils.exportExcelToTarget(response, null, "用户管理", list, SysUserExcel.class);
}
@GetMapping("getDeptInfoFromJH")
@ApiOperation("从金宏获取行政区划信息并保存到表中")
public Result getDeptInfoFromJH(){
return sysUserService.getDeptInfoFromJH();
}
@GetMapping("getUserInfoFromJH")
@ApiOperation("从金宏获取用户信息并保存到表中")
public Result getUserInfoFromJH() {
return sysUserService.getUserInfoFromJH();
}
}

View File

@ -41,4 +41,8 @@ public interface SysUserDao extends BaseDao<SysUserEntity> {
SysUserEntity getByDeptIdAndRoleId(@Param("deptId") Long deptId, @Param("roleId") Long roleId);
Long countAllUser();
void batchSaveUser(@Param("list")List<Map> list);
SysUserEntity getUserByName(@Param("username") String username);
}

View File

@ -73,5 +73,10 @@ public class SysUserEntity extends BaseEntity {
*/
@TableField(exist=false)
private String deptName;
/**
* 用户guid
* 2022-06-21 ytl根据黄工的需求新增
*/
private String guid;
}

View File

@ -0,0 +1,114 @@
package io.renren.modules.sys.enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 金宏项目LDAP查询用户的根节点enum
*/
public enum JhDeptEnum {
//人大常委会("1","人大常委会"),
即墨区("即墨区",new String[]{
"即墨区人大","即墨区委办公室","即墨区委宣传部","即墨区委组织部","即墨区推进大数据发展","即墨区政协办公室",
"即墨区新型冠状病毒感染肺炎疫情防控指挥部","即墨区监察委","即墨区直单位","即墨区纪委","即墨区街道办事处","即墨区项目指挥部"
})
, 城阳区("城阳区",new String[]{
"区属机关","城阳区乡镇及街道办事处","城阳区人大","城阳区委办公室","城阳区政协","城阳区政府办公室","城阳区网上审批","工作机构"
})
, 崂山区("崂山区",new String[]{
"中共崂山区纪委监委机关","区委区政府议事协调机构","区直事业单位","区直企业","崂山区人大机关","崂山区党委部门","崂山区政协机关",
"崂山区政府部门","崂山区武装部","崂山区科技创新委员会","群团部门","街道科室及社区","青岛东亿实业总公司","青岛金家岭金融聚集区管委会",
"驻区企业","驻区单位"
})
,市南区("市南区",new String[]{
"市南区人大","市南区公检法","市南区区委","市南区政协","市南区政府","市南区电子政务和信息资源管理办公室","市南区纪委"
})
,市直企业("市直企业",new String[]{"世园集团","中石化青岛石油分公司","中石化经纬有限公司","中路财产保险股份有限公司",
"二轻总公司","交运集团","华电青岛热力有限公司","国信实业有限公司","国际机场集团","市政集团","海尔集团技术研发中心",
"纺织总公司","青岛万通证券公司","青岛中泰集团","青岛公交集团","青岛区域经济合作有限公司","青岛华通国有资本运营(集团)有限责任公司",
"青岛华青公司","青岛双星集团","青岛啤酒股份有限公司制造中心","青岛啤酒集团","青岛国信集团","青岛国投有限公司", "青岛城市发展集团有限公司",
"青岛城市建设集团有限公司","青岛旅游集团","青岛水务集团有限公司","青岛海信集团","青岛海尔集团","青岛海湾集团有限公司","青岛港集团",
"青岛澳柯玛集团","青岛红星化工集团有限责任公司","青岛能源集团有限公司","青岛西海岸有限公司","青岛银行","青岛饮料集团有限公司",
"青钢集团"
})
,市直机关("市直机关",new String[]{
"中共青岛中德生态园党组","中级法院","人力资源和社会保障局","人防办","企业托管中心","供销社","侨联","信访局","公安局","其他单位",
"出版社","医疗保障局","卫生健康委","司法局","商务局","团市委","国家统计局青岛调查队","国资委","外办","妇联","审计局","宣传部",
"崂山风景区管理局","工商联","市农业农村局","市发展改革委","市场监督管理局","市城市管理局","市委党校","市委军民融合办","市委政研室",
"市委网信办","市工业和信息化局","市政府研究室","市政府驻京办","市直机关工委","市纪委监委机关","市经济发展研究院","市自然资源和规划局",
"广播电视局","应急管理局","建管局","总工会","政法委","教育局","文联","日报社","机关事务局","档案馆","检察院","残联","民政局",
"气象局","电大","畜牧兽医局","社科院","科协","科技局","红十字会","组织部","统战部","统计局","综合行政执法支队","编委办",
"老干局","财政局","贸促会","退役军人事务局","青岛仲裁委员会办公室","青岛前湾保税港区","青岛国际邮轮港管理局","青岛工程职业学院",
"青岛市乡村振兴局","青岛市交通运输局","青岛市住房公积金管理中心","青岛市住房和城乡建设局","青岛市体育局","青岛市信息产业局",
"青岛市园林和林业局","青岛市地铁工程建设指挥部","青岛市大数据发展管理局","青岛市委党史研究院","青岛市委台港澳工作办公室",
"青岛市政府驻沪办","青岛市文化和旅游局","青岛市民营经济发展局","青岛市水务管理局","青岛市水文局","青岛市海洋发展局","青岛市深圳联络办事处",
"青岛市生态环境局","青岛市董家口港区开发建设指挥部","青岛市行政审批服务局","青岛市金融工作办公室","青岛市驻济南办事办",
"青岛技师学院","青岛技院","青岛海洋科学与技术国家实验室发展中心","青岛蓝谷管理局","青岛蓝谷管理局"
})
,平度市("平度市",new String[]{
"人大","企业用户","市委办","市直各单位","政协","政府办"
})
,新市北区("新市北区",new String[]{
"区属企业","四方区","市北区","市北区人大","市北区委","市北区政协","市北区政府","市北区政法机关","市北区纪委","驻区单位"
})
,李沧区("李沧区",new String[]{
"“五位一体”联合督查","其他企业","区属机关","李沧区人大办公室","李沧区委“作风能力提升年”活动领导小组","李沧区委办公室",
"李沧区政协办公室","李沧区政府办公室","李沧区街道办事处","青岛市李沧区行政审批大厅"
})
,胶州市("胶州市",new String[]{
"12345","365便民服务中心","中共胶州市纪律检查委员会机关(胶州市监察委员会机关)","垂直管理机构","市委机构","政协胶州市委员会机构",
"政府机构","胶州市人大常委会","胶州市人民团体","胶州市人民检察院","胶州市人民武装部","胶州市人民法院","胶州市企业发展局",
"胶州市发展和改革局","胶州市镇及街道办事处","集团公司"
})
,莱西市用户("",new String[]{
"人大办","区属机关","双管单位","市委办","市级领导","政协办","政府办","省青岛市驻莱西机构","莱西市疫情防控指挥部",
"重点企业"
})
,青岛市级("青岛市级",new String[]{
})
,驻青单位("驻青单位",new String[]{
"中国农科院烟草研究所","中国动物卫生与流行病学中心","中国铁塔股份有限公司青岛市分公司","交通运输部北海航海保障中心青岛通信中心",
"国家体育总局青岛航海运动学校","安全局","山东广电网络有限公司青岛分公司","山东省海警第二支队","市邮政管理局",
"民航青岛安监管理局","气象局","海事局","烟草专卖局","省胶东调水局青岛分局","财政部青岛监管局","铁路分局","青岛出入境检验检疫局",
"青岛地质勘查开发局","青岛大学","青岛市税务局","青岛市驻青国企党建研究会","青岛广电影视传媒集团有限公司","青岛机场检验检疫局",
"青岛海关"
})
,黄岛区("黄岛区",new String[]{
"中共青岛市黄岛区委军民融合发展委员会办公室","中央驻区单位","公众投诉热线","其他联网单位","凤凰岛南岛片区村庄拆迁工作指挥部",
"垂直机构","胶南市委办公室","董家口管委","西海岸中央公园建设指挥部","西海岸新区新型冠状病毒感染肺炎疫情防控指挥部",
"西海岸新区涉稳隐患排查化解指挥部","西海岸新区解放思想大讨论工作推进小组办公室","西海岸经济新区中央商务区开发建设指挥部",
"西海岸经济新区工委管委","西海岸轨道交通指挥部","转型发展区建设推进指挥部","青岛中央活力区规划建设指挥部","青岛海洋高新区管理委员会",
"青岛西海岸新区“啤酒之城”攻坚战指挥部","青岛西海岸新区六大攻坚战总指挥部","青岛西海岸新区教育卫生项目建设推进工作领导小组",
"驻青单位","黄岛区人大","黄岛区企业","黄岛区区直机关","黄岛区委","黄岛区政协","黄岛区政府办公室","黄岛区督导巡查组","黄岛区骨干企业(原胶南市骨干企业)"
})
;
private String[] value;
private String code;
JhDeptEnum(String code,String[] value) {
this.code = code;
this.value = value;
}
public String[] getValue(){
return value;
}
public String getCode(){
return code;
}
public static List<Map> getAllToList() {
List<Map> list = new ArrayList<>();
JhDeptEnum[] values = values();
for(JhDeptEnum r:values){
Map pd = new HashMap();
pd.put(r.getCode(),r.getValue());
list.add(pd);
}
return list;
}
}

View File

@ -0,0 +1,50 @@
package io.renren.modules.sys.enums;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public enum JhDeptsEnum {
即墨区("1","即墨区"),
城阳区("2","城阳区"),
崂山区("3","崂山区"),
市南区("4","市南区"),
市直企业("5","市直企业"),
市直机关("6","市直机关"),
平度市("7","平度市"),
新市北区("8","新市北区"),
李沧区("9","李沧区"),
胶州市("10","胶州市"),
莱西市用户("11","莱西市用户"),
青岛市级("12","青岛市级"),
驻青单位("13","驻青单位"),
黄岛区("14","黄岛区")
;
private String value;
private String code;
JhDeptsEnum(String code,String value) {
this.code = code;
this.value = value;
}
public String getValue(){
return value;
}
public String getCode(){
return code;
}
public static List<Map> getAllToList() {
List<Map> list = new ArrayList<>();
JhDeptsEnum[] values = values();
for(JhDeptsEnum r:values){
Map pd = new HashMap();
pd.put(r.getCode(),r.getValue());
list.add(pd);
}
return list;
}
}

View File

@ -2,6 +2,7 @@ package io.renren.modules.sys.service;
import io.renren.common.page.PageData;
import io.renren.common.service.BaseService;
import io.renren.common.utils.Result;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.entity.SysUserEntity;
@ -55,4 +56,8 @@ public interface SysUserService extends BaseService<SysUserEntity> {
*/
Long countAllUser();
Result getDeptInfoFromJH();
Result getUserInfoFromJH();
}

View File

@ -1,16 +1,25 @@
package io.renren.modules.sys.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.BaseServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.common.utils.JhlDAPTool;
import io.renren.common.utils.Result;
import io.renren.modules.security.password.PasswordUtils;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.sys.dao.SysDeptDao;
import io.renren.modules.sys.dao.SysRegionDao;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.entity.SysDeptEntity;
import io.renren.modules.sys.entity.SysRegionEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.enums.JhDeptEnum;
import io.renren.modules.sys.enums.JhDeptsEnum;
import io.renren.modules.sys.enums.SuperAdminEnum;
import io.renren.modules.sys.service.SysDeptService;
import io.renren.modules.sys.service.SysRoleUserService;
@ -21,9 +30,11 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.naming.ldap.LdapContext;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;
/**
@ -37,6 +48,14 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
private SysDeptService sysDeptService;
@Autowired
private SysUserPostService sysUserPostService;
@Autowired
private JhlDAPTool jhlDAPTool;
@Autowired
private SysDeptDao sysDeptDao;
@Autowired
private SysUserDao sysUserDao;
@Autowired
private SysRegionDao regionDao;
@Override
public PageData<SysUserDTO> page(Map<String, Object> params) {
@ -177,4 +196,265 @@ public class SysUserServiceImpl extends BaseServiceImpl<SysUserDao, SysUserEntit
return baseDao.countAllUser();
}
@Override
public Result getDeptInfoFromJH(){
List<Map> deptList = JhDeptEnum.getAllToList();
int size = deptList.size();
try{
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
for (int n = 0; n < size; n++) {
Map map1 = deptList.get(n);
Set<String> set = map1.keySet();
String mName = "";
for(String s:set){
mName = s;
}
String key = mName;//区名即墨区
String[] ouStr = (String[])map1.get(key);
for(String ou:ouStr){
String OU = ou+","+"OU="+mName;
LdapContext ldapContext = jhlDAPTool.LDAP_connect(OU);
List<Map<String,Object>> lists = jhlDAPTool.readLdap(ldapContext,"(&(OU=*)(ou=*)(!(sAMAccountType=*))(instanceType=4))");
//Iterator<Map<String,Object>> iterator = lists.iterator();
//给pid pids赋值
if (lists.size() > 0) {
lists.forEach(dept->{//1.遍历每一个map
String namespace = dept.get("namespace").toString();
//OU=地税局分局,OU=驻区单位,OU=新市北区,DC=qd,DC=gov,DC=cn
String[] namespaces = namespace.split(",");
//判断namespaces的长度
for(int i=1;i<namespaces.length-3;i++) {//遍历每一个map的namespace
String dName = namespaces[i].split("=")[1];//具体的上级部门名称
int c = i;
for (int j = 0; j < lists.size(); j++) {
Map<String, Object> map = new HashMap<>();
if (dName.equals(lists.get(j).get("name").toString())) {
String id = lists.get(j).get("id").toString();
String pidsOld = dept.get("pids").toString() == ""? "" : (dept.get("pids").toString() + ",");
if (c == 1) {
dept.put("pid", id);
dept.put("pids", pidsOld + id);
} else {
dept.put("pids", pidsOld + id);
}
break;
}
}
}
});
//给district和type赋值
String districtName,type;
Long distict;
switch (key){
case "新市北区":
districtName = "市北区";
distict = getDistict(districtName);
lists.forEach(l->{
l.put("district",distict);
String name = l.get("name").toString();
if(name.contains("企业") || name.contains("集团") || name.contains("公司")){
l.put("type",4);
}else{
l.put("type",3);
}
});
break;
case "青岛市级":
districtName = "青岛市";
distict = getDistict(districtName);
lists.forEach(l->{
l.put("district",distict);
l.put("type",2);
});
break;
case "莱西市用户":
districtName = "莱西市";
distict = getDistict(districtName);
lists.forEach(l->{
l.put("district",distict);
String name = l.get("name").toString();
if(name.contains("企业") || name.contains("集团") || name.contains("公司")){
l.put("type",4);
}else{
l.put("type",3);
}
});
break;
case "黄岛区":
districtName = "西海岸新区";
distict = getDistict(districtName);
lists.forEach(l->{
l.put("district",distict);
String name = l.get("name").toString();
if(name.contains("企业") || name.contains("集团") || name.contains("公司")){
l.put("type",4);
}else{
l.put("type",3);
}
});
break;
case "市直企业":
distict = getDistict("青岛市");
lists.forEach(l->{
l.put("district",distict);
l.put("type",4);
});
break;
case "市直机关":
distict = getDistict("青岛市");
lists.forEach(l->{
l.put("district",distict);
l.put("type",2);
});
break;
case "驻青单位":
distict = getDistict("山东省");
lists.forEach(l->{
l.put("district",distict);
l.put("type",1);
});
break;
default:
distict = getDistict(mName);
lists.forEach(l->{
l.put("district",distict);
String name = l.get("name").toString();
if(name.contains("企业") || name.contains("集团") || name.contains("公司")){
l.put("type",4);
}else{
l.put("type",3);
}
});
}
lists.forEach(list->{//如果有该ID和name目前暂不处理否则插入
SysDeptEntity dept = sysDeptDao.getById(Long.valueOf(list.get("id").toString()));
SysDeptEntity deptNew = new SysDeptEntity();
deptNew.setName(list.get("name").toString());
deptNew.setId(Long.valueOf(list.get("id").toString()));
deptNew.setPid(Long.valueOf(list.get("pid").toString()));
deptNew.setPids(list.get("pids").toString());
deptNew.setDistrict(Long.valueOf(list.get("district").toString()));
deptNew.setType(Integer.parseInt(list.get("type").toString()));
if(dept == null){
System.out.println("deptname->"+deptNew.getName());
sysDeptDao.insert(deptNew);
}
});
}
}
}
}
});
return new Result().ok("保存成功");
}catch (Exception e){
e.printStackTrace();
return new Result().error("保存失败");
}
}
@Override
public Result getUserInfoFromJH(){
List<Map> deptList = JhDeptsEnum.getAllToList();
int size = deptList.size();
try {
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
for (int i = 1; i <= size; i++) {
LdapContext ldapContext = jhlDAPTool.LDAP_connect(deptList.get(i - 1).get(String.valueOf(i)).toString());
List<Map> maps = jhlDAPTool.readLdap(ldapContext);
if (maps.size() > 0) {
maps.forEach(m-> {
//根据username判断
if(m.get(("username")) != null){
String userName = m.get("username").toString();
SysUserEntity user = sysUserDao.getUserByName(userName);
if(user == null){//用户表中没有该用户插入
SysUserEntity newUser = new SysUserEntity();
newUser.setUsername(userName);
newUser.setSuperAdmin(0);
newUser.setGuid(m.get("guid") == null ? "":m.get("guid").toString());
newUser.setId(Long.valueOf(m.get("id") == null ? "0":m.get("id").toString()));
newUser.setRealName(m.get("real_name") == null ?"":m.get("real_name").toString());
newUser.setEmail(m.get("email") == null ?"":m.get("email").toString());
newUser.setMobile(m.get("mobile") == null ?"":m.get("mobile").toString());
newUser.setStatus(1);//账号状态 1正常 0停用
//给dept_id赋值
String deptNames = m.get("distinguishedName") == null ? "":m.get("distinguishedName").toString();
if(deptNames == null){
newUser.setDeptId(0L);
}else{
String[] deptArray = deptNames.split(",");
String dept,deptFather;
dept = deptArray[1];
deptFather = deptArray[2];
long id = getDeptId(dept.substring(3,dept.length()),deptFather.substring(3,deptFather.length()));
newUser.setDeptId(id);
sysUserDao.insert(newUser);
}
}
}
});
}
}
}
});
return new Result().ok("保存成功");
} catch (Exception e) {
e.printStackTrace();
return new Result().error("保存失败");
}
}
public SysRegionEntity getRegion(String name){
QueryWrapper<SysRegionEntity> regionWrapper = new QueryWrapper<>();
regionWrapper.eq("name",name);
SysRegionEntity region = regionDao.selectOne(regionWrapper);
return region;
}
public long getDeptId(String deptName,String fatherDeptName){
QueryWrapper<SysDeptEntity> deptWrapper = new QueryWrapper<>();
deptWrapper.eq("name",deptName);
List<SysDeptEntity> deptList = sysDeptDao.selectList(deptWrapper);
if(deptList.size() == 0){
return 0;
}else if(deptList.size() == 1){
return deptList.get(0).getId();
}else{//出现多个相同的deptname,根据他们的父级来确定
AtomicLong newId = new AtomicLong();
deptList.forEach(dept->{
long fatherId = dept.getPid();//获取其中一个的父级ID
SysDeptEntity fatherEntity = sysDeptDao.getById(fatherId);//根据父级ID查询管理部门
if(fatherEntity != null && fatherEntity.getName().equals(fatherDeptName)){//如果该管理部门的名称等于传进来的父级名称那么这条dept就是我们需要的
if(fatherEntity.getId() == fatherId){//如果父级ID等于
newId.set(dept.getId());
}
}
});
return newId.get();
}
}
public Long getDistict(String deptName){
QueryWrapper<SysRegionEntity> regionWrapper = new QueryWrapper<>();
regionWrapper.eq("name",deptName);
SysRegionEntity entity = regionDao.selectOne(regionWrapper);
if (entity == null) {
return 0L;
}else{
return entity.getId();
}
}
}

View File

@ -73,5 +73,18 @@
WHERE
`status` = 1
</select>
<insert id="batchSaveUser" parameterType="java.util.List">
INSERT INTO user_bak (displayName,distinguishedName,userPrincipalName,telephoneNumber,objectGUID,sAMAccountName,primaryGroupID)
values
<foreach collection="list" item="item" separator="," >
(
#{item.displayName},#{item.distinguishedName},#{item.userPrincipalName},#{item.telephoneNumber},
#{item.objectGUID},#{item.sAMAccountName},#{item.primaryGroupID}
)
</foreach>
</insert>
<select id="getUserByName" parameterType="java.lang.String" resultType="io.renren.modules.sys.entity.SysUserEntity">
SELECT id,username FROM sys_user WHERE username = #{username} limit 1
</select>
</mapper>

View File

@ -0,0 +1,292 @@
package io.renren.common.utils;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.*;
import java.util.*;
/**
* 通过该类完成金宏系统中 部门和用户名信息的提取
*/
@Component
public class JhlDAPTool {
private String URL = "ldap://15.72.158.50:389/";
private String BASEDN = "DC=qd,DC=gov,DC=cn";//指定从哪里开始搜索从上往下推
private String username = "CN=智慧发改项目认证接入,OU=管理开发用户,DC=qd,DC=gov,DC=cn";//要登录的账号所在位置从下往上推
private String password = "QD@zhfg2019";
private String FACTORY = "com.sun.jndi.ldap.LdapCtxFactory";
LdapContext ctx = null;
Control[] connCtls = null;
//登录LDAP服务器
public LdapContext LDAP_connect(String OU) {
//1. 设置初始LDAP上下文的属性并初始化LDAP上下文
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, FACTORY);
if(StringUtils.isEmpty(OU)){
env.put(Context.PROVIDER_URL, URL +BASEDN);//路径
}else{
env.put(Context.PROVIDER_URL, URL + "OU="+OU+","+BASEDN);//路径
}
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, username); // 管理员
env.put(Context.SECURITY_CREDENTIALS, password); // 管理员密码
// **解决 乱码 的关键一句
env.put("java.naming.ldap.attributes.binary","objectGUID");
try {
ctx = new InitialLdapContext(env, connCtls);
System.out.println( "连接成功" );
return ctx;
} catch (javax.naming.AuthenticationException e) {
System.out.println("连接失败:");
e.printStackTrace();
} catch (Exception e) {
System.out.println("连接出错:"+e.getMessage());
e.printStackTrace();
}
return null;
}
private void closeContext(){
if (ctx != null) {
try {
ctx.close();
}
catch (NamingException e) {
e.printStackTrace();
}
}
}
/**
* 根据区名获取用户信息
* @param
* @param
* @return
*/
public List<Map> readLdap(LdapContext ctx){//OU=即墨区,
List<Map> lm=new ArrayList<Map>(1000);
byte[] cookie = null;
try {
if(ctx!=null) {
//2. 设置查询的属性
SearchControls searchControls = new SearchControls();//搜索控件
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);//搜索范围,1只搜索指定命名对象的一个级别这是缺省值2以指定命名对象为根结点的整棵树
//分页
ctx.setRequestControls(new Control[]{new PagedResultsControl(2, Control.CRITICAL)});
do {
NamingEnumeration<SearchResult> answer = ctx.search("", "sAMAccountType=805306368", searchControls);
//NamingEnumeration<SearchResult> answer = ctx.search("", "objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=gov,DC=cn", searchControls);
while (answer.hasMore()) {
SearchResult result = (SearchResult) answer.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
//System.out.println("getNameInNamespace-》"+result.getNameInNamespace());//CN=李平先,OU=抬三,OU=即墨普东中心社区,OU=即墨中心社区,OU=即墨区,DC=qd,DC=gov,DC=cn
Map<String,Object> user = new HashMap<>();
while (attrs.hasMore()) {
Attribute next = attrs.next();
//System.out.println(next);
if ("displayName".equals(next.getID())) {
user.put("real_name",next.get().toString());
//user.setDisplayName(next.get().toString());
}else if("sAMAccountName".equals(next.getID())){
user.put("username",next.get().toString());
//user.setSamaccountName(next.get().toString());
}else if("userPrincipalName".equals(next.getID())){
user.put("email",next.get().toString());
//user.setUserPrincipalName(next.get().toString());
}else if("telephoneNumber".equals(next.getID())){
user.put("mobile",next.get().toString());
//user.setTelephoneNumber(next.get().toString());
}else if("distinguishedName".equals(next.getID())){
//CN=葛琳,OU=城阳区疾病预防控制中心,OU=城阳区卫生健康局,OU=区属机关,OU=城阳区,DC=qd,DC=gov,DC=cn
// String distinguishedName = next.get().toString();
// String[] distinguishedNames = distinguishedName.split(",");
// String deptName = distinguishedNames[1].split("=")[1];
user.put("distinguishedName",next.get().toString());
}else if("objectGUID".equals(next.getID())){
String guidStr = next.getID().toString();
user.put("id",SingleID.getSingleID(guidStr));
String guid = guidStr.substring(1,guidStr.length()-1);
user.put("guid",guid);
}
}
lm.add(user);
}
cookie = parseControls(ctx.getResponseControls());
ctx.setRequestControls(new Control[]{new PagedResultsControl(2, cookie, Control.CRITICAL)});
} while (cookie != null && (cookie.length != 0));
}
}catch (Exception e) {
System.out.println("获取用户信息异常:");
e.printStackTrace();
}finally {
closeContext();
}
System.out.println(lm.size());
return lm;
}
/**
* 获取管理部门信息
* @param ctx
* @param filter
* @return
*/
public List<Map<String,Object>> readLdap(LdapContext ctx,String filter){
List<Map<String,Object>> lm=new ArrayList<>(1000);
byte[] cookie = null;
try {
if(ctx!=null) {
//过滤条件
//String filter = "(&(objectClass=*)(uid=*))";
//String filter = "(&(userAccountControl=66048)(sAMAccountType=805306368))";
//String[] attrPersonArray = {"sAMAccountName", "distinguishedName", "displayName"};
//String[] attrPersonArray = { "uid", "userPassword", "displayName", "cn", "sn", "mail", "description","uidNumber","gidNumber" };
//2. 设置查询的属性
SearchControls searchControls = new SearchControls();//搜索控件
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);//搜索范围,1只搜索指定命名对象的一个级别这是缺省值2以指定命名对象为根结点的整棵树 SearchControls.SUBTREE_SCOPE
//searchControls.setReturningAttributes(attrPersonArray);
//分页
ctx.setRequestControls(new Control[]{new PagedResultsControl(2, Control.CRITICAL)});
//IdentifierGenerator identifierGenerator=new DefaultIdentifierGenerator();
do {
//3.(1)要搜索的上下文或对象的名称(2).过滤条件可为null默认搜索所有信息(3).搜索控件可为null使用默认的搜索控件
//objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=gov,DC=cn
//sAMAccountType=805306368
NamingEnumeration<SearchResult> answer = ctx.search("", filter, searchControls);
//NamingEnumeration<SearchResult> answer = ctx.search("", "objectCategory=CN=Person,CN=Schema,CN=Configuration,DC=gov,DC=cn", searchControls);
//<SearchResult> answer = ctx.search("",filter.toString(),searchControls);
while (answer.hasMore()) {
SearchResult result = (SearchResult) answer.next();
NamingEnumeration<? extends Attribute> attrs = result.getAttributes().getAll();
//System.out.println(result.getName());//CN=李平先,OU=抬三,OU=即墨普东中心社区,OU=即墨中心社区
//System.out.println(result.getClass());
System.out.println("getNameInNamespace-》"+result.getNameInNamespace());//CN=李平先,OU=抬三,OU=即墨普东中心社区,OU=即墨中心社区,OU=即墨区,DC=qd,DC=gov,DC=cn
Map<String,Object> dept = new HashMap<>();
while (attrs.hasMore()) {
Attribute next = attrs.next();
//System.out.println(next);
if ("name".equals(next.getID())) {
String name = next.get().toString();
dept.put("name",name);
//dept.put("id",SingleID.getSingleID(name));
}else if("distinguishedName".equals(next.getID())){
//OU=事业发展中心,OU=办公厅,OU=人大常委会,DC=qd,DC=gov,DC=cn
dept.put("namespace",next.get());
}else if("instanceType".equals(next.getID())){
dept.put("instancetype",next.get());
}
else if("objectGUID".equals(next.getID())){
//{49D369CC-9DD3-407D-B618-01B00496039B}
byte[] GUID = (byte[])next.get();
String guid = getGUID(GUID);
String id = SingleID.getSingleID(guid);
dept.put("id",String.valueOf(id));
}
}
dept.put("pid",0);
dept.put("pids","");
if(!dept.get("name").toString().contains("停用") && !dept.get("name").toString().contains("删除") && !dept.get("name").toString().contains("人员") && !dept.get("name").toString().contains("临时")){
lm.add(dept);
}
//System.out.println("-----------------------------------------------");
}
cookie = parseControls(ctx.getResponseControls());
ctx.setRequestControls(new Control[]{new PagedResultsControl(2, cookie, Control.CRITICAL)});
} while (cookie != null && (cookie.length != 0));
}
}catch (Exception e) {
System.out.println("获取区域信息异常:");
e.printStackTrace();
}finally {
closeContext();
}
System.out.println(lm.size());
return lm;
}
//解决objectGUID乱码的具体方法
private static String getGUID(byte[] GUID) {
String strGUID = "";
String byteGUID = "";
//Convert the GUID into string using the byte format
for (int c=0;c<GUID.length;c++) {
byteGUID = byteGUID + "\\" + AddLeadingZero((int)GUID[c] & 0xFF);
}
strGUID = "{";
strGUID = strGUID + AddLeadingZero((int)GUID[3] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[2] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[1] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[0] & 0xFF);
strGUID = strGUID + "-";
strGUID = strGUID + AddLeadingZero((int)GUID[5] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[4] & 0xFF);
strGUID = strGUID + "-";
strGUID = strGUID + AddLeadingZero((int)GUID[7] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[6] & 0xFF);
strGUID = strGUID + "-";
strGUID = strGUID + AddLeadingZero((int)GUID[8] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[9] & 0xFF);
strGUID = strGUID + "-";
strGUID = strGUID + AddLeadingZero((int)GUID[10] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[11] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[12] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[13] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[14] & 0xFF);
strGUID = strGUID + AddLeadingZero((int)GUID[15] & 0xFF);
strGUID = strGUID + "}";
return strGUID;
}
static String AddLeadingZero(int k) {
return (k <= 0xF) ? "0" + Integer.toHexString(k) : Integer
.toHexString(k);
}
//分页查询时下次查询要用的cookie
private static byte[] parseControls(Control[] controls)
throws NamingException {
byte[] cookie = null;
if (controls != null) {
for (int i = 0; i < controls.length; i++) {
if (controls[i] instanceof PagedResultsResponseControl) {
PagedResultsResponseControl prrc = (PagedResultsResponseControl) controls[i];
cookie = prrc.getCookie();
System.out.println(">>Next Page \n");
}
}
}
return (cookie == null) ? new byte[0] : cookie;
}
}

View File

@ -0,0 +1,25 @@
package io.renren.common.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
* 字符串根据MD5计算出定长的唯一数字符合mysql bigint的取值范围
*/
public class SingleID {
public static String getSingleID(String s) throws Exception{
// 第一步获取MessageDigest对象参数为MD5字符串表示这是一个MD5算法
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(s.getBytes());
//计算MD5值
byte[] bytes = md5.digest();
byte[] newBytes = new byte[8];
//因为转化的数字太长了所以截取部分进行转化
System.arraycopy(bytes,6,newBytes,0,8);
BigInteger bigInt = new BigInteger(1, newBytes);
String resultStr = bigInt.toString(10);
return resultStr.substring(0,resultStr.length()-1);
}
}