Browse Source

open

master
pioneer 2 years ago
commit
3cef69d78c
  1. 7
      README.md
  2. BIN
      lib/finekit-10.0.jar
  3. BIN
      lib/java-jwt-3.10.2.jar
  4. 21
      plugin.xml
  5. 21
      src/main/java/com/eco/plugin/xx/jbsync/config/InitializeMonitor.java
  6. 57
      src/main/java/com/eco/plugin/xx/jbsync/config/PluginSimpleConfig.java
  7. 14
      src/main/java/com/eco/plugin/xx/jbsync/controller/ControllerRegisterProvider.java
  8. 84
      src/main/java/com/eco/plugin/xx/jbsync/controller/ControllerSelf.java
  9. 109
      src/main/java/com/eco/plugin/xx/jbsync/kit/DepartmentServiceKit.java
  10. 81
      src/main/java/com/eco/plugin/xx/jbsync/kit/PostServiceKit.java
  11. 28
      src/main/java/com/eco/plugin/xx/jbsync/kit/UserServiceKit.java
  12. 104
      src/main/java/com/eco/plugin/xx/jbsync/utils/FRDepartmentUtils.java
  13. 75
      src/main/java/com/eco/plugin/xx/jbsync/utils/FRPostUtils.java
  14. 221
      src/main/java/com/eco/plugin/xx/jbsync/utils/FRUserUtils.java
  15. 323
      src/main/java/com/eco/plugin/xx/jbsync/utils/FRUtils.java
  16. 35
      src/main/java/com/eco/plugin/xx/jbsync/utils/JWTUtils.java
  17. 117
      src/main/java/com/eco/plugin/xx/jbsync/utils/LogUtils.java
  18. 87
      src/main/java/com/eco/plugin/xx/jbsync/utils/OrgUtils.java
  19. 145
      src/main/java/com/eco/plugin/xx/jbsync/utils/PostUtils.java
  20. 108
      src/main/java/com/eco/plugin/xx/jbsync/utils/ResponseUtils.java
  21. 142
      src/main/java/com/eco/plugin/xx/jbsync/utils/UserUtils.java
  22. 329
      src/main/java/com/eco/plugin/xx/jbsync/utils/Utils.java

7
README.md

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

BIN
lib/finekit-10.0.jar

Binary file not shown.

BIN
lib/java-jwt-3.10.2.jar

Binary file not shown.

21
plugin.xml

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.eco.plugin.xx.jbsync</id>
<name><![CDATA[数据同步]]></name>
<active>yes</active>
<version>1.0.11</version>
<env-version>10.0</env-version>
<jartime>2018-07-31</jartime>
<vendor>fr.open</vendor>
<description><![CDATA[数据同步]]></description>
<change-notes><![CDATA[
]]></change-notes>
<main-package>com.eco.plugin.xx.jbsync</main-package>
<lifecycle-monitor class="com.eco.plugin.xx.jbsync.config.InitializeMonitor"/>
<extra-decision>
<ControllerRegisterProvider class="com.eco.plugin.xx.jbsync.controller.ControllerRegisterProvider"/>
</extra-decision>
<function-recorder class="com.eco.plugin.xx.jbsync.config.PluginSimpleConfig"/>
</plugin>

21
src/main/java/com/eco/plugin/xx/jbsync/config/InitializeMonitor.java

@ -0,0 +1,21 @@
package com.eco.plugin.xx.jbsync.config;
import com.fr.plugin.context.PluginContext;
import com.fr.plugin.observer.inner.AbstractPluginLifecycleMonitor;
/**
* @author xx
* @version 10.0
* Created by xx on 2021-12-03
*/
public class InitializeMonitor extends AbstractPluginLifecycleMonitor {
@Override
public void afterRun(PluginContext pluginContext) {
PluginSimpleConfig.getInstance();
}
@Override
public void beforeStop(PluginContext pluginContext) {
}
}

57
src/main/java/com/eco/plugin/xx/jbsync/config/PluginSimpleConfig.java

@ -0,0 +1,57 @@
package com.eco.plugin.xx.jbsync.config;
import com.fr.config.*;
import com.fr.config.holder.Conf;
import com.fr.config.holder.factory.Holders;
import com.fr.intelli.record.Focus;
import com.fr.intelli.record.Original;
import com.fr.record.analyzer.EnableMetrics;
@Visualization(category = "数据同步配置")
@EnableMetrics
public class PluginSimpleConfig extends DefaultConfiguration {
private static volatile PluginSimpleConfig config = null;
@Focus(id="com.eco.plugin.xx.jbsync.config", text = "数据同步配置", source = Original.PLUGIN)
public static PluginSimpleConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(PluginSimpleConfig.class);
}
return config;
}
@Identifier(value = "secret", name = "密钥", description = "密钥", status = Status.SHOW)
private Conf<String> secret = Holders.simple("");
@Identifier(value = "debugSwitch", name = "插件调试开关", description = "日志调试模式", status = Status.SHOW)
private Conf<Boolean> debugSwitch = Holders.simple(true);
public String getSecret() {
return secret.get();
}
public void setSecret(String url) {
this.secret.set(url);
}
public Boolean getDebugSwitch() {
return debugSwitch.get();
}
public void setDebugSwitch(Boolean url) {
this.debugSwitch.set(url);
}
@Override
public Object clone() throws CloneNotSupportedException {
PluginSimpleConfig cloned = (PluginSimpleConfig) super.clone();
// cloned.text = (Conf<String>) text.clone();
// cloned.count = (Conf<Integer>) count.clone();
// cloned.price = (Conf<Double>) price.clone();
// cloned.time = (Conf<Long>) time.clone();
// cloned.student = (Conf<Boolean>) student.clone();
return cloned;
}
}

14
src/main/java/com/eco/plugin/xx/jbsync/controller/ControllerRegisterProvider.java

@ -0,0 +1,14 @@
package com.eco.plugin.xx.jbsync.controller;
import com.fr.decision.fun.impl.AbstractControllerRegisterProvider;
import com.fr.plugin.transform.FunctionRecorder;
@FunctionRecorder
public class ControllerRegisterProvider extends AbstractControllerRegisterProvider {
@Override
public Class<?>[] getControllers() {
return new Class[]{
ControllerSelf.class
};
}
}

84
src/main/java/com/eco/plugin/xx/jbsync/controller/ControllerSelf.java

