Browse Source

open

master
pioneer 2 years ago
commit
4d64dd43d5
  1. 7
      README.md
  2. 23
      plugin.xml
  3. 21
      src/main/java/com/eco/plugin/xxx/bjgjdata/config/InitializeMonitor.java
  4. 90
      src/main/java/com/eco/plugin/xxx/bjgjdata/config/PluginSimpleConfig.java
  5. 14
      src/main/java/com/eco/plugin/xxx/bjgjdata/controller/ControllerRegisterProvider.java
  6. 160
      src/main/java/com/eco/plugin/xxx/bjgjdata/controller/ControllerSelf.java
  7. 167
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/bean/DBEntity.java
  8. 133
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/bean/OrgEntity.java
  9. 68
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/bean/RecordEntity.java
  10. 262
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/controller/DBController.java
  11. 75
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/dao/DBDao.java
  12. 75
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/dao/OrgDao.java
  13. 70
      src/main/java/com/eco/plugin/xxx/bjgjdata/db/dao/RecordDao.java
  14. 241
      src/main/java/com/eco/plugin/xxx/bjgjdata/utils/DataUtils.java
  15. 227
      src/main/java/com/eco/plugin/xxx/bjgjdata/utils/DateUtilSelf.java
  16. 257
      src/main/java/com/eco/plugin/xxx/bjgjdata/utils/FRUtils.java
  17. 265
      src/main/java/com/eco/plugin/xxx/bjgjdata/utils/HttpUtils.java
  18. 108
      src/main/java/com/eco/plugin/xxx/bjgjdata/utils/ResponseUtils.java
  19. 244
      src/main/java/com/eco/plugin/xxx/bjgjdata/utils/Utils.java

7
README.md

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

23
plugin.xml

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?><plugin>
<id>com.eco.plugin.xxx.bjgjdata</id>
<name><![CDATA[数据同步]]></name>
<active>yes</active>
<version>1.0.9</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.xxx.bjgjdata</main-package>
<lifecycle-monitor class="com.eco.plugin.xxx.bjgjdata.config.InitializeMonitor"/>
<extra-decision>
<ControllerRegisterProvider class="com.eco.plugin.xxx.bjgjdata.controller.ControllerRegisterProvider"/>
</extra-decision>
<extra-core>
<DBAccessProvider class="com.eco.plugin.xxx.bjgjdata.db.controller.DBController"/>
</extra-core>
<function-recorder class="com.eco.plugin.xxx.bjgjdata.config.PluginSimpleConfig"/>
</plugin>

21
src/main/java/com/eco/plugin/xxx/bjgjdata/config/InitializeMonitor.java

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

90
src/main/java/com/eco/plugin/xxx/bjgjdata/config/PluginSimpleConfig.java

@ -0,0 +1,90 @@
package com.eco.plugin.xxx.bjgjdata.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.xxx.bjgjdata.config", text = "单点登录配置", source = Original.PLUGIN)
public static PluginSimpleConfig getInstance() {
if (config == null) {
config = ConfigContext.getConfigInstance(PluginSimpleConfig.class);
}
return config;
}
@Identifier(value = "apikey", name = "apikey", description = "apikey", status = Status.SHOW)
private Conf<String> apikey = Holders.simple("");
@Identifier(value = "clientId", name = "clientId", description = "clientId", status = Status.SHOW)
private Conf<String> clientId = Holders.simple("");
@Identifier(value = "secret", name = "clientSecret", description = "clientSecret", status = Status.SHOW)
private Conf<String> secret = Holders.simple("");
@Identifier(value = "tokenurl", name = "获取token接口", description = "获取token接口", status = Status.SHOW)
private Conf<String> tokenurl = Holders.simple("http://localhost:8075/webroot/decision");
@Identifier(value = "dataurl", name = "获取数据接口", description = "获取数据接口", status = Status.SHOW)
private Conf<String> dataurl = Holders.simple("");
public String getApikey() {
return apikey.get();
}
public void setapikey(String url) {
this.apikey.set(url);
}
public String getClientId() {
return clientId.get();
}
public void setClientId(String url) {
this.clientId.set(url);
}
public String getSecret() {
return secret.get();
}
public void setSecret(String url) {
this.secret.set(url);
}
public String getTokenurl() {
return tokenurl.get();
}
public void setTokenurl(String url) {
this.tokenurl.set(url);
}
public String getDataurl() {
return dataurl.get();
}
public void setDataurl(String url) {
this.dataurl.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/xxx/bjgjdata/controller/ControllerRegisterProvider.java

@ -0,0 +1,14 @@
package com.eco.plugin.xxx.bjgjdata.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
};
}
}

160
src/main/java/com/eco/plugin/xxx/bjgjdata/controller/ControllerSelf.java

