Browse Source

open

master
pioneer 2 years ago
commit
a8ee954f7b
  1. 6
      README.md
  2. 33
      plugin.xml
  3. 47
      pom.xml
  4. 12
      src/main/java/com/fr/plugin/xx/IDaaS/sync/Constants.java
  5. 24
      src/main/java/com/fr/plugin/xx/IDaaS/sync/LRGT.java
  6. 34
      src/main/java/com/fr/plugin/xx/IDaaS/sync/RequestHandlerBridge.java
  7. 21
      src/main/java/com/fr/plugin/xx/IDaaS/sync/RequestURLAliasBridge.java
  8. 43
      src/main/java/com/fr/plugin/xx/IDaaS/sync/SyncDBAccessProvider.java
  9. 60
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/dept/OrgAddHandler.java
  10. 47
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/dept/OrgDelHandler.java
  11. 55
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/dept/OrgEditHandler.java
  12. 98
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/init/DeptInitHandler.java
  13. 119
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/init/UserInitHandler.java
  14. 85
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/user/UserAddHandler.java
  15. 55
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/user/UserDelHandler.java
  16. 103
      src/main/java/com/fr/plugin/xx/IDaaS/sync/action/user/UserEditHandler.java
  17. 91
      src/main/java/com/fr/plugin/xx/IDaaS/sync/conf/SyncConfig.java
  18. 17
      src/main/java/com/fr/plugin/xx/IDaaS/sync/dao/DeptDao.java
  19. 265
      src/main/java/com/fr/plugin/xx/IDaaS/sync/entity/DeptEntity.java
  20. 122
      src/main/java/com/fr/plugin/xx/IDaaS/sync/util/LogUtils.java
  21. 167
      src/main/java/com/fr/plugin/xx/IDaaS/sync/util/SyncUtil.java

6
README.md

@ -0,0 +1,6 @@
# open-JSD-10333
JSD-10333 用户同步\
免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\
仅作为开发者学习参考使用!禁止用于任何商业用途!\
为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。

33
plugin.xml

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<plugin>
<id>com.fr.plugin.xx.IDaaS.sync</id>
<name><![CDATA[IDaaS用户组织同步]]></name>
<active>yes</active>
<version>1.10</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[IDaaS用户组织同步]]></description>
<change-notes><![CDATA[
[2022-05-29]【1.0】初始化插件。<br/>
[2022-06-01]【1.1】代码问题修改。<br/>
[2022-06-08]【1.2】增加附加表存储。<br/>
[2022-06-08]【1.3】增加附加表存储。<br/>
[2022-06-08]【1.4】增加附加表存储字段。<br/>
[2022-06-14]【1.5】增加初始化导入。<br/>
[2022-06-15]【1.6】修改poi依赖。<br/>
[2022-06-15]【1.7】列调整。<br/>
[2022-06-16]【1.8】列调整。<br/>
[2022-06-16]【1.9】接口404。<br/>
[2022-06-17]【1.10】增加字段<br/>
]]></change-notes>
<extra-core>
<DBAccessProvider class="com.fr.plugin.xx.IDaaS.sync.SyncDBAccessProvider"/>
</extra-core>
<extra-decision>
<HttpHandlerProvider class="com.fr.plugin.xx.IDaaS.sync.RequestHandlerBridge"/>
<URLAliasProvider class="com.fr.plugin.xx.IDaaS.sync.RequestURLAliasBridge" />
</extra-decision>
<function-recorder class="com.fr.plugin.xx.IDaaS.sync.RequestURLAliasBridge"/>
<lifecycle-monitor class="com.fr.plugin.xx.IDaaS.sync.LRGT"/>
</plugin>

47
pom.xml

@ -0,0 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>starter</artifactId>
<groupId>com.fr.plugin</groupId>
<version>10.0</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>jsd10333</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<build>
<!---如果要更改调试插件,改这里的配置就可以了-->
<outputDirectory>
${project.basedir}/../../webroot/WEB-INF/plugins/plugin-${project.groupId}.${project.artifactId}-${project.version}/classes
</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*</include>
</includes>
</resource>
</resources>
</build>
</project>

12
src/main/java/com/fr/plugin/xx/IDaaS/sync/Constants.java

@ -0,0 +1,12 @@
package com.fr.plugin.xx.IDaaS.sync;
/**
* @author xx
* @date 2020/5/14
*/
public class Constants {
public static final String PLUGIN_ID = "com.fr.plugin.xx.IDaaS.sync";
public static final String PLUGIN_NAME= "IDaaS用户组织同步";
}

24
src/main/java/com/fr/plugin/xx/IDaaS/sync/LRGT.java

@ -0,0 +1,24 @@
package com.fr.plugin.xx.IDaaS.sync;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.xx.IDaaS.sync.conf.SyncConfig;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
public class LRGT extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
SyncConfig.getInstance();
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
@Override
public void beforeUninstall(PluginContext pluginContext) {
}
@Override
public void afterInstall(PluginContext var1) {
}
}

34
src/main/java/com/fr/plugin/xx/IDaaS/sync/RequestHandlerBridge.java