@ -0,0 +1,84 @@
package com.eco.plugin.xx.jbsync.controller;
import com.eco.plugin.xx.jbsync.config.PluginSimpleConfig;
import com.eco.plugin.xx.jbsync.utils.*;
import com.fr.decision.webservice.annotation.LoginStatusChecker;
import com.fr.json.JSONObject;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.third.springframework.stereotype.Controller;
import com.fr.third.springframework.web.bind.annotation.PostMapping;
import com.fr.third.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
@LoginStatusChecker(required = false)
@FunctionRecorder
public class ControllerSelf {
@PostMapping(value = "/org")
@ResponseBody
public void org(HttpServletRequest req,HttpServletResponse res){
String token =req.getParameter("access_token");
boolean verify = JWTUtils.verify(token, PluginSimpleConfig.getInstance().getSecret());
if(!verify){
JSONObject result = new JSONObject();
result.put("code","302");
result.put("msg","token鉴权失败");
ResponseUtils.response(res,result);
return ;
}
JSONObject param = Utils.getRequestBody(req);
LogUtils.debug4plugin("组织操作请求报文[{}]", param);
JSONObject result = OrgUtils.operOrg(param);
LogUtils.debug4plugin("组织操作响应报文[{}]", result);
ResponseUtils.response(res,result);
}
@PostMapping(value = "/job")
@ResponseBody
public void job(HttpServletRequest req,HttpServletResponse res){
String token =req.getParameter("access_token");
boolean verify = JWTUtils.verify(token, PluginSimpleConfig.getInstance().getSecret());
if(!verify){
JSONObject result = new JSONObject();
result.put("code","302");
result.put("msg","token鉴权失败");
ResponseUtils.response(res,result);
return ;
}
JSONObject param = Utils.getRequestBody(req);
LogUtils.debug4plugin("职务操作请求报文[{}]", param);
JSONObject result = PostUtils.operPost(param);
LogUtils.debug4plugin("职务操作响应报文[{}]", result);
ResponseUtils.response(res,result);
}
@PostMapping(value = "/users")
@ResponseBody
public void users(HttpServletRequest req,HttpServletResponse res){
String token =req.getParameter("access_token");
boolean verify = JWTUtils.verify(token, PluginSimpleConfig.getInstance().getSecret());
if(!verify){
JSONObject result = new JSONObject();
result.put("code","302");
result.put("msg","token鉴权失败");
ResponseUtils.response(res,result);
return ;
}
JSONObject param = Utils.getRequestBody(req);
LogUtils.debug4plugin("用户操作请求报文[{}]", param);
JSONObject result = UserUtils.operUser(param);
LogUtils.debug4plugin("用户操作响应报文[{}]", param);
ResponseUtils.response(res,result);
}
}

109
src/main/java/com/eco/plugin/xx/jbsync/kit/DepartmentServiceKit.java

@ -0,0 +1,109 @@
/*
* Copyright (C), 2018-2021
* Project: starter
* FileName: DepartmentServiceKit
* Author: Louis
* Date: 2021/5/14 9:38
*/
package com.eco.plugin.xx.jbsync.kit;
import com.eco.plugin.xx.jbsync.utils.Utils;
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.webservice.exception.general.DuplicatedNameException;
import com.fr.decision.webservice.v10.user.DepartmentService;
import com.fr.general.ComparatorUtils;
import com.fr.stable.StableUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.Restriction;
import com.fr.stable.query.restriction.RestrictionFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* <Function Description><br>
* <DepartmentServiceKit>
*
* @author xx
* @since 1.0.0
*/
public class DepartmentServiceKit extends DepartmentService {
public static final String DECISION_DEP_ROOT = "decision-dep-root";
private static volatile DepartmentServiceKit departmentServiceKit = null;
public DepartmentServiceKit() {
}
public static DepartmentServiceKit getInstance() {
if (departmentServiceKit == null) {
departmentServiceKit = new DepartmentServiceKit();
}
return departmentServiceKit;
}
/**
* 根据id获取部门
* @param id
* @return
* @throws Exception
*/
public Department getByid(String id) throws Exception {
return AuthorityContext.getInstance().getDepartmentController().getById(id);
}
/**
* 添加部门
* @param id
* @param pId
* @param depName
* @return
* @throws Exception
*/
public Department addDepartment(String id, String pId, String depName) throws Exception {
if ((Utils.isNotNullStr(pId) && pId.equals(DECISION_DEP_ROOT)) || Utils.isNullStr(pId)) {
pId = null;
}
this.checkDuplicatedDepartmentName(pId, depName);
Department department = (new Department()).id(id).name(depName).parentId(pId).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true);
AuthorityContext.getInstance().getDepartmentController().add(department);
return department;
}
private void checkDuplicatedDepartmentName(String parentId, String depName) throws Exception {
QueryCondition condition = QueryFactory.create().addRestriction(RestrictionFactory.and(new Restriction[]{RestrictionFactory.eq("name", depName), RestrictionFactory.eq("parentId", parentId)}));
Department sameNameDep = AuthorityContext.getInstance().getDepartmentController().findOne(condition);
if (sameNameDep != null) {
throw new DuplicatedNameException();
}
}
private String getDepartmentFullPath(String pId, String depName, String splitter) throws Exception {
List<String> paths = new ArrayList<>();
paths.add(depName);
while (!ComparatorUtils.equals(pId, DECISION_DEP_ROOT) && pId != null) {
Department parentDepartment = AuthorityContext.getInstance().getDepartmentController().getById(pId);
paths.add(parentDepartment.getName());
pId = parentDepartment.getParentId();
}
Collections.reverse(paths);
return StableUtils.join(paths.toArray(new String[0]), splitter);
}
public void editDepartment(String departmentId, String depName, String pId) throws Exception {
if (Utils.isNotNullStr(pId) && pId.equals(DECISION_DEP_ROOT)) {
pId = null;
}
Department department = AuthorityContext.getInstance().getDepartmentController().getById(departmentId);
String departmentFullPath = DepartmentService.getInstance().getDepartmentFullPath(departmentId);
if (!ComparatorUtils.equals(department.getName(), depName)) {
this.checkDuplicatedDepartmentName(department.getParentId(), depName);
department.setName(depName);
department.setParentId(pId);
AuthorityContext.getInstance().getDepartmentController().update(department);
}
}
}

81
src/main/java/com/eco/plugin/xx/jbsync/kit/PostServiceKit.java