@ -0,0 +1,160 @@
package com.eco.plugin.xxx.bjgjdata.controller;
import com.eco.plugin.xxx.bjgjdata.config.PluginSimpleConfig;
import com.eco.plugin.xxx.bjgjdata.db.bean.DBEntity;
import com.eco.plugin.xxx.bjgjdata.db.bean.OrgEntity;
import com.eco.plugin.xxx.bjgjdata.db.bean.RecordEntity;
import com.eco.plugin.xxx.bjgjdata.db.controller.DBController;
import com.eco.plugin.xxx.bjgjdata.utils.DataUtils;
import com.eco.plugin.xxx.bjgjdata.utils.DateUtilSelf;
import com.eco.plugin.xxx.bjgjdata.utils.ResponseUtils;
import com.eco.plugin.xxx.bjgjdata.utils.Utils;
import com.fr.decision.webservice.annotation.LoginStatusChecker;
import com.fr.json.JSONObject;
import com.fr.plugin.context.PluginContexts;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.stable.fun.Authorize;
import com.fr.third.springframework.stereotype.Controller;
import com.fr.third.springframework.web.bind.annotation.GetMapping;
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;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@Controller
@LoginStatusChecker(required = false)
@FunctionRecorder
@Authorize(callSignKey = "com.eco.plugin.xxx.bjgjdata")
public class ControllerSelf {
@GetMapping(value = "/getAllData")
@ResponseBody
public void getAllData(HttpServletRequest request,HttpServletResponse response){
if(!PluginContexts.currentContext().isAvailable()){
ResponseUtils.failedResponse(response,"插件授权过期,请联系管理员!");
return ;
}
List<DBEntity> list = new ArrayList<DBEntity>();
try {
DataUtils.getData("RY","",1,"", PluginSimpleConfig.getInstance(),list);
} catch (Exception e) {
ResponseUtils.failedResponse(response,"同步人员数据异常"+e.getMessage());
return ;
}
DBController.batch(list,null);
}
@GetMapping(value = "/getWBRYData")
@ResponseBody
public void getWBRYData(HttpServletRequest request,HttpServletResponse response){
if(!PluginContexts.currentContext().isAvailable()){
ResponseUtils.failedResponse(response,"插件授权过期,请联系管理员!");
return ;
}
List<DBEntity> list = new ArrayList<DBEntity>();
try {
DataUtils.getData("WBRY","",1,"", PluginSimpleConfig.getInstance(),list);
} catch (Exception e) {
ResponseUtils.failedResponse(response,"同步人员数据异常"+e.getMessage());
return ;
}
DBController.batch(list,null);
}
@GetMapping(value = "/getAllOrgData")
@ResponseBody
public void getAllOrgData(HttpServletRequest request,HttpServletResponse response){
if(!PluginContexts.currentContext().isAvailable()){
ResponseUtils.failedResponse(response,"插件授权过期,请联系管理员!");
return ;
}
List<OrgEntity> orgList = new ArrayList<OrgEntity>();
try {
DataUtils.getOrgData("JG","",1,"", PluginSimpleConfig.getInstance(),orgList);
} catch (Exception e) {
ResponseUtils.failedResponse(response,"同步机构数据异常"+e.getMessage());
return ;
}
DBController.batchOrg(orgList,null);
}
@GetMapping(value = "/getWBJGData")
@ResponseBody
public void getWBJGData(HttpServletRequest request,HttpServletResponse response){
if(!PluginContexts.currentContext().isAvailable()){
ResponseUtils.failedResponse(response,"插件授权过期,请联系管理员!");
return ;
}
List<OrgEntity> orgList = new ArrayList<OrgEntity>();
try {
DataUtils.getOrgData("WBJG","",1,"", PluginSimpleConfig.getInstance(),orgList);
} catch (Exception e) {
ResponseUtils.failedResponse(response,"同步机构数据异常"+e.getMessage());
return ;
}
DBController.batchOrg(orgList,null);
}
@PostMapping(value = "/incrementData")
@ResponseBody
public StringBuilder incrementData(HttpServletRequest request,HttpServletResponse response){
if(!PluginContexts.currentContext().isAvailable()){
return new StringBuilder("插件授权过期,请联系管理员!");
}
JSONObject param = Utils.getRequestBody(request);
String tableAlias = param.getString("tableAlias");
String updateTime = param.getString("updateTime");
Long notifyId = param.getLong("notifyId");
String createTime = DateUtilSelf.DateToString(new Date(),"yyyy-MM-dd HH:mm:ss");
//添加日志
RecordEntity record = new RecordEntity();
record.setTableAlias(tableAlias);
record.setCreatetime(new Date());
record.setUpdateTime(updateTime);
record.setNotifyId(notifyId);
record.setId(UUID.randomUUID().toString());
DBController.addRecord(record);
if("RY".equals(tableAlias) || "WBRY".equals(tableAlias)){
//添加人员信息
List<DBEntity> list = new ArrayList<DBEntity>();
try {
DataUtils.getData(tableAlias,updateTime,1,"", PluginSimpleConfig.getInstance(),list);
} catch (Exception e) {
ResponseUtils.failedResponse(response,"同步数据异常"+e.getMessage());
return new StringBuilder("FAIL");
}
DBController.batch(list,null);
}else{
//添加机构信息
List<OrgEntity> list = new ArrayList<OrgEntity>();
try {
DataUtils.getOrgData(tableAlias,updateTime,1,"", PluginSimpleConfig.getInstance(),list);
} catch (Exception e) {
ResponseUtils.failedResponse(response,"同步机构数据异常"+e.getMessage());
return new StringBuilder("FAIL");
}
DBController.batchOrg(list,null);
}
return new StringBuilder("SUCCESS");
}
}

167
src/main/java/com/eco/plugin/xxx/bjgjdata/db/bean/DBEntity.java

