synchronizers optimize

This commit is contained in:
MaxKey 2022-01-25 12:53:01 +08:00
parent b56496a6df
commit 50dd3ef566
14 changed files with 251 additions and 194 deletions

View File

@ -53,7 +53,7 @@ public class Organizations extends JpaBaseEntity implements Serializable {
@Column @Column
private String namePath; private String namePath;
@Column @Column
private String level; private int level;
@Column @Column
private String hasChild; private String hasChild;
@Column @Column
@ -174,11 +174,11 @@ public class Organizations extends JpaBaseEntity implements Serializable {
this.type = type; this.type = type;
} }
public String getLevel() { public int getLevel() {
return level; return level;
} }
public void setLevel(String level) { public void setLevel(int level) {
this.level = level; this.level = level;
} }

View File

@ -44,7 +44,7 @@ public class ScimOrganization extends ScimResource{
private String namePath; private String namePath;
private String level; private int level;
private String division; private String division;
@ -130,11 +130,11 @@ public class ScimOrganization extends ScimResource{
this.namePath = namePath; this.namePath = namePath;
} }
public String getLevel() { public int getLevel() {
return level; return level;
} }
public void setLevel(String level) { public void setLevel(int level) {
this.level = level; this.level = level;
} }

View File

@ -17,12 +17,16 @@
package org.maxkey.synchronizer.activedirectory; package org.maxkey.synchronizer.activedirectory;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import javax.naming.NamingEnumeration; import javax.naming.NamingEnumeration;
import javax.naming.NamingException; import javax.naming.NamingException;
import javax.naming.directory.Attribute; import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult; import javax.naming.directory.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.maxkey.constants.ConstsStatus;
import org.maxkey.constants.ldap.OrganizationalUnit; import org.maxkey.constants.ldap.OrganizationalUnit;
import org.maxkey.entity.HistorySynchronizer; import org.maxkey.entity.HistorySynchronizer;
import org.maxkey.entity.Organizations; import org.maxkey.entity.Organizations;
@ -42,50 +46,95 @@ public class ActiveDirectoryOrganizationService extends AbstractSynchronizerSer
public void sync() { public void sync() {
loadOrgsById("1"); loadOrgsById("1");
_logger.info("Sync Organizations ..."); _logger.info("Sync ActiveDirectory Organizations ...");
try { try {
SearchControls constraints = new SearchControls(); SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope()); constraints.setSearchScope(ldapUtils.getSearchScope());
NamingEnumeration<SearchResult> results = ldapUtils.getConnection() String filter = "(&(objectClass=OrganizationalUnit))";
.search(ldapUtils.getBaseDN(), "(&(objectClass=OrganizationalUnit))", constraints); if(StringUtils.isNotBlank(this.getSynchronizer().getFilters())) {
//filter = this.getSynchronizer().getFilters();
}
NamingEnumeration<SearchResult> results =
ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints);
ArrayList<Organizations> orgsList = new ArrayList<Organizations>();
int maxLevel = 0;
long recordCount = 0; long recordCount = 0;
while (null != results && results.hasMoreElements()) { while (null != results && results.hasMoreElements()) {
Object obj = results.nextElement(); Object obj = results.nextElement();
if (obj instanceof SearchResult) { if (obj instanceof SearchResult) {
recordCount ++; SearchResult sr = (SearchResult) obj;
SearchResult si = (SearchResult) obj; if("OU=Domain Controllers,DC=maxkey,DC=top".endsWith(sr.getNameInNamespace())) {
_logger.info("Sync OrganizationalUnit Record " + recordCount+" --------------------------------------------------"); _logger.info("Skip 'OU=Domain Controllers' .");
_logger.trace("name " + si.getName()); continue;
_logger.info("NameInNamespace " + si.getNameInNamespace()); }
_logger.debug("Sync OrganizationalUnit {} , name {} , NameInNamespace {}" ,
(++recordCount),sr.getName(),sr.getNameInNamespace());
HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>(); HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>();
NamingEnumeration<? extends Attribute> attrs = si.getAttributes().getAll(); NamingEnumeration<? extends Attribute> attrs = sr.getAttributes().getAll();
while (null != attrs && attrs.hasMoreElements()) { while (null != attrs && attrs.hasMoreElements()) {
Attribute objAttrs = attrs.nextElement(); Attribute objAttrs = attrs.nextElement();
_logger.trace("attribute "+objAttrs.getID() + " : " + objAttrs.get()); _logger.trace("attribute "+objAttrs.getID() + " : " + objAttrs.get());
attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs);
} }
Organizations organization = buildOrganization(attributeMap,si.getName(),si.getNameInNamespace()); Organizations organization = buildOrganization(attributeMap,sr.getName(),sr.getNameInNamespace());
if(organization != null) {
orgsList.add(organization);
maxLevel = (maxLevel < organization.getLevel()) ? organization.getLevel() : maxLevel ;
}
}
}
for (int level = 2 ; level <= maxLevel ; level++) {
for(Organizations organization : orgsList) {
if(organization.getLevel() == level) {
String parentNamePath= organization.getNamePath().substring(0, organization.getNamePath().lastIndexOf("/"));
if(orgsNamePathMap.get(organization.getNamePath())!=null) {
_logger.info("org " + orgsNamePathMap.get(organization.getNamePath()).getNamePath()+" exists.");
continue;
}
Organizations parentOrg = orgsNamePathMap.get(parentNamePath);
if(parentOrg == null ) {
parentOrg = rootOrganization;
}
organization.setParentId(parentOrg.getId());
organization.setParentName(parentOrg.getName());
organization.setCodePath(parentOrg.getCodePath()+"/"+organization.getId());
_logger.info("parentNamePath " + parentNamePath+" , namePah " + organization.getNamePath());
organizationsService.saveOrUpdate(organization); organizationsService.saveOrUpdate(organization);
_logger.info("Organizations " + organization); orgsNamePathMap.put(organization.getNamePath(), organization);
HistorySynchronizer historySynchronizer =new HistorySynchronizer();
historySynchronizer.setId(historySynchronizer.generateId());
historySynchronizer.setSyncId(this.synchronizer.getId());
historySynchronizer.setSyncName(this.synchronizer.getName());
historySynchronizer.setObjectId(organization.getId());
historySynchronizer.setObjectName(organization.getName());
historySynchronizer.setObjectType(Organizations.class.getSimpleName());
historySynchronizer.setInstId(synchronizer.getInstId());
historySynchronizer.setResult("success");
this.historySynchronizerService.insert(historySynchronizer);
}
} }
} }
//ldapUtils.close(); //ldapUtils.close();
} catch (NamingException e) { } catch (NamingException e) {
e.printStackTrace(); _logger.error("NamingException " , e);
} }
} }
public Organizations buildOrganization(HashMap<String,Attribute> attributeMap,String name,String nameInNamespace) { public Organizations buildOrganization(HashMap<String,Attribute> attributeMap,String name,String nameInNamespace) {
if("OU=Domain Controllers,DC=maxkey,DC=top".endsWith(nameInNamespace)) { try {
_logger.info("to skip.");
return null;
}
Organizations org = new Organizations(); Organizations org = new Organizations();
org.setLdapDn(nameInNamespace); org.setLdapDn(nameInNamespace);
nameInNamespace = nameInNamespace.replaceAll(",OU=", "/").replaceAll("OU=", "/"); nameInNamespace = nameInNamespace.replaceAll(",OU=", "/").replaceAll("OU=", "/");
@ -95,25 +144,14 @@ public class ActiveDirectoryOrganizationService extends AbstractSynchronizerSer
for(int i = namePaths.length -1 ; i >= 0 ; i --) { for(int i = namePaths.length -1 ; i >= 0 ; i --) {
namePah = namePah + "/" + namePaths[i]; namePah = namePah + "/" + namePaths[i];
} }
namePah = namePah.substring(0, namePah.length() - 1); namePah = namePah.substring(0, namePah.length() - 1);
String parentNamePath= namePah.substring(0, namePah.lastIndexOf("/"));
if(orgsNamePathMap.get(namePah)!=null) {
_logger.info("org " + orgsNamePathMap.get(namePah).getNamePath()+" exists.");
return null;
}
Organizations parentOrg = orgsNamePathMap.get(parentNamePath);
org.setId(org.generateId()); org.setId(org.generateId());
org.setCode(org.getId());
org.setNamePath(namePah); org.setNamePath(namePah);
org.setParentId(parentOrg.getId()); org.setLevel(namePaths.length);
org.setParentName(parentOrg.getName());
org.setCodePath(parentOrg.getCodePath()+"/"+org.getId());
_logger.info("parentNamePath " + parentNamePath+" , namePah " + namePah);
try {
org.setName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap)); org.setName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap));
org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap)); org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap));
org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap)); org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap));
org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap)); org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap));
@ -121,22 +159,14 @@ public class ActiveDirectoryOrganizationService extends AbstractSynchronizerSer
org.setPostalCode(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALCODE,attributeMap)); org.setPostalCode(LdapUtils.getAttributeStringValue(OrganizationalUnit.POSTALCODE,attributeMap));
org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap)); org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap));
org.setInstId(this.synchronizer.getInstId()); org.setInstId(this.synchronizer.getInstId());
orgsNamePathMap.put(org.getNamePath(), org); org.setStatus(ConstsStatus.ACTIVE);
_logger.info("org " + org);
organizationsService.merge(org); _logger.debug("Organization " + org);
HistorySynchronizer historySynchronizer =new HistorySynchronizer();
historySynchronizer.setId(historySynchronizer.generateId());
historySynchronizer.setSyncId(this.synchronizer.getId());
historySynchronizer.setSyncName(this.synchronizer.getName());
historySynchronizer.setObjectId(org.getId());
historySynchronizer.setObjectName(org.getName());
historySynchronizer.setObjectType(Organizations.class.getSimpleName());
historySynchronizer.setResult("success");
this.historySynchronizerService.insert(historySynchronizer);
} catch (NamingException e) {
e.printStackTrace();
}
return org; return org;
} catch (NamingException e) {
_logger.error("NamingException " , e);
}
return null;
} }