@ -0,0 +1,34 @@
package com.fr.plugin.xx.IDaaS.sync;
import com.fr.decision.fun.HttpHandler;
import com.fr.decision.fun.impl.AbstractHttpHandlerProvider;
import com.fr.plugin.xx.IDaaS.sync.action.dept.OrgAddHandler;
import com.fr.plugin.xx.IDaaS.sync.action.dept.OrgDelHandler;
import com.fr.plugin.xx.IDaaS.sync.action.dept.OrgEditHandler;
import com.fr.plugin.xx.IDaaS.sync.action.init.DeptInitHandler;
import com.fr.plugin.xx.IDaaS.sync.action.init.UserInitHandler;
import com.fr.plugin.xx.IDaaS.sync.action.user.UserAddHandler;
import com.fr.plugin.xx.IDaaS.sync.action.user.UserDelHandler;
import com.fr.plugin.xx.IDaaS.sync.action.user.UserEditHandler;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.fun.Authorize;
@FunctionRecorder
@Authorize(callSignKey = Constants.PLUGIN_ID)
public class RequestHandlerBridge extends AbstractHttpHandlerProvider {
@Override
public HttpHandler[] registerHandlers() {
return new HttpHandler[]{
new OrgAddHandler(),
new OrgEditHandler(),
new OrgDelHandler(),
new UserAddHandler(),
new UserEditHandler(),
new UserDelHandler(),
new DeptInitHandler(),
new UserInitHandler(),
};
}
}

21
src/main/java/com/fr/plugin/xx/IDaaS/sync/RequestURLAliasBridge.java

@ -0,0 +1,21 @@
package com.fr.plugin.xx.IDaaS.sync;
import com.fr.decision.fun.impl.AbstractURLAliasProvider;
import com.fr.decision.webservice.url.alias.URLAlias;
import com.fr.decision.webservice.url.alias.URLAliasFactory;
/**
* @author xx
* @since 2021/07/28
*/
public class RequestURLAliasBridge extends AbstractURLAliasProvider {
@Override
public URLAlias[] registerAlias() {
return new URLAlias[]{
URLAliasFactory.createPluginAlias("/scim/organization", "/scim/organization", true),
URLAliasFactory.createPluginAlias("/scim/account", "/scim/account", true),
URLAliasFactory.createPluginAlias("/init/user", "/init/user", true),
URLAliasFactory.createPluginAlias("/init/dept", "/init/dept", true),
};
}
}

43
src/main/java/com/fr/plugin/xx/IDaaS/sync/SyncDBAccessProvider.java

@ -0,0 +1,43 @@
package com.fr.plugin.xx.IDaaS.sync;
import com.fr.db.fun.impl.AbstractDBAccessProvider;
import com.fr.plugin.xx.IDaaS.sync.dao.DeptDao;
import com.fr.plugin.xx.IDaaS.sync.entity.DeptEntity;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
/**
* @Author xx
* @Date 2022/06/06
**/
public class SyncDBAccessProvider extends AbstractDBAccessProvider {
private static DBAccessor dbAccessor = null;
public static DBAccessor getDbAccessor() {
return dbAccessor;
}
@Override
public DAOProvider[] registerDAO() {
return new DAOProvider[]{
new DAOProvider() {
@Override
public Class getEntityClass() {
return DeptEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return DeptDao.class;
}
}
};
}
@Override
public void onDBAvailable(DBAccessor dbAccessor) {
SyncDBAccessProvider.dbAccessor = dbAccessor;
}
}

60
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/dept/OrgAddHandler.java

@ -0,0 +1,60 @@
package com.fr.plugin.xx.IDaaS.sync.action.dept;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Department;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.plugin.xx.IDaaS.sync.conf.SyncConfig;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OrgAddHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.POST;
}
@Override
public String getPath() {
return "/scim/organization";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!SyncUtil.checkAuth(request.getHeader("Authorization"))){
SyncUtil.setError(response, "Authorization验证失败");
return;
}
JSONObject body = SyncUtil.getBody(request);
if (JSONObject.EMPTY.equals(body)) {
SyncUtil.setError(response, "请求为空");
return;
}
String parent = StringUtils.equals(body.getString("organizationUuid"), SyncConfig.getInstance().getRootId()) ? null : body.getString("parentUuid");
Department department = (new Department()).id(body.getString("organizationUuid")).name(body.getString("organization")).parentId(parent).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true);
Department query = AuthorityContext.getInstance().getDepartmentController().findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("name", department.getName())));
if(query != null){
SyncUtil.setError(response, "部门已存在");
return;
}
AuthorityContext.getInstance().getDepartmentController().add(department);
SyncUtil.saveDept(body, department);
SyncUtil.setSuccess(response);
}
}

47
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/dept/OrgDelHandler.java

@ -0,0 +1,47 @@
package com.fr.plugin.xx.IDaaS.sync.action.dept;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.v10.user.DepartmentService;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.stable.StringUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OrgDelHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.DELETE;
}
@Override
public String getPath() {
return "/scim/organization";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!SyncUtil.checkAuth(request.getHeader("Authorization"))){
SyncUtil.setError(response, "Authorization验证失败");
return;
}
String id = WebUtils.getHTTPRequestParameter(request, "id");
if (StringUtils.isBlank(id)) {
SyncUtil.setError(response, "id不能为空");
return;
}
DepartmentService.getInstance().deleteDepartment(id);
SyncUtil.delDept(id);
SyncUtil.setSuccess(response);
}
}

