commit 1cc92d8c6c1dceca73616708eff7f761b390bba3 Author: pioneer Date: Wed Nov 9 16:25:36 2022 +0800 open diff --git a/README.md b/README.md new file mode 100644 index 0000000..b24e2a0 --- /dev/null +++ b/README.md @@ -0,0 +1,6 @@ +# open-JSD-9954 + +JSD-9954 logdb的用户操作日志定期推送到客户的日志接口内\ +免责说明:该源码为第三方爱好者提供,不保证源码和方案的可靠性,也不提供任何形式的源码教学指导和协助!\ +仅作为开发者学习参考使用!禁止用于任何商业用途!\ +为保护开发者隐私,开发者信息已隐去!若原开发者希望公开自己的信息,可联系【pioneer】处理。 \ No newline at end of file diff --git a/plugin.xml b/plugin.xml new file mode 100644 index 0000000..4c5280c --- /dev/null +++ b/plugin.xml @@ -0,0 +1,20 @@ + + com.eco.plugin.xx.bjgjlog + + yes + 1.0.9 + 10.0 + 2018-07-31 + fr.open + + + com.eco.plugin.xx.bjgjlog + + + + + + + + \ No newline at end of file diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/config/InitializeMonitor.java b/src/main/java/com/eco/plugin/xx/bjgjlog/config/InitializeMonitor.java new file mode 100644 index 0000000..b38fdc0 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/config/InitializeMonitor.java @@ -0,0 +1,21 @@ +package com.eco.plugin.xx.bjgjlog.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) { + PluginLogSimpleConfig.getInstance(); + } + + @Override + public void beforeStop(PluginContext pluginContext) { + + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/config/PluginLogSimpleConfig.java b/src/main/java/com/eco/plugin/xx/bjgjlog/config/PluginLogSimpleConfig.java new file mode 100644 index 0000000..1ce940f --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/config/PluginLogSimpleConfig.java @@ -0,0 +1,79 @@ +package com.eco.plugin.xx.bjgjlog.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 PluginLogSimpleConfig extends DefaultConfiguration { + + private static volatile PluginLogSimpleConfig config = null; + + @Focus(id="com.eco.plugin.xx.bjgjlog.config", text = "日志推送配置", source = Original.PLUGIN) + public static PluginLogSimpleConfig getInstance() { + if (config == null) { + config = ConfigContext.getConfigInstance(PluginLogSimpleConfig.class); + } + return config; + } + + @Identifier(value = "appid", name = "appid", description = "appid", status = Status.SHOW) + private Conf appid = Holders.simple(""); + + @Identifier(value = "appSecret", name = "appSecret", description = "appSecret", status = Status.SHOW) + private Conf appSecret = Holders.simple(""); + + @Identifier(value = "dataset", name = "数据集名称", description = "数据集名称", status = Status.SHOW) + private Conf dataset = Holders.simple(""); + + @Identifier(value = "rjjk", name = "批量推送日志接口", description = "批量推送日志接口", status = Status.SHOW) + private Conf rjjk = Holders.simple(""); + + public String getAppSecret() { + return appSecret.get(); + } + + public void setAppSecret(String url) { + this.appSecret.set(url); + } + + public String getAppid() { + return appid.get(); + } + + public void setAppid(String url) { + this.appid.set(url); + } + + public String getDataset() { + return dataset.get(); + } + + public void setClientId(String url) { + this.dataset.set(url); + } + + public String getRjjk() { + return rjjk.get(); + } + + public void setRjjk(String url) { + this.rjjk.set(url); + } + + @Override + public Object clone() throws CloneNotSupportedException { + PluginLogSimpleConfig cloned = (PluginLogSimpleConfig) super.clone(); +// cloned.text = (Conf) text.clone(); +// cloned.count = (Conf) count.clone(); +// cloned.price = (Conf) price.clone(); +// cloned.time = (Conf) time.clone(); +// cloned.student = (Conf) student.clone(); + return cloned; + } + +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/db/bean/TimeRecordEntity.java b/src/main/java/com/eco/plugin/xx/bjgjlog/db/bean/TimeRecordEntity.java new file mode 100644 index 0000000..22fd240 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/db/bean/TimeRecordEntity.java @@ -0,0 +1,30 @@ +package com.eco.plugin.xx.bjgjlog.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; + +/** + * @author xx + * @version 10.0 + * Created by xx on 2021-07-29 + **/ +@Entity +@Table(name = "plugin_xx_entity_timerecord") +@TableAssociation(associated = true) +public class TimeRecordEntity extends BaseEntity { + + //数据表名 + @Column(name = "time") + private String time = null; + + public String getTime() { + return time; + } + + public void setTime(String time) { + this.time = time; + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/db/controller/DBController.java b/src/main/java/com/eco/plugin/xx/bjgjlog/db/controller/DBController.java new file mode 100644 index 0000000..b4521db --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/db/controller/DBController.java @@ -0,0 +1,69 @@ +package com.eco.plugin.xx.bjgjlog.db.controller; + +import com.eco.plugin.xx.bjgjlog.db.bean.TimeRecordEntity; +import com.eco.plugin.xx.bjgjlog.db.dao.RecordDao; +import com.eco.plugin.xx.bjgjlog.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 com.fr.third.jgroups.util.UUID; + +/** + * @author xx + * @version 10.0 + * Created by xx 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[]{ + RecordDao.DAO + }; + } + + @Override + public void onDBAvailable(DBAccessor accessor) { + DBController.accessor = accessor; + } + + + /** + * 添加记录 + * @param recordEntity + * @return + */ + public static boolean addRecord(TimeRecordEntity recordEntity){ + + try{ + accessor.runDMLAction(new DBAction() { + @Override + public Boolean run(DAOContext context) throws Exception { + recordEntity.setId(UUID.randomUUID().toString()); + context.getDAO(RecordDao.class).add(recordEntity); + return true; + } + }); + }catch(Throwable e){ + FRUtils.FRLogError("addRecord exception ->"+e.getMessage() ); + return false; + } + + + return true; + } + + +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/db/dao/RecordDao.java b/src/main/java/com/eco/plugin/xx/bjgjlog/db/dao/RecordDao.java new file mode 100644 index 0000000..83b308f --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/db/dao/RecordDao.java @@ -0,0 +1,69 @@ +package com.eco.plugin.xx.bjgjlog.db.dao; + +import com.eco.plugin.xx.bjgjlog.db.bean.TimeRecordEntity; +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 xx + * @version 10.0 + * Created by xx on 2021-12-03 + **/ +public class RecordDao extends BaseDAO { + + public RecordDao(DAOSession session) { + super(session); + } + + @Override + protected Class getEntityClass() { + return TimeRecordEntity.class; + } + + public final static DAOProvider DAO = new DAOProvider() { + @Override + public Class getEntityClass() { + return TimeRecordEntity.class; + } + + @Override + public Class getDAOClass() { + return RecordDao.class; + } + }; + + public void add(TimeRecordEntity 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(TimeRecordEntity entity) throws Exception { + getSession().merge(entity); + } + + + public TimeRecordEntity getByUsername(String username) throws Exception { + QueryCondition condition = QueryFactory.create() + .addRestriction(RestrictionFactory.eq("username", username)); + + return findOne(condition); + } + + + public List like(String pid, String type)throws Exception{ + QueryCondition condition = QueryFactory.create() + .addRestriction(RestrictionFactory.like("", pid)).addRestriction(RestrictionFactory.like(TimeRecordEntity.COLUMN_ID,type)); + return find(condition); + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/function/AuthFunction.java b/src/main/java/com/eco/plugin/xx/bjgjlog/function/AuthFunction.java new file mode 100644 index 0000000..099f7ad --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/function/AuthFunction.java @@ -0,0 +1,123 @@ +package com.eco.plugin.xx.bjgjlog.function; + +import com.eco.plugin.xx.bjgjlog.config.PluginLogSimpleConfig; +import com.eco.plugin.xx.bjgjlog.db.bean.TimeRecordEntity; +import com.eco.plugin.xx.bjgjlog.db.controller.DBController; +import com.eco.plugin.xx.bjgjlog.utils.DateUtilSelf; +import com.eco.plugin.xx.bjgjlog.utils.FRUtils; +import com.eco.plugin.xx.bjgjlog.utils.HttpUtils; +import com.eco.plugin.xx.bjgjlog.utils.Utils; +import com.fr.general.data.DataModel; +import com.fr.general.data.TableDataException; +import com.fr.json.JSONArray; +import com.fr.json.JSONObject; +import com.fr.plugin.context.PluginContexts; +import com.fr.script.AbstractFunction; +import com.fr.stable.fun.Authorize; + +import java.util.HashMap; +import java.util.Map; + +@Authorize(callSignKey = "com.eco.plugin.xx.bjgjlog") +public class AuthFunction extends AbstractFunction { + + @Override + public Object run(Object[] objects) { + FRUtils.FRLogInfo("日志推送"); + if(!PluginContexts.currentContext().isAvailable()){ + return "FAIL"; + } + String now = DateUtilSelf.getNow(); + //获取配置参数 + PluginLogSimpleConfig psc = PluginLogSimpleConfig.getInstance(); + //从数据集获取日志数组 + JSONArray logs = null; + FRUtils.FRLogInfo("获取数据集开始"); + try { + logs = getLogArray(psc); + } catch (TableDataException e) { + FRUtils.FRLogError("获取数据集数据失败:"+e.getMessage()); + return "FAIL"; + } + FRUtils.FRLogInfo("获取数据集结束"); + + //推送日志,根据返回值选择返回true or false + JSONObject param = new JSONObject(); + param.put("operLogs",logs); + + FRUtils.FRLogInfo("推送开始"); + FRUtils.FRLogInfo(param.toString()); + Map header = new HashMap(); + header.put("appId",psc.getAppid()); + header.put("appSecret",psc.getAppSecret()); + String result = HttpUtils.HttpPostJson(psc.getRjjk(),param.toString(),header); + FRUtils.FRLogInfo("推送结束"); + + if(Utils.isNullStr(result)){ + FRUtils.FRLogError("推送日志失败"); + return "FAIL"; + } + + JSONObject resultJson = new JSONObject(result); + int code = resultJson.getInt("code"); + + if(200 != code){ + FRUtils.FRLogError("推送日志失败:"+resultJson.getString("msg")); + return "FAIL"; + } + FRUtils.FRLogInfo("推送结束2"); + + TimeRecordEntity tre = new TimeRecordEntity(); + tre.setTime(now); + FRUtils.FRLogInfo("addRecord开始"); + + DBController.addRecord(tre); + FRUtils.FRLogInfo("addRecord开始"); + + return "SUCCESS"; + } + + private JSONArray getLogArray(PluginLogSimpleConfig psc) throws TableDataException { + DataModel dm = FRUtils.getTableData(psc.getDataset()); + int rowcount = dm.getRowCount(); + + int appIdIndex = dm.getColumnIndex("appId"); + int titleIndex = dm.getColumnIndex("title"); + int businessTypeIndex = dm.getColumnIndex("businessType"); + int methodIndex = dm.getColumnIndex("method"); + int requestMethodIndex = dm.getColumnIndex("requestMethod"); + int operatorTypeIndex = dm.getColumnIndex("operatorType"); + int operNameIndex = dm.getColumnIndex("operName"); + int operUrlIndex = dm.getColumnIndex("operUrl"); + int operIpIndex = dm.getColumnIndex("operIp"); + int operParamIndex = dm.getColumnIndex("operParam"); + int jsonResultIndex = dm.getColumnIndex("jsonResult"); + int statusIndex = dm.getColumnIndex("status"); + int tenantIdIndex = dm.getColumnIndex("tenantId"); + int operTimeIndex = dm.getColumnIndex("operTime"); + + JSONArray result = new JSONArray(); + + for(int i =0;i getDateList(String date,int length){ + List dateList = new ArrayList(); + 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); + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/utils/FRUtils.java b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/FRUtils.java new file mode 100644 index 0000000..3a2b5f0 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/FRUtils.java @@ -0,0 +1,300 @@ +package com.eco.plugin.xx.bjgjlog.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.data.User; +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.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 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); + } + + /** + * 根据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; + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/utils/HttpUtils.java b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/HttpUtils.java new file mode 100644 index 0000000..7890e0f --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/HttpUtils.java @@ -0,0 +1,265 @@ +package com.eco.plugin.xx.bjgjlog.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 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 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 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 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 header,Map param){ + FineLoggerFactory.getLogger().info("FRLOG:HttpWWWForm:url:"+url); + + HttpPost postMethod = new HttpPost(url); + + if(header != null && header.size() > 0){ + Set keySet = header.keySet(); + + for(String key : keySet){ + postMethod.setHeader(key,header.get(key)); + } + } + + if(param != null && param.size() > 0){ + List params = new ArrayList(param.size()); + + for(Map.Entry 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; + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/utils/ResponseUtils.java b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/ResponseUtils.java new file mode 100644 index 0000000..bf41d84 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/ResponseUtils.java @@ -0,0 +1,108 @@ +package com.eco.plugin.xx.bjgjlog.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(); + } +} diff --git a/src/main/java/com/eco/plugin/xx/bjgjlog/utils/Utils.java b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/Utils.java new file mode 100644 index 0000000..17a5c46 --- /dev/null +++ b/src/main/java/com/eco/plugin/xx/bjgjlog/utils/Utils.java @@ -0,0 +1,244 @@ +package com.eco.plugin.xx.bjgjlog.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("\\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 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 parameterMap){ + if(parameterMap == null){ + parameterMap = new HashMap(); + } + + 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)); + } +}