@ -0,0 +1,81 @@
/*
* Copyright (C), 2018-2021
* Project: starter
* FileName: DepartmentServiceKit
* Author: Louis
* Date: 2021/5/14 9:38
*/
package com.eco.plugin.xx.jbsync.kit;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.SoftRoleType;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.Post;
import com.fr.decision.record.OperateMessage;
import com.fr.decision.webservice.exception.general.DuplicatedNameException;
import com.fr.decision.webservice.v10.user.DepartmentService;
import com.fr.intelli.record.MetricRegistry;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.Restriction;
import com.fr.stable.query.restriction.RestrictionFactory;
/**
* <Function Description><br>
* <PostServiceKit>
*
* @author xx
* @since 1.0.0
*/
public class PostServiceKit extends DepartmentService {
public static final String DECISION_DEP_ROOT = "decision-dep-root";
private static volatile PostServiceKit postServiceKit = null;
public PostServiceKit() {
}
public static PostServiceKit getInstance() {
if (postServiceKit == null) {
postServiceKit = new PostServiceKit();
}
return postServiceKit;
}
/**
* 根据id获取职务
* @param id
* @return
* @throws Exception
*/
public Post getByid(String id) throws Exception {
return AuthorityContext.getInstance().getPostController().getById(id);
}
/**
* 添加部门
* @param postname
* @param postid
* @return
* @throws Exception
*/
public Post addPost(String postname,String postid) throws Exception {
this.checkDuplicatedPost(postname);
Post post = (new Post()).id(postid).name(postname).creationType(ManualOperationType.KEY).lastOperationType(ManualOperationType.KEY).enable(true).description("");
AuthorityContext.getInstance().getPostController().add(post);
this.deleteSoftData(post.getName());
MetricRegistry.getMetric().submit(OperateMessage.build("Dec-Module-User_Manager", "Dec-Dec-Post",postname, "Dec-Log_Add"));
return post;
}
private void checkDuplicatedPost(String postname) throws Exception {
Post post = (Post)AuthorityContext.getInstance().getPostController().findOne(QueryFactory.create().addRestriction(RestrictionFactory.eq("name", postname)));
if (post != null) {
throw new DuplicatedNameException("Duplicated names! ", post.getName());
}
}
private void deleteSoftData(String var1) throws Exception {
QueryCondition var2 = QueryFactory.create().addRestriction(RestrictionFactory.and(new Restriction[]{RestrictionFactory.eq("deletedName", var1), RestrictionFactory.eq("type", SoftRoleType.POST)}));
AuthorityContext.getInstance().getSoftDataController().remove(var2);
}
}

28
src/main/java/com/eco/plugin/xx/jbsync/kit/UserServiceKit.java

@ -0,0 +1,28 @@
package com.eco.plugin.xx.jbsync.kit;
import com.fr.decision.webservice.bean.user.UserBean;
import com.fr.decision.webservice.v10.user.UserService;
public class UserServiceKit extends UserService {
private static volatile UserServiceKit userServiceKit = null;
public UserServiceKit() {
}
public static UserServiceKit getInstance() {
if (userServiceKit == null) {
userServiceKit = new UserServiceKit();
}
return userServiceKit;
}
public void editUser(UserBean var1, String var2) throws Exception {
this.editUserInfo(var1);
if (var1.isResetPassword()) {
this.resetPassword(var1);
}
this.updateUserRoles(var2, var1);
this.updateUserDepartmentPost(var2, var1);
}
}

104
src/main/java/com/eco/plugin/xx/jbsync/utils/FRDepartmentUtils.java

@ -0,0 +1,104 @@
package com.eco.plugin.wink.jbsync.utils;
import com.fr.decision.webservice.bean.user.DepartmentPostBean;
import com.fr.decision.webservice.v10.user.DepartmentService;
import java.util.List;
public class FRDepartmentUtils {
public static void main(String[] args) {
}
/**
* 获取用户Service
* @return
*/
public static DepartmentService getDepartmentService(){
return DepartmentService.getInstance();
}
/**
* 添加部门
* @param pId 父节点id
* @param dpName 部门名称
*/
public static DepartmentPostBean addDP(String pId, String dpName) throws Exception {
if(Utils.isNullStr(pId)){
pId = "decision-dep-root";
}
return getDepartmentService().addDepartment(pId,dpName);
}
/**
* 修改组织
* @param id
* @param dpName
*/
public static void updateDP(String id,String dpName) throws Exception {
getDepartmentService().editDepartment(id,dpName);
}
/**
* 删除机构
* @param id
* @return
*/
public static void deleteDepartment(String id) throws Exception {
getDepartmentService().deleteDepartment(id);
}
/**
* 获取所有组织机构
* @param adminUserid
* @return
* @throws Exception
*/
public static List<DepartmentPostBean> getDepartmentTree(String adminUserid) throws Exception {
List<DepartmentPostBean> departmentTree = getDepartmentService().getDepartmentTree(adminUserid);
return departmentTree;
}
/**
* 获取pid下组织机构
* @param adminUserid
* @param pid
* @return
* @throws Exception
*/
public static List<DepartmentPostBean> getDepartmentsUnderParentDepartment(String adminUserid,String pid) throws Exception {
if(pid == null || pid.isEmpty()){
pid = "decision-dep-root";
}
List<DepartmentPostBean> departmentTree = getDepartmentService().getDepartmentsUnderParentDepartment(adminUserid,pid);
return departmentTree;
}
/**
* 获取pid下对应名字的组织机构
* @param adminUserid
* @param departname
* @param pid
* @return
* @throws Exception
*/
public static DepartmentPostBean getDepartment(String adminUserid,String departname,String pid) throws Exception {
if(pid == null || pid.isEmpty()){
pid = "decision-dep-root";
}
List<DepartmentPostBean> departmentTree = getDepartmentsUnderParentDepartment(adminUserid,pid);
DepartmentPostBean result = null;
for(DepartmentPostBean dpb : departmentTree){
if(dpb.getText().equals(departname)){
result = dpb;
break;
}
}
return result;
}
}

75
src/main/java/com/eco/plugin/xx/jbsync/utils/FRPostUtils.java

@ -0,0 +1,75 @@
package com.eco.plugin.xx.jbsync.utils;
import com.fr.decision.webservice.bean.user.DepPostUpdateBean;
import com.fr.decision.webservice.v10.user.PositionService;
public class FRPostUtils {
private static PositionService postService = null;
static{
postService = PositionService.getInstance();
}
/**
* 获取职务Service
* @return
*/
public static PositionService getPositionService(){
return PositionService.getInstance();
}
/**
* 添加职务
* @param postName
* @param description
* @return 职务id
* @throws Exception
*/
public static String addPost(String postName,String description) throws Exception {
String postId = postService.addPosition(postName,description);
return postId;
}
/**
* 删除职务
* @param postId
* @throws Exception
*/
public static void deletePost(String postId) throws Exception {
postService.deletePosition(postId);
}
/**
* 修改职务
* @param postId
* @param postName
* @param decription
* @throws Exception
*/
public static void updatePost(String postId,String postName,String decription) throws Exception {
postService.updatePosition(postId,postName,decription);
}
/**
* 添加或删除部门下的职务
* @param depId
* @param addPost
* @param removePost
* @return 成功条数
* @throws Exception
*/
public static int updateDepPost(String depId,String[] addPost, String[] removePost) throws Exception {
DepPostUpdateBean dub = new DepPostUpdateBean();
if(addPost != null && addPost.length > 0){
dub.setAddPostIds(addPost);
}
if(removePost != null && removePost.length > 0){
dub.setRemovePostIds(removePost);
}
return postService.updateDepPositions(depId,dub);
}
}

221
src/main/java/com/eco/plugin/xx/jbsync/utils/FRUserUtils.java