@ -0,0 +1,167 @@
package com.eco.plugin.xxx.bjgjdata.db.bean;
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 java.util.Date;
/**
* @author xxx
* @version 10.0
* Created by xxx on 2021-07-29
**/
@Entity
@Table(name = "plugin_xxx_entity_ry")
@TableAssociation(associated = true)
public class DBEntity extends BaseEntity {
//人员编号
@Column(name = "rybh",length=100)
private String rybh = null;
//人员名称
@Column(name = "rymc",length=100)
private String rymc = null;
//物理卡号
@Column(name = "wlkh")
private String wlkh = null;
//分公司名称
@Column(name = "fgsmc",length=100)
private String fgsmc = null;
//机构名称
@Column(name = "jgmc",length=100)
private String jgmc = null;
//机构名称
@Column(name = "jgid",length=100)
private String jgid = null;
//机构名称
@Column(name = "wbgsid",length=100)
private String wbgsid = null;
//外部公司名称
@Column(name = "wbgsmc",length=100)
private String wbgsmc = null;
//外部机构名称
@Column(name = "wbryid",length=100)
private String WBRYID = null;
//创建时间
@Column(name = "createtime")
private Date createtime = null;
//修改时间
@Column(name = "updatetime")
private Date updatetime = null;
/**
* 类型 1内部人员 2.外部人员
*
*/
@Column(name = "type",length = 2)
private String type = null;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getWBRYID() {
return WBRYID;
}
public void setWBRYID(String WBRYID) {
this.WBRYID = WBRYID;
}
public String getWbgsid() {
return wbgsid;
}
public void setWbgsid(String wbgsid) {
this.wbgsid = wbgsid;
}
public String getWbgsmc() {
return wbgsmc;
}
public void setWbgsmc(String wbgsmc) {
this.wbgsmc = wbgsmc;
}
public String getJgid() {
return jgid;
}
public void setJgid(String jgid) {
this.jgid = jgid;
}
public String getRybh() {
return rybh;
}
public void setRybh(String rybh) {
this.rybh = rybh;
}
public String getRymc() {
return rymc;
}
public void setRymc(String rymc) {
this.rymc = rymc;
}
public String getWlkh() {
return wlkh;
}
public void setWlkh(String wlkh) {
this.wlkh = wlkh;
}
public String getFgsmc() {
return fgsmc;
}
public void setFgsmc(String fgsmc) {
this.fgsmc = fgsmc;
}
public String getJgmc() {
return jgmc;
}
public void setJgmc(String jgmc) {
this.jgmc = jgmc;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
}

133
src/main/java/com/eco/plugin/xxx/bjgjdata/db/bean/OrgEntity.java

@ -0,0 +1,133 @@
package com.eco.plugin.xxx.bjgjdata.db.bean;
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 java.util.Date;
@Entity
@Table(name = "plugin_xxx_entity_jg")
@TableAssociation(associated = true)
public class OrgEntity extends BaseEntity {
@Column(name = "jgid",length = 100)
private String jgid = null;
@Column(name = "jgbm",length = 100)
private String jgbm = null;
@Column(name = "jgmc",length = 100)
private String jgmc = null;
@Column(name = "zgjgid",length = 100)
private String zgjgid = null;
@Column(name = "px",length = 25)
private String px = null;
@Column(name = "jgzt",length = 25)
private String jgzt = null;
/**
* 上机机构树
*/
@Column(name = "sjjgs",length = 1000)
private String sjjgs = null;
/**
* 类型 1内部机构 2.外部机构
*
*/
@Column(name = "type",length = 2)
private String type = null;
//创建时间
@Column(name = "createtime")
private Date createtime = null;
//修改时间
@Column(name = "updatetime")
private Date updatetime = null;
public String getSjjgs() {
return sjjgs;
}
public void setSjjgs(String sjjgs) {
this.sjjgs = sjjgs;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getJgid() {
return jgid;
}
public void setJgid(String jgid) {
this.jgid = jgid;
}
public String getJgbm() {
return jgbm;
}
public void setJgbm(String jgbm) {
this.jgbm = jgbm;
}
public String getJgmc() {
return jgmc;
}
public void setJgmc(String jgmc) {
this.jgmc = jgmc;
}
public String getZgjgid() {
return zgjgid;
}
public void setZgjgid(String zgjgid) {
this.zgjgid = zgjgid;
}
public String getPx() {
return px;
}
public void setPx(String px) {
this.px = px;
}
public String getJgzt() {
return jgzt;
}
public void setJgzt(String jgzt) {
this.jgzt = jgzt;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public Date getUpdatetime() {
return updatetime;
}
public void setUpdatetime(Date updatetime) {
this.updatetime = updatetime;
}
}

68
src/main/java/com/eco/plugin/xxx/bjgjdata/db/bean/RecordEntity.java

@ -0,0 +1,68 @@
package com.eco.plugin.xxx.bjgjdata.db.bean;
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 java.util.Date;
/**
* @author xxx
* @version 10.0
* Created by xxx on 2021-07-29
**/
@Entity
@Table(name = "plugin_xxx_entity_record")
@TableAssociation(associated = true)
public class RecordEntity extends BaseEntity {
//数据表名
@Column(name = "tableAlias",length = 5)
private String tableAlias = null;
//更新时间点
@Column(name = "updateTime" ,length = 50)
private String updateTime = null;
//通知唯一主键
@Column(name = "notifyId")
private Long notifyId = null;
//创建时间
@Column(name = "createtime")
private Date createtime = null;
public String getTableAlias() {
return tableAlias;
}
public void setTableAlias(String tableAlias) {
this.tableAlias = tableAlias;
}
public String getUpdateTime() {
return updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public Long getNotifyId() {
return notifyId;
}
public void setNotifyId(Long notifyId) {
this.notifyId = notifyId;
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}

262
src/main/java/com/eco/plugin/xxx/bjgjdata/db/controller/DBController.java

@ -0,0 +1,262 @@
package com.eco.plugin.xxx.bjgjdata.db.controller;
import com.eco.plugin.xxx.bjgjdata.db.bean.DBEntity;
import com.eco.plugin.xxx.bjgjdata.db.bean.OrgEntity;
import com.eco.plugin.xxx.bjgjdata.db.bean.RecordEntity;
import com.eco.plugin.xxx.bjgjdata.db.dao.DBDao;
import com.eco.plugin.xxx.bjgjdata.db.dao.OrgDao;
import com.eco.plugin.xxx.bjgjdata.db.dao.RecordDao;
import com.eco.plugin.xxx.bjgjdata.utils.FRUtils;
import com.fr.db.fun.impl.AbstractDBAccessProvider;
import com.fr.plugin.transform.FunctionRecorder;
import com.fr.record.analyzer.EnableMetrics;
import com.fr.stable.db.accessor.DBAccessor;
import com.fr.stable.db.action.DBAction;
import com.fr.stable.db.dao.DAOContext;
import com.fr.stable.db.dao.DAOProvider;
import java.util.List;
/**
* @author xxx
* @version 10.0
* Created by xxx on 2021-07-29
**/
@EnableMetrics
@FunctionRecorder
public class DBController extends AbstractDBAccessProvider {
private static DBAccessor accessor;
public static DBAccessor getAccessor() {
return accessor;
}
@Override
public DAOProvider[] registerDAO() {
return new DAOProvider[]{
DBDao.DAO, RecordDao.DAO, OrgDao.DAO
};
}
@Override
public void onDBAvailable(DBAccessor accessor) {
DBController.accessor = accessor;
}
/**
* 批量操作
* @param addOrUpdate
* @param delete
* @return
*/
public static boolean batch(List<DBEntity> addOrUpdate, List<DBEntity> delete){
//新增或者删除
if(addOrUpdate != null && addOrUpdate.size() > 0){
for(final DBEntity dbe : addOrUpdate){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
DBEntity ae =context.getDAO(DBDao.class).getByRybh(dbe.getRybh());
if(ae != null ){
ae.setUpdatetime(dbe.getUpdatetime());
ae.setJgmc(dbe.getJgmc());
ae.setFgsmc(dbe.getFgsmc());
ae.setWlkh(dbe.getWlkh());
ae.setRymc(dbe.getRymc());
context.getDAO(DBDao.class).update(ae);
}else{
context.getDAO(DBDao.class).add(dbe);
}
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("batch addOrUpdate exception ->"+e.getMessage() + dbe.toString());
}
}
}
if(delete != null && delete.size() > 0){
for(final DBEntity dbe : delete){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
context.getDAO(DBDao.class).remove(dbe.getId());
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("batch delete exception ->"+e.getMessage() + dbe.toString());
}
}
}
return true;
}
/**
* 批量操作组织
* @param addOrUpdate
* @param delete
* @return
*/
public static boolean batchOrg(List<OrgEntity> addOrUpdate, List<OrgEntity> delete){
//新增或者删除
if(addOrUpdate != null && addOrUpdate.size() > 0){
for(final OrgEntity dbe : addOrUpdate){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
OrgEntity ae =context.getDAO(OrgDao.class).getByRybh(dbe.getJgid());
if(ae != null ){
dbe.setId(ae.getId());
context.getDAO(OrgDao.class).update(ae);
}else{
context.getDAO(OrgDao.class).add(dbe);
}
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("batch addOrUpdateOrg exception ->"+e.getMessage() + dbe.toString());
}
}
}
if(delete != null && delete.size() > 0){
for(final OrgEntity dbe : delete){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
context.getDAO(OrgDao.class).remove(dbe.getId());
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("batch deleteOrg exception ->"+e.getMessage() + dbe.toString());
}
}
}
return true;
}
/**
* 批量操作
* @param addOrUpdate
* @param delete
* @return
*/
public static boolean single(DBEntity addOrUpdate,DBEntity delete){
//新增或者删除
if(addOrUpdate != null ){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
DBEntity ae =context.getDAO(DBDao.class).getById(addOrUpdate.getId());
if(ae != null ){
context.getDAO(DBDao.class).update(addOrUpdate);
}else{
context.getDAO(DBDao.class).add(addOrUpdate);
}
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("single addOrUpdate exception ->"+e.getMessage() + addOrUpdate.toString());
}
}
if(delete != null ){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
context.getDAO(DBDao.class).remove(delete.getId());
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("single delete exception ->"+e.getMessage() + delete.toString());
}
}
return true;
}
/**
* 添加记录
* @param recordEntity
* @return
*/
public static boolean addRecord(RecordEntity recordEntity){
try{
accessor.runDMLAction(new DBAction<Boolean>() {
@Override
public Boolean run(DAOContext context) throws Exception {
context.getDAO(RecordDao.class).add(recordEntity);
return true;
}
});
}catch(Throwable e){
FRUtils.FRLogError("addRecord exception ->"+e.getMessage() );
return false;
}
return true;
}
/**
* 根据username获取信息
* @param username
* @return
*/
public static DBEntity getByUsername(final String username){
try{
return accessor.runQueryAction(new DBAction<DBEntity>() {
@Override
public DBEntity run(DAOContext context) throws Exception {
DBEntity result = context.getDAO(DBDao.class).getByUsername(username);
return result == null ? new DBEntity() : result;
}
});
}catch(Throwable e){
FRUtils.FRLogError("exception getByUsername:"+e.getMessage());
}
return new DBEntity();
}
/**
* 根据id获取信息
* @param id
* @return
*/
public static DBEntity getById(final String id){
try{
return accessor.runQueryAction(new DBAction<DBEntity>() {
@Override
public DBEntity run(DAOContext context) throws Exception {
DBEntity result = context.getDAO(DBDao.class).getById(id);
return result == null ? new DBEntity() : result;
}
});
}catch(Throwable e){
FRUtils.FRLogError("exception getById:"+e.getMessage());
}
return new DBEntity();
}
}