View File

@ -23,6 +23,8 @@ import javax.naming.NamingException;
import javax.naming.directory.Attribute; import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult; import javax.naming.directory.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.maxkey.constants.ldap.ActiveDirectoryUser; import org.maxkey.constants.ldap.ActiveDirectoryUser;
import org.maxkey.entity.HistorySynchronizer; import org.maxkey.entity.HistorySynchronizer;
import org.maxkey.entity.Organizations; import org.maxkey.entity.Organizations;
@ -42,57 +44,55 @@ public class ActiveDirectoryUsersService extends AbstractSynchronizerService
ActiveDirectoryUtils ldapUtils; ActiveDirectoryUtils ldapUtils;
public void sync() { public void sync() {
_logger.info("Sync Users..."); _logger.info("Sync ActiveDirectory Users...");
loadOrgsById("1"); loadOrgsById("1");
try { try {
SearchControls constraints = new SearchControls(); SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope()); constraints.setSearchScope(ldapUtils.getSearchScope());
NamingEnumeration<SearchResult> results = ldapUtils.getConnection() String filter = StringUtils.isNotBlank(this.getSynchronizer().getFilters())?
.search(ldapUtils.getBaseDN(), "(&(objectClass=User))", constraints); getSynchronizer().getFilters() : "(&(objectClass=User))";
NamingEnumeration<SearchResult> results =
ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints);
long recordCount = 0; long recordCount = 0;
while (null != results && results.hasMoreElements()) { while (null != results && results.hasMoreElements()) {
Object obj = results.nextElement(); Object obj = results.nextElement();
if (obj instanceof SearchResult) { if (obj instanceof SearchResult) {
recordCount ++; SearchResult sr = (SearchResult) obj;
SearchResult si = (SearchResult) obj; if(sr.getNameInNamespace().indexOf("CN=Users,DC=maxkey,DC=top")>-1
_logger.info("Sync Users Record " + recordCount+" --------------------------------------------------"); ||sr.getNameInNamespace().indexOf("OU=Domain Controllers,DC=maxkey,DC=top")>-1) {
_logger.trace("name " + si.getName()); _logger.info("to skip.");
_logger.info("NameInNamespace " + si.getNameInNamespace()); continue;
}
_logger.debug("Sync User {} , name {} , NameInNamespace {}" ,
(++recordCount),sr.getName(),sr.getNameInNamespace());
HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>(); HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>();
NamingEnumeration<? extends Attribute> attrs = si.getAttributes().getAll(); NamingEnumeration<? extends Attribute> attrs = sr.getAttributes().getAll();
while (null != attrs && attrs.hasMoreElements()) { while (null != attrs && attrs.hasMoreElements()) {
Attribute objAttrs = attrs.nextElement(); Attribute objAttrs = attrs.nextElement();
_logger.trace("attribute "+objAttrs.getID() + " : " + objAttrs.get()); _logger.trace("attribute "+objAttrs.getID() + " : " + objAttrs.get());
attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs);
} }
UserInfo userInfo =buildUserInfo(attributeMap,si.getName(),si.getNameInNamespace()); UserInfo userInfo =buildUserInfo(attributeMap,sr.getName(),sr.getNameInNamespace());
if(userInfo != null) {
userInfo.setPassword(userInfo.getUsername() + "Maxkey@888"); userInfo.setPassword(userInfo.getUsername() + "Maxkey@888");
userInfoService.saveOrUpdate(userInfo); userInfoService.saveOrUpdate(userInfo);
_logger.info("userInfo " + userInfo); _logger.info("userInfo " + userInfo);
} }
} }
}
//ldapUtils.close(); //ldapUtils.close();
} catch (NamingException e) { } catch (NamingException e) {
e.printStackTrace(); _logger.error("NamingException " , e);
} }
} }
public void postSync(UserInfo userInfo) {
}
public UserInfo buildUserInfo(HashMap<String,Attribute> attributeMap,String name,String nameInNamespace) { public UserInfo buildUserInfo(HashMap<String,Attribute> attributeMap,String name,String nameInNamespace) {
if(nameInNamespace.indexOf("CN=Users,DC=maxkey,DC=top")>-1
||nameInNamespace.indexOf("OU=Domain Controllers,DC=maxkey,DC=top")>-1) {
_logger.info("to skip.");
return null;
}
UserInfo userInfo = new UserInfo(); UserInfo userInfo = new UserInfo();
userInfo.setLdapDn(nameInNamespace); userInfo.setLdapDn(nameInNamespace);
nameInNamespace = nameInNamespace.replaceAll(",OU=", "/").replaceAll("OU=", "/").replaceAll("CN=", "/"); nameInNamespace = nameInNamespace.replaceAll(",OU=", "/").replaceAll("OU=", "/").replaceAll("CN=", "/");
@ -107,6 +107,10 @@ public class ActiveDirectoryUsersService extends AbstractSynchronizerService
String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/")); String deptNamePath= namePah.substring(0, namePah.lastIndexOf("/"));
_logger.info("deptNamePath " + deptNamePath); _logger.info("deptNamePath " + deptNamePath);
Organizations deptOrg = orgsNamePathMap.get(deptNamePath); Organizations deptOrg = orgsNamePathMap.get(deptNamePath);
if(deptOrg == null ) {
deptOrg = rootOrganization;
}
userInfo.setDepartment(deptOrg.getName()); userInfo.setDepartment(deptOrg.getName());
userInfo.setDepartmentId(deptOrg.getId()); userInfo.setDepartmentId(deptOrg.getId());
try { try {
@ -153,13 +157,7 @@ public class ActiveDirectoryUsersService extends AbstractSynchronizerService
userInfo.setTimeZone("Asia/Shanghai"); userInfo.setTimeZone("Asia/Shanghai");
userInfo.setStatus(1); userInfo.setStatus(1);
userInfo.setInstId(this.synchronizer.getInstId()); userInfo.setInstId(this.synchronizer.getInstId());
UserInfo quser=new UserInfo();
quser.setUsername(userInfo.getUsername());
UserInfo loadedUser=userInfoService.load(quser);
if(loadedUser == null) {
userInfo.setPassword(userInfo.generateId());
userInfoService.insert(userInfo);
HistorySynchronizer historySynchronizer =new HistorySynchronizer(); HistorySynchronizer historySynchronizer =new HistorySynchronizer();
historySynchronizer.setId(historySynchronizer.generateId()); historySynchronizer.setId(historySynchronizer.generateId());
historySynchronizer.setSyncId(this.synchronizer.getId()); historySynchronizer.setSyncId(this.synchronizer.getId());
@ -167,11 +165,10 @@ public class ActiveDirectoryUsersService extends AbstractSynchronizerService
historySynchronizer.setObjectId(userInfo.getId()); historySynchronizer.setObjectId(userInfo.getId());
historySynchronizer.setObjectName(userInfo.getUsername()); historySynchronizer.setObjectName(userInfo.getUsername());
historySynchronizer.setObjectType(Organizations.class.getSimpleName()); historySynchronizer.setObjectType(Organizations.class.getSimpleName());
historySynchronizer.setInstId(synchronizer.getInstId());
historySynchronizer.setResult("success"); historySynchronizer.setResult("success");
this.historySynchronizerService.insert(historySynchronizer); this.historySynchronizerService.insert(historySynchronizer);
}else {
_logger.info("username " + userInfo.getUsername()+" exists.");
}
} catch (NamingException e) { } catch (NamingException e) {
e.printStackTrace(); e.printStackTrace();

View File

@ -42,7 +42,7 @@ public class DingtalkOrganizationService extends AbstractSynchronizerService im
String access_token; String access_token;
public void sync() { public void sync() {
_logger.info("Sync Organizations ..."); _logger.info("Sync Dingtalk Organizations ...");
LinkedBlockingQueue<Long> deptsQueue = new LinkedBlockingQueue<Long>(); LinkedBlockingQueue<Long> deptsQueue = new LinkedBlockingQueue<Long>();
deptsQueue.add(1L); deptsQueue.add(1L);
HashMap<Long,DeptBaseResponse> deptMap = new HashMap<Long,DeptBaseResponse>(); HashMap<Long,DeptBaseResponse> deptMap = new HashMap<Long,DeptBaseResponse>();
@ -77,8 +77,6 @@ public class DingtalkOrganizationService extends AbstractSynchronizerService im
return rspDepts; return rspDepts;
} }
public Organizations buildOrganization(DeptBaseResponse dept,DeptBaseResponse parentDept) { public Organizations buildOrganization(DeptBaseResponse dept,DeptBaseResponse parentDept) {
Organizations org = new Organizations(); Organizations org = new Organizations();
org.setId(dept.getDeptId()+""); org.setId(dept.getDeptId()+"");

View File

@ -44,7 +44,7 @@ public class DingtalkUsersService extends AbstractSynchronizerService implement
String access_token; String access_token;
public void sync() { public void sync() {
_logger.info("Sync Users..."); _logger.info("Sync Dingtalk Users...");
try { try {
List<Organizations> organizations = List<Organizations> organizations =
@ -55,6 +55,7 @@ public class DingtalkUsersService extends AbstractSynchronizerService implement
for(Organizations dept : organizations) { for(Organizations dept : organizations) {
DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list"); DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/list");
OapiV2UserListRequest req = new OapiV2UserListRequest(); OapiV2UserListRequest req = new OapiV2UserListRequest();
_logger.info("DingTalk deptId : {}" , dept.getCode());
req.setDeptId(Long.parseLong(dept.getCode())); req.setDeptId(Long.parseLong(dept.getCode()));
req.setCursor(0L); req.setCursor(0L);
req.setSize(100L); req.setSize(100L);
@ -62,16 +63,15 @@ public class DingtalkUsersService extends AbstractSynchronizerService implement
req.setContainAccessLimit(true); req.setContainAccessLimit(true);
req.setLanguage("zh_CN"); req.setLanguage("zh_CN");
OapiV2UserListResponse rsp = client.execute(req, access_token); OapiV2UserListResponse rsp = client.execute(req, access_token);
_logger.info("response : " + rsp.getBody()); _logger.trace("response : {}" , rsp.getBody());
if(rsp.getErrcode()==0) { if(rsp.getErrcode()==0) {
for(ListUserResponse user :rsp.getResult().getList()) { for(ListUserResponse user :rsp.getResult().getList()) {
_logger.info("name : " + user.getName()+" , "+user.getLoginId()+" , "+user.getUserid()); _logger.debug("name : {} , {} , {}", user.getName(),user.getLoginId(),user.getUserid());
UserInfo userInfo = buildUserInfo(user); UserInfo userInfo = buildUserInfo(user);
_logger.info("userInfo " + userInfo); _logger.trace("userInfo {}" , userInfo);
userInfo.setPassword(userInfo.getUsername() + "Maxkey@888"); userInfo.setPassword(userInfo.getUsername() + "Maxkey@888");
userInfoService.saveOrUpdate(userInfo); userInfoService.saveOrUpdate(userInfo);
} }
} }
} }
@ -83,10 +83,6 @@ public class DingtalkUsersService extends AbstractSynchronizerService implement
} }
public void postSync(UserInfo userInfo) {
}
public UserInfo buildUserInfo(ListUserResponse user) { public UserInfo buildUserInfo(ListUserResponse user) {
UserInfo userInfo = new UserInfo(); UserInfo userInfo = new UserInfo();

View File

@ -43,7 +43,7 @@ public class FeishuOrganizationService extends AbstractSynchronizerService imple
static String DEPTS_URL="https://open.feishu.cn/open-apis/contact/v3/departments/%s/children?page_size=50"; static String DEPTS_URL="https://open.feishu.cn/open-apis/contact/v3/departments/%s/children?page_size=50";
public void sync() { public void sync() {
_logger.info("Sync Organizations ..."); _logger.info("Sync Feishu Organizations ...");
LinkedBlockingQueue<String> deptsQueue = new LinkedBlockingQueue<String>(); LinkedBlockingQueue<String> deptsQueue = new LinkedBlockingQueue<String>();
deptsQueue.add("0"); deptsQueue.add("0");

View File

@ -44,7 +44,7 @@ public class FeishuUsersService extends AbstractSynchronizerService implements I
static String USERS_URL="https://open.feishu.cn/open-apis/contact/v3/users/find_by_department"; static String USERS_URL="https://open.feishu.cn/open-apis/contact/v3/users/find_by_department";
public void sync() { public void sync() {
_logger.info("Sync Users..."); _logger.info("Sync Feishu Users...");
try { try {
List<Organizations> organizations = List<Organizations> organizations =
organizationsService.find("instid = ?", organizationsService.find("instid = ?",

View File

@ -17,6 +17,7 @@
package org.maxkey.synchronizer.ldap; package org.maxkey.synchronizer.ldap;
import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import javax.naming.NamingEnumeration; import javax.naming.NamingEnumeration;
@ -24,6 +25,9 @@ import javax.naming.NamingException;
import javax.naming.directory.Attribute; import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult; import javax.naming.directory.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.maxkey.constants.ConstsStatus;
import org.maxkey.constants.ldap.OrganizationalUnit; import org.maxkey.constants.ldap.OrganizationalUnit;
import org.maxkey.entity.HistorySynchronizer; import org.maxkey.entity.HistorySynchronizer;
import org.maxkey.entity.Organizations; import org.maxkey.entity.Organizations;
@ -41,38 +45,80 @@ public class LdapOrganizationService extends AbstractSynchronizerService implem
LdapUtils ldapUtils; LdapUtils ldapUtils;
public void sync() { public void sync() {
_logger.info("Sync Organizations ..."); _logger.info("Sync Ldap Organizations ...");
loadOrgsById("1"); loadOrgsById("1");
try { try {
SearchControls constraints = new SearchControls(); SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope()); constraints.setSearchScope(ldapUtils.getSearchScope());
NamingEnumeration<SearchResult> results = ldapUtils.getConnection() String filter = "(&(objectClass=OrganizationalUnit))";
.search(ldapUtils.getBaseDN(), "(&(objectClass=OrganizationalUnit))", constraints); if(StringUtils.isNotBlank(this.getSynchronizer().getFilters())) {
//filter = this.getSynchronizer().getFilters();
}
NamingEnumeration<SearchResult> results =
ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter , constraints);
ArrayList<Organizations> orgsList = new ArrayList<Organizations>();
int maxLevel = 0;
long recordCount = 0; long recordCount = 0;
while (null != results && results.hasMoreElements()) { while (null != results && results.hasMoreElements()) {
Object obj = results.nextElement(); Object obj = results.nextElement();
if (obj instanceof SearchResult) { if (obj instanceof SearchResult) {
recordCount ++; SearchResult sr = (SearchResult) obj;
SearchResult si = (SearchResult) obj; _logger.debug("Sync OrganizationalUnit {} , name {} , NameInNamespace {}" ,
_logger.info("Sync OrganizationalUnit Record " + recordCount+" --------------------------------------------------"); (++recordCount),sr.getName(),sr.getNameInNamespace());
_logger.trace("name " + si.getName());
_logger.info("NameInNamespace " + si.getNameInNamespace());
HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>(); HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>();
NamingEnumeration<? extends Attribute> attrs = si.getAttributes().getAll(); NamingEnumeration<? extends Attribute> attrs = sr.getAttributes().getAll();
while (null != attrs && attrs.hasMoreElements()) { while (null != attrs && attrs.hasMoreElements()) {
Attribute objAttrs = attrs.nextElement(); Attribute objAttrs = attrs.nextElement();
_logger.trace("attribute "+objAttrs.getID() + " : " + objAttrs.get()); _logger.trace("attribute "+objAttrs.getID() + " : " + objAttrs.get());
attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs); attributeMap.put(objAttrs.getID().toLowerCase(), objAttrs);
} }
Organizations organization = buildOrganization(attributeMap,si.getName(),si.getNameInNamespace()); Organizations organization = buildOrganization(attributeMap,sr.getName(),sr.getNameInNamespace());
organizationsService.saveOrUpdate(organization); if(organization != null) {
_logger.info("Organizations " + organization); orgsList.add(organization);
maxLevel = (maxLevel < organization.getLevel()) ? organization.getLevel() : maxLevel ;
}
} }
} }
for (int level = 2 ; level <= maxLevel ; level++) {
for(Organizations organization : orgsList) {
if(organization.getLevel() == level) {
String parentNamePath= organization.getNamePath().substring(0, organization.getNamePath().lastIndexOf("/"));
if(orgsNamePathMap.get(organization.getNamePath())!=null) {
_logger.info("org " + orgsNamePathMap.get(organization.getNamePath()).getNamePath()+" exists.");
continue;
}
Organizations parentOrg = orgsNamePathMap.get(parentNamePath);
if(parentOrg == null ) {
parentOrg = rootOrganization;
}
organization.setParentId(parentOrg.getId());
organization.setParentName(parentOrg.getName());
organization.setCodePath(parentOrg.getCodePath()+"/"+organization.getId());
_logger.info("parentNamePath " + parentNamePath+" , namePah " + organization.getNamePath());
organizationsService.saveOrUpdate(organization);
orgsNamePathMap.put(organization.getNamePath(), organization);
_logger.info("Organizations " + organization);
HistorySynchronizer historySynchronizer =new HistorySynchronizer();
historySynchronizer.setId(historySynchronizer.generateId());
historySynchronizer.setSyncId(this.synchronizer.getId());
historySynchronizer.setSyncName(this.synchronizer.getName());
historySynchronizer.setObjectId(organization.getId());
historySynchronizer.setObjectName(organization.getName());
historySynchronizer.setObjectType(Organizations.class.getSimpleName());
historySynchronizer.setInstId(synchronizer.getInstId());
historySynchronizer.setResult("success");
this.historySynchronizerService.insert(historySynchronizer);
}
}
}
//ldapUtils.close(); //ldapUtils.close();
} catch (NamingException e) { } catch (NamingException e) {
e.printStackTrace(); e.printStackTrace();
@ -81,6 +127,7 @@ public class LdapOrganizationService extends AbstractSynchronizerService implem
} }
public Organizations buildOrganization(HashMap<String,Attribute> attributeMap,String name,String nameInNamespace) { public Organizations buildOrganization(HashMap<String,Attribute> attributeMap,String name,String nameInNamespace) {
try {
Organizations org = new Organizations(); Organizations org = new Organizations();
org.setLdapDn(nameInNamespace); org.setLdapDn(nameInNamespace);
nameInNamespace = nameInNamespace.replaceAll(",ou=", "/").replaceAll("ou=", "/"); nameInNamespace = nameInNamespace.replaceAll(",ou=", "/").replaceAll("ou=", "/");
@ -91,23 +138,12 @@ public class LdapOrganizationService extends AbstractSynchronizerService implem
namePah = namePah + "/"+namePaths[i]; namePah = namePah + "/"+namePaths[i];
} }
namePah = namePah.substring(0, namePah.length() -1); namePah = namePah.substring(0, namePah.length() -1);
String parentNamePath= namePah.substring(0, namePah.lastIndexOf("/"));
if(orgsNamePathMap.get(namePah)!=null) {
_logger.info("org " + orgsNamePathMap.get(namePah).getNamePath()+" exists.");
return null;
}
Organizations parentOrg = orgsNamePathMap.get(parentNamePath);
org.setId(org.generateId()); org.setId(org.generateId());
org.setCode(org.getId());
org.setNamePath(namePah); org.setNamePath(namePah);
org.setParentId(parentOrg.getId()); org.setLevel(namePaths.length);
org.setParentName(parentOrg.getName());
org.setCodePath(parentOrg.getCodePath()+"/"+org.getId());
_logger.info("parentNamePath " + parentNamePath+" , namePah " + namePah);
try {
org.setName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap)); org.setName(LdapUtils.getAttributeStringValue(OrganizationalUnit.OU,attributeMap));
//org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap)); //org.setCountry(LdapUtils.getAttributeStringValue(OrganizationalUnit.CO,attributeMap));
org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap)); org.setRegion(LdapUtils.getAttributeStringValue(OrganizationalUnit.ST,attributeMap));
org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap)); org.setLocality(LdapUtils.getAttributeStringValue(OrganizationalUnit.L,attributeMap));
@ -118,9 +154,8 @@ public class LdapOrganizationService extends AbstractSynchronizerService implem
org.setFax(LdapUtils.getAttributeStringValue(OrganizationalUnit.FACSIMILETELEPHONENUMBER,attributeMap)); org.setFax(LdapUtils.getAttributeStringValue(OrganizationalUnit.FACSIMILETELEPHONENUMBER,attributeMap));
org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap)); org.setDescription(LdapUtils.getAttributeStringValue(OrganizationalUnit.DESCRIPTION,attributeMap));
org.setInstId(this.synchronizer.getInstId()); org.setInstId(this.synchronizer.getInstId());
orgsNamePathMap.put(org.getNamePath(), org); org.setStatus(ConstsStatus.ACTIVE);
_logger.info("org " + org); _logger.info("org " + org);
organizationsService.insert(org);
HistorySynchronizer historySynchronizer =new HistorySynchronizer(); HistorySynchronizer historySynchronizer =new HistorySynchronizer();
historySynchronizer.setId(historySynchronizer.generateId()); historySynchronizer.setId(historySynchronizer.generateId());
historySynchronizer.setSyncId(this.synchronizer.getId()); historySynchronizer.setSyncId(this.synchronizer.getId());
@ -128,12 +163,14 @@ public class LdapOrganizationService extends AbstractSynchronizerService implem
historySynchronizer.setObjectId(org.getId()); historySynchronizer.setObjectId(org.getId());
historySynchronizer.setObjectName(org.getName()); historySynchronizer.setObjectName(org.getName());
historySynchronizer.setObjectType(Organizations.class.getSimpleName()); historySynchronizer.setObjectType(Organizations.class.getSimpleName());
historySynchronizer.setInstId(synchronizer.getInstId());
historySynchronizer.setResult("success"); historySynchronizer.setResult("success");
this.historySynchronizerService.insert(historySynchronizer); this.historySynchronizerService.insert(historySynchronizer);
} catch (NamingException e) {
e.printStackTrace();
}
return org; return org;
} catch (NamingException e) {
_logger.error("NamingException " , e);
}
return null;
} }

View File

@ -23,6 +23,8 @@ import javax.naming.NamingException;
import javax.naming.directory.Attribute; import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls; import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult; import javax.naming.directory.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.maxkey.constants.ldap.InetOrgPerson; import org.maxkey.constants.ldap.InetOrgPerson;
import org.maxkey.entity.HistorySynchronizer; import org.maxkey.entity.HistorySynchronizer;
import org.maxkey.entity.Organizations; import org.maxkey.entity.Organizations;
@ -41,30 +43,33 @@ public class LdapUsersService extends AbstractSynchronizerService implements IS
LdapUtils ldapUtils; LdapUtils ldapUtils;
public void sync() { public void sync() {
_logger.info("Sync Users..."); _logger.info("Sync Ldap Users ...");
loadOrgsById("1"); loadOrgsById("1");
try { try {
SearchControls constraints = new SearchControls(); SearchControls constraints = new SearchControls();
constraints.setSearchScope(ldapUtils.getSearchScope()); constraints.setSearchScope(ldapUtils.getSearchScope());
NamingEnumeration<SearchResult> results = ldapUtils.getConnection() String filter = StringUtils.isNotBlank(this.getSynchronizer().getFilters()) ?
.search(ldapUtils.getBaseDN(), "(&(objectClass=inetOrgPerson))", constraints); getSynchronizer().getFilters() : "(&(objectClass=inetOrgPerson))";
NamingEnumeration<SearchResult> results =
ldapUtils.getConnection().search(ldapUtils.getBaseDN(), filter, constraints);
long recordCount = 0;
while (null != results && results.hasMoreElements()) { while (null != results && results.hasMoreElements()) {
Object obj = results.nextElement(); Object obj = results.nextElement();
if (obj instanceof SearchResult) { if (obj instanceof SearchResult) {
SearchResult si = (SearchResult) obj; SearchResult sr = (SearchResult) obj;
_logger.trace("name " + si.getName()); _logger.debug("Sync User {} , name {} , NameInNamespace {}" ,
_logger.info("NameInNamespace " + si.getNameInNamespace()); (++recordCount),sr.getName(),sr.getNameInNamespace());
HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>(); HashMap<String,Attribute> attributeMap = new HashMap<String,Attribute>();
NamingEnumeration<? extends Attribute> attrs = si.getAttributes().getAll(); NamingEnumeration<? extends Attribute> attrs = sr.getAttributes().getAll();
while (null != attrs && attrs.hasMoreElements()) { while (null != attrs && attrs.hasMoreElements()) {
Attribute objAttrs = attrs.nextElement(); Attribute objAttrs = attrs.nextElement();
_logger.trace("attribute "+objAttrs.getID() + " , " + objAttrs.get()); _logger.trace("attribute "+objAttrs.getID() + " , " + objAttrs.get());
attributeMap.put(objAttrs.getID(), objAttrs); attributeMap.put(objAttrs.getID(), objAttrs);
} }
UserInfo userInfo = buildUserInfo(attributeMap,si.getName(),si.getNameInNamespace()); UserInfo userInfo = buildUserInfo(attributeMap,sr.getName(),sr.getNameInNamespace());
userInfo.setPassword(userInfo.getUsername() + "Maxkey@888"); userInfo.setPassword(userInfo.getUsername() + "Maxkey@888");
userInfoService.saveOrUpdate(userInfo); userInfoService.saveOrUpdate(userInfo);
_logger.info("userInfo " + userInfo); _logger.info("userInfo " + userInfo);
@ -141,12 +146,7 @@ public class LdapUsersService extends AbstractSynchronizerService implements IS
userInfo.setTimeZone("Asia/Shanghai"); userInfo.setTimeZone("Asia/Shanghai");
userInfo.setStatus(1); userInfo.setStatus(1);
userInfo.setInstId(this.synchronizer.getInstId()); userInfo.setInstId(this.synchronizer.getInstId());
UserInfo quser=new UserInfo();
quser.setUsername(userInfo.getUsername());
UserInfo loadedUser=userInfoService.load(quser);
if(loadedUser == null) {
userInfo.setPassword(userInfo.generateId());
userInfoService.insert(userInfo);
HistorySynchronizer historySynchronizer =new HistorySynchronizer(); HistorySynchronizer historySynchronizer =new HistorySynchronizer();
historySynchronizer.setId(historySynchronizer.generateId()); historySynchronizer.setId(historySynchronizer.generateId());
historySynchronizer.setSyncId(this.synchronizer.getId()); historySynchronizer.setSyncId(this.synchronizer.getId());
@ -154,11 +154,10 @@ public class LdapUsersService extends AbstractSynchronizerService implements IS
historySynchronizer.setObjectId(userInfo.getId()); historySynchronizer.setObjectId(userInfo.getId());
historySynchronizer.setObjectName(userInfo.getUsername()); historySynchronizer.setObjectName(userInfo.getUsername());
historySynchronizer.setObjectType(Organizations.class.getSimpleName()); historySynchronizer.setObjectType(Organizations.class.getSimpleName());
historySynchronizer.setInstId(synchronizer.getInstId());
historySynchronizer.setResult("success"); historySynchronizer.setResult("success");
this.historySynchronizerService.insert(historySynchronizer); this.historySynchronizerService.insert(historySynchronizer);
}else {
_logger.info("username " + userInfo.getUsername()+" exists.");
}
} catch (NamingException e) { } catch (NamingException e) {
e.printStackTrace(); e.printStackTrace();
} }

View File

@ -38,7 +38,7 @@ public class WorkweixinOrganizationService extends AbstractSynchronizerService i
static String DEPTS_URL="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s"; static String DEPTS_URL="https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s";
public void sync() { public void sync() {
_logger.info("Sync Organizations ..."); _logger.info("Sync Workweixin Organizations ...");
try { try {
WorkWeixinDeptsResponse rsp = requestDepartmentList(access_token); WorkWeixinDeptsResponse rsp = requestDepartmentList(access_token);

View File

@ -42,7 +42,7 @@ public class WorkweixinUsersService extends AbstractSynchronizerService implemen
static String USERS_URL="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=%s&department_id=%s&fetch_child=0"; static String USERS_URL="https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=%s&department_id=%s&fetch_child=0";
public void sync() { public void sync() {
_logger.info("Sync Users..."); _logger.info("Sync Workweixin Users...");
try { try {
List<Organizations> organizations = List<Organizations> organizations =
organizationsService.find("instid = ?", organizationsService.find("instid = ?",

View File

@ -49,7 +49,7 @@ public abstract class AbstractSynchronizerService {
protected Organizations rootOrganization = null; protected Organizations rootOrganization = null;
public void loadOrgsById(String orgId) { public HashMap<String,Organizations> loadOrgsById(String orgId) {
List<Organizations> orgsList = organizationsService.query(null); List<Organizations> orgsList = organizationsService.query(null);
if(orgId== null || orgId.equals("")) { if(orgId== null || orgId.equals("")) {
orgId="1"; orgId="1";
@ -72,7 +72,7 @@ public abstract class AbstractSynchronizerService {
push(orgsNamePathMap,orgsList,rootOrganization); push(orgsNamePathMap,orgsList,rootOrganization);
_logger.trace("orgsNamePathMap " + orgsNamePathMap); _logger.trace("orgsNamePathMap " + orgsNamePathMap);
return orgsNamePathMap;
} }
public void push(HashMap<String,Organizations> orgsNamePathMap, public void push(HashMap<String,Organizations> orgsNamePathMap,

View File

@ -248,7 +248,7 @@ public class OrganizationsController {
organization.setDivision(ExcelUtils.getValue(row, 8)); organization.setDivision(ExcelUtils.getValue(row, 8));
// 级别 // 级别
String level = ExcelUtils.getValue(row, 9); String level = ExcelUtils.getValue(row, 9);
organization.setLevel(level.equals("") ? "1" : level); organization.setLevel(level.equals("") ? 1 : Integer.parseInt(level));
// 排序 // 排序
String sortIndex = ExcelUtils.getValue(row, 10); String sortIndex = ExcelUtils.getValue(row, 10);
organization.setSortIndex(sortIndex.equals("") ? 1 : Integer.parseInt(sortIndex)); organization.setSortIndex(sortIndex.equals("") ? 1 : Integer.parseInt(sortIndex));