@ -0,0 +1,221 @@
package com.eco.plugin.xx.jbsync.utils;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.controller.UserController;
import com.fr.decision.authority.data.User;
import com.fr.decision.privilege.TransmissionTool;
import com.fr.decision.webservice.bean.user.*;
import com.fr.decision.webservice.v10.login.ExtendTokenProcessor;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.user.UserService;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class FRUserUtils {
/**
* 获取用户Service
* @return
*/
public static UserService getUserService(){
return UserService.getInstance();
}
/**
* 获取全量用户
* @return
* @throws Exception
*/
public static List<UserAdditionBean> getAllUsers() throws Exception {
// List<UserBean> userbean = UserMiddleRoleService.getInstance().getAllUsers(false);
List<UserAdditionBean> users = new ArrayList<UserAdditionBean>();
getAllUser(getAdminUser().getUsername(),0,1000,users);
return users;
}
/**
*
* @param adminUsername 管理员用户名
* @param page 页数
* @param num 每页的数据
* @param users 保存用户的列表
*/
private static void getAllUser(String adminUsername,int page,int num,List<UserAdditionBean> users) throws Exception {
Map<String,Object> result = getUserService().getAllUsers(adminUsername,page,num,"","",true);
Long total = (Long)result.get("total");
List<UserAdditionBean> item = (List<UserAdditionBean>)result.get("items");
users.addAll(item);
page = page+1;
if(page * num >= total){
return ;
}
getAllUser(adminUsername,page,num,users);
}
/**
* 添加用户
* @param userBean
*/
public static void addUser(UserBean userBean) throws Exception {
userBean.setPassword(TransmissionTool.defaultEncrypt(userBean.getPassword()));
getUserService().addUser(userBean);
}
/**
* 删除用户
* @param userBean
*/
public static void updateUser(User userBean) throws Exception {
UserController userController = AuthorityContext.getInstance().getUserController();
userController.update(userBean);
// UserServiceKit.getInstance().editUser(userBean,getAdminUser().getId());
}
/**
* 删除用户
* @param user
* @return
*/
public static int deleteUser(User user) throws Exception {
String userId = user.getId();
UserUpdateBean userUpdateBean = new UserUpdateBean();
userUpdateBean.setRemoveUserIds(new String[]{userId});
return getUserService().deleteUsers(userUpdateBean);
}
/**
* 根据用户名获取用户实体
* @param userName
* @return
*/
public static User getUserByUserName(String userName) throws Exception {
return getUserService().getUserByUserName(userName);
}
/**
* 根据用户名获取用户实体
* @param userName
* @return
*/
public static UserBean getUserBeanByUserName(String userName ) throws Exception {
String id = getUserService().getUserByUserName(userName).getId();
return getUser(id);
}
/**
* 根据id获取用户
* @param id
* @return
* @throws Exception
*/
public static UserBean getUser(String id) throws Exception {
return getUserService().getUser(id);
}
/**
* 判断是否是管理员
* @param username
* @return
*/
public static boolean isAdmin(String username) throws Exception{
return getUserService().isAdmin(getUserByUserName(username).getId());
}
/**
* 禁用启用用户
* @param userId
* @param state false 禁用 true 启用
* @throws Exception 异常说明失败
*/
public static void forbidUser(String userId,boolean state) throws Exception {
getUserService().forbidUser(userId,state);
}
/**
* 修改用户部门
* @param departmentId
* @param postId
// * @param ud
* @throws Exception
*/
public static void updateDepartmentPostUsers(String departmentId, String postId, String userid) throws Exception {
AuthorityContext.getInstance().getUserController().addUserToDepartmentAndPost(userid, departmentId, postId);
// getUserService().updateDepartmentPostUsers(departmentId,postId,ud);
}
// /**
// * 验证密码是否正确
// * @param psd 明文密码
// * @param user 根据用户名获取得用户对象
// * @return
// */
public static User getCurrentUser(HttpServletRequest req) throws Exception {
String username = LoginService.getInstance().getCurrentUserNameFromRequestCookie(req);
if(Utils.isNullStr(username)){
return null;
}
return getUserByUserName(username);
}
public static UserBean getCurrentUserBean(HttpServletRequest req) throws Exception {
String username = LoginService.getInstance().getCurrentUserNameFromRequestCookie(req);
if(Utils.isNullStr(username)){
return null;
}
return getUserBeanByUserName(username);
}
/**
* 获取用户部门角色
* @param username
* @return
* @throws Exception
*/
private static UserRolesBean getUserRolesBean(String username) throws Exception {
return FRUserUtils.getUserService().getUserDepAndCustomRoles(username);
}
/**
* 获取部门职务
* @param username
* @return
* @throws Exception
*/
public static List<DepRoleBean> getDepRoleBean(String username) throws Exception{
return getUserRolesBean(username).getDepRoles();
}
/**
* 获取角色
* @param username
* @return
* @throws Exception
*/
public static List<String> getCustomRoles(String username) throws Exception{
return getUserRolesBean(username).getCustomRoles();
}
public static UserBean getAdminUser() throws Exception {
String adminid = getUserService().getAdminUserIdList().get(0);
return getUser(adminid);
}
public static String getUsernameFromToken(String token){
String username = ExtendTokenProcessor.KEY.getUsername(token);
return username;
}
}

323
src/main/java/com/eco/plugin/xx/jbsync/utils/FRUtils.java