55
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/dept/OrgEditHandler.java

@ -0,0 +1,55 @@
package com.fr.plugin.xx.IDaaS.sync.action.dept;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Department;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.json.JSONObject;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class OrgEditHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.PUT;
}
@Override
public String getPath() {
return "/scim/organization";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!SyncUtil.checkAuth(request.getHeader("Authorization"))){
SyncUtil.setError(response, "Authorization验证失败");
return;
}
JSONObject body = SyncUtil.getBody(request);
if (JSONObject.EMPTY.equals(body)) {
SyncUtil.setError(response, "请求为空");
return;
}
String parent = body.getBoolean("rootNode") ? null : body.getString("parentUuid");
Department department = (new Department()).id(body.getString("organizationUuid")).name(body.getString("organization")).parentId(parent).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true);
Department query = AuthorityContext.getInstance().getDepartmentController().getById(department.getId());
if(query == null){
SyncUtil.setError(response, "部门不存在");
return;
}
AuthorityContext.getInstance().getDepartmentController().update(department);
SyncUtil.saveDept(body, department);
SyncUtil.setSuccess(response);
}
}

98
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/init/DeptInitHandler.java

@ -0,0 +1,98 @@
package com.fr.plugin.xx.IDaaS.sync.action.init;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Department;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.plugin.xx.IDaaS.sync.SyncDBAccessProvider;
import com.fr.plugin.xx.IDaaS.sync.conf.SyncConfig;
import com.fr.plugin.xx.IDaaS.sync.dao.DeptDao;
import com.fr.plugin.xx.IDaaS.sync.entity.DeptEntity;
import com.fr.plugin.xx.IDaaS.sync.util.LogUtils;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Row;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Sheet;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Workbook;
import com.fr.third.v2.org.apache.poi.ss.usermodel.WorkbookFactory;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
public class DeptInitHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.GET;
}
@Override
public String getPath() {
return "/init/dept";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (!SyncUtil.checkAuth(request.getHeader("Authorization"))) {
SyncUtil.setError(response, "Authorization验证失败");
return;
}
if (!SyncConfig.getInstance().getInitSwitch()) {
SyncUtil.setError(response, "初始化开关未开启,无法初始化");
return;
}
String path = WebUtils.getHTTPRequestParameter(request, "path");
if (StringUtils.isBlank(path)) {
SyncUtil.setError(response, "初始化文件路径为空");
return;
}
Workbook workbook = WorkbookFactory.create(new File(path));
Sheet sheet = workbook.getSheetAt(0);
for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
Row row = sheet.getRow(i);
try {
Department department = getDeptByRow(row);
if(department == null){
LogUtils.warn("第{}行获取用户信息失败", i);
continue;
}
AuthorityContext.getInstance().getDepartmentController().add(department);
DeptEntity entity = DeptEntity.fromRow(row);
SyncDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<DeptEntity>() {
@Override
public DeptEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(DeptDao.class).addOrUpdate(entity);
return entity;
}
});
} catch (Exception e) {
LogUtils.error("第{}行插入部门信息失败", i);
LogUtils.error(e.getMessage(), e);
}
}
SyncUtil.setSuccess(response);
}
private Department getDeptByRow(Row row) {
if (row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
return null;
}
String id = row.getCell(0).getStringCellValue();
String name = row.getCell(1).getStringCellValue();
String parent = row.getCell(2).getStringCellValue();
parent = StringUtils.equals(id, SyncConfig.getInstance().getRootId()) ? null : parent;
return (new Department()).id(id).name(name).parentId(parent).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true);
}
}

119
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/init/UserInitHandler.java