75
src/main/java/com/eco/plugin/xxx/bjgjdata/db/dao/DBDao.java

@ -0,0 +1,75 @@
package com.eco.plugin.xxx.bjgjdata.db.dao;
import com.eco.plugin.xxx.bjgjdata.db.bean.DBEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.stable.db.session.DAOSession;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import java.util.List;
/**
* @author xxx
* @version 10.0
* Created by xxx on 2021-12-03
**/
public class DBDao extends BaseDAO<DBEntity> {
public DBDao(DAOSession session) {
super(session);
}
@Override
protected Class<DBEntity> getEntityClass() {
return DBEntity.class;
}
public final static DAOProvider DAO = new DAOProvider() {
@Override
public Class getEntityClass() {
return DBEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return DBDao.class;
}
};
public void add(DBEntity entity) throws Exception {
getSession().persist(entity);
}
public void remove(String id) throws Exception {
getSession().remove(QueryFactory.create()
.addRestriction(RestrictionFactory.eq("id", id)),
this.getEntityClass());
}
public void update(DBEntity entity) throws Exception {
getSession().merge(entity);
}
public DBEntity getByUsername(String username) throws Exception {
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.eq("username", username));
return findOne(condition);
}
public DBEntity getByRybh(String rybh) throws Exception {
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.eq("rybh", rybh));
return findOne(condition);
}
public List<DBEntity> like(String pid, String type)throws Exception{
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.like("", pid)).addRestriction(RestrictionFactory.like(DBEntity.COLUMN_ID,type));
return find(condition);
}
}

75
src/main/java/com/eco/plugin/xxx/bjgjdata/db/dao/OrgDao.java

@ -0,0 +1,75 @@
package com.eco.plugin.xxx.bjgjdata.db.dao;
import com.eco.plugin.xxx.bjgjdata.db.bean.OrgEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.stable.db.session.DAOSession;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import java.util.List;
/**
* @author xxx
* @version 10.0
* Created by xxx on 2021-12-03
**/
public class OrgDao extends BaseDAO<OrgEntity> {
public OrgDao(DAOSession session) {
super(session);
}
@Override
protected Class<OrgEntity> getEntityClass() {
return OrgEntity.class;
}
public final static DAOProvider DAO = new DAOProvider() {
@Override
public Class getEntityClass() {
return OrgEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return OrgDao.class;
}
};
public void add(OrgEntity entity) throws Exception {
getSession().persist(entity);
}
public void remove(String id) throws Exception {
getSession().remove(QueryFactory.create()
.addRestriction(RestrictionFactory.eq("id", id)),
this.getEntityClass());
}
public void update(OrgEntity entity) throws Exception {
getSession().merge(entity);
}
public OrgEntity getByUsername(String username) throws Exception {
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.eq("username", username));
return findOne(condition);
}
public OrgEntity getByRybh(String rybh) throws Exception {
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.eq("jgid", rybh));
return findOne(condition);
}
public List<OrgEntity> like(String pid, String type)throws Exception{
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.like("", pid)).addRestriction(RestrictionFactory.like(OrgEntity.COLUMN_ID,type));
return find(condition);
}
}