@ -0,0 +1,323 @@
package com.eco.plugin.xx.jbsync.utils;
import com.fr.base.ServerConfig;
import com.fr.base.TableData;
import com.fr.base.TemplateUtils;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.base.constant.type.operation.ManualOperationType;
import com.fr.decision.authority.data.User;
import com.fr.decision.base.util.UUIDUtil;
import com.fr.decision.privilege.encrpt.PasswordValidator;
import com.fr.decision.webservice.bean.authentication.OriginUrlResponseBean;
import com.fr.decision.webservice.interceptor.handler.ReportTemplateRequestChecker;
import com.fr.decision.webservice.login.LogInOutResultInfo;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
import com.fr.decision.webservice.utils.DecisionStatusService;
import com.fr.decision.webservice.utils.UserSourceFactory;
import com.fr.decision.webservice.v10.login.LoginService;
import com.fr.decision.webservice.v10.login.event.LogInOutEvent;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.event.EventDispatcher;
import com.fr.file.TableDataConfig;
import com.fr.general.data.DataModel;
import com.fr.log.FineLoggerFactory;
import com.fr.script.Calculator;
import com.fr.stable.StringUtils;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.restriction.RestrictionFactory;
import com.fr.third.springframework.web.method.HandlerMethod;
import com.fr.web.controller.ReportRequestService;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
public class FRUtils {
/**
* 判断用户是否存在
* @param userName
* @return
*/
public static boolean isUserExist(String userName){
if (StringUtils.isEmpty(userName)) {
return false;
} else {
try {
List param1 = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName)));
return param1 != null && !param1.isEmpty();
} catch (Exception param2) {
FineLoggerFactory.getLogger().error(param2.getMessage());
return false;
}
}
}
/**
* 判断是否登录FR
* @param req
* @return
*/
public static boolean isLogin(HttpServletRequest req){
return LoginService.getInstance().isLogged(req);
}
/**
* 帆软登录
* @param httpServletRequest
* @param httpServletResponse
* @param userName
* @param url
*/
public static void login(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String userName,String url){
FineLoggerFactory.getLogger().info("FRLOG:用户名:"+userName);
FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url);
//判断用户名是否为空
if(!Utils.isNullStr(userName)){
if(isUserExist(userName)){
String FRToken = "";
try {
//HttpSession session = httpServletRequest.getSession(true);
FRToken = LoginService.getInstance().login(httpServletRequest, httpServletResponse, userName);
//httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,FRToken);
//session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, FRToken);
EventDispatcher.fire(LogInOutEvent.LOGIN,new LogInOutResultInfo(httpServletRequest,httpServletResponse,userName,true));
FineLoggerFactory.getLogger().info("FRLOG:登陆成功!");
if(!Utils.isNullStr(url)){
httpServletResponse.sendRedirect(url);
}
} catch (Exception e) {
ResponseUtils.failedResponse(httpServletResponse,"登录异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOG:登录异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage());
}
}else{
ResponseUtils.failedResponse(httpServletResponse,"用户在报表系统中不存在!");
FineLoggerFactory.getLogger().info("FRLOG:用户在报表系统中不存在!");
}
}else{
ResponseUtils.failedResponse(httpServletResponse,"用户名不能为空!");
FineLoggerFactory.getLogger().info("FRLOG:用户名不能为空!");
}
}
/**
* 帆软登录
* @param httpServletRequest
* @param httpServletResponse
* @param token
* @param url
*/
public static void loginByToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String token,String url){
FineLoggerFactory.getLogger().info("FRLOG:token:"+token);
FineLoggerFactory.getLogger().info("FRLOG:跳转链接:"+url);
//判断用户名是否为空
if(!Utils.isNullStr(token)){
writeToken2Cookie(httpServletResponse,token,-1);
HttpSession session = httpServletRequest.getSession(true);
httpServletRequest.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME,token);
session.setAttribute(DecisionServiceConstants.FINE_AUTH_TOKEN_NAME, token);
if(!Utils.isNullStr(url)){
try {
httpServletResponse.sendRedirect(url);
} catch (IOException e) {
ResponseUtils.failedResponse(httpServletResponse,"跳转异常!");
FineLoggerFactory.getLogger().info("FRLOG:跳转异常!");
}
}
}else{
ResponseUtils.failedResponse(httpServletResponse,"token不能为空!");
FineLoggerFactory.getLogger().info("FRLOG:token不能为空!");
}
}
/**
* 获取token
* @param httpServletRequest
* @param httpServletResponse
* @param username
* @return
*/
public static String getToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String username){
String token = "";
try {
token = LoginService.getInstance().login(httpServletRequest, httpServletResponse, username);
} catch (Exception e) {
FineLoggerFactory.getLogger().info("FRLOG:获取token失败"+e.getMessage());
}
return token;
}
private static void writeToken2Cookie(HttpServletResponse param1, String param2, int param3) {
try {
if (StringUtils.isNotEmpty(param2)) {
Cookie param4 = new Cookie("fine_auth_token", param2);
long param5 = param3 == -2 ? 1209600000L : (long)param3;
param4.setMaxAge((int)param5);
param4.setPath(ServerConfig.getInstance().getCookiePath());
param1.addCookie(param4);
Cookie param7 = new Cookie("fine_remember_login", String.valueOf(param3 == -2 ? -2 : -1));
param7.setMaxAge((int)param5);
param7.setPath(ServerConfig.getInstance().getCookiePath());
param1.addCookie(param7);
} else {
FineLoggerFactory.getLogger().error("empty token cannot save.");
}
} catch (Exception param8) {
FineLoggerFactory.getLogger().error(param8.getMessage(), param8);
}
}
/**
* 后台登出
* @param httpServletRequest
* @param httpServletResponse
*/
public static void logoutByToken(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,String token)
{
httpServletRequest.setAttribute("fine_auth_token",token);
logout(httpServletRequest,httpServletResponse);
}
/**
*
* @param httpServletRequest
* @param httpServletResponse
*/
public static void logout(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse)
{
if(!isLogin(httpServletRequest)){
return ;
}
try {
LoginService.getInstance().logout(httpServletRequest,httpServletResponse);
} catch (Exception e) {
ResponseUtils.failedResponse(httpServletResponse,"登出异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOG:登出异常,请联系管理员!");
FineLoggerFactory.getLogger().info("FRLOGException:"+e.getMessage());
}
}
/**
* 打印FR日志
* @param message
*/
public static void FRLogInfo(String message){
FineLoggerFactory.getLogger().info("FRLOG:"+message);
}
/**
* 打印FR日志-error
* @param message
*/
public static void FRLogError(String message){
FineLoggerFactory.getLogger().error("FRLOG:"+message);
}
/**
* 根据用户名获取用户信息
* @param userName
* @return
*/
public static User getFRUserByUserName(String userName){
try {
return UserService.getInstance().getUserByUserName(userName);
} catch (Exception e) {
FRLogInfo("获取用户信息异常:"+e.getMessage());
}
return null;
}
/**
* 根据明文密码生成数据库中的密码用户密码校验用
* @return
*/
public static String getDBPsd(String username,String password){
PasswordValidator pv = UserSourceFactory.getInstance().getUserSource(ManualOperationType.KEY).getPasswordValidator();
String uuid = UUIDUtil.generate();
return pv.encode(username, password, uuid);
}
/**
* 获取带参数的访问链接
* @return
*/
public static String getAllUrl(HttpServletRequest httpServletRequest){
return WebUtils.getOriginalURL(httpServletRequest);
}
/**
* 根据originKey获取源链接
* @param originKey
* @return
* @throws Exception
*/
public static String getOriginUrl(String originKey) throws Exception {
if (StringUtils.isNotEmpty(originKey)) {
OriginUrlResponseBean originUrlResponseBean = (OriginUrlResponseBean) DecisionStatusService.originUrlStatusService().get(originKey);
DecisionStatusService.originUrlStatusService().delete(originKey);
if (originUrlResponseBean != null) {
return originUrlResponseBean.getOriginUrl();
}
}
return new OriginUrlResponseBean(TemplateUtils.render("${fineServletURL}")).getOriginUrl();
}
/**
* 判断是否开启模板认证
* @param
* @return
* @throws Exception
*/
public static boolean isTempAuth(HttpServletRequest req,HttpServletResponse res) throws Exception {
ReportTemplateRequestChecker checker = new ReportTemplateRequestChecker();
HandlerMethod hm = new HandlerMethod(new ReportRequestService(),ReportRequestService.class.getMethod("preview", HttpServletRequest.class, HttpServletResponse.class, String.class));
return checker.checkRequest(req,res,hm);
}
/**
* 获取数据集数据
* @param serverDataSetName
* @return
*/
public static DataModel getTableData(String serverDataSetName){
TableData userInfo = TableDataConfig.getInstance().getTableData(serverDataSetName);
DataModel userInfoDM = userInfo.createDataModel(Calculator.createCalculator());
// userInfoDM.getRowCount();
// userInfoDM.getColumnIndex();
// userInfoDM.getValueAt()
return userInfoDM;
}
public static String getIndex(HttpServletRequest req){
String url = req.getScheme()+"://"+req.getServerName()+":"+String.valueOf(req.getServerPort())+req.getRequestURI();
return url;
}
}