@ -0,0 +1,119 @@
package com.fr.plugin.xx.IDaaS.sync.action.init;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.User;
import com.fr.decision.base.util.UUIDUtil;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.privilege.encrpt.PasswordValidator;
import com.fr.decision.webservice.bean.user.DepPostUserUpdateBean;
import com.fr.decision.webservice.utils.UserSourceFactory;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.plugin.xx.IDaaS.sync.conf.SyncConfig;
import com.fr.plugin.xx.IDaaS.sync.util.LogUtils;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Row;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Sheet;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Workbook;
import com.fr.third.v2.org.apache.poi.ss.usermodel.WorkbookFactory;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
public class UserInitHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.GET;
}
@Override
public String getPath() {
return "/init/user";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (!SyncUtil.checkAuth(request.getHeader("Authorization"))) {
SyncUtil.setError(response, "Authorization验证失败");
return;
}
if (!SyncConfig.getInstance().getInitSwitch()) {
SyncUtil.setError(response, "初始化开关未开启,无法初始化");
return;
}
String path = WebUtils.getHTTPRequestParameter(request, "path");
if (StringUtils.isBlank(path)) {
SyncUtil.setError(response, "初始化文件路径为空");
return;
}
Workbook workbook = WorkbookFactory.create(new File(path));
Sheet sheet = workbook.getSheetAt(0);
for (int i = 2; i < sheet.getPhysicalNumberOfRows(); i++) {
Row row = sheet.getRow(i);
User user = getUserByRow(row);
if (user == null) {
LogUtils.warn("第{}行获取用户信息失败", i);
continue;
}
try {
User userByUserName = UserService.getInstance().getUserByUserName(user.getUserName());
if (userByUserName == null) {
AuthorityContext.getInstance().getUserController().add(user);
}
String dept = row.getCell(5).getStringCellValue();
if (StringUtils.isNotBlank(dept)) {
Department department = AuthorityContext.getInstance().getDepartmentController().findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("id", dept)));
if (department != null) {
String postId = SyncUtil.generateDefaultPosition(dept);
DepPostUserUpdateBean bean = new DepPostUserUpdateBean();
bean.setDepartmentId(dept);
bean.setPostId(postId);
bean.setAddUserIds(new String[]{user.getId()});
LogUtils.debug4plugin("init user {} to dep-[{}] post-[{}]", user.getUserName(), dept, postId);
UserService.getInstance().updateDepartmentPostUsers(dept, postId, bean);
}else{
LogUtils.error("第{}行插入用户无对应组织,更新所属组织失败", i);
}
}
} catch (Exception e) {
LogUtils.error("第{}行插入用户信息失败", i);
LogUtils.error(e.getMessage(),e);
}
}
SyncUtil.setSuccess(response);
}
private User getUserByRow(Row row) {
if (row.getCell(1) == null || StringUtils.isBlank(row.getCell(1).getStringCellValue())) {
return null;
}
String id = row.getCell(1).getStringCellValue();
String email = row.getCell(0).getStringCellValue();
String name = row.getCell(2).getStringCellValue();
String phone = row.getCell(4).getStringCellValue();
User user = (new User()).id(id).userName(id)
.realName(name).email(email)
.workPhone(phone).creationType(ManualOperationType.KEY)
.lastOperationType(ManualOperationType.KEY).enable(true);
String uuid = UUIDUtil.generate();
PasswordValidator validator = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator();
user.password(validator.encode(user.getUserName(), uuid, uuid)).salt(uuid);
return user;
}
}

85
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/user/UserAddHandler.java

@ -0,0 +1,85 @@
package com.fr.plugin.xx.IDaaS.sync.action.user;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.User;
import com.fr.decision.base.util.UUIDUtil;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.privilege.encrpt.PasswordValidator;
import com.fr.decision.webservice.bean.user.DepPostUserUpdateBean;
import com.fr.decision.webservice.utils.UserSourceFactory;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.xx.IDaaS.sync.util.LogUtils;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserAddHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.POST;
}
@Override
public String getPath() {
return "/scim/account";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!SyncUtil.checkAuth(request.getHeader("Authorization"))){
SyncUtil.setError(response, "Authorization验证失败");
return;
}
JSONObject body = SyncUtil.getBody(request);
if (JSONObject.EMPTY.equals(body)) {
SyncUtil.setError(response, "请求为空");
return;
}
User user = SyncUtil.getUser(body);
String uuid = UUIDUtil.generate();
PasswordValidator validator = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator();
user.password(validator.encode(user.getUserName(), uuid, uuid)).salt(uuid);
User userByUserName = UserService.getInstance().getUserByUserName(user.getUserName());
if (userByUserName != null) {
SyncUtil.setError(response, "用户名重复");
return;
}
AuthorityContext.getInstance().getUserController().add(user);
JSONArray belongs = body.getJSONArray("belongs");
if (belongs != null) {
for (int i = 0; i < belongs.size(); i++) {
JSONObject object = belongs.getJSONObject(i);
String uid = object.getString("belongOuUuid");
Department query = AuthorityContext.getInstance().getDepartmentController().getById(uid);
if(query != null){
String postId = SyncUtil.generateDefaultPosition(uid);
DepPostUserUpdateBean bean = new DepPostUserUpdateBean();
bean.setDepartmentId(uid);
bean.setPostId(postId);
bean.setAddUserIds(new String[]{user.getId()});
LogUtils.debug4plugin("set user {} to dep-[{}] post-[{}]",user.getUserName(),uid,postId);
UserService.getInstance().updateDepartmentPostUsers(uid, postId, bean);
}else {
LogUtils.debug4plugin("org {} not exist",uid);
}
}
}
SyncUtil.setSuccess(response);
}
}

55
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/user/UserDelHandler.java

@ -0,0 +1,55 @@
package com.fr.plugin.xx.IDaaS.sync.action.user;
import com.fr.decision.authority.data.User;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.bean.user.UserUpdateBean;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.stable.StringUtils;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserDelHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.DELETE;
}
@Override
public String getPath() {
return "/scim/organization";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!SyncUtil.checkAuth(request.getHeader("Authorization"))){
SyncUtil.setError(response, "Authorization验证失败");
return;
}
String id = WebUtils.getHTTPRequestParameter(request, "id");
if (StringUtils.isBlank(id)) {
SyncUtil.setError(response, "id不能为空");
return;
}
User user = UserService.getInstance().getUserByUserId(id);
if (user == null) {
SyncUtil.setError(response, "用户不存在");
return;
}
UserUpdateBean userUpdateBean = new UserUpdateBean();
userUpdateBean.setRemoveUserIds(new String[]{user.getId()});
UserService.getInstance().deleteUsers(userUpdateBean);
SyncUtil.setSuccess(response);
}
}

103
src/main/java/com/fr/plugin/xx/IDaaS/sync/action/user/UserEditHandler.java