70
src/main/java/com/eco/plugin/xxx/bjgjdata/db/dao/RecordDao.java

@ -0,0 +1,70 @@
package com.eco.plugin.xxx.bjgjdata.db.dao;
import com.eco.plugin.xxx.bjgjdata.db.bean.DBEntity;
import com.eco.plugin.xxx.bjgjdata.db.bean.RecordEntity;
import com.fr.stable.db.dao.BaseDAO;
import com.fr.stable.db.dao.DAOProvider;
import com.fr.stable.db.session.DAOSession;
import com.fr.stable.query.QueryFactory;
import com.fr.stable.query.condition.QueryCondition;
import com.fr.stable.query.restriction.RestrictionFactory;
import java.util.List;
/**
* @author xxx
* @version 10.0
* Created by xxx on 2021-12-03
**/
public class RecordDao extends BaseDAO<RecordEntity> {
public RecordDao(DAOSession session) {
super(session);
}
@Override
protected Class<RecordEntity> getEntityClass() {
return RecordEntity.class;
}
public final static DAOProvider DAO = new DAOProvider() {
@Override
public Class getEntityClass() {
return RecordEntity.class;
}
@Override
public Class<? extends BaseDAO> getDAOClass() {
return RecordDao.class;
}
};
public void add(RecordEntity entity) throws Exception {
getSession().persist(entity);
}
public void remove(String id) throws Exception {
getSession().remove(QueryFactory.create()
.addRestriction(RestrictionFactory.eq("id", id)),
this.getEntityClass());
}
public void update(RecordEntity entity) throws Exception {
getSession().merge(entity);
}
public RecordEntity getByUsername(String username) throws Exception {
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.eq("username", username));
return findOne(condition);
}
public List<RecordEntity> like(String pid, String type)throws Exception{
QueryCondition condition = QueryFactory.create()
.addRestriction(RestrictionFactory.like("", pid)).addRestriction(RestrictionFactory.like(DBEntity.COLUMN_ID,type));
return find(condition);
}
}

241
src/main/java/com/eco/plugin/xxx/bjgjdata/utils/DataUtils.java