35
src/main/java/com/eco/plugin/xx/jbsync/utils/JWTUtils.java

@ -0,0 +1,35 @@
package com.eco.plugin.xx.jbsync.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
public class JWTUtils {
/**
* 校验token是否有效
* @param token
* @param secret
* @return
*/
public static boolean verify(String token,String secret){
boolean result = true;
token = token.replace("Bearer ","");
DecodedJWT decode = JWT.decode(token);
int jwtTimeout = 60000;
try {
Date date = decode.getIssuedAt();
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).acceptIssuedAt((long)(jwtTimeout / 1000)).build();
jwtVerifier.verify(token);
} catch (JWTVerificationException e) {
FRUtils.FRLogInfo("verifyToken exception :"+e.getMessage());
result = false;
}
return result;
}
}

117
src/main/java/com/eco/plugin/xx/jbsync/utils/LogUtils.java

@ -0,0 +1,117 @@
package com.eco.plugin.xx.jbsync.utils;
import com.eco.plugin.xx.jbsync.config.PluginSimpleConfig;
import com.fr.log.FineLoggerFactory;
import com.fr.log.FineLoggerProvider;
import com.fr.plugin.context.PluginContexts;
import com.fr.stable.StringUtils;
public final class LogUtils {
private static final String DEBUG_PREFIX = "[插件调试] ";
private static String LOG_PREFIX = "[数据同步] ";
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 (PluginSimpleConfig.getInstance().getDebugSwitch()) {
LOGGER.error(DEBUG_PREFIX + LOG_PREFIX + s);
} else {
LOGGER.debug(LOG_PREFIX + s);
}
}
public static void debug4plugin(String s, Object... objects) {
if (PluginSimpleConfig.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 (PluginSimpleConfig.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);
}
}

87
src/main/java/com/eco/plugin/xx/jbsync/utils/OrgUtils.java

@ -0,0 +1,87 @@
package com.eco.plugin.xx.jbsync.utils;
import com.eco.plugin.xx.jbsync.kit.DepartmentServiceKit;
import com.fr.decision.authority.data.Department;
import com.fr.json.JSONObject;
/**
* 机构操作类
*/
public class OrgUtils {
/**
* 操作机构
* @param param
* @return
*/
public static JSONObject operOrg(JSONObject param) {
JSONObject result = new JSONObject();
result.put("code","-1");
//获取参数
String orgCode = param.getString("orgCode");
String orgName = param.getString("orgName");
String status = param.getString("status");
String parentCode = param.getString("parentCode");
DepartmentServiceKit departmentService = DepartmentServiceKit.getInstance();
Department dept = null;
try {
dept = departmentService.getByid(orgCode);
} catch (Exception e) {
result.put("msg","获取机构失败!");
return result;
}
//判断操作类型做不同的操作 status 1正常 0停用
//org已经存在
if(dept != null && Utils.isNotNullStr(dept.getId())){
//删除机构
if("0".equals(status)){
try {
FRDepartmentUtils.deleteDepartment(orgCode);
} catch (Exception e) {
result.put("msg","删除机构失败!");
return result;
}
}
else{
try {
updateOrg(orgCode,orgName);
} catch (Exception e) {
result.put("msg","修改机构失败!");
return result;
}
}
}else{
//删除机构
if("0".equals(status)){
result.put("code","0");
result.put("msg","删除成功");
}
else{
try {
departmentService.addDepartment(orgCode,parentCode,orgName);
} catch (Exception e) {
result.put("msg","添加机构失败!");
return result;
}
}
}
result.put("code","0");
result.put("msg","成功");
return result;
}
/**
* 修改机构
* @param orgName
* @param orgid
* @throws Exception
*/
private static void updateOrg(String orgid,String orgName) throws Exception {
FRDepartmentUtils.updateDP(orgid,orgName);
}
}

145
src/main/java/com/eco/plugin/xx/jbsync/utils/PostUtils.java

@ -0,0 +1,145 @@
package com.eco.plugin.xx.jbsync.utils;
import com.eco.plugin.xx.jbsync.kit.PostServiceKit;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.controller.DepartmentController;
import com.fr.decision.authority.controller.PostController;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.Post;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.stable.query.QueryFactory;
import java.util.List;
/**
* 职务操作类
*/
public class PostUtils {
public static JSONObject operPost(JSONObject param) {
JSONObject result = new JSONObject();
result.put("code","-1");
String status = param.getString("status");
String code = param.getString("code");
if("0".equals(status)){
try {
deletePost(param);
result.put("code",0);
result.put("msd","成功");
return result;
} catch (Exception e) {
FRUtils.FRLogInfo("deletepost:"+e.getMessage());
result.put("msg","删除职务失败");
return result;
}
}
Post post = null;
try {
post = PostServiceKit.getInstance().getByid(code);
} catch (Exception e) {
result.put("msg","获取职务失败");
return result;
}
if(post == null || Utils.isNullStr(post.getId())){
try {
addPost(param);
} catch (Exception e) {
FRUtils.FRLogInfo("addPost:"+e.getMessage());
result.put("msg","添加职务失败");
return result;
}
}else{
try {
updatePost(param);
} catch (Exception e) {
FRUtils.FRLogInfo("updatePost:"+e.getMessage());
result.put("msg","修改职务失败");
return result;
}
}
result.put("code",0);
result.put("msd","成功");
return result;
}
/**
* 修改职务
* @param param
* @throws Exception
*/
private static void updatePost(JSONObject param) throws Exception {
JSONArray orgs = param.getJSONArray("orgs");
String code = param.getString("code");
String name = param.getString("name");
String status = param.getString("status");
FRPostUtils.updatePost(code,name,"");
String[] addPost = new String[]{code};
clearPostDeparent(code);
for(int i=0;i<orgs.size();i++){
String orgCode = orgs.getJSONObject(i).getString("orgCode");
FRPostUtils.updateDepPost(orgCode,addPost,null);
}
}
/**
* 清除职务的部门
* @param code
*/
private static void clearPostDeparent(String code) throws Exception {
DepartmentController departmentController = AuthorityContext.getInstance().getDepartmentController();
PostController postController = AuthorityContext.getInstance().getPostController();
List<Department> departments = departmentController.findByPost(code,QueryFactory.create());
for(Department department : departments){
postController.removePostFromDepartment(code,department.getId());
}
}
/**
* 删除职务
* @param param
* @throws Exception
*/
private static void deletePost(JSONObject param) throws Exception {
String code = param.getString("code");
Post post = PostServiceKit.getInstance().getByid(code);
//职务不存在,直接返回
if(post == null || Utils.isNullStr(post.getId())){
return ;
}
FRPostUtils.deletePost(code);
}
/**
* 添加职务
* @param param
* @throws Exception
*/
private static void addPost(JSONObject param) throws Exception {
JSONArray orgs = param.getJSONArray("orgs");
String code = param.getString("code");
String name = param.getString("name");
Post post = PostServiceKit.getInstance().addPost(name,code);
//将职务添加到部门下
String[] addPost = new String[]{code};
for(int i=0;i<orgs.size();i++){
String orgCode = orgs.getJSONObject(i).getString("orgCode");
FRPostUtils.updateDepPost(orgCode,addPost,null);
}
}
}