@ -0,0 +1,103 @@
package com.fr.plugin.xx.IDaaS.sync.action.user;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.User;
import com.fr.decision.authority.data.personnel.DepRole;
import com.fr.decision.fun.impl.BaseHttpHandler;
import com.fr.decision.webservice.bean.user.DepPostUserUpdateBean;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.xx.IDaaS.sync.util.LogUtils;
import com.fr.plugin.xx.IDaaS.sync.util.SyncUtil;
import com.fr.third.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class UserEditHandler extends BaseHttpHandler {
@Override
public RequestMethod getMethod() {
return RequestMethod.PUT;
}
@Override
public String getPath() {
return "/scim/account";
}
@Override
public boolean isPublic() {
return true;
}
@Override
public void handle(HttpServletRequest request, HttpServletResponse response) throws Exception {
if(!SyncUtil.checkAuth(request.getHeader("Authorization"))){
SyncUtil.setError(response, "Authorization验证失败");
return;
}
JSONObject body = SyncUtil.getBody(request);
if (JSONObject.EMPTY.equals(body)) {
SyncUtil.setError(response, "请求为空");
return;
}
User user = SyncUtil.getUser(body);
User userByUserName = UserService.getInstance().getUserByUserName(user.getUserName());
if (userByUserName == null) {
SyncUtil.setError(response, "用户不存在");
return;
}
user.setPassword(userByUserName.getPassword());
AuthorityContext.getInstance().getUserController().update(user);
List<DepRole> depts = AuthorityContext.getInstance().getDepartmentController().findDepRoleByUser(user.getId());
Set<String> deptSet = depts.stream().map(DepRole::getDepartmentId).collect(Collectors.toSet());
Set<String> nowSet = new HashSet<>();
JSONArray belongs = body.getJSONArray("belongs");
if (belongs != null) {
for (int i = 0; i < belongs.size(); i++) {
JSONObject object = belongs.getJSONObject(i);
String uid = object.getString("belongOuUuid");
//不存在则新增
if (!deptSet.contains(uid)) {
Department query = AuthorityContext.getInstance().getDepartmentController().getById(uid);
if(query != null){
String postId = SyncUtil.generateDefaultPosition(uid);
DepPostUserUpdateBean bean = new DepPostUserUpdateBean();
bean.setDepartmentId(uid);
bean.setPostId(postId);
bean.setAddUserIds(new String[]{user.getId()});
LogUtils.debug4plugin("set user {} to dep-[{}] post-[{}]", user.getUserName(), uid, postId);
UserService.getInstance().updateDepartmentPostUsers(uid, postId, bean);
}else {
LogUtils.debug4plugin("org {} not exist",uid);
}
}
nowSet.add(uid);
}
}
deptSet.stream().filter(e -> !nowSet.contains(e)).forEach(e -> {
try {
String postId = SyncUtil.generateDefaultPosition(e);
DepPostUserUpdateBean bean = new DepPostUserUpdateBean();
bean.setDepartmentId(e);
bean.setPostId(postId);
bean.setRemoveUserIds(new String[]{user.getId()});
LogUtils.debug4plugin("remove user {} to dep-[{}] post-[{}]", user.getUserName(), e, postId);
UserService.getInstance().updateDepartmentPostUsers(e, postId, bean);
} catch (Exception ex) {
LogUtils.error(ex.getMessage(), e);
}
});
SyncUtil.setSuccess(response);
}
}

91
src/main/java/com/fr/plugin/xx/IDaaS/sync/conf/SyncConfig.java

@ -0,0 +1,91 @@
package com.fr.plugin.xx.IDaaS.sync.conf;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.stable.StringUtils;
/**
* @author xx
* @since 2021/12/04
*/
@Visualization(category = "IDaaS同步配置")
@EnableMetrics
public class SyncConfig extends DefaultConfiguration {
private static volatile SyncConfig config = null;
public static SyncConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(SyncConfig.class);
}
return config;
}
@Identifier(value = "debugSwitch", name = "插件调试开关", description = "日志调试模式", status = Status.SHOW)
private Conf<Boolean> debugSwitch = Holders.simple(true);
@Identifier(value = "authUser", name = "接口鉴权用户名", description = "接口鉴权用户名", status = Status.SHOW)
private Conf<String> authUser = Holders.simple(StringUtils.EMPTY);
public String getAuthUser() {
return authUser.get();
}
public void setAuthUser(String authUser) {
this.authUser.set(authUser);
}
@Identifier(value = "authPass", name = "接口鉴权密码", description = "接口鉴权密码", status = Status.SHOW)
private Conf<String> authPass = Holders.simple(StringUtils.EMPTY);
public String getAuthPass() {
return authPass.get();
}
public void setAuthPass(String authPass) {
this.authPass.set(authPass);
}
public Boolean getDebugSwitch() {
return this.debugSwitch.get();
}
public void setDebugSwitch(Boolean debugSwitch) {
this.debugSwitch.set(debugSwitch);
}
@Identifier(value = "rootId", name = "部门根节点ID", description = "部门根节点ID", status = Status.SHOW)
private Conf<String> rootId = Holders.simple("xx");
public String getRootId() {
return rootId.get();
}
public void setRootId(String rootId) {
this.rootId.set(rootId);
}
@Identifier(value = "initSwitch", name = "初始化开关", description = "初始化开关", status = Status.SHOW)
private Conf<Boolean> initSwitch = Holders.simple(false);
public Boolean getInitSwitch() {
return initSwitch.get();
}
public void setInitSwitch(Boolean initSwitch) {
this.initSwitch.set(initSwitch);
}
@Override
public Object clone() throws CloneNotSupportedException {
SyncConfig cloned = (SyncConfig) super.clone();
cloned.debugSwitch = (Conf<Boolean>) debugSwitch.clone();
cloned.authUser = (Conf<String>) authUser.clone();
cloned.authPass = (Conf<String>) authPass.clone();
cloned.rootId = (Conf<String>) rootId.clone();
return cloned;
}
}