@ -0,0 +1,241 @@
package com.eco.plugin.xxx.bjgjdata.utils;
import com.eco.plugin.xxx.bjgjdata.config.PluginSimpleConfig;
import com.eco.plugin.xxx.bjgjdata.db.bean.DBEntity;
import com.eco.plugin.xxx.bjgjdata.db.bean.OrgEntity;
import com.fr.json.JSONArray;
import com.fr.json.JSONObject;
import java.util.*;
public class DataUtils {
private static String getToken() throws Exception {
PluginSimpleConfig psc = PluginSimpleConfig.getInstance();
String apikey = psc.getApikey();
String clientid = psc.getClientId();
String secret = psc.getSecret();
String tokenurl = psc.getTokenurl();
Map<String,String> header = new HashMap<String,String>();
header.put("apikey",apikey);
header.put("Content-Type","application/json");
JSONObject param = new JSONObject();
param.put("clientId",clientid);
param.put("clientSecret",secret);
String result = HttpUtils.HttpPostJson(tokenurl,param.toString(),header);
if(Utils.isNullStr(result)){
throw new Exception("获取token异常!");
}
JSONObject resultJson = new JSONObject(result);
int code = resultJson.getInt("code");
if(code != 0 ){
String msg = resultJson.getString("message");
throw new Exception(msg);
}
String token = resultJson.getJsonObject("data").getString("accessToken");
return token;
}
public static void getData(String tableName, String updateTime, int pageNum, String token, PluginSimpleConfig psc, List<DBEntity> dbentity) throws Exception {
if(Utils.isNullStr(token)){
token = "Bearer "+getToken();
}
JSONObject param = new JSONObject();
param.put("pageNo",pageNum);
param.put("pageSize",1000);
param.put("tableAlias",tableName);
param.put("updateTime",updateTime);
String apikey = psc.getApikey();
Map<String,String> header = new HashMap<String,String>();
header.put("apikey",apikey);
header.put("Content-Type","application/json");
header.put("Authorization",token);
String dataurl = psc.getDataurl();
String result = HttpUtils.HttpPostJson(dataurl,param.toString(),header);
if(Utils.isNullStr(result)){
throw new Exception("获取数据异常");
}
JSONObject resultJson = new JSONObject(result);
int code = resultJson.getInt("code");
if(code != 0 ){
String msg = resultJson.getString("message");
throw new Exception(msg);
}
JSONObject data = resultJson.getJSONObject("data");
int total = data.getInt("pageCount");
if(total == 0){
dbentity = new ArrayList<DBEntity>();
return ;
}
JSONArray dataList = data.getJSONArray("dataList");
arrayToList(dataList,dbentity,tableName);
if(total == pageNum){
return ;
}
getData(tableName,updateTime,pageNum+1,token,psc,dbentity);
}
public static void main(String[] args) {
JSONObject json = new JSONObject();
String a = json.getString("a");
System.out.println();
}
private static void arrayToList(JSONArray dataList, List<DBEntity> dbentity,String tablename) {
for(int i=0;i<dataList.length();i++){
JSONObject json = dataList.getJSONObject(i);
Date now = new Date();
DBEntity dbEntity = new DBEntity();
if("RY".equals(tablename)){
String rybh = json.getString("rybh");
String rymc = json.getString("rymc");
String wlkh = json.getString("wlkh");
String fgsmc = json.getString("fgsmc");
String jgmc = json.getString("jgmc");
String jgid = json.getString("jgid");
dbEntity.setId(UUID.randomUUID().toString());
dbEntity.setRybh(rybh);
dbEntity.setRymc(rymc);
dbEntity.setWlkh(wlkh);
dbEntity.setFgsmc(fgsmc);
dbEntity.setJgmc(jgmc);
dbEntity.setCreatetime(now);
dbEntity.setUpdatetime(now);
dbEntity.setJgid(jgid);
dbEntity.setType("1");
}else{
String WBRYID = json.getString("WBRYID");
String rybh = json.getString("RYBH");
String rymc = json.getString("RYMC");
String WBGSID = json.getString("WBGSID");
String WBGSMC = json.getString("WBGSMC");
String jgmc = json.getString("WBJGMC");
String jgid = json.getString("WBJGID");
dbEntity.setId(UUID.randomUUID().toString());
dbEntity.setRybh(rybh);
dbEntity.setRymc(rymc);
dbEntity.setJgmc(jgmc);
dbEntity.setCreatetime(now);
dbEntity.setUpdatetime(now);
dbEntity.setJgid(jgid);
dbEntity.setWBRYID(WBRYID);
dbEntity.setWbgsid(WBGSID);
dbEntity.setWbgsmc(WBGSMC);
dbEntity.setType("2");
}
dbentity.add(dbEntity);
}
}
private static void arrayToOrgList(JSONArray dataList, List<OrgEntity> dbentity,String tablename) {
for(int i=0;i<dataList.length();i++){
Date now = new Date();
JSONObject json = dataList.getJSONObject(i);
OrgEntity dbEntity = new OrgEntity();
if("JG".equals(tablename)){
String jgid = json.getString("jgid");
String jgbm = json.getString("jgbm");
String jgmc = json.getString("jgmc");
String zgjgid = json.getString("zgjgid");
String px = json.getString("px");
String jgzt = json.getString("jgzt");
dbEntity.setId(UUID.randomUUID().toString());
dbEntity.setJgbm(jgbm);
dbEntity.setZgjgid(zgjgid);
dbEntity.setPx(px);
dbEntity.setJgzt(jgzt);
dbEntity.setJgmc(jgmc);
dbEntity.setCreatetime(now);
dbEntity.setUpdatetime(now);
dbEntity.setJgid(jgid);
dbEntity.setType("1");
}else{
String jgid = json.getString("WBJGID");
String jgbm = json.getString("JGBM");
String jgmc = json.getString("JGMC");
String zgjgid = json.getString("ZGJGID");
String SJJGS = json.getString("SJJGS");
dbEntity.setId(UUID.randomUUID().toString());
dbEntity.setJgbm(jgbm);
dbEntity.setZgjgid(zgjgid);
dbEntity.setSjjgs(SJJGS);
dbEntity.setJgmc(jgmc);
dbEntity.setCreatetime(now);
dbEntity.setUpdatetime(now);
dbEntity.setJgid(jgid);
dbEntity.setType("2");
}
dbentity.add(dbEntity);
}
}
public static void getOrgData(String tableName, String updateTime, int pageNum, String token, PluginSimpleConfig psc, List<OrgEntity> dbentity) throws Exception{
if(Utils.isNullStr(token)){
token = "Bearer "+getToken();
}
JSONObject param = new JSONObject();
param.put("pageNo",pageNum);
param.put("pageSize",1000);
param.put("tableAlias",tableName);
param.put("updateTime",updateTime);
String apikey = psc.getApikey();
Map<String,String> header = new HashMap<String,String>();
header.put("apikey",apikey);
header.put("Content-Type","application/json");
header.put("Authorization",token);
String dataurl = psc.getDataurl();
String result = HttpUtils.HttpPostJson(dataurl,param.toString(),header);
if(Utils.isNullStr(result)){
throw new Exception("获取数据异常");
}
JSONObject resultJson = new JSONObject(result);
int code = resultJson.getInt("code");
if(code != 0 ){
String msg = resultJson.getString("message");
throw new Exception(msg);
}
JSONObject data = resultJson.getJSONObject("data");
int total = data.getInt("pageCount");
if(total == 0){
dbentity = new ArrayList<OrgEntity>();
return ;
}
JSONArray dataList = data.getJSONArray("dataList");
arrayToOrgList(dataList,dbentity,tableName);
if(total == pageNum){
return ;
}
getOrgData(tableName,updateTime,pageNum+1,token,psc,dbentity);
}
}

227
src/main/java/com/eco/plugin/xxx/bjgjdata/utils/DateUtilSelf.java