108
src/main/java/com/eco/plugin/xx/jbsync/utils/ResponseUtils.java

@ -0,0 +1,108 @@
package com.eco.plugin.xx.jbsync.utils;
import com.fr.json.JSONObject;
import com.fr.log.FineLoggerFactory;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class ResponseUtils {
private static final int SUCCESS = 200;
private static final int FAILED = -1;
public static void successResponse(HttpServletResponse res, String body) {
response(res, body, SUCCESS);
}
public static void failedResponse(HttpServletResponse res, String body) {
response(res, body, FAILED);
}
private static void response(HttpServletResponse res, String body, int code) {
JSONObject object = new JSONObject();
PrintWriter pw;
try {
object.put("code", code);
object.put("data", body);
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("application/json;charset=utf-8");
String result = object.toString();
pw.println(result);
pw.flush();
pw.close();
}
public static void response(HttpServletResponse res,JSONObject json){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("application/json;charset=utf-8");
String result = json.toString();
pw.println(result);
pw.flush();
pw.close();
}
public static void responseText(HttpServletResponse res,String text){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("text/html;charset=utf-8");
pw.println(text);
pw.flush();
pw.close();
}
public static void responseXml(HttpServletResponse res,String xml){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("text/xml;charset=utf-8");
pw.println(xml);
pw.flush();
pw.close();
}
public static void setCSRFHeader(HttpServletResponse httpServletResponse){
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
httpServletResponse.setHeader("Access-Control-Max-Age", "36000");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization");
}
public static void responseJsonp(HttpServletRequest req, HttpServletResponse res, JSONObject json){
PrintWriter pw;
try {
pw = WebUtils.createPrintWriter(res);
} catch (Exception e) {
FineLoggerFactory.getLogger().info(e.getMessage());
return;
}
res.setContentType("text/javascript;charset=utf-8;charset=utf-8");
String result = json.toString();
String jsonp=req.getParameter("callback");
pw.println(jsonp+"("+result+")");
pw.flush();
pw.close();
}
}

142
src/main/java/com/eco/plugin/xx/jbsync/utils/UserUtils.java

@ -0,0 +1,142 @@
package com.eco.plugin.xx.jbsync.utils;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.controller.DepartmentController;
import com.fr.decision.authority.controller.PostController;
import com.fr.decision.authority.controller.UserController;
import com.fr.decision.authority.data.Department;
import com.fr.decision.authority.data.Post;
import com.fr.decision.authority.data.User;
import com.fr.decision.webservice.bean.user.UserBean;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import com.fr.stable.query.QueryFactory;
import java.util.List;
/**
* 用户操作类
*/
public class UserUtils {
public static JSONObject operUser(JSONObject param){
JSONObject result = new JSONObject();
result.put("code","-1");
String username = param.getString("accountNo");
boolean hasUser = FRUtils.isUserExist(username);
if(hasUser){
try {
updateUser(param);
} catch (Exception e) {
FRUtils.FRLogInfo("updateUser exception:"+e.getMessage());
result.put("msg","修改用户失败");
return result;
}
}else{
try {
addUser(param);
} catch (Exception e) {
FRUtils.FRLogInfo("addUser exception:"+e.getMessage());
result.put("msg","添加用户失败");
return result;
}
}
result.put("code","0");
result.put("msg","成功");
return result;
}
/**
* 修改用户
* @param param
* @throws Exception
*/
private static void updateUser(JSONObject param) throws Exception {
String username = param.getString("accountNo");
User user = FRUserUtils.getUserByUserName(username);
UserBean userBean = FRUserUtils.getUserBeanByUserName(username);
String realname = param.getString("userName");
String mobile = param.getString("mobile");
String email = param.getString("email");
String status = param.getString("status");
user.setRealName(realname);
user.setMobile(mobile);
user.setEmail(email);
FRUserUtils.updateUser(user);
//更新用户状态
FRUserUtils.forbidUser(userBean.getId(),!"0".equals(status));
clearUserDepAndPost(userBean.getId());
JSONArray codes = param.getJSONArray("jobs");
for(int i=0;i<codes.length();i++){
String orgCode = codes.getJSONObject(i).getString("orgCode");
String postid = codes.getJSONObject(i).getString("code");
FRUserUtils.updateDepartmentPostUsers(orgCode,postid,userBean.getId());
}
}
/**
* 清楚用户的机构和职务
* @param userid
* @throws Exception
*/
private static void clearUserDepAndPost(String userid) throws Exception {
DepartmentController departmentController = AuthorityContext.getInstance().getDepartmentController();
PostController postController = AuthorityContext.getInstance().getPostController();
// List<Department> departmentList = departmentController.findByUser(userid, QueryFactory.create());
List<Post> postBeanList = postController.findByUser(userid, QueryFactory.create());
UserController userController = AuthorityContext.getInstance().getUserController();
for(Post post : postBeanList){
List<Department> departments = departmentController.findByPost(post.getId(),QueryFactory.create());
for(Department department:departments){
userController.removeUserFromDepartmentAndPost(userid, department.getId(), post.getId());
}
}
}
/**
* 添加用户
* @param param
* @throws Exception
*/
private static void addUser(JSONObject param) throws Exception {
String username = param.getString("accountNo");
String realname = param.getString("userName");
String mobile = param.getString("mobile");
String email = param.getString("email");
// JSONArray orgs = param.getJSONArray("orgs");
String status = param.getString("status");
JSONArray codes = param.getJSONArray("jobs");
UserBean userBean = new UserBean();
userBean.setUsername(username);
userBean.setRealName(realname);
userBean.setMobile(mobile);
userBean.setEmail(email);
userBean.setPassword("123");
FRUserUtils.addUser(userBean);
User user = FRUtils.getFRUserByUserName(username);
//更新用户状态
FRUserUtils.forbidUser(user.getId(),!"0".equals(status));
String userid =user.getId();
// for(int i=0;i<orgs.length();i++){
// String orgCode = orgs.getJSONObject(i).getString("orgCode");
// FRUserUtils.updateDepartmentPostUsers(orgCode,"",userid);
// }
for(int i=0;i<codes.length();i++){
String orgCode = codes.getJSONObject(i).getString("orgCode");
String postid = codes.getJSONObject(i).getString("code");
FRUserUtils.updateDepartmentPostUsers(orgCode,postid,userid);
}
}
}

329
src/main/java/com/eco/plugin/xx/jbsync/utils/Utils.java

@ -0,0 +1,329 @@
package com.eco.plugin.xx.jbsync.utils;
import com.fr.base.TemplateUtils;
import com.fr.data.NetworkHelper;
import com.fr.decision.webservice.v10.user.UserService;
import com.fr.io.utils.ResourceIOUtils;
import com.fr.json.JSONObject;
import com.fr.stable.CodeUtils;
import com.fr.stable.StringUtils;
import com.fr.third.org.apache.commons.codec.digest.DigestUtils;
import com.fr.web.utils.WebUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils {
/**
* 判断字符串是否为空
* @param str
* @return true 空字符串 false 非空字符串
*/
public static boolean isNullStr(String str){
return !(str != null && !str.isEmpty() && !"null".equals(str));
}
/**
* 判断字符串是否非空
* @param str
* @return
*/
public static boolean isNotNullStr(String str){
return !isNullStr(str);
}
/**
* MD5加密
* @param str
* @return
*/
public static String getMd5Str(String str)
{
return DigestUtils.md5Hex(str);
}
/**
* 帆软shaEncode加密
*/
public static String shaEncode(String str){
return CodeUtils.sha256Encode(str);
}
/**
* 获取uuid
*/
public static String uuid(){
return UUID.randomUUID().toString();
}
/**
* 替换空字符串
* @param str
* @param replace
* @return
*/
public static String replaceNullStr(String str,String replace){
if(isNullStr(str)){
return replace;
}
return str;
}
/**
* 获取请求体
* @param req
* @return
*/
public static JSONObject getRequestBody(HttpServletRequest req){
StringBuffer sb = new StringBuffer();
String line = null;
try {
BufferedReader reader = req.getReader();
while ((line = reader.readLine()) != null)
sb.append(line);
} catch (Exception e) {
FRUtils.FRLogInfo("getRequestBody:exception:"+e.getMessage());
}
//将空格和换行符替换掉避免使用反序列化工具解析对象时失败
String jsonString = sb.toString().replaceAll("\\s","").replaceAll("\n","");
JSONObject json = new JSONObject(jsonString);
return json;
}
/**
* 获取ip
* @return
*/
public static String getIp(HttpServletRequest req){
String realIp = req.getHeader("X-Real-IP");
String fw = req.getHeader("X-Forwarded-For");
if (StringUtils.isNotEmpty(fw) && !"unKnown".equalsIgnoreCase(fw)) {
int para3 = fw.indexOf(",");
return para3 != -1 ? fw.substring(0, para3) : fw;
} else {
fw = realIp;
if (StringUtils.isNotEmpty(realIp) && !"unKnown".equalsIgnoreCase(realIp)) {
return realIp;
} else {
if (StringUtils.isBlank(realIp) || "unknown".equalsIgnoreCase(realIp)) {
fw = req.getHeader("Proxy-Client-IP");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isBlank(fw) || "unknown".equalsIgnoreCase(fw)) {
fw = req.getRemoteAddr();
}
return fw;
}
}
}
/**
* 根据key获取cookie
* @param req
* @return
*/
public static String getCookieByKey(HttpServletRequest req,String key){
Cookie[] cookies = req.getCookies();
String cookie = "";
if(cookies == null || cookies.length <=0){
return "";
}
for(int i = 0; i < cookies.length; i++) {
Cookie item = cookies[i];
if (item.getName().equalsIgnoreCase(key)) {
cookie = item.getValue();
}
}
FRUtils.FRLogInfo("cookie:"+cookie);
return cookie;
}
/**
* 判断是否是手机端的链接
* @param req
* @return
*/
public static boolean isMobile(HttpServletRequest req) {
String[] mobileArray = {"iPhone", "iPad", "android", "windows phone", "xiaomi"};
String userAgent = req.getHeader("user-agent");
if (userAgent != null && userAgent.toUpperCase().contains("MOBILE")) {
for(String mobile : mobileArray) {
if(userAgent.toUpperCase().contains(mobile.toUpperCase())) {
return true;
}
}
}
return NetworkHelper.getDevice(req).isMobile();
}
/**
* 只编码中文
* @param url
* @return
*/
public static String encodeCH(String url ){
Matcher matcher = Pattern.compile("[\\u4e00-\\u9fa5]").matcher(url);
while(matcher.find()){
String chn = matcher.group();
url = url.replaceAll(chn, URLEncoder.encode(chn));
}
return url;
}
/**
* 获取web-inf文件夹下的文件
* filename /resources/ip4enc.properties
*/
public static InputStream getResourcesFile(String filename){
return ResourceIOUtils.read(filename);
}
/**
*
* @param res
* @param path /com/fr/plugin/loginAuth/html/getMac.html
* @param parameterMap
*/
public static void toErrorPage(HttpServletResponse res,String path,Map<String, String> parameterMap){
if(parameterMap == null){
parameterMap = new HashMap<String, String>();
}
try {
String macPage = TemplateUtils.renderTemplate(path, parameterMap);
WebUtils.printAsString(res, macPage);
}catch (Exception e){
FRUtils.FRLogError("跳转页面异常");
}
}
/**
* 判断是否是管理员
* @param username
* @return
*/
public static boolean isAdmin(String username) throws Exception{
return UserService.getInstance().isAdmin(UserService.getInstance().getUserByUserName(username).getId());
}
/**
* 去掉浏览器中的参数
* @param url
* @param param
* @return
*/
public static String removeParam(String url,String param){
if(!url.contains("?"+param) && !url.contains("&"+param)){
return url;
}
return url.substring(0,url.indexOf(url.contains("?"+param) ? "?"+param : "&"+param));
}
/**
* 获取跳转链接
* @param req
* @param param
* @return
*/
public static String getRedirectUrl(HttpServletRequest req,String param){
String url = FRUtils.getAllUrl(req);
if(isNotNullStr(param)){
url = removeParam(url,param);
}
url = encodeCH(url);
return url;
}
/**
* 去除空格换行
* @param str
* @return
*/
public static String trim(String str){
return str.trim().replaceAll("\n","").replaceAll("\r","");
}
/**
* list 转化为指定字符分割的字符串
* @param list
* @param list
* @return
*/
public static String listToStr(List<String> list, String split){
String result = "";
if(list == null || list.size() <= 0){
return result;
}
for(String str : list){
result+=","+str;
}
result = result.substring(1);
return result;
}
/**
* array 转化为指定字符分割的字符串
* @param list
* @param list
* @return
*/
public static String arrayToStr(String[] list, String split){
String result = "";
if(list == null ||list.length <= 0){
return result;
}
for(int i=0;i<list.length;i++){
String str = list[i];
result+=","+str;
}
result = result.substring(1);
return result;
}
}
Loading…
Cancel
Save