17
src/main/java/com/fr/plugin/xx/IDaaS/sync/dao/DeptDao.java

@ -0,0 +1,17 @@
package com.fr.plugin.xx.IDaaS.sync.dao;
import com.fr.plugin.xx.IDaaS.sync.entity.DeptEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.session.DAOSession;
public class DeptDao extends BaseDAO<DeptEntity> {
public DeptDao(DAOSession daoSession) {
super(daoSession);
}
@Override
protected Class<DeptEntity> getEntityClass() {
return DeptEntity.class;
}
}

265
src/main/java/com/fr/plugin/xx/IDaaS/sync/entity/DeptEntity.java

@ -0,0 +1,265 @@
package com.fr.plugin.xx.IDaaS.sync.entity;
import com.fr.json.JSONObject;
import com.fr.stable.StringUtils;
import com.fr.stable.db.entity.BaseEntity;
import com.fr.stable.db.entity.TableAssociation;
import com.fr.third.javax.persistence.Column;
import com.fr.third.javax.persistence.Entity;
import com.fr.third.javax.persistence.Table;
import com.fr.third.org.apache.commons.lang3.math.NumberUtils;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Cell;
import com.fr.third.v2.org.apache.poi.ss.usermodel.Row;
@Entity
@Table(name = "fine_plugin_dept")
@TableAssociation(associated = true)
public class DeptEntity extends BaseEntity {
@Column(name = "parent_id")
private String parentId;
@Column(name = "name")
private String name;
@Column(name = "type")
private String type;
@Column(name = "short_name")
private String shortName;
@Column(name = "level_number")
private Integer levelNumber;
@Column(name = "logical_org_id")
private String logicalOrgId;
@Column(name = "org_id")
private String orgId;
@Column(name = "org_adress")
private String orgAdress;
@Column(name = "country")
private String country;
@Column(name = "org_status")
private String orgStatus;
@Column(name = "org_plate")
private String orgPlate;
@Column(name = "org_category")
private String orgCategory;
@Column(name = "org_properties")
private String orgProperties;
@Column(name = "parentDepartmentId")
private String parentDepartmentId;
@Column(name = "isReal")
private String isReal;
@Column(name = "org_code")
private String orgCode;
public static DeptEntity fromBody(JSONObject object) {
if (object == null) {
return null;
}
DeptEntity entity = new DeptEntity();
entity.setId(object.getString("organizationUuid"));
entity.setName(object.getString("organization"));
entity.setParentId(object.getString("parentUuid"));
entity.setType(object.getString("type"));
entity.setLevelNumber(object.getInt("levelNumber"));
JSONObject extendField = object.getJSONObject("extendField");
if (extendField != null) {
JSONObject attributes = extendField.getJSONObject("attributes");
if (attributes != null) {
entity.setLogicalOrgId(attributes.getString("logicalOrgId"));
entity.setOrgId(attributes.getString("OrgID"));
entity.setShortName(attributes.getString("OrgShortName"));
entity.setOrgAdress(attributes.getString("OrgAdress"));
entity.setCountry(attributes.getString("Country"));
entity.setOrgStatus(attributes.getString("OrgStatus"));
entity.setOrgPlate(attributes.getString("OrgPlate"));
entity.setOrgCategory(attributes.getString("OrgCategory"));
entity.setOrgProperties(attributes.getString("OrgProperties"));
entity.setParentDepartmentId(attributes.getString("parentlogicalOrgId"));
entity.setIsReal(attributes.getString("IsReal"));
entity.setOrgCode(attributes.getString("OrgCode"));
}
}
return entity;
}
public static DeptEntity fromRow(Row row) {
if (row == null || row.getCell(0) == null || StringUtils.isBlank(row.getCell(0).getStringCellValue())) {
return null;
}
DeptEntity entity = new DeptEntity();
entity.setId(entity.getCellValue(row.getCell(0)));
entity.setName(entity.getCellValue(row.getCell(1)));
entity.setParentId(entity.getCellValue(row.getCell(2)));
entity.setType(entity.getCellValue(row.getCell(4)));
String level = entity.getCellValue(row.getCell(5));
if (StringUtils.isNotBlank(level) && NumberUtils.isCreatable(level)) {
entity.setLevelNumber(Integer.valueOf(level));
}
entity.setLogicalOrgId(entity.getCellValue(row.getCell(7)));
entity.setOrgId(entity.getCellValue(row.getCell(8)));
entity.setShortName(entity.getCellValue(row.getCell(11)));
entity.setOrgAdress(entity.getCellValue(row.getCell(13)));
entity.setCountry(entity.getCellValue(row.getCell(15)));
entity.setOrgStatus(entity.getCellValue(row.getCell(19)));
entity.setOrgPlate(entity.getCellValue(row.getCell(20)));
entity.setOrgCategory(entity.getCellValue(row.getCell(21)));
entity.setOrgProperties(entity.getCellValue(row.getCell(22)));
entity.setParentDepartmentId(entity.getCellValue(row.getCell(27)));
entity.setIsReal(entity.getCellValue(row.getCell(37)));
entity.setOrgCode(entity.getCellValue(row.getCell(38)));
return entity;
}
public String getIsReal() {
return isReal;
}
public void setIsReal(String isReal) {
this.isReal = isReal;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
return cell.getStringCellValue();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLogicalOrgId() {
return logicalOrgId;
}
public void setLogicalOrgId(String logicalOrgId) {
this.logicalOrgId = logicalOrgId;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
public String getOrgAdress() {
return orgAdress;
}
public void setOrgAdress(String orgAdress) {
this.orgAdress = orgAdress;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getOrgStatus() {
return orgStatus;
}
public void setOrgStatus(String orgStatus) {
this.orgStatus = orgStatus;
}
public String getOrgPlate() {
return orgPlate;
}
public void setOrgPlate(String orgPlate) {
this.orgPlate = orgPlate;
}
public String getOrgCategory() {
return orgCategory;
}
public void setOrgCategory(String orgCategory) {
this.orgCategory = orgCategory;
}
public String getOrgProperties() {
return orgProperties;
}
public void setOrgProperties(String orgProperties) {
this.orgProperties = orgProperties;
}
public String getParentDepartmentId() {
return parentDepartmentId;
}
public void setParentDepartmentId(String parentDepartmentId) {
this.parentDepartmentId = parentDepartmentId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getShortName() {
return shortName;
}
public void setShortName(String shortName) {
this.shortName = shortName;
}
public Integer getLevelNumber() {
return levelNumber;
}
public void setLevelNumber(Integer levelNumber) {
this.levelNumber = levelNumber;
}
}

122
src/main/java/com/fr/plugin/xx/IDaaS/sync/util/LogUtils.java

@ -0,0 +1,122 @@
package com.fr.plugin.xx.IDaaS.sync.util;
import com.fr.log.FineLoggerFactory;
import com.fr.log.FineLoggerProvider;
import com.fr.plugin.context.PluginContexts;
import com.fr.plugin.xx.IDaaS.sync.Constants;
import com.fr.plugin.xx.IDaaS.sync.conf.SyncConfig;
import com.fr.stable.StringUtils;
/**
* @author xx
* @since 2021/12/04
*/
public final class LogUtils {
private static final String DEBUG_PREFIX = "[插件调试] ";
private static String LOG_PREFIX = Constants.PLUGIN_NAME;
private static final String PLUGIN_VERSION;
private static final FineLoggerProvider LOGGER = FineLoggerFactory.getLogger();
static {
String version = PluginContexts.currentContext().getMarker().getVersion();
if (StringUtils.isNotBlank(version)) {
PLUGIN_VERSION = "[v" + version + "] ";
} else {
PLUGIN_VERSION = "[unknown version] ";
}
LOG_PREFIX = LOG_PREFIX + PLUGIN_VERSION;
}
public static void setPrefix(String prefix) {
if (prefix != null) {
LOG_PREFIX = prefix;
}
}
public static boolean isDebugEnabled() {
return LOGGER.isDebugEnabled();
}
public static void debug(String s) {
LOGGER.debug(LOG_PREFIX + s);
}
public static void debug(String s, Object... objects) {
LOGGER.debug(LOG_PREFIX + s, objects);
}
public static void debug(String s, Throwable throwable) {
LOGGER.debug(LOG_PREFIX + s, throwable);
}
public static void debug4plugin(String s) {
if (SyncConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s);
} else {
LOGGER.debug(LOG_PREFIX + s);
}
}
public static void debug4plugin(String s, Object... objects) {
if (SyncConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, objects);
} else {
LOGGER.debug(LOG_PREFIX + s, objects);
}
}
public static void debug4plugin(String s, Throwable throwable) {
if (SyncConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s, throwable);
} else {
LOGGER.debug(LOG_PREFIX + s, throwable);
}
}
public static boolean isInfoEnabled() {
return LOGGER.isInfoEnabled();
}
public static void info(String s) {
LOGGER.info(LOG_PREFIX + s);
}
public static void info(String s, Object... objects) {
LOGGER.info(LOG_PREFIX + s, objects);
}
public static void warn(String s) {
LOGGER.warn(LOG_PREFIX + s);
}
public static void warn(String s, Object... objects) {
LOGGER.warn(LOG_PREFIX + s, objects);
}
public static void warn(String s, Throwable throwable) {
LOGGER.warn(LOG_PREFIX + s, throwable);
}
public static void warn(Throwable throwable, String s, Object... objects) {
LOGGER.warn(throwable, LOG_PREFIX + s, objects);
}
public static void error(String s) {
LOGGER.error(LOG_PREFIX + s);
}
public static void error(String s, Object... objects) {
LOGGER.error(LOG_PREFIX + s, objects);
}
public static void error(String s, Throwable throwable) {
LOGGER.error(LOG_PREFIX + s, throwable);
}
public static void error(Throwable throwable, String s, Object... objects) {
LOGGER.error(throwable, LOG_PREFIX + s, objects);
}
}

167
src/main/java/com/fr/plugin/xx/IDaaS/sync/util/SyncUtil.java

@ -0,0 +1,167 @@
package com.fr.plugin.xx.IDaaS.sync.util;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.User;
import com.fr.decision.webservice.bean.user.DepartmentPostBean;
import com.fr.decision.webservice.v10.user.PositionService;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.plugin.xx.IDaaS.sync.SyncDBAccessProvider;
import com.fr.plugin.xx.IDaaS.sync.conf.SyncConfig;
import com.fr.plugin.xx.IDaaS.sync.dao.DeptDao;
import com.fr.plugin.xx.IDaaS.sync.entity.DeptEntity;
import com.fr.stable.StringUtils;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.third.org.apache.commons.codec.binary.Base64;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
public class SyncUtil {
/**
* 处理请求报文
*
* @param req
* @return
*/
public static JSONObject getBody(HttpServletRequest req) {
try {
BufferedReader br = req.getReader();
String str = "";
String listString = "";
while ((str = br.readLine()) != null) {
listString += str;
}
JSONObject jsonObject = new JSONObject(listString);
LogUtils.debug4plugin("body is {}", jsonObject);
return jsonObject;
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
return JSONObject.EMPTY;
}
/**
* 返回错误
*
* @param response
* @param mess
*/
public static void setError(HttpServletResponse response, String mess) {
JSONObject object = JSONObject.create();
object.put("errorNumber", -1);
object.put("errors", String.format("[%s]", mess));
try {
WebUtils.printAsJSON(response, object);
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
}
public static void setSuccess(HttpServletResponse response) {
JSONObject object = JSONObject.create();
object.put("errorNumber", 0);
try {
WebUtils.printAsJSON(response, object);
} catch (Exception e) {
LogUtils.error(e.getMessage(), e);
}
}
private static String getEmail(JSONArray emails) {
if (emails != null && !JSONArray.create().equals(emails) && emails.size() > 0) {
JSONObject jsonObject = emails.getJSONObject(0);
return jsonObject.getString("value");
}
return null;
}
private static String getPhone(JSONArray phoneNumbers) {
if (phoneNumbers != null && !JSONArray.create().equals(phoneNumbers) && phoneNumbers.size() > 0) {
JSONObject jsonObject = phoneNumbers.getJSONObject(0);
return jsonObject.getString("value");
}
return null;
}
public static User getUser(JSONObject body) {
return (new User()).id(body.getString("id")).userName(body.getString("userName"))
.realName(body.getString("displayName")).email(getEmail(body.getJSONArray("emails")))
.workPhone(getPhone(body.getJSONArray("phoneNumbers"))).creationType(ManualOperationType.KEY)
.lastOperationType(ManualOperationType.KEY).enable(!body.getBoolean("locked"));
}
public static String generateDefaultPosition(String depID) throws Exception {
String positionName = "部门成员";
String adminId = UserService.getInstance().getAdminUserIdList().get(0);
List<DepartmentPostBean> postBeanList = PositionService.getInstance().getPositionsUnderParentDepartment(adminId, depID, null);
boolean hasDefaultPosition = false;
String positionId = "";
for (DepartmentPostBean postBean : postBeanList) {
if (StringUtils.equals(positionName, postBean.getText())) {
return postBean.getId();
}
}
List<DepartmentPostBean> postBeans = PositionService.getInstance().getPositions(adminId, null);
for (DepartmentPostBean postBean : postBeans) {
if (StringUtils.equals(positionName, postBean.getText())) {
hasDefaultPosition = true;
positionId = postBean.getId();
}
}
if (!hasDefaultPosition) {
positionId = PositionService.getInstance().addPosition(positionName).getId();
}
AuthorityContext.getInstance().getPostController().addPostToDepartment(positionId, depID);
return positionId;
}
public static boolean checkAuth(String auth) {
String authUser = SyncConfig.getInstance().getAuthUser();
String authPass = SyncConfig.getInstance().getAuthPass();
if (StringUtils.isBlank(authUser) && StringUtils.isBlank(authPass)) {
return true;
}
if (StringUtils.isBlank(auth)) {
return false;
}
String datap = authUser + ":" + authPass;
try {
String authorization = Base64.encodeBase64String(datap.getBytes("UTF-8")).trim();
return StringUtils.equals(auth, "Basic " + authorization);
} catch (UnsupportedEncodingException e) {
LogUtils.error(e.getMessage(), e);
}
return false;
}
public static void saveDept(JSONObject body, Department department) throws Exception {
DeptEntity entity = DeptEntity.fromBody(body);
SyncDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<DeptEntity>() {
@Override
public DeptEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(DeptDao.class).addOrUpdate(entity);
return entity;
}
});
}
public static void delDept(String id) throws Exception {
SyncDBAccessProvider.getDbAccessor().runDMLAction(new DBAction<DeptEntity>() {
@Override
public DeptEntity run(DAOContext daoContext) throws Exception {
daoContext.getDAO(DeptDao.class).remove(id);
return null;
}
});
}
}
Loading…
Cancel
Save