@ -0,0 +1,227 @@
package com.eco.plugin.xxx.bjgjdata.utils;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateUtilSelf {
/**
* 日期转换为日期字符串
* @param date
* @param formatStr
* @return String
*/
public static String DateToString(Date date,String formatStr) {
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
String dateStr = sdf.format(date).toString();
return dateStr;
}
/**
* 日期字符串转换日期
* @param dateStr
* @param formatStr
* @return Date
*/
public static Date strToDate(String dateStr,String formatStr){
SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
Date date = null;
try {
date = sdf.parse(dateStr);
}
catch(Exception e) {
}
return date;
}
/**
* Date转Timestamp
* @param date
* @return
*/
public static Timestamp dateToTimestamp(Date date) {
Date transDate = DateUtilSelf.strToDate(DateUtilSelf.DateToString(date, "yyyy-MM-dd hh:mm:ss"),"yyyy-MM-dd hh:mm:ss");
Timestamp timestamp = new Timestamp(transDate.getTime());
return timestamp;
}
/**
* Date字符串转Timestamp
* @param dateStr
* @param format
* @return
*/
public static Timestamp strToTimestamp(String dateStr,String format) {
Date date = strToDate(dateStr,format);
Timestamp timestamp = new Timestamp(date.getTime());
return timestamp;
}
/**
* 获取两个日期字符串之间的天数
* @param startDateStr
* @param endDateStr
* @param formatStr
* @return
*/
public static int getDays(String startDateStr,String endDateStr,String formatStr) {
Date startDate = strToDate(startDateStr,formatStr);
Date endDate = strToDate(endDateStr,formatStr);
long startTime = startDate.getTime();
long endTime = endDate.getTime();
int days = (int) ((endTime - startTime)/(60*60*24*1000));
return days;
}
/**
* 获取给定时间之前之后的时间
* @param type
* @param dateStr
* @param count
* @param formatStr
* @return
*/
public static String getAfterDateStr(int type,String dateStr,int count,String formatStr) {
Date startDate = strToDate(dateStr,formatStr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
calendar.add(type, count);
String endDateStr = DateToString(calendar.getTime(),formatStr);
return endDateStr;
}
/**
* 获取给定时间之前之后的时间
* @param type
* @param date
* @param count
* @param formatStr
* @return
*/
public static String getAfterDateStr(int type,Date date,int count,String formatStr) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(type, count);
String endDateStr = DateToString(calendar.getTime(),formatStr);
return endDateStr;
}
/**
* 获取给定时间之前之后的时间
* @param type
* @param date
* @param count
* @return
*/
public static Date getAfterDateStr(int type,Date date,int count) {
Calendar dateResult = Calendar.getInstance();
dateResult.setTime(date);
dateResult.add(type, count);
return dateResult.getTime();
}
/**
* 时间戳转日期
* @param timestamp
* @return
*/
public static Date timestampToDate(Timestamp timestamp) {
Date date = new Date(timestamp.getTime());
return date;
}
/**
* 时间戳转时间字符串
* @param timestamp
* @param format 日期格式
* @return
*/
public static String timestampToStr(Timestamp timestamp,String format) {
Date date = timestampToDate(timestamp);
String timeStr = DateToString(date, format);
return timeStr;
}
/**
* 获取所给日期length天内每s一天的日期
* @param date 所给日期yyyy-MM-dd
* @param length 长度
* @return
*/
public static List<String> getDateList(String date,int length){
List<String> dateList = new ArrayList<String>();
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//获取length天后的日期
String targetDate = getAfterDateStr(Calendar.DATE,date,length,format);
Date start = null;
Date end = null;
if(length >= 0) {
start = strToDate(date,format);
end = strToDate(targetDate,format);
}else {
start = strToDate(targetDate,format);
end = strToDate(date,format);
}
Calendar calBegin = Calendar.getInstance();
calBegin.setTime(start);
Calendar calEnd = Calendar.getInstance();
calEnd.setTime(end);
while (end.after(calBegin.getTime())) {
calBegin.add(Calendar.DATE, 1);
String dayStr = sdf.format(calBegin.getTime());
dateList.add(dayStr);
}
return dateList;
}
/**
* 比较startDate是否在endDate之前
* @param startDate
* @param endDate
* @param format
* @return 0 两个日期相等 <0 开始日期在结束日期之前 >0 开始日期在结束日期之后
*/
public static int comparisonDate(String startDate,String endDate,String format) {
Date start = strToDate(startDate,format);
Date end = strToDate(endDate,format);
return start.compareTo(end);
}
//获取当前日期年、月、日、时、分、秒
public static int getCount(int type){
Calendar calendar = Calendar.getInstance();
return calendar.get(type);
}
}

257
src/main/java/com/eco/plugin/xxx/bjgjdata/utils/FRUtils.java

@ -0,0 +1,257 @@
package com.eco.plugin.xxx.bjgjdata.utils;
import com.fr.base.ServerConfig;
import com.fr.base.TableData;
import com.fr.decision.authority.AuthorityContext;
import com.fr.decision.authority.data.User;
import com.fr.decision.webservice.login.LogInOutResultInfo;
import com.fr.decision.webservice.utils.DecisionServiceConstants;
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.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 var1 = AuthorityContext.getInstance().getUserController().find(QueryFactory.create().addRestriction(RestrictionFactory.eq("userName", userName)));
return var1 != null && !var1.isEmpty();
} catch (Exception var2) {
FineLoggerFactory.getLogger().error(var2.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 var1, String var2, int var3) {
try {
if (StringUtils.isNotEmpty(var2)) {
Cookie var4 = new Cookie("fine_auth_token", var2);
long var5 = var3 == -2 ? 1209600000L : (long)var3;
var4.setMaxAge((int)var5);
var4.setPath(ServerConfig.getInstance().getCookiePath());
var1.addCookie(var4);
Cookie var7 = new Cookie("fine_remember_login", String.valueOf(var3 == -2 ? -2 : -1));
var7.setMaxAge((int)var5);
var7.setPath(ServerConfig.getInstance().getCookiePath());
var1.addCookie(var7);
} else {
FineLoggerFactory.getLogger().error("empty token cannot save.");
}
} catch (Exception var8) {
FineLoggerFactory.getLogger().error(var8.getMessage(), var8);
}
}
/**
*
* @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;
}
/**
* 解密FR密码
* @param password
* @return
*/
// public static String decryptFRPsd(String password){
// FRLogInfo("解密密码:"+password);
// return TransmissionTool.decrypt(password);
// }
/**
* 获取带参数的访问链接
* @return
*/
public static String getAllUrl(HttpServletRequest httpServletRequest){
return WebUtils.getOriginalURL(httpServletRequest);
}
public static TableData getTableData(String serverDataSetName){
TableData userInfo = TableDataConfig.getInstance().getTableData("serverDataSetName");
// DataModel userInfoDM = userInfo.createDataModel(Calculator.createCalculator());
return userInfo;
}
}

265
src/main/java/com/eco/plugin/xxx/bjgjdata/utils/HttpUtils.java

@ -0,0 +1,265 @@
package com.eco.plugin.xxx.bjgjdata.utils;
import com.fr.log.FineLoggerFactory;
import com.fr.third.org.apache.http.HttpEntity;
import com.fr.third.org.apache.http.HttpResponse;
import com.fr.third.org.apache.http.HttpStatus;
import com.fr.third.org.apache.http.NameValuePair;
import com.fr.third.org.apache.http.client.CookieStore;
import com.fr.third.org.apache.http.client.entity.UrlEncodedFormEntity;
import com.fr.third.org.apache.http.client.methods.HttpGet;
import com.fr.third.org.apache.http.client.methods.HttpPost;
import com.fr.third.org.apache.http.conn.ssl.NoopHostnameVerifier;
import com.fr.third.org.apache.http.entity.StringEntity;
import com.fr.third.org.apache.http.impl.client.BasicCookieStore;
import com.fr.third.org.apache.http.impl.client.CloseableHttpClient;
import com.fr.third.org.apache.http.impl.client.HttpClients;
import com.fr.third.org.apache.http.impl.cookie.BasicClientCookie;
import com.fr.third.org.apache.http.message.BasicNameValuePair;
import com.fr.third.org.apache.http.ssl.SSLContexts;
import com.fr.third.org.apache.http.ssl.TrustStrategy;
import com.fr.third.org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import javax.servlet.http.Cookie;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class HttpUtils {
/**
* httpGet请求
* @param url
* @return
*/
public static String httpGet(String url,Cookie[] cookies,Map<String,String> header){
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--url:"+url);
//创建httpClient
CloseableHttpClient httpclient = createHttpClient(cookies);
HttpGet getMethod = new HttpGet(url);
if(header != null && header.size() > 0){
Set<String> keySet = header.keySet();
for(String key : keySet){
getMethod.setHeader(key,header.get(key));
}
}
try {
HttpResponse response = httpclient.execute(getMethod);
int status =response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String returnResult = EntityUtils.toString(entity, "utf-8");
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--status:"+status);
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--returnResult:"+returnResult);
httpclient.close();
if (status == HttpStatus.SC_OK) {
return returnResult;
}
} catch (Exception e) {
FineLoggerFactory.getLogger().info("FRLOG:HttpUtils.get--exception:"+e.getMessage());
}
try {
httpclient.close();
} catch (Exception e) {
FineLoggerFactory.getLogger().info("FRLOG:http关闭异常:"+e.getMessage());
}
return "";
}
/**
* HttpPost请求
* @param postMethod
* @return
*/
private static String HttpPost(HttpPost postMethod){
CloseableHttpClient httpclient = createHttpClient(null);
try {
HttpResponse response = httpclient.execute(postMethod);
int status = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String returnResult = EntityUtils.toString(entity, "utf-8");
FineLoggerFactory.getLogger().info("FRLOG:HttpPost:status:"+status);
FineLoggerFactory.getLogger().info("FRLOG:HttpPost:returnResult:"+returnResult);
httpclient.close();
if (status == HttpStatus.SC_OK) {
return returnResult;
}
} catch (Exception e) {
FineLoggerFactory.getLogger().info("FRLOG:HttpPost:exception:"+e.getMessage());
}
try {
httpclient.close();
} catch (Exception e) {
FineLoggerFactory.getLogger().info("FRLOG:http关闭异常:"+e.getMessage());
}
return "";
}
public static String HttpPostXML(String url, String xmlParam){
FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:url:"+url);
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader("Content-type", "text/html");
HttpEntity entity2 = null;
try {
entity2 = new StringEntity(xmlParam);
} catch (UnsupportedEncodingException e) {
FineLoggerFactory.getLogger().info("FRLOG:HttpPostXML:参数异常:"+e.getMessage());
return "";
}
postMethod.setEntity(entity2);
return HttpPost(postMethod);
}
public static String HttpPostText(String url, String xmlParam){
FineLoggerFactory.getLogger().info("FRLOG:HttpPostText:url:"+url);
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader("Content-type", "text/plain");
HttpEntity entity2 = null;
try {
entity2 = new StringEntity(xmlParam);
} catch (UnsupportedEncodingException e) {
FineLoggerFactory.getLogger().info("FRLOG:HttpPostText:参数异常:"+e.getMessage());
return "";
}
postMethod.setEntity(entity2);
return HttpPost(postMethod);
}
public static String HttpPostJson(String url, String param,Map<String,String> header){
FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:url:"+url);
HttpPost postMethod = new HttpPost(url);
postMethod.setHeader("Content-Type","application/json");
if(header != null && header.size() > 0){
Set<String> keySet = header.keySet();
for(String key : keySet){
postMethod.setHeader(key,header.get(key));
}
}
if(!Utils.isNullStr(param)){
HttpEntity entity2 = null;
try {
entity2 = new StringEntity(param);
} catch (UnsupportedEncodingException e) {
FineLoggerFactory.getLogger().info("FRLOG:HttpPostJSON:参数异常:"+e.getMessage());
return "";
}
postMethod.setEntity(entity2);
}
return HttpPost(postMethod);
}
public static String HttpPostWWWForm(String url, Map<String,String> header,Map<String,String> param){
FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:url:"+url);
HttpPost postMethod = new HttpPost(url);
if(header != null && header.size() > 0){
Set<String> keySet = header.keySet();
for(String key : keySet){
postMethod.setHeader(key,header.get(key));
}
}
if(param != null && param.size() > 0){
List<NameValuePair> params = new ArrayList<NameValuePair>(param.size());
for(Map.Entry<String,String> map : param.entrySet()){
params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
}
try {
postMethod.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:异常:"+e.getMessage());
return "";
}
}
return HttpPost(postMethod);
}
private static CloseableHttpClient createHttpClient(Cookie[] cookies){
SSLContext sslContext = null;
try {
sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
} catch (Exception e) {
FRUtils.FRLogInfo("exception:"+e.getMessage());
}
CloseableHttpClient httpclient = null;
if(cookies != null && cookies.length > 0){
CookieStore cookieStore = cookieToCookieStore(cookies);
httpclient = HttpClients.custom().setSslcontext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultCookieStore(cookieStore).build();
}
else{
httpclient = HttpClients.custom().setSslcontext(sslContext).
setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
}
return httpclient;
}
/**
* cookies转cookieStore
* @param cookies
* @return
*/
public static CookieStore cookieToCookieStore(Cookie[] cookies){
CookieStore cookieStore = new BasicCookieStore();
if(cookies != null && cookies.length>0){
for(Cookie cookie : cookies){
BasicClientCookie cookie1 = new BasicClientCookie(cookie.getName(), cookie.getValue());
cookieStore.addCookie(cookie1);
}
}
return cookieStore;
}
}

108
src/main/java/com/eco/plugin/xxx/bjgjdata/utils/ResponseUtils.java

@ -0,0 +1,108 @@
package com.eco.plugin.xxx.bjgjdata.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();
}
}

244
src/main/java/com/eco/plugin/xxx/bjgjdata/utils/Utils.java

@ -0,0 +1,244 @@
package com.eco.plugin.xxx.bjgjdata.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.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("\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 var3 = fw.indexOf(",");
return var3 != -1 ? fw.substring(0, var3) : 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);
}
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());
}
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));
}
}
Loading…
Cancel
Save