版本2.0更新

This commit is contained in:
yunian
2022-06-23 16:27:20 +08:00
parent 5a9e9a03f5
commit db6b7991af
899 changed files with 72581 additions and 0 deletions

View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ddp-common</artifactId>
<groupId>com.fibo.ddp</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<dependencies>
<!--websocket连接需要使用到的包-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
<artifactId>ddp-common-utils</artifactId>
</project>

View File

@@ -0,0 +1,91 @@
package com.fibo.ddp.common.utils.common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* ClassName:MD5 <br/>
* Description: md5加密工具类. <br/>
*/
public class MD5 {
/**
* 全局数组
*/
private static final String[] DIGITS = { "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "H", "i",
"j", "k", "l", "m", "n", "~", "$", "@", "%", "*", "#", "&", "!" };
public MD5() {
}
/**
* byteToArrayString:(返回形式为数字跟字符串). <br/>
* @author wz
* @param bByte byte
* @return 返回形式为数字跟字符串
*/
private static String byteToArrayString(byte bByte) {
int iRet = bByte;
if (iRet < 0) {
iRet += 256;
}
int iD1 = iRet / 32;
int iD2 = iRet % 32;
return DIGITS[iD1] + DIGITS[iD2];
}
/**
* byteToNum:(返回形式只为数字). <br/>
* @param bByte byte
* @return 返回形式只为数字
*/
private static String byteToNum(byte bByte) {
int iRet = bByte;
System.out.println("iRet1=" + iRet);
if (iRet < 0) {
iRet += 256;
}
return String.valueOf(iRet);
}
/**
* byteToString:(转换字节数组为16进制字串). <br/>
* @param bByte byte数组
* @return 返回转换字节数组为16进制字串
*/
private static String byteToString(byte[] bByte) {
StringBuffer sBuffer = new StringBuffer();
for (int i = 0; i < bByte.length; i++) {
sBuffer.append(byteToArrayString(bByte[i]));
}
return sBuffer.toString();
}
/**
* GetMD5Code:(md5加密). <br/>
* @author wz
* @param param 需要加密的字段
* @return 加密后的字段
*/
public static String GetMD5Code(String param) {
String resultString = null;
try {
resultString = new String(param);
MessageDigest md = MessageDigest.getInstance("MD5");
// md.digest() 该函数返回值为存放哈希值结果的byte数组
resultString = byteToString(md.digest(param.getBytes()));
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return resultString;
}
// public static void main(String[] args) {
// MD5 getMD5 = new MD5();
// System.out.println(getMD5.GetMD5Code("123456"));
// }
}

View File

@@ -0,0 +1,13 @@
package com.fibo.ddp.common.utils.constant;
public class AnalyseConst {
//统计维度1.调用次数 engine_call,2.决策结果 decision_result,3规则命中 rule_hit 4.评分卡 scorecard 5.决策表 decision_tables 6.节点命中 NODE_HIT
public static final String ENGINE_CALL = "engine_call";
public static final String DECISION_RESULT = "decision_result";
public static final String RULE_HIT = "rule_hit";
public static final String SCORECARD = "scorecard";
public static final String DECISION_TABLES = "decision_tables";
// public static final String LIST_DB = "list_db";
public static final String NODE_HIT = "node_hit";
public static final String[] KEYS = {ENGINE_CALL,DECISION_RESULT,RULE_HIT,SCORECARD,DECISION_TABLES,NODE_HIT};
}

View File

@@ -0,0 +1,18 @@
package com.fibo.ddp.common.utils.constant;
public class ApprovalConsts {
public static final class ApplyStatus {
public static final int CANCEL = -1;//取消申请
public static final int WAIT = 0;//待审批
public static final int PASS = 1;//通过
public static final int DENY = 2;//拒绝
}
public static final class ApprovalType {
public static final String DECISION_FLOW_VERSION_DEPLOY = "jclbbbs";//决策流版本部署审批
}
public static final class ApprovalStatus {
public static final int DELETE = -1;//取消申请
public static final int OFF = 0;//待审批
public static final int ON = 1;//通过
}
}

View File

@@ -0,0 +1,51 @@
package com.fibo.ddp.common.utils.constant;
public class CommonConst {
/**
* 逗号
*/
public static final String SYMBOL_COMMA = ",";
/**
* 单引号
*/
public static final String SYMBOL_SINGLE_QUOTA = "\'";
/**
* 空格
*/
public static final String SYMBOL_BLANK = " ";
/**
* 空字符串
*/
public static final String STRING_EMPTY = "";
/**
* 评分卡前缀
*/
public static final String SCORECARD_STARTION = "sc";
/**
* 字段前缀
*/
public static final String SELF_FIELD_STARTION = "f";
/**
* 是否命中
* */
public static final String IS_HIT = "是否命中";
/**
* 得分
* */
public static final String SCORE = "得分";
/**
* 30分钟(s)
* */
public static final long MINUTE_30 = 1800000;
public static String DROOLS_KSESSION_KEY_PREFIX = "DROOLS_KSESSION#";
public static String JEDIS_KSESSION_KEY_PREFIX = "JEDIS_KSESSION#";
}

View File

@@ -0,0 +1,41 @@
package com.fibo.ddp.common.utils.constant;
/**
* 公共变量约定
*/
public class Constants {
// token名称
public static final String SYSTEM_KEY_TOKEN = "token";
// token时间 单位秒
public static final Long LOGIN_TOKEN_TIME = 7200L;
// token最大剩余时间需刷新 单位秒
public static final Long LOGIN_TOKEN_REFRESH_TIME = 600L;
// 规则集节点相关常量
public interface ruleNode {
// 互斥组
int MUTEXGROUP = 1;
// 执行组
int EXECUTEGROUP = 2;
}
public interface switchFlag {
// 开关打开
String ON = "on";
// 开关关闭
String OFF = "off";
}
public interface fieldName {
// 字段英文名
String fieldEn = "field_en";
//字段中文名
String fieldCn = "field_cn";
}
public interface cacheConf {
// 缓存时间
int cacheSecond = 120;
String cachePrefix = "runner:cache:";
}
}

View File

@@ -0,0 +1,647 @@
package com.fibo.ddp.common.utils.constant;
public class OpTypeConst {
/**
* 登入
* */
public static final String LOGIN = "登入";
/**
* 登出
* */
public static final String LOGOUT = "登出";
/**
* 保存菜单
* */
public static final String SAVE_MENU = " 保存菜单";
/**
* 修改菜单
* */
public static final String UPDATE_MENU = "修改菜单";
/**
* 删除菜单
* */
public static final String DELETE_MENU = " 删除菜单";
/**
* 保存相应角色的菜单权限
* */
public static final String SAVE_MENU_ROLE = "新增相应角色的菜单权限";
/**
* 保存系统菜单
* */
public static final String SAVE_SYS_MENU = "新增系统菜单";
/**
* 修改系统菜单
* */
public static final String UPDATE_SYS_MENU = "修改系统菜单";
/**
* 修改评分卡版本状态
*/
public static final String UPDATE_SYS_MENU_STATUS = "修改评分卡版本状态";
/**
* 删除系统菜单
* */
public static final String DELETE_SYS_MENU = "删除系统菜单";
/**
* 批量删除系统菜单
* */
public static final String BATCH_DELETE_SYS_MENU = "批量删除系统菜单";
/**
* 保存、修改资源树
* */
public static final String SAVE_OR_UPDATE_MENU_ROLE = "保存、修改资源树";
/**
* 保存、修改引擎树
* */
public static final String SAVE_ROLE_ENGINE = "保存、修改引擎树";
/**
* 保存组织信息
* */
public static final String SAVE_ORGAN = "保存组织信息";
/**
* 修改组织信息
* */
public static final String UPDATE_ORGAN = " 修改组织信息";
/**
*删除组织信息
* */
public static final String DELTET_ORGAN = "删除组织信息";
/**
*批量删除组织信息
* */
public static final String BATCH_DELTET_ORGAN ="批量删除组织信息";
/**
*修改组织状态信息
* */
public static final String UPDATE_ORGAN_STATUS ="修改组织状态信息";
/**
*保存本组织角色
* */
public static final String SAVE_SYS_ROLE ="保存本组织角色";
/**
*修改本组织角色
* */
public static final String UPDATE_SYS_ROLE ="修改本组织角色";
/**
*删除本组织角色
* */
public static final String DELETE_SYS_ROLE ="删除本组织角色";
/**
*批量删除本组织角色
* */
public static final String BATCH_DELETE_SYS_ROLE ="批量删除本组织角色";
/**
*保存公司管理员角色
* */
public static final String SAVE_ORANG_MANAGER_ROLE ="保存公司管理员角色";
/**
*修改本组织角色状态
* */
public static final String UPDATE_SYS_ROLE_STATUS ="修改本组织角色状态";
/**
*保存用户信息
* */
public static final String SAVE_SYS_USER ="保存用户信息";
/**
*修改用户信息
* */
public static final String UPDATE_SYS_USER ="修改用户信息";
/**
*删除用户信息
* */
public static final String DELETE_SYS_USER ="删除用户信息";
/**
*批量删除用户信息
* */
public static final String BATCH_DELETE_SYS_USER ="批量删除用户信息";
/**
*修改用户状态
* */
public static final String UPDATE_SYS_USER_STATUS ="修改用户状态";
/**
*重置用户密码
* */
public static final String RESET_PASSWORD ="重置用户密码";
/**
*修改用户密码
* */
public static final String UPDTE_PASSWORD ="修改用户密码";
/**
* 保存字段映射或数据管理目录
* */
public static final String SAVE_FILED_TREE = "保存字段映射或数据管理目录";
/**
* 修改字段映射或数据管理目录
* */
public static final String UPDATE_FILED_TREE = "修改字段映射或数据管理目录";
/**
* 保存数据管理中的字段
* */
public static final String SAVE_FILED = "保存数据管理中的字段";
/**
* 修改数据管理中的字段
* */
public static final String UPDATE_FILED= "修改数据管理中的字段";
/**
* 修改数据管理中的字段
* */
public static final String UPDATE_FILED_STATUS = "修改数据管理中的字段";
/**
* 保存字段映射中的字段
* */
public static final String SAVE_MAPPING_FILED = "保存字段映射中的字段";
/**
* 修改字段映射中的字段
* */
public static final String UPDATE_MAPPING_FILED= "修改字段映射中的字段";
/**
* 修改字段映射中的字段状态
* */
public static final String UPDATE_MAPPING_FILED_STATUS= "修改字段映射中的字段状态";
/**
* 更新字段所属文件夹
*/
public static final String UPDATE_FIELD_FOLDER = "更换字段所属文件夹";
/**
* 保存黑白名单
* */
public static final String SAVE_BLACK_OR_WHITE_LIST = "保存黑白名单";
/**
* 修改黑白名单
* */
public static final String UPDATE_BLACK_OR_WHITE_LIST = " 修改黑白名单";
/**
* 删除黑白名单
* */
public static final String DELETE_BLACK_OR_WHITE_LIST = " 删除黑白名单";
/**
* 保存黑白名单库
* */
public static final String SAVE_BLACK_OR_WHITE_LIST_DB = " 保存黑白名单库";
/**
* 修改黑白名单库
* */
public static final String UPDATE_BLACK_OR_WHITE_LIST_DB = "修改黑白名单库";
/**
* 保存黑白名单库的状态
* */
public static final String SAVE_BLACK_OR_WHITE_LIST_DB_STATUS = "保存黑白名单库的状态";
/**
* 更新黑白名单所属文件夹
*/
public static final String UPDATE_BLACK_OR_WHITE_LIST_DB_FOLDER = "更新黑白名单所属文件夹";
/**
* 保存知识库或规则管理目录
* */
public static final String SAVE_KNOWLEDGE_TREE = "保存知识库或规则管理目录";
/**
* 修改规则知识库或规则管理目录
* */
public static final String UPDATE_KNOWLEDGE_TREE = "修改规则知识库或规则管理目录";
/**
* 保存规则
* */
public static final String SAVE_RULE = "保存规则";
/**
* 修改规则
* */
public static final String UPDATE_RULE = "修改规则";
/**
* 修改规则状态
* */
public static final String UPDATE_RULE_STATUS = "修改规则状态";
/**
* 查询简单规则
* */
public static final String SELECT_SAMPLE_RULE = "查询简单规则";
/**
* 版本规则
*/
/**
* 保存评分卡
* */
public static final String SAVE_SCORECARD = "保存评分卡";
/**
* 修改评分卡
* */
public static final String UPDATE_SCORECARD = "修改评分卡";
/**
*修改分卡状态
* */
public static final String UPDATE_SCORECARD_STATUS = "修改分卡状态";
/**
*节点重命名
* */
public static final String RENAME_NODE = "节点重命名";
/**
*保存节点
* */
public static final String SAVE_NODE = "保存节点";
/**
*修改节点
* */
public static final String UPDATE_NODE = "修改节点";
/**
*删除节点
* */
public static final String DELETE_NODE ="删除节点";
/**
* 批量删除节点
* */
public static final String BATCH_DELETE_NODE ="批量删除节点";
/**
* 删除节点之间的连线
* */
public static final String DELETE_NODE_LINK ="删除节点之间的连线";
/**
* 复制节点
* */
public static final String COPY_NODE ="复制节点";
/**
* 保存引擎
* */
public static final String SAVE_ENGINE ="保存引擎";
/**
* 保存或修改引擎
* */
public static final String UPDATE_ENGINE ="保存或修改引擎";
/**
* 保存版本
* */
public static final String SAVE_VERSION ="保存版本";
/**
* 修改版本
* */
public static final String UPDATE_VERSION ="修改版本";
/**
* 删除版本
* */
public static final String DELETE_VERSION ="删除版本";
/**
* 引擎部署
* */
public static final String ENGINDE_DEPLOY="引擎部署";
/**
* 引擎停止部署
* */
public static final String ENGINDE_UNDEPLOY="引擎停止部署";
/**
* 清空引擎节点
* */
public static final String CLEAR_NODE ="清空引擎节点";
/**
* 添加引擎引用规则关系
* */
public static final String ADD_RULE_QUOTES_REL = "添加引擎引用规则关系";
/**
* 批量修改引擎引用规则状态
* */
public static final String BATCH_UPDATE_STATUS_FOR_QUOTES_RULE ="批量修改引擎引用规则状态";
/**
* 添加引擎引用字段关系
* */
public static final String ADD_FIELD_QUOTES_REL = "添加引擎引用字段关系";
/**
* 数据填写
* */
public static final String FILL_DATA="数据填写";
/**
* 保存数据源
*/
public static final String DATA_SOURCE_SAVE = "保存数据源";
/**
* 修改数据源
*/
public static final String DATA_SOURCE_MODIFY = "修改数据源";
/**
* 删除数据源
*/
public static final String DATA_SOURCE_DELETE = "删除数据源";
/**
* 新增决策表
*/
public static final String ADD_DECISION_TABLES = "新增决策表";
/**
* 更新决策表
*/
public static final String UPDATE_DECISION_TABLES = "更新决策表";
/**
* 更新决策表状态
*/
public static final String UPDATE_DECISION_TABLES_STATUS = "更新决策表状态";
/**
* 更新决策表所属文件
*/
public static final String UPDATE_DECISION_TABLES_FOLDER = "更新决策表所属文件";
/**
* 新增决策表版本
*/
public static final String ADD_DECISION_TABLES_VERSION = "新增决策表版本";
/**
* 复制决策表版本
*/
public static final String COPY_DECISION_TABLES_VERSION = "复制决策表版本";
/**
* 更新决策表版本
*/
public static final String UPDATE_DECISION_TABLES_VERSION = "更新决策表版本";
/**
* 修改决策表版本状态
*/
public static final String UPDATE_DECISION_TABLES_VERSION_STATUS = "修改决策表版本状态";
/**
* 新增决策树
*/
public static final String ADD_DECISION_TREE = "新增决策树";
/**
* 更新决策树
*/
public static final String UPDATE_DECISION_TREE = "更新决策树";
/**
* 更新决策树状态
*/
public static final String UPDATE_DECISION_TREE_STATUS = "更新决策树状态";
/**
* 更新决策树所属文件夹
*/
public static final String UPDATE_DECISION_TREE_FOLDER = "更新决策树所属文件夹";
/**
* 新增决策树版本
*/
public static final String ADD_DECISION_TREE_VERSION = "新增决策树版本";
/**
* 复制决策树版本
*/
public static final String COPY_DECISION_TREE_VERSION = "复制决策树版本";
/**
* 修改决策树版本
*/
public static final String UPDATE_DECISION_TREE_VERSION = "修改决策树版本";
/**
* 修改决策树版本状态
*/
public static final String UPDATE_DECISION_TREE_VERSION_STATUS = "修改决策树版本状态";
/**
* 新增接口
*/
public static final String ADD_INTERFACE = "新增接口";
/**
* 删除接口
*/
public static final String DELETE_INTERFACE = "删除接口";
/**
* 修改接口
*/
public static final String UPDATE_INTERFACE = "修改接口";
/**
* 修改接口状态
*/
public static final String UPDATE_INTERFACE_STATUS = "修改接口状态";
/**
* 新增黑白名单版本
*/
public static final String ADD_BLACK_OR_WHITE_LIST_DB_VERSION = "新增黑白名单版本";
/**
* 复制名单库版本
*/
public static final String COPY_BLACK_OR_WHITE_LIST_DB_VERSION = "复制名单库版本";
/**
* 添加模型
*/
public static final String SAVE_MODELS = "添加模型";
/**
* 删除模型
*/
public static final String DELETE_MODELS = "删除模型";
/**
* 修改模型
*/
public static final String UPDATE_MODELS = "修改模型";
/**
* 保存规则版本
*/
public static final String SAVE_RULE_VERSION = "保存规则版本";
/**
* 复制规则版本
*/
public static final String COPY_RULE_VERSION = "复制规则版本";
/**
* 更新规则版本
*/
public static final String UPDATE_RULE_VERSION = "更新规则版本";
/**
* 更新规则版本状态
*/
public static final String UPDATE_RULE_VERSION_STATUS = "更新规则版本状态";
/**
* 保存脚本规则版本
*/
public static final String SAVE_RULE_SCRIPT_VERSION = "保存脚本规则版本";
/**
* 复制脚本规则版本
*/
public static final String COPY_RULE_SCRIPT_VERSION = "复制脚本规则版本";
/**
* 更新脚本规则版本
*/
public static final String UPDATE_RULE_SCRIPT_VERSION = "更新规则版本";
/**
* 更新脚本规则版本状态
*/
public static final String UPDATE_RULE_VERSION_SCRIPT_STATUS = "更新规则版本状态";
/**
* 新增评分卡版本
*/
public static final String ADD_SCORECARD_VERSION = "新增评分卡版本";
/**
* 复制评分卡版本
*/
public static final String COPY_SCORECARD_VERSION = "复制评分卡版本";
/**
* 修改评分卡版本
*/
public static final String UPDATE_SCORECARD_VERSION = "修改评分卡版本";
/**
* 修改评分卡版本状态
*/
public static final String UPDATE_SCORECARD_VERSION_STATUS = "修改评分卡版本状态";
/**
* 新增业务类型和规则关联
*/
public static final String BUSINESS_RULE_REL_ADD = "业务类型和规则关联-新增";
/**
* 编辑业务类型和规则关联
*/
public static final String BUSINESS_RULE_REL_EDIT = "业务类型和规则关联-编辑";
/**
* 删除业务类型和规则关联
*/
public static final String BUSINESS_RULE_REL_DELETE = "业务类型和规则关联-删除";
/**
* 详情业务类型和规则关联
*/
public static final String BUSINESS_RULE_REL_DETAIL = "业务类型和规则关联-详情";
/**
* 分页列表
*/
public static final String BUSINESS_RULE_REL_PAGE = "业务类型和规则关联-分页查询";
/**
* 分页列表
*/
public static final String QUERY_BY_BUSINESSTYPE = "根据业务类型查询对应规则(对外接口)";
/**
* 新增标签
*/
public static final String ADD_TAG = "新增标签";
/**
* 更新标签
*/
public static final String UPDATE_TAG = "更新标签";
/**
* 更新标签状态
*/
public static final String UPDATE_TAG_STATUS = "更新标签状态";
/**
* 更新标签所属文件夹
*/
public static final String UPDATE_TAG_FOLDER = "更新标签所属文件夹";
/**
* 新增标签版本
*/
public static final String ADD_TAG_VERSION = "新增标签版本";
/**
* 复制标签版本
*/
public static final String COPY_TAG_VERSION = "复制标签版本";
/**
* 修改标签版本
*/
public static final String UPDATE_TAG_VERSION = "修改标签版本";
/**
* 修改标签版本状态
*/
public static final String UPDATE_TAG_VERSION_STATUS = "修改标签版本状态";
}

View File

@@ -0,0 +1,387 @@
package com.fibo.ddp.common.utils.constant;
public enum OpTypeEnum {
/**
* 登入
* */
LOGIN ("login",OpTypeConst.LOGIN),
/**
* 登出
* */
LOGOUT("logout",OpTypeConst.LOGOUT),
/**
* 保存菜单
* */
SAVE_MENU("saveMenu",OpTypeConst.SAVE_MENU),
/**
* 修改菜单
* */
UPDATE_MENU("updateMenu",OpTypeConst.UPDATE_MENU),
/**
* 删除菜单
* */
DELETE_MENU("deleteMenu",OpTypeConst.DELETE_MENU),
/**
* 保存相应角色的菜单权限
* */
SAVE_MENU_ROLE("saveMenuRole",OpTypeConst.SAVE_MENU_ROLE),
/**
* 保存系统菜单
* */
SAVE_SYS_MENU("saveSysMenu",OpTypeConst.SAVE_SYS_MENU),
/**
* 修改系统菜单
* */
UPDATE_SYS_MENU("updateSysMenu",OpTypeConst.UPDATE_SYS_MENU),
/**
* 删除系统菜单
* */
DELETE_SYS_MENU("deleteSysMenu",OpTypeConst.DELETE_SYS_MENU),
/**
* 批量删除系统菜单
* */
BATCH_DELETE_SYS_MENU("batchDeleteSysMenu",OpTypeConst.BATCH_DELETE_SYS_MENU),
/**
* 保存、修改资源树
* */
SAVE_OR_UPDATE_MENU_ROLE("saveOrUpdateMenuRole",OpTypeConst.SAVE_OR_UPDATE_MENU_ROLE),
/**
* 保存、修改引擎树
* */
SAVE_ROLE_ENGINE("saveRoleEngine",OpTypeConst.SAVE_ROLE_ENGINE),
/**
* 保存组织信息
* */
SAVE_ORGAN("saveOrgan",OpTypeConst.SAVE_ORGAN),
/**
* 修改组织信息
* */
UPDATE_ORGAN("updateOrgan",OpTypeConst.UPDATE_ORGAN),
/**
*删除组织信息
* */
DELTET_ORGAN("deleteOrgan",OpTypeConst.DELTET_ORGAN),
/**
*批量删除组织信息
* */
BATCH_DELTET_ORGAN("batchDeleteOrgan",OpTypeConst.BATCH_DELTET_ORGAN),
/**
*修改组织状态信息
* */
UPDATE_ORGAN_STATUS("updateOrganStatus",OpTypeConst.UPDATE_ORGAN_STATUS),
/**
*保存本组织角色
* */
SAVE_SYS_ROLE("saveSysRole",OpTypeConst.SAVE_SYS_ROLE),
/**
*修改本组织角色
* */
UPDATE_SYS_ROLE("updateSysRole",OpTypeConst.UPDATE_SYS_ROLE),
/**
*删除本组织角色
* */
DELETE_SYS_ROLE("deleteSysRole",OpTypeConst.DELETE_SYS_ROLE),
/**
*批量删除本组织角色
* */
BATCH_DELETE_SYS_ROLE("batchDeleteSysRole",OpTypeConst.BATCH_DELETE_SYS_ROLE),
/**
*保存公司管理员角色
* */
SAVE_ORANG_MANAGER_ROLE("saveOrganManagerRole",OpTypeConst.SAVE_ORANG_MANAGER_ROLE),
/**
*修改本组织角色状态
* */
UPDATE_SYS_ROLE_STATUS("updateSysRoleStatus",OpTypeConst.UPDATE_SYS_ROLE_STATUS),
/**
*保存用户信息
* */
SAVE_SYS_USER("saveSysUser",OpTypeConst.SAVE_SYS_USER),
/**
*修改用户信息
* */
UPDATE_SYS_USER("updateSysUser",OpTypeConst.UPDATE_SYS_USER),
/**
*删除用户信息
* */
DELETE_SYS_USER("deleteSysUser",OpTypeConst.DELETE_SYS_USER),
/**
*批量删除用户信息
* */
BATCH_DELETE_SYS_USER("batchDeleteSysUser",OpTypeConst.BATCH_DELETE_SYS_USER),
/**
*修改用户状态
* */
UPDATE_SYS_USER_STATUS("updateSysUserStatus",OpTypeConst.UPDATE_SYS_USER_STATUS),
/**
*重置用户密码
* */
RESET_PASSWORD("resetPassword",OpTypeConst.RESET_PASSWORD),
/**
*修改用户密码
* */
UPDTE_PASSWORD("updatePassword",OpTypeConst.UPDTE_PASSWORD),
/**
* 保存字段映射或数据管理目录
* */
SAVE_FILED_TREE("saveFieldTree",OpTypeConst.SAVE_FILED_TREE),
/**
* 修改字段映射或数据管理目录
* */
UPDATE_FILED_TREE("updateFieldTree",OpTypeConst.UPDATE_FILED_TREE),
/**
* 保存数据管理中的字段
* */
SAVE_FILED("saveField",OpTypeConst.SAVE_FILED),
/**
* 修改数据管理中的字段
* */
UPDATE_FILED("updateField",OpTypeConst.UPDATE_FILED),
/**
* 修改数据管理中的字段
* */
UPDATE_FILED_STATUS("updateFieldStatus",OpTypeConst.UPDATE_FILED_STATUS),
/**
* 保存字段映射中的字段
* */
SAVE_MAPPING_FILED("saveMappingField",OpTypeConst.SAVE_MAPPING_FILED),
/**
* 修改字段映射中的字段
* */
UPDATE_MAPPING_FILED("updateMappingField",OpTypeConst.UPDATE_MAPPING_FILED),
/**
* 修改字段映射中的字段状态
* */
UPDATE_MAPPING_FILED_STATUS("updateMappingFieldStatus",OpTypeConst.UPDATE_MAPPING_FILED_STATUS),
/**
* 保存黑白名单
* */
SAVE_BLACK_OR_WHITE_LIST("saveBLackOrWhiteList",OpTypeConst.SAVE_BLACK_OR_WHITE_LIST),
/**
* 修改黑白名单
* */
UPDATE_BLACK_OR_WHITE_LIST("updateBLackOrWhiteList",OpTypeConst.UPDATE_BLACK_OR_WHITE_LIST),
/**
* 删除黑白名单
* */
DELETE_BLACK_OR_WHITE_LIST("deleteBLackOrWhiteList",OpTypeConst.DELETE_BLACK_OR_WHITE_LIST),
/**
* 保存黑白名单库
* */
SAVE_BLACK_OR_WHITE_LIST_DB("saveBLackOrWhiteListDB",OpTypeConst.SAVE_BLACK_OR_WHITE_LIST_DB),
/**
* 修改黑白名单库
* */
UPDATE_BLACK_OR_WHITE_LIST_DB("updateBLackOrWhiteListDB",OpTypeConst.UPDATE_BLACK_OR_WHITE_LIST_DB),
/**
* 保存黑白名单库的状态
* */
SAVE_BLACK_OR_WHITE_LIST_DB_STATUS("updateBLackOrWhiteListDBStatus",OpTypeConst.SAVE_BLACK_OR_WHITE_LIST_DB_STATUS),
/**
* 保存知识库或规则管理目录
* */
SAVE_KNOWLEDGE_TREE("saveKnowledgeTree",OpTypeConst.SAVE_KNOWLEDGE_TREE),
/**
* 修改规则知识库或规则管理目录
* */
UPDATE_KNOWLEDGE_TREE("updateKnowledgeTree",OpTypeConst.UPDATE_KNOWLEDGE_TREE),
/**
* 保存规则
* */
SAVE_RULE("saveRule",OpTypeConst.SAVE_RULE),
/**
* 修改规则
* */
UPDATE_RULE("upadteRule",OpTypeConst.UPDATE_RULE),
/**
* 修改规则状态
* */
UPDATE_RULE_STATUS("upadteRuleStatus",OpTypeConst.UPDATE_RULE_STATUS),
/**
* 保存评分卡
* */
SAVE_SCORECARD("saveScorecard",OpTypeConst.SAVE_SCORECARD),
/**
* 修改评分卡
* */
UPDATE_SCORECARD("upadteScorecard",OpTypeConst.UPDATE_SCORECARD),
/**
*修改规则状态
* */
UPDATE_SCORECARD_STATUS("upadteScorecardStatus",OpTypeConst.UPDATE_SCORECARD_STATUS),
/**
*节点重命名
* */
RENAME_NODE("renameNode",OpTypeConst.RENAME_NODE),
/**
*保存节点
* */
SAVE_NODE("saveNode",OpTypeConst.SAVE_NODE),
/**
*修改节点
* */
UPDATE_NODE("updateNode",OpTypeConst.UPDATE_NODE),
/**
*删除节点
* */
DELETE_NODE("deleteNode",OpTypeConst.DELETE_NODE),
/**
*批量删除节点
* */
BATCH_DELETE_NODE("batchDeleteNode",OpTypeConst.BATCH_DELETE_NODE),
/**
*删除节点之间的连线
* */
DELETE_NODE_LINK("beleteNodeLink",OpTypeConst.DELETE_NODE_LINK),
/**
*复制节点
* */
COPY_NODE("copyNode",OpTypeConst.COPY_NODE),
/**
*保存引擎
* */
SAVE_ENGINE("saveEngine",OpTypeConst.SAVE_ENGINE),
/**
*修改引擎
* */
UPDATE_ENGINE("updateEngine",OpTypeConst.UPDATE_ENGINE),
/**
*保存版本
* */
SAVE_VERSION("saveVersion",OpTypeConst.SAVE_VERSION),
/**
*修改版本
* */
UPDATE_VERSION("updateVersion",OpTypeConst.UPDATE_VERSION),
/**
*删除版本
* */
DELETE_VERSION("deleteVersion",OpTypeConst.DELETE_VERSION),
/**
* 引擎部署
* */
ENGINDE_DEPLOY("engineDepoly",OpTypeConst.ENGINDE_DEPLOY),
/**
* 引擎停止部署
* */
ENGINDE_UNDEPLOY("engineUndepoly",OpTypeConst.ENGINDE_UNDEPLOY),
/**
* 清空引擎节点
* */
CLEAR_NODE("clearNode",OpTypeConst.CLEAR_NODE),
/**
* 添加引擎引用规则关系
* */
ADD_RULE_QUOTES_REL("addRuleQuotesRel",OpTypeConst.ADD_RULE_QUOTES_REL),
/**
* 批量修改引擎引用规则状态
* */
BATCH_UPDATE_STATUS_FOR_QUOTES_RULE("batchUpadteStatusForQuotesRule",OpTypeConst.BATCH_UPDATE_STATUS_FOR_QUOTES_RULE),
/**
* 添加引擎引用字段关系
* */
ADD_FIELD_QUOTES_REL("addFieldQuotesRel",OpTypeConst.ADD_FIELD_QUOTES_REL),
/**
* 数据填写
* */
FILL_DATA("fillData",OpTypeConst.FILL_DATA);
private String value;
private String type;
private OpTypeEnum(String value, String type)
{
this.value = value;
this.type = type;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}

View File

@@ -0,0 +1,28 @@
package com.fibo.ddp.common.utils.constant;
/**
* Created by niuge on 2021/11/11.
*/
public class RuleInfoConstants {
/**
* 黑名单
*/
public static final String BLACK_LIST = "blacklist";
/**
* 阈值规则
*/
public static final String THRESHOLD = "threshold";
/**
* 互斥规则
*/
public static final String MUTEX = "mutex";
/**
* 合并规则
*/
public static final String MERGE = "merge";
/**
* 拦截规则
*/
public static final String INTERCEPT = "intercept";
}

View File

@@ -0,0 +1,24 @@
package com.fibo.ddp.common.utils.constant;
import java.util.HashSet;
import java.util.Set;
/**
* 服务过滤配置 此处配置的uri都是不需要通过session管理免token传参。
*/
public class ServiceFilterConstant {
private static Set<String> uriSet = new HashSet<String>();
static {
uriSet.add("/Riskmanage/v2/login/login");// 密码登录
uriSet.add("/Riskmanage/v2/datamanage/datamanage/downTemplate");// 指标模板下载
uriSet.add("/Riskmanage/v2/datamanage/listmanage/downTemplate");// 名单库模板下载
uriSet.add("/Riskmanage/v3/analyse/decision");
}
public static boolean isSessionFilter(String uri) {
if (uriSet.contains(uri)) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,8 @@
package com.fibo.ddp.common.utils.constant;
public class StatusConst {
//状态
public static final int STATUS_ENABLED = 1;//启用状态,默认
public static final int STATUS_DEAD = 0;//停用状态
public static final int STATUS_DELETE = -1;//删除状态
}

View File

@@ -0,0 +1,94 @@
package com.fibo.ddp.common.utils.constant;
/**
* @ClassName: SysConstant
* @Description: 系统常量类
*/
public final class SysConstant {
public static final String EMPTY_STRING ="";
public static final String SPACE =" ";
public static final String COMMA =",";
public static final String SEMICOLON =";";
public static final String MINUS ="-";
public static final String UNDERLINE ="_";
public static final String DATA_POINT =".";
public static final String POINT ="\\.";
public static final String COLON =":";
public static final String WN ="// ";
public static final String AT ="@";
public static final String SLASH ="/";
public static final String BACKSLASH ="\\\\";
public static final String YES ="Y";
public static final String NO ="N";
public static final String TRUE ="true";
public static final String FALSE ="false";
public static final String LEFT_BRACKET ="(";
public static final String RIGHT_BRACKET =")";
public static final String ELLIPSIS ="...";
public static final String ESCAPE ="\\";
public static final String EXCLAMATION ="!";
public static final String INFINITY ="";
/**
* 系统统一操作成功码
*/
public static final String SUCCESS_CODE = "200";
/**
* 系统统一操作成功提示信息
*/
public static final String SUCCESS_MESSAGE = "操作成功";
/**
* 系统统一操作失败码
*/
public static final String FAIL_CODE = "500";
/**
* 系统统一操作失败提示信息
*/
public static final String FAIL_MESSAGE = "操作失败";
/**
* 系统统一操作失败码
*/
public static final String UNUSE_CODE = "300";
/**
* 系统统一操作失败提示信息
*/
public static final String UNUSE_MESSAGE = "已停用";
/**
* 系统统一操作失败码
*/
public static final String DEL_CODE = "400";
/**
* 系统统一操作失败提示信息
*/
public static final String DEL_MESSAGE = "已删除";
}

View File

@@ -0,0 +1,23 @@
package com.fibo.ddp.common.utils.constant.enginex;
public enum CallBackTypeEnum {
SYNC(1,"同步"),
ASYNC(2,"异步");
private int code;
private String message;
CallBackTypeEnum(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}

View File

@@ -0,0 +1,25 @@
package com.fibo.ddp.common.utils.constant.enginex;
/**
* 引擎使用常量
*/
public class EngineConst {
/**
* 版本部署待审批状态
*/
public static final int BOOT_STATE_DEPLOY_APPLY = 2;
/**
* 版本部署状态
*/
public static final int BOOT_STATE_DEPLOY = 1;
/**
* 版本未部署状态
*/
public static final int BOOT_STATE_UNDEPLOY = 0;
/**
* 决策选项结果集key
*/
public static final String DECISION_COLLECTION_KEY = "formulaList";
}

View File

@@ -0,0 +1,21 @@
package com.fibo.ddp.common.utils.constant.enginex;
public interface EngineContentConst {
String NODE_LIST_KEY = "nodeList";
String SOURCE_ID = "sourceId";
String Event_Dispose = "eventDispose";
interface DataFlowEngine{
String NODE_TYPE = "nodeType";
interface NodeType{
String BEGIN = "begin";
String WHERE = "where";
String OR = "or";
String WITHIN = "within";
String NEXT = "next";
String FOLLOWED_BY = "followedBy";
String ONE_OR_MORE = "oneOrMore";
String TIMES = "times";
String TIMES_OR_MORE = "timesOrMore";
}
}
}

View File

@@ -0,0 +1,34 @@
package com.fibo.ddp.common.utils.constant.enginex;
public class EngineMsg {
/**
* 部署成功
*/
public static final int STATUS_SUCCESS = 1;
/**
* 部署待审批
*/
public static final int STATUS_WAIT = 2;
public static final String DEPLOY_WAIT = "部署待审批";
public static final String DEPLOY_SUCCESS = "部署成功!";
public static final String UNDEPLOY_SUCCESS = "当前版本已停用!";
/**
* 部署失败
*/
public static final int STATUS_FAILED = 0;
public static final String DEPLOY_FAILED = "部署失败!";
public static final String UNDEPLOY_FAILED = "停用当前版本失败!";
public static final String DELETE_RUNNING_FAILED = "当前版本正在运行,不能删除!";
public static final String DELETE_VERSION_SUCCESS = "当前版本删除成功!";
public static final String DELETE_VERSION_FAILED = "未知异常,当前版本删除失败!";
}

View File

@@ -0,0 +1,153 @@
package com.fibo.ddp.common.utils.constant.enginex;
/**
* 解析器可用的算法和符号
*/
public class EngineOperator {
/*---------------------------- 关系运算符 ----------------------------*/
public static final String OPERATOR_AND_RELATION = "&&";
public static final String OPERATOR_OR_RELATION = "||";
public static final String OPERATOR_NOT_RELATION = "!";
public static final String OPERATOR_EQUALS_RELATION = "==";
public static final String OPERATOR_GREATER_RELATION = ">";
public static final String OPERATOR_GREATER_EQUALS_RELATION = ">=";
public static final String OPERATOR_LESS_RELATION = "<";
public static final String OPERATOR_LESS_EQUALS_RELATION = "<=";
public static final String OPERATOR_NOT_EQUALS_RELATION = "!=";
public static final String OPERATOR_AND_STRING_RELATION = "AND";
public static final String OPERATOR_OR_STRING_RELATION = "OR";
/*---------------------------- 数学运算符 ----------------------------*/
public static final String OPERATOR_ADD_MATH = "+";
public static final String OPERATOR_MINUS_MATH = "-";
public static final String OPERATOR_MULITI_MATH = "*";
public static final String OPERATOR_DIVIDE_MATH = "/";
public static final String OPERATOR_MODULU_MATH = "%";
public static final String OPERATOR_ABS_MATH = "abs";
public static final String OPERATOR_ACOS_MATH = "acos";
public static final String OPERATOR_ASIN_MATH = "asin";
public static final String OPERATOR_ATAN_MATH = "atan";
public static final String OPERATOR_ATAN2_MATH = "atan2";
public static final String OPERATOR_AVERAGE_MATH = "avg";
public static final String OPERATOR_CEIL_MATH = "ceil";
public static final String OPERATOR_COS_MATH = "cos";
public static final String OPERATOR_EXP_MATH = "exp";
public static final String OPERATOR_FLOOR_MATH = "floor";
public static final String OPERATOR_IEEE_MATH = "IEEEremainder";
public static final String OPERATOR_LN_MATH = "ln";
public static final String OPERATOR_LOG_MATH = "log";
public static final String OPERATOR_MAX_MATH = "max";
public static final String OPERATOR_MIN_MATH = "min";
public static final String OPERATOR_POW_MATH = "pow";
public static final String OPERATOR_RANDOM_MATH = "random";
public static final String OPERATOR_RINT_MATH = "rint";
public static final String OPERATOR_ROUND_MATH = "round";
public static final String OPERATOR_SIN_MATH = "sin";
public static final String OPERATOR_SQRT_MATH = "sqrt";
public static final String OPERATOR_SUM_MATH = "sum";
public static final String OPERATOR_TAN_MATH = "tan";
public static final String OPERATOR_TODEGREES_MATH = "toDegrees";
public static final String OPERATOR_TORADIANS_MATH = "toRadians";
/*---------------------------- 字符串运算符 ----------------------------*/
public static final String OPERATOR_CHARAT_STRING = "charAt";
public static final String OPERATOR_COMPARE_STRING = "compareTo";
public static final String OPERATOR_CTIC_STRING = "compareToIgnoreCase";
public static final String OPERATOR_CONCAT_STRING = "concat";
public static final String OPERATOR_ENDSWITH_STRING = "endsWith";
public static final String OPERATOR_EIC_STRING = "equalsIgnoreCase";
public static final String OPERATOR_EVAL_STRING = "eval";
public static final String OPERATOR_INDEXOF_STRING = "indexOf";
public static final String OPERATOR_LASTINDEXOF_STRING = "lastIndexOf";
public static final String OPERATOR_LENGTH_STRING = "length";
public static final String OPERATOR_REPLACE_STRING = "replace";
public static final String OPERATOR_STARTSWITH_STRING = "startsWith";
public static final String OPERATOR_SUB_STRING = "substring";
public static final String OPERATOR_TLC_STRING = "toLowerCase";
public static final String OPERATOR_TUC_STRING = "toUpperCase";
public static final String OPERATOR_TRIM_STRING = "trim";
public static final String OPERATOR_CONTAINS_STRING = "contains";
public static final String OPERATOR_UNCONTAINS_STRING = "notContains";
public static final String OPERATOR_EQUALS_STRING = "equals";
public static final String OPERATOR_UNEQUALS_STRING = "notEquals";
/*---------------------------- 符号 ----------------------------*/
public static final String OPERATOR_LEFT_BRACE = "{";
public static final String OPERATOR_RIGHT_BRACE = "}";
public static final String OPERATOR_VARIABLE_LEFT = "#"+OPERATOR_LEFT_BRACE;
public static final String OPERATOR_VARIABLE_RIGHT = "}";
public static final String OPERATOR_LEFT_PARENTHESES = "(";
public static final String OPERATOR_RIGHT_PARENTHESES = ")";
public static final String OPERATOR_LEFT_BRACKET = "[";
public static final String OPERATOR_RIGHT_BRACKET = "]";
}

View File

@@ -0,0 +1,15 @@
package com.fibo.ddp.common.utils.constant.enginex;
public class EngineTypeConst {
public static final String RULE_ENGINE = "rule_engine";
public static final String RISK_CONTROL_ENGINE = "risk_control_engine";
public static final String DATA_FLOW_ENGINE = "data_flow_engine";
public static final String PERSONAS_ENGINE = "personas_engine";
public static final String MARKETING_ENGINE = "marketing_engine";
public static final String WARNING_ENGINE = "warning_engine";
public static final String SCORING_ENGINE = "scoring_engine";
public static final String LOGIC_ENGINE = "logic_engine";
public static final String QUESTIONNAIRE_ENGINE = "questionnaire_engine";
public static final String PAGE_ENGINE = "page_engine";
public static final String MATCHING_ENGINE = "matching_engine";
}

View File

@@ -0,0 +1,49 @@
package com.fibo.ddp.common.utils.constant.enginex;
/**
* 枚举使用到的常量
*/
public class EnumConst {
public static final String NODE_START = "开始";
public static final String NODE_POLICY = "规则集";
public static final String NODE_CLASSIFY = "分组";
public static final String NODE_SCORECARD = "评分卡";
public static final String NODE_BLACK = "名单库";//原黑名单改为名单库
public static final String NODE_WHITE = "白名单";
public static final String NODE_SANDBOX = "分流";
public static final String NODE_CREDIT_LEVEL = "信用评级";
public static final String NODE_DECISION = "决策选项";
public static final String NODE_QUOTA_CALC = "额度计算";
public static final String NODE_REPORT = "报表分析";
public static final String NODE_CUSTOMIZE = "自定义按钮";
public static final String NODE_COMPLEXRULE = "复杂规则";
public static final String NODE_CHILD_ENGINE = "子引擎";
public static final String NODE_MODEL_ENGINE = "模型";
public static final String NODE_DECISION_TABLES = "决策表";
public static final String NODE_DECISION_TREE = "决策树";
public static final String NODE_RPC = "远程调用";
public static final String NODE_PARALLEL = "并行";
public static final String NODE_AGGREGATION = "聚合";
public static final String NODE_CHAMPION_CHALLENGE= "冠军挑战";
}

View File

@@ -0,0 +1,123 @@
package com.fibo.ddp.common.utils.constant.enginex;
public enum NodeTypeEnum {
/**
* 开始节点
*/
START(1, EnumConst.NODE_START),
/**
* 规则节点
*/
POLICY(2,EnumConst.NODE_POLICY),
/**
* 分组节点
*/
CLASSIFY(3, EnumConst.NODE_CLASSIFY),
/**
* 评分卡节点
*/
SCORECARD(4,EnumConst.NODE_SCORECARD),
/**
* 黑名单节点
*/
BLACKLIST(5,EnumConst.NODE_BLACK),
/**
* 白名单节点
*/
WHITELIST(6,EnumConst.NODE_WHITE),
/**
* 分流节点
*/
SANDBOX(7,EnumConst.NODE_SANDBOX),
/**
* 信用评级节点
*/
CREDITLEVEL(8,EnumConst.NODE_CREDIT_LEVEL),
/**
* 决策选项节点
*/
DECISION(9,EnumConst.NODE_DECISION),
/**
* 额度计算节点
*/
QUOTACALC(10,EnumConst.NODE_QUOTA_CALC),
/**
* 报表分析节点
*/
REPORT(11,EnumConst.NODE_REPORT),
/**
* 自定义节点
*/
CUSTOMIZE(12,EnumConst.NODE_CUSTOMIZE),
/**
* 复杂规则
*/
NODE_COMPLEXRULE(13,EnumConst.NODE_COMPLEXRULE),
/**
* 子引擎
*/
CHILD_ENGINE(14,EnumConst.NODE_CHILD_ENGINE),
/**
* 模型
*/
MODEL_ENGINE(15,EnumConst.NODE_MODEL_ENGINE),
/**
* 决策表
*/
DECISION_TABLES(16,EnumConst.NODE_DECISION_TABLES),
/**
* 决策树
*/
DECISION_TREE(17,EnumConst.NODE_DECISION_TREE),
/**
* 远程调用
*/
RPC(18, EnumConst.NODE_RPC),
/**
* 并行节点
*/
PARALLEL(19, EnumConst.NODE_PARALLEL),
/**
* 聚合节点
*/
AGGREGATION(20, EnumConst.NODE_AGGREGATION),
/**
* 冠军挑战节点
*/
CHAMPION_CHALLENGE(21, EnumConst.NODE_CHAMPION_CHALLENGE);
private int value;
private String type;
private NodeTypeEnum(int value, String type)
{
this.value = value;
this.type = type;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public static NodeTypeEnum adapad(int value) {
for (NodeTypeEnum nodeTypeEnum : NodeTypeEnum.values()) {
if (nodeTypeEnum.getValue() == value) {
return nodeTypeEnum;
}
}
return null;
}
}

View File

@@ -0,0 +1,233 @@
package com.fibo.ddp.common.utils.constant.monitor;
/**
* 常量定义
*/
public class Constants {
/**
*<h2> UserInfo hbase table</h2>
*/
public class UserInfoTable{
/**
* 表名
*/
public static final String TABLE_NAME = "user_info";
/**
*基本信息列族
*/
public static final String FAMILY_BASE_INFO="base_info";
/**
* 列
*/
public static final String BASEINFO="baseInfo";
}
/**
*<h2> monitor_decision_flow hbase table</h2>
* 决策流监控
*/
public class MonitorDecisionFlow{
/**
* 表名
*/
public static final String TABLE_NAME = "monitor_decision_flow";
/**
*决策流监控信息(列族)
*/
public static final String MONITOR_INFO = "monitor_info";
/**
*入参
*/
public static final String PARAMS = "params";
/**
* 快照
*/
public static final String SNAPSHOT = "snapshot";
/**
* 执行过程
*/
public static final String PROCESS = "process";
/**
* 决策流基本信息
*/
public static final String BASE_INFO = "base_info";
/**
* 业务id
*/
public static final String BUSINESS_ID = "business_id";
/**
*决策流名称
*/
public static final String ENGINE_NAME = "engine_name";
/**
* 决策流版本id
*/
public static final String ENGINE_VERSION_ID = "engine_version_id";
/**
* 引擎版本信息
*/
public static final String ENGINE_INFO = "engine_info";
}
/**
*<h2> monitor_node hbase table</h2>
* 节点监控
*/
public class MonitorNode{
/**
* 表名
*/
public static final String TABLE_NAME = "monitor_node";
/**
*节点监控信息(列族)
*/
public static final String MONITOR_INFO = "monitor_info";
/**
*入参
*/
public static final String PARAMS = "params";
/**
* 快照
*/
public static final String SNAPSHOT = "snapshot";
/**
* 节点输出结果
*/
public static final String RESULT = "result";
/**
* 节点基本信息
*/
public static final String BASE_INFO = "base_info";
/**
* 业务id
*/
public static final String BUSINESS_ID = "business_id";
/**
*节点名称
*/
public static final String NODE_ID = "node_id";
/**
*节点名称
*/
public static final String NODE_NAME = "node_name";
/**
* 节点类型
*/
public static final String NODE_TYPE = "node_type";
/**
* 节点基本信息
*/
public static final String NODE_INFO = "node_info";
/**
* 决策流版本id
*/
public static final String ENGINE_VERSION_ID = "engine_version_id";
/**
* 引擎版本信息
*/
public static final String ENGINE_INFO = "engine_info";
}
/**
*<h2> monitor_strategy hbase table</h2>
* 策略监控
*/
public class MonitorStrategy{
/**
* 表名
*/
public static final String TABLE_NAME = "monitor_strategy";
/**
*策略监控信息(列族)
*/
public static final String MONITOR_INFO = "monitor_info";
/**
*入参
*/
public static final String PARAMS = "params";
/**
* 快照
*/
public static final String SNAPSHOT = "snapshot";
/**
* 策略输出结果
*/
public static final String RESULT = "result";
/**
* 策略基本信息
*/
public static final String BASE_INFO = "base_info";
/**
* 业务id
*/
public static final String BUSINESS_ID = "business_id";
/**
*策略id
*/
public static final String STRATEGY_ID = "strategy_id";
/**
*策略名称
*/
public static final String STRATEGY_NAME = "strategy_name";
/**
*策略类型
*/
public static final String STRATEGY_TYPE = "strategy_type";
/**
*节点id
*/
public static final String NODE_ID = "node_id";
/**
*节点类型
*/
public static final String NODE_TYPE = "node_type";
/**
* 决策流版本id
*/
public static final String ENGINE_VERSION_ID = "engine_version_id";
}
/**
*<h2> monitor_strategy hbase table</h2>
* 全量指标记录
*/
public class RunnerFeatureRecord{
/**
* 表名
*/
public static final String TABLE_NAME = "runner_feature_record";
/**
*执行前指标集合(列族)
*/
public static final String BEFORE_FEATURE = "before_feature";
/**
*执行后指标集合(列族)
*/
public static final String AFTER_FEATURE = "after_feature";
/**
* 基本信息(列族)
*/
public static final String BASE_INFO = "base_info";
/**
* 业务id
*/
public static final String BUSINESS_ID = "business_id";
/**
*引擎id
*/
public static final String ENGINE_ID = "engine_id";
/**
*引擎名称
*/
public static final String ENGINE_NAME = "engine_name";
/**
*组织id
*/
public static final String ORGAN_ID = "organ_id";
/**
* 决策流版本id
*/
public static final String ENGINE_VERSION_ID = "engine_version_id";
}
}

View File

@@ -0,0 +1,9 @@
package com.fibo.ddp.common.utils.constant.monitor;
public class MonitorStorageType {
/**
* 监控中心数据存储类型
*/
public static final String Mysql = "mysql";
public static final String HBase = "hbase";
}

View File

@@ -0,0 +1,16 @@
package com.fibo.ddp.common.utils.constant.monitor;
public class RowKeyUtil {
/**
* Long.MAX_VALUE - lastUpdate 得到的值再补齐20位
* @param lastUpdate
* @return
*/
public static String formatLastUpdate(long lastUpdate){
if(lastUpdate<0){
lastUpdate = 0;
}
long diff = Long.MAX_VALUE - lastUpdate;
return String.format("%0"+20+"d",diff);
}
}

View File

@@ -0,0 +1,8 @@
package com.fibo.ddp.common.utils.constant.runner;
public class ParamTypeConst {
public static final int CONSTANT = 1;
public static final int VARIABLE = 2;
public static final int CUSTOM = 3;
public static final int REGEX = 4;
}

View File

@@ -0,0 +1,19 @@
package com.fibo.ddp.common.utils.constant.strategyx;
public class CondConst {
public static final long DEFAULT_CONDITION_PARENT_ID = 0;//根节点父ID
public static class CondType{
public static final int RELATION_CONDITION_TYPE = 1;//关系节点类型
public static final int EXPRESSION_CONDITION_TYPE = 2;//表达式节点类型
public static final int LOOP_RULE_ROOT = 3 ;//循环规则的根节点
public static final int LOOP_RULE_RESULT_CONDITION = 4;//循环规则的结果条件
public static final int CONDITION_GROUP_ROOT = 5;//条件组的根节点
public static final int CONDITION_GROUP_RESULT_CONDITION = 6;//条件组的结果条件
}
public static class CondLogic{
public static final String LOOP_RULE_LOGICAL = "for";//循环规则的逻辑符号
public static final String CONDITION_GROUP_LOGICAL = "condGroup";//条件组的逻辑符号
}
}

View File

@@ -0,0 +1,13 @@
package com.fibo.ddp.common.utils.constant.strategyx;
public class DecisionTablesDetailConst{
public static final String LEFT_DETAIL_NAME = "left";
public static final int LEFT_DETAIL_NUM = 1;
public static final String TOP_DETAIL_NAME = "top";
public static final int TOP_DETAIL_NUM = 2;
public static final long ROOT_PARENT_ID = 0;
}

View File

@@ -0,0 +1,73 @@
package com.fibo.ddp.common.utils.constant.strategyx;
import java.util.UUID;
public class DecisionTablesRunnerConst {
public static final String DECISION_FILE_HEAD = " package com.baoying.enginex.executor.drools \\r\\n" +
" import java.util.Map;\\r\\n" +
" import java.util.List;\\r\\n" +
" import java.util.ArrayList;\\r\\n" +
" import java.util.HashMap;\\r\\n" +
" import com.baoying.enginex.executor.engine.model.InputParam;\\r\\n" +
" import com.baoying.enginex.executor.engine.model.Result;\\r\\n" +
" import com.baoying.enginex.executor.engine.model.EngineRule;\\r\\n";
public static final String RULE_NAME_PREFIX = " rule \t";
public static final String RULE_SALIENCE_PREFIX = "\\r\\n salience\\t ";
public static final String RULE_CONDITION_PREFIX = "\\r\\n when \\r\\n";
public static final String CONDITION_DETAIL_PREFIX = "\\t $inputParam : InputParam();\\r\\n Map";
public static final String CONDITION_DETAIL_SUFFIX = " \t from $inputParam.inputParam;\\r\\n";
public static final String RULE_DISPOSE_PREFIX = "\\t then \\r\\n";
public static final String DISPOSE_PREFIX =
"\\t List<Result> resultList =$inputParam.getResult();\\r\\n" +
"\\t Result result =new Result(); \\r\\n" +
"\\t result.setResultType(\"";
public static final String DISPOSE_INFIX = "\"); \\r\\n" +
"\\t result.setVersionCode(\"";
public static final String DISPOSE_SUFFIX = "\"); \\r\\n" +
"\\t Map<String, Object> map =new HashMap<>(); \\r\\n";
public static final String HIT_RESULT = "\\t map.put(\"result\",true); \\r\\n";
public static final String RULE_END = "\\t result.setMap(map); \\r\\n" +
" resultList.add(result); \\r\\n" +
"\\t $inputParam.setResult(resultList); \\r\\n" +
" end\\r\\n";
public static final int DEFAULT_TYPE = 1;
//拼装规则执行的content
public static String fitContent(String condition) {
String content = "";
String name = "decisionTables"+UUID.randomUUID().toString().replace("-", "");
content += DECISION_FILE_HEAD +
RULE_NAME_PREFIX + name +
RULE_SALIENCE_PREFIX + 10 +
RULE_CONDITION_PREFIX +
CONDITION_DETAIL_PREFIX + condition +
CONDITION_DETAIL_SUFFIX +
RULE_DISPOSE_PREFIX +
DISPOSE_PREFIX + DEFAULT_TYPE +
DISPOSE_INFIX + name +
DISPOSE_SUFFIX;
content += HIT_RESULT + RULE_END;
return content;
}
// public static void main(String[] args) {
// String versionCode = "rule1";
// Integer salience = null;
// String rule = "age>10";
// Integer type = null;
// Integer score = 10;
// Map<String,String> contentMap = new HashMap<>();
// contentMap.put("a","a");
// contentMap.put("b","b");
// contentMap.put("c","c");
// String s = fitContent(versionCode, salience, rule, type, score,contentMap);
// System.out.println(s);
// }
}

View File

@@ -0,0 +1,30 @@
package com.fibo.ddp.common.utils.constant.strategyx;
/**
* ClassName:ExcelHeader <br/>
* Description: Excel表头配置. <br/>
*/
public class ExcelHeader {
/**
* 规则表头名称
* */
public static final String[] RULE_HEADER = {"规则名称","规则代码","规则描述","优先级","条件","输出"};
/**
* 规则表头对应属性名称
* */
public static final String[] RULE_ClASS = {"name","versionCode","description","priority","fieldContent","content"};
/**
* 评分卡表头名称
* */
public static final String[] SCORECARD_HEADER = {"评分卡名称","评分卡代码","评分卡描述","版本号","指标详情","评分卡规则内容"};
/**
* 评分卡表头对应属性名称
* */
public static final String[] SCORECARD_ClASS = {"name","versionCode","description","version","fieldContent","content"};
}

View File

@@ -0,0 +1,17 @@
package com.fibo.ddp.common.utils.constant.strategyx;
public class RuleConditionConst {
public static final long DEFAULT_CONDITION_PARENT_ID = 0;//根节点父ID
public static final int RELATION_CONDITION_TYPE = 1;//关系节点类型
public static final int EXPRESSION_CONDITION_TYPE = 2;//表达式节点类型
public static final String LOOP_RULE_LOGICAL = "for";//循环规则的逻辑符号
public static final int LOOP_RULE_ROOT = 3;//循环规则的根节点
public static final int LOOP_RULE_RESULT_CONDITION = 4;//循环规则的结果条件
public static final String CONDITION_GROUP_LOGICAL = "condGroup";//循环规则的逻辑符号
public static final int CONDITION_GROUP_ROOT = 5;//循环规则的根节点
public static final int CONDITION_GROUP_RESULT_CONDITION = 6;//循环规则的结果条件
}

View File

@@ -0,0 +1,42 @@
package com.fibo.ddp.common.utils.constant.strategyx;
public class RuleConst {
public static final int STATUS_ENABLED = 1;//启用状态,默认
public static final int STATUS_DEAD = 0;//停用状态
public static final int STATUS_DELETE = -1;//删除状态
public static final int TYPE_SYSTEM = 0;//系统规则
public static final int TYPE_ORGAN = 1;//组织规则,默认
public static final int TYPE_ENGINE = 2;//引擎规则
public static final int RULE_TYPE_TERMINATION = 0;//终止
public static final int RULE_TYPE_SCORING = 1;//计分
public static final int RULE_AUDIT_TERMINATION = 2;//终止
public static final int RULE_AUDIT_SCORING = 5;//继续
// runner
public static final int CONST_TYPE = 1;//常量
public static final int VARIABLE_TYPE = 2;//变量
public static final int RELATION_CONDITION = 1;//关系节点表示&&或者||
public static final int EXPRESSION_CONDITION = 2;//表达式条件
public static final int LOOP_CONDITION = 3;//循环条件
public static final int LOOP_RESULT_CONDITION = 4;//循环规则条件
public static final int CONDITION_GROUP_CONDITION = 5;//条件组节点
public static final int CONDITION_RESULT_CONDITION = 6;//条件组节点
public static final int LOOP_GROUP_ACTION_TYPE_SUM = 1;//循环中求和
public static final int LOOP_GROUP_ACTION_TYPE_ASSIGNMENT = 2;//赋值
public static final int LOOP_GROUP_ACTION_TYPE_OUT_VARIABLE = 3;//输出变量
public static final int LOOP_GROUP_ACTION_TYPE_OUT_CONST = 4;//输出常量
public static class ScriptType {
public static final String GROOVY = "groovy";
public static final String PYTHON = "python";
public static final String JAVASCRIPT = "js";
}
}

View File

@@ -0,0 +1,86 @@
package com.fibo.ddp.common.utils.constant.strategyx;
import java.util.Map;
public class RuleRunnerConst {
public static final String RULE_FILE_HEAD = " package com.baoying.enginex.executor.drools \\r\\n" +
" import java.util.Map;\\r\\n" +
" import java.util.List;\\r\\n" +
" import java.util.ArrayList;\\r\\n" +
" import java.util.HashMap;\\r\\n" +
" import com.baoying.enginex.executor.engine.model.InputParam;\\r\\n" +
" import com.baoying.enginex.executor.engine.model.Result;\\r\\n" +
" import com.baoying.enginex.executor.engine.model.EngineRule;\\r\\n";
public static final String RULE_NAME_PREFIX = " rule \t";
public static final String RULE_SALIENCE_PREFIX = "\\r\\n salience\\t ";
public static final String RULE_CONDITION_PREFIX = "\\r\\n when \\r\\n";
public static final String CONDITION_DETAIL_PREFIX = "\\t $inputParam : InputParam();\\r\\n Map";
public static final String CONDITION_DETAIL_SUFFIX = " \t from $inputParam.inputParam;\\r\\n";
public static final String RULE_DISPOSE_PREFIX = "\\t then \\r\\n";
public static final String DISPOSE_PREFIX =
"\\t List<Result> resultList =$inputParam.getResult();\\r\\n" +
"\\t Result result =new Result(); \\r\\n" +
"\\t result.setResultType(\"";
public static final String DISPOSE_INFIX = "\"); \\r\\n" +
"\\t result.setVersionCode(\"";
public static final String DISPOSE_SUFFIX = "\"); \\r\\n" +
"\\t Map<String, Object> map =new HashMap<>(); \\r\\n";
public static final String SCORE_PREFIX = "\\t map.put(\"score\",";
public static final String SCORE_SUFFIX = "); \\r\\n";
public static final String RULE_END = "\\t result.setMap(map); \\r\\n" +
" resultList.add(result); \\r\\n" +
"\\t $inputParam.setResult(resultList); \\r\\n" +
" end\\r\\n";
public static final int DEFAULT_TYPE = 1;
//拼装规则执行的content
public static String fitRuleContent(String code, Integer salience, String rule, Integer type, Integer score, Map<String,String> contentMap) {
String content = "";
if (salience == null || salience < 0) {
salience = 0;
}
if (type == null) {
type = DEFAULT_TYPE;
}
content += RULE_FILE_HEAD +
RULE_NAME_PREFIX + code +
RULE_SALIENCE_PREFIX + salience +
RULE_CONDITION_PREFIX +
CONDITION_DETAIL_PREFIX + rule +
CONDITION_DETAIL_SUFFIX +
RULE_DISPOSE_PREFIX +
DISPOSE_PREFIX + type +
DISPOSE_INFIX + code+
DISPOSE_SUFFIX;
if (score!=null){
content += SCORE_PREFIX+score+SCORE_SUFFIX;
}
if (contentMap!=null&&!contentMap.isEmpty()){
for (String s : contentMap.keySet()) {
content+="\\t\\t map.put(\""+s+"\",\""+contentMap.get(s)+"\");\\n";
}
}
content += RULE_END;
return content;
}
// public static void main(String[] args) {
// String versionCode = "rule1";
// Integer salience = null;
// String rule = "age>10";
// Integer type = null;
// Integer score = 10;
// Map<String,String> contentMap = new HashMap<>();
// contentMap.put("a","a");
// contentMap.put("b","b");
// contentMap.put("c","c");
// String s = fitContent(versionCode, salience, rule, type, score,contentMap);
// System.out.println(s);
// }
}

View File

@@ -0,0 +1,35 @@
package com.fibo.ddp.common.utils.constant.strategyx;
/**
* ClassName:ExcelHeader <br/>
* Description: 通用状态. <br/>
*/
public class Status {
/**
* 启用
* */
public static final int ENABLED = 1;
/**
* 停用
* */
public static final int DISABLE =0;
/**
* 删除
* */
public static final int DELETE =-1;
/**
* 输出
* */
public static final int IS_OUTPUT =1;
/**
* 不输出
* */
public static final int IS_NOT_OUTPUT =0;
}

View File

@@ -0,0 +1,17 @@
package com.fibo.ddp.common.utils.constant.strategyx;
public class StrategyType {
public static final String DECISION_TABLES = "decision_tables";//决策表
public static final String DECISION_TREE = "decision_tree";//决策树
public static final String SCORECARD = "scorecard";//评分卡
public static final String LIST_DB = "list_db";//名单库
public static final String MODELS = "models";//模型
public static final String COMPLEX_RULE = "complex_rule";//复杂规则
public static final String BASE_RULE = "base_rule";//基础规则
public static class OutType{
public static final String SUCCESS_OUT = "success";//成功时输出
public static final String FAIL_OUT = "fail";//失败时输出
}
}

View File

@@ -0,0 +1,44 @@
package com.fibo.ddp.common.utils.constant.strategyx;
/**
* ClassName:ExcelHeader <br/>
* Description: 通用类型. <br/>
* @see
*/
public class Type {
/**
* 系统的
* */
public static final int SYSTEMATIC =0;
/**
* 组织的
* */
public static final int ORGANIZATIONAL =1;
/**
* 引擎的
* */
public static final int ENGINE =2;
/**
* 树类型为规则集
* */
public static final int RULE_TREE =0;
/**
* 树类型为评分卡
* */
public static final int SCORECARD_TREE =0;
/**
* 树类型为回收站
* */
public static final int RECYCLE_TREE =0;
/**
* 知识库映射类型
*/
public static final int POLICY = 1;
public static final int SCORECARD = 2;
}

View File

@@ -0,0 +1,53 @@
package com.fibo.ddp.common.utils.exception;
/**
* 自定义异常消息处理
*/
public class ApiException extends RuntimeException {
private static final long serialVersionUID = 1136843834946392402L;
/**
* 异常编码
*/
public final String errCode;
/**
* 异常消息
*/
public final String message;
/**
* data
*/
public final Object data;
public ApiException(Throwable e) {
super(e);
errCode = "";
message = "";
data = null;
}
public ApiException(String errCode, String message) {
super(message);
this.errCode = errCode;
this.message = message;
this.data = null;
}
public ApiException(String errCode, String message, Object data) {
super(message);
this.errCode = errCode;
this.message = message;
this.data = data;
}
public ApiException(String errCode, String message, Throwable e) {
super(message, e);
this.errCode = errCode;
this.message = message;
this.data = null;
}
}

View File

@@ -0,0 +1,104 @@
package com.fibo.ddp.common.utils.util;
import java.util.*;
public class CollectionUtil {
/**
* 集合判非空
*
* @param collection
* @return
*/
public static boolean isNotNullOrEmpty(Collection<?> collection) {
if (null == collection || collection.isEmpty()){
return false;
}
return true;
}
/**
* map判非空
*
* @param map
* @return
*/
public static boolean isNotNullOrEmpty(Map<?, ?> map) {
if (null == map || map.isEmpty()){
return false;
}
return true;
}
/**
* 获取多个集合并集
* @param list
* @return
*/
public static Set<Object> getUnion(List<List<Object>> list) {
Set<Object> set = new HashSet<Object>();
if (list == null) {
list = new ArrayList<List<Object>>();
}
int size = list.size();
if (size > 1) {
for (int i = 0; i < size; i++) {
int j = i + 1;
if (j < size) {
list.get(0).removeAll(list.get(j));
list.get(0).addAll(list.get(j));
if (i == size - 2) {
List<Object> resultList = list.get(0);
for (Object result : resultList) {
set.add(result);
}
}
}
}
} else {
// 只有一个集合则直接插入结果
for (List<Object> subList : list) {
for (Object result : subList) {
set.add(result);
}
}
}
return set;
}
/**
* 获取多个集合交集
* @param list
* @return
*/
public static Set<Object> getIntersection(List<List<Object>> list) {
Set<Object> set = new HashSet<Object>();
int size = list.size();
if (size > 1) {
// 集合个数大于1取交集
for (int i = 0; i < size; i++) {
int j = i + 1;
if (j < size) {
list.get(0).retainAll(list.get(j));
if (i == size - 2) {
List<Object> resultList = list.get(0);
for (Object result : resultList) {
set.add(result);
}
}
}
}
} else {
// 只有一个集合则不取交集
for (List<Object> subList : list) {
for (Object result : subList) {
set.add(result);
}
}
}
return set;
}
}

View File

@@ -0,0 +1,40 @@
package com.fibo.ddp.common.utils.util;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DataHelp {
public static int day=0;
public static String getNowDate(){
Date date = new Date();
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = simple.format(date);
return s;
}
public static String getEndDate(){
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.add(Calendar.DATE, + DataHelp.day);
Date monday = c.getTime();
String s = simple.format(monday);
return s;
}
public static String getNowDateString(){
Date date = new Date();
SimpleDateFormat simple = new SimpleDateFormat("yyyyMMddHHmmss");
String s = simple.format(date);
return s;
}
public static String getDay(){
Date date = new Date();
SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
String s = simple.format(date);
return s;
}
public static void main(String[] args) {
System.out.println(getNowDate());
System.out.println(getNowDateString());
}
}

View File

@@ -0,0 +1,37 @@
package com.fibo.ddp.common.utils.util;
import javax.servlet.http.HttpServletRequest;
public class RequestUtil {
/**
* 获取客户端IP, 考虑web server代理
*
* @param request
* @return
*/
public static String getClientIP(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null&&ip.indexOf(',') > 0) {
ip = ip.substring(0, ip.indexOf(',')).trim();
}
return ip;
}
}

View File

@@ -0,0 +1,16 @@
package com.fibo.ddp.common.utils.util;
import com.github.pagehelper.PageInfo;
import java.util.HashMap;
import java.util.Map;
public class ResponseUtil {
public static Map<String,Object> getResponseMap(PageInfo pageInfo){
HashMap<String, Object> responseMap = new HashMap<>();
responseMap.put("pageInfo",pageInfo);
responseMap.put("klist",pageInfo.getList());
pageInfo.setList(null);
return responseMap;
}
}

View File

@@ -0,0 +1,42 @@
package com.fibo.ddp.common.utils.util;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Random;
@Component
@Slf4j
public class SnowFlakUtil {
// @JsonFormat(shape = JsonFormat.Shape.STRING)
private static long workerId = 1;//为终端ID
private static long datacenterId = 1;//数据中心ID
private static Snowflake snowflake;
@PostConstruct
public void init() {
try {
workerId = NetUtil.ipv4ToLong(NetUtil.getLocalhostStr()) % 32;
}catch (Exception e){
workerId = (1+new Random().nextInt(30));
}
log.info("当前机器的workId:{}", workerId);
snowflake = IdUtil.createSnowflake(workerId, datacenterId);
}
public static synchronized long snowflakeId() {
return snowflake.nextId();
}
public static synchronized String snowflakeIdStr() {
return snowflake.nextId() + "";
}
public static synchronized long snowflakeId(long workerId, long datacenterId) {
Snowflake snowflake = IdUtil.createSnowflake(workerId, datacenterId);
return snowflake.nextId();
}
}

View File

@@ -0,0 +1,465 @@
package com.fibo.ddp.common.utils.util;
import com.fibo.ddp.common.utils.constant.SysConstant;
import java.math.BigDecimal;
import java.util.*;
/**
* @ClassName: StringUtil
* @Description: String 工具类
*/
public class StringUtil {
/**
* <p>判断是否是有效的字符串,空字符串为无效字符串</p>
*
* @param str
* @return boolean
*/
public static boolean isValidStr(String str) {
return str != null && str.trim().length() > 0;
}
/**
* <p>判断是字符串否是为空,字符串为空,返回 "",反之返回其字符串本身.</p>
*
* <p>if str is null then convret str to "".</p>
*
* @param str
* @return String
*/
public static String convertStrIfNull(String str) {
return str == null ? SysConstant.EMPTY_STRING : str;
}
/**
* <p>根据字符串转换为布尔值.</p>
*
* @param str
* @return boolean
*/
public static boolean getStrToBoolean(String str) {
return isValidStr(str) ? str.toLowerCase().trim().equals(SysConstant.TRUE) : false;
}
/**
* <p>根据字符串转换为 整型int并返回;转换失败则返回0.</p>
*
* <p>convert str dictValue to int. if fail,then return 0.</p>
*
* @param str
* @return int
*/
public static int getStrToInt(String str) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return 0;
}
}
/**
* <p>根据字符串转换为 整型int并返回;转换失败,则返回 指定的值.</p>
*
* <p>convert str dictValue to int. if fail,then return defaultvalue.</p>
*
* @param str
* @param defaultValue
* @return int
*/
public static int getStrToInt(String str, int defaultValue) {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* <p>根据字符串转换为long.</p>
*
* @param str
* @return long
*/
public static long getStrTolong(String str) {
long result = 0;
if (!isValidStr(str)) {
return result;
}
try {
result = Long.parseLong(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
/**
* <p>根据字符串转换为double.</p>
*
* <p>convert String to double</p>
*
* @param str
* @return double
*/
public static double getStrTodouble(String str) {
double result = 0;
if (!isValidStr(str)) {
return result;
}
try {
result = Double.parseDouble(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
/**
* <p>根据字符串转换为BigDecimal.</p>
*
* <p>convert String object to BigDecimal</p>
*
* @param str
* @return BigDecimal
*/
public static BigDecimal getStrToBigDecimal(String str) {
BigDecimal result = new BigDecimal(0);
if (!isValidStr(str)) {
return result;
}
try {
result = new BigDecimal(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
/**
* <p>根据字符串转换为Integer.</p>
*
* <p>convert String to Integer.</p>
*
* @param str
* @return Integer
*/
public static Integer getStrToInteger(String str) {
Integer result = new Integer(0);
if (!isValidStr(str)) {
return result;
}
try {
result = Integer.valueOf(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
/**
* <p>根据字符串转换为Long.</p>
*
* <p>convert String to Long.</p>
*
* @param str
* @return Long
*/
public static Long getStrToLong(String str) {
Long result = new Long(0);
if (!isValidStr(str)) {
return result;
}
try {
result = Long.valueOf(str.trim());
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
/**
* <p>根据字符串转换为Double.</p>
*
* <p>convert String to Double</p>
*
* @param str
* @return Double
*/
public static Double getStrToDouble(String str) {
Double result = new Double(0);
if (!isValidStr(str)) {
return result;
}
try {
result = Double.valueOf(str);
} catch (NumberFormatException e) {
e.printStackTrace();
}
return result;
}
/**
* <p>根据数组转换为字符串,用","拼接.</p>
* <p>例:</p>
* <p>&nbsp;&nbsp;&nbsp;&nbsp;String[] strArray = new String[]{"How","do","you","do"};</p>
* <p>&nbsp;&nbsp;&nbsp;&nbsp;拼接后字符串样例How,do,you,do</p>
*
* <p>convert Object array to String use ",".</p>
*
* @param Object[]
* @return String
*/
public static String getArrToStr(Object[] obj) {
if (obj == null) {
return null;
}
StringBuffer buffer = new StringBuffer();
if (obj.length > 0) {
buffer.append(obj[0]);
}
for (int m = 1; m < obj.length; m++) {
buffer.append(SysConstant.COMMA).append(obj[m]);
}
return buffer.toString();
}
/**
* <p>去掉重复数据(1,2,3,2,4 => 1,2,3,4)</p>
*
* @param metadata
* @param tagStr
* @return String
*/
public static String removeEqualStr(String metadata, String tagStr) {
if (!StringUtil.isValidStr(metadata)) {
return SysConstant.EMPTY_STRING;
}
Set<String> set = new HashSet<String>();
String[] arr = metadata.split(tagStr);
for (String temp : arr) {
if (StringUtil.isValidStr(temp)) {
set.add(temp);
}
}
Iterator<String> it = set.iterator();
StringBuffer returnMetadata = new StringBuffer();
while (it.hasNext()) {
returnMetadata.append(it.next() + tagStr);
}
return returnMetadata.toString().substring(0,returnMetadata.length() - 1);
}
/**
* <p>查询是否有重复数据</p>
*
* @param strArr
* @param str
* @param tagStr
* @return boolean
*/
public static boolean hasEqualStr(String strArr, String str, String tagStr) {
boolean bool = false;
if (StringUtil.isValidStr(strArr)) {
String[] arr = strArr.split(tagStr);
for (String temp : arr) {
if (temp.equals(str)) {
bool = true;
break;
}
}
}
return bool;
}
/**
* <p>根据字符串将其转换编码为UTF-8的字符串.</p>
*
* <p>convert type to utf-8</p>
*
* @param str
* @return utf-8 string
*/
public static String toUtf8String(String str) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c >= 0 && c <= 255) {
sb.append(c);
} else {
byte[] b;
try {
b = Character.toString(c).getBytes("utf-8");
} catch (Exception ex) {
b = new byte[0];
}
for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0)
k += 256;
sb.append("%" + Integer.toHexString(k).toUpperCase());
}
}
}
return sb.toString();
}
/**
* <p>根据字符串指定的位置更新字符串内容</p>
*
* @param formString 被更新字符串
* @param updateIndex 选择更新位数
* @param updateValue 更新为值
*
* @return String
*/
public static String formatIntegrity(String formatString, int updateIndex, char updateValue) {
if (!isValidStr(formatString)) {
return formatString;
}
if (updateIndex < 1) {
return formatString;
}
if (updateIndex > formatString.length()) {
return formatString;
}
char[] formatStringChar = formatString.toCharArray();
formatStringChar[updateIndex] = updateValue;
return String.valueOf(formatStringChar);
}
/**
* <p>转换特殊字符</p>
*
* @param str 含有特殊字符的字符串
*
* @return String
*/
public static String converSpecialChar(String str) {
if (!isValidStr(str)) {
return str;
}
str = str.trim();
if (str.indexOf("\\") >= 0) {
str = str.replaceAll("\\\\", "\\\\\\\\\\\\\\\\");
}
if (str.indexOf("'") >= 0) {
str = str.replaceAll("'", "\\\\'");
}
if (str.indexOf("\"") >= 0) {
str = str.replaceAll("\"", "\\\\\"");
}
if (str.indexOf("%") >= 0) {
str = str.replaceAll("%", "\\\\%");
}
return str;
}
/**
* <p>获取字符串字节长度(包含中文和中文符号)</p>
*
* @param str 含有中文和中文符号的字符串
*
* @return int
*/
public static int getLength(String str){
return str.replaceAll("[\u4E00-\u9FA5\u3000-\u303F\uFF00-\uFFEF]", "rr").length();
}
/**
* <p>此排序方法仅应用于数字类型的string数字排序</p>
*
* @param arrays 有long类型的数字组成的String 数组
* @return 排序后的数组
*/
public static String[] sortArrays(String[] arrays){
for(int i = 0; i < arrays.length - 1; i++) {
String temp ="";
for(int j = 0; j < arrays.length - i - 1; j++) {
if(StringUtil.getStrTolong(arrays[j]) >StringUtil.getStrTolong(arrays[j +1])) {
temp = arrays[j + 1];
arrays[j + 1] = arrays[j];
arrays[j] = temp;
}
}
}
return arrays;
}
/**
* <p>此排序方法仅应用于浮点类型的string数字排序</p>
*
* @param arrays 有浮点类型的数字组成的String 数组
* @return 排序后的数组
*/
public static String[] sortArraystoBigDecimal(String[] arrays) {
for (int i = 0; i < arrays.length - 1; i++) {
String temp = "";
for (int j = 0; j < arrays.length - i - 1; j++) {
if (StringUtil.getStrToBigDecimal(arrays[j]).compareTo(
StringUtil.getStrToBigDecimal(arrays[j + 1])) == 1) {
temp = arrays[j + 1];
arrays[j + 1] = arrays[j];
arrays[j] = temp;
}
}
}
return arrays;
}
/**
*<p>判断字符串是否为NUll或者为空字符</p>
* @param str 字符串
* @return boolean
* */
public static boolean isBlank(String str){
if(str == null || str.equals("")){
return true;
}
return false;
}
/**
* <p>将字符拆分并放入list集合</p>
* @param str 字符串
* @return list
* */
public static List<Long> toLongList(String str){
List<Long> idList = new ArrayList<Long>();
if(!isBlank(str)){
String[] idsArray = str.split(",");
for (int i = 0; i < idsArray.length; i++) {
idList.add(Long.parseLong(idsArray[i]));
}
}
return idList;
}
public static String listToString(List list, char separator) {
return org.apache.commons.lang.StringUtils.join(list.toArray(),separator);
}
public static void main(String[] args) {
//String result = "aaaa aaa";
//System.out.println(getLength(result));
String[] strArray = new String[]{"How","d$o","you","do"};
strArray = new String[]{"5.36","5.003","1.36","9.87","3.33333379"};
//strArray = StringUtil.sortArrays(strArray);
strArray = StringUtil.sortArraystoBigDecimal(strArray);
String str = StringUtil.getArrToStr(strArray);
System.out.println(str);
//System.out.println(StringUtil.formatIntegrity("dkkemnkn", 2, '6'));
}
}

View File

@@ -0,0 +1,29 @@
package com.fibo.ddp.common.utils.util.runner;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import java.util.Date;
public class DictVariableUtils {
public static Object getValueFromJsonObject(JSONObject jsonObject){
Object result = "";
if (jsonObject.get("value") != null) {
switch (jsonObject.getString("type")){
case "date":
try {
result = DateUtil.format(new Date(),jsonObject.getString("value"));
}catch (Exception e){
e.printStackTrace();
result = DateUtil.format(new Date(),"yyyyMMdd");
}
break;
default:
result = jsonObject.get("value");
}
}
return result;
}
}

View File

@@ -0,0 +1,167 @@
package com.fibo.ddp.common.utils.util.runner;
import com.fibo.ddp.common.utils.constant.CommonConst;
import com.fibo.ddp.common.utils.constant.enginex.EngineOperator;
import com.fibo.ddp.common.utils.util.CollectionUtil;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationException;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import java.util.Map;
/**
* 表达式解析器入口
*/
public class JevalUtil {
/**
* 获取执行布尔值结果
* @param expression
* @param params
* @return
* @throws EvaluationException
*/
public static Boolean evaluateBoolean(String expression,Map<String,Object> params) throws EvaluationException {
Evaluator evaluator = getEvaluator(params);
return evaluator.getBooleanResult(expression);
}
/**
* 获取执行数字结果
* @param expression
* @param params
* @return
* @throws EvaluationException
*/
public static Double evaluateNumric(String expression,Map<String,Object> params) throws EvaluationException{
Evaluator evaluator = getEvaluator(params);
return evaluator.getNumberResult(expression);
}
/**
* 获取执行String结果
* @param expression
* @param params
* @return
* @throws EvaluationException
*/
public static String evaluateString(String expression,Map<String,Object> params) throws EvaluationException{
Evaluator evaluator = getEvaluator(params);
return evaluator.evaluate(expression,false,true);
}
/**
* 获取绑定参数的Evaluator
* @param params
* @return
* @throws EvaluationException
*/
private static Evaluator getEvaluator(Map<String,Object> params){
Evaluator evaluator = new Evaluator();
if(params != null && !params.isEmpty()){
for (Map.Entry<String, Object> entry : params.entrySet()) {
if(null!=entry.getValue()){
evaluator.putVariable(entry.getKey(), entry.getValue().toString());
}
}
}
return evaluator;
}
/**
* 根据区间表达式解析区间
* @param expression,eg:[3,5],inputParam:字段code
* @return
*/
public static String getNumericInterval(String expression,String param){
StringBuffer result = new StringBuffer();
//先把变量进行加工#{inputParam}
param = EngineOperator.OPERATOR_VARIABLE_LEFT+param+EngineOperator.OPERATOR_VARIABLE_RIGHT;
//如果是纯数字,代表==,直接拼接
if(!expression.startsWith(EngineOperator.OPERATOR_LEFT_PARENTHESES) && !expression.startsWith(EngineOperator.OPERATOR_LEFT_BRACKET)
&& !expression.endsWith(EngineOperator.OPERATOR_RIGHT_PARENTHESES) && !expression.endsWith(EngineOperator.OPERATOR_RIGHT_BRACKET)){
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_EQUALS_RELATION).append(CommonConst.SYMBOL_BLANK).append(expression);
return result.toString();
}
//获取到取值区间
String exp = expression.substring(1, expression.length()-1);
String[] segments = null;
if(exp.startsWith(CommonConst.SYMBOL_COMMA)){
segments = new String[1];
segments[0] = exp.substring(1);
}else{
segments = exp.split(CommonConst.SYMBOL_COMMA);
}
//判断取值范围(,3)(4,)
if(segments.length == 1){
//说明是(,3),(4,)
if(expression.substring(1, expression.length()-1).startsWith(CommonConst.SYMBOL_COMMA)){
//以逗号开始(,3)
if(expression.endsWith(EngineOperator.OPERATOR_RIGHT_PARENTHESES)){
//小括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_LESS_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[0]);
}else if(expression.endsWith(EngineOperator.OPERATOR_RIGHT_BRACKET)){
//大括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_LESS_EQUALS_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[0]);
}
}else{
//以逗号结尾(4,)
if(expression.startsWith(EngineOperator.OPERATOR_LEFT_PARENTHESES)){
//小括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_GREATER_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[0]);
}else if(expression.startsWith(EngineOperator.OPERATOR_LEFT_BRACKET)){
//大括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_GREATER_EQUALS_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[0]);
}
}
}else if(segments.length == 2){
//开始符号
if(expression.startsWith(EngineOperator.OPERATOR_LEFT_PARENTHESES)){
//小括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_GREATER_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[0]);
}else if(expression.startsWith(EngineOperator.OPERATOR_LEFT_BRACKET)){
//大括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_GREATER_EQUALS_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[0]);
}
//都是&&关系
result.append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_AND_RELATION).append(CommonConst.SYMBOL_BLANK);
//结束符号
if(expression.endsWith(EngineOperator.OPERATOR_RIGHT_PARENTHESES)){
//小括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_LESS_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[1]);
}else if(expression.endsWith(EngineOperator.OPERATOR_RIGHT_BRACKET)){
//大括号
result.append(param).append(CommonConst.SYMBOL_BLANK).append(EngineOperator.OPERATOR_LESS_EQUALS_RELATION).append(CommonConst.SYMBOL_BLANK).append(segments[1]);
}
}
return result.toString();
}
/**
* 变量值转义
* @param fieldsMap
* @param variablesMap
* @return
*/
public static Map<String,Object> convertVariables(Map<String,Integer> fieldsMap,Map<String,Object> variablesMap){
if(CollectionUtil.isNotNullOrEmpty(variablesMap)){
if(!CollectionUtil.isNotNullOrEmpty(fieldsMap)){
return variablesMap;
}
String key = "";
Integer value = null;
for (Map.Entry<String, Object> entry : variablesMap.entrySet()) {
key = entry.getKey();
value = fieldsMap.get(key);
if(value == null){
continue;
}
//2代表字符串
if(value == 2){
String variableValue = CommonConst.SYMBOL_SINGLE_QUOTA+variablesMap.get(key).toString()+CommonConst.SYMBOL_SINGLE_QUOTA;
variablesMap.put(key, variableValue);
}
}
}
return variablesMap;
}
}

View File

@@ -0,0 +1,23 @@
package com.fibo.ddp.common.utils.util.runner;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class NumUtils {
public static double toDouble(Object o){
double d = 0D;
if (o==null){
return d;
}
try {
d = Double.valueOf(o.toString()).doubleValue();
}catch (Exception e){
log.error("转换为double失败原值{}",o);
e.printStackTrace();
}
return d;
}
}

View File

@@ -0,0 +1,32 @@
package com.fibo.ddp.common.utils.util.runner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StrUtils {
//判断是否为一个数字
public static boolean isNum(String str){
if (str==null||"".equals(str)){
return false;
}
Pattern pattern = Pattern.compile("^(-|\\+)?\\d+(\\.\\d+)?$");
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
//将字符串转为Long类型
public static Long strToLong(String str){
if (isNum(str)){
return Long.valueOf(str);
}
return null;
}
public static Double strToDouble(String str){
if (isNum(str)){
return Double.valueOf(str);
}
return null;
}
}

View File

@@ -0,0 +1,119 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
import java.util.Enumeration;
/**
* This class allow for tokenizer methods to be called on a String of arguments.
*/
public class ArgumentTokenizer implements Enumeration {
/**
* The default delimitor.
*/
public final char defaultDelimiter =
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR;
// The arguments to be tokenized. This is updated every time the nextToken
// method is called.
private String arguments = null;
// The separator between the arguments.
private char delimiter = defaultDelimiter;
/**
* Constructor that takes a String of arguments and a delimitoer.
*
* @param arguments
* The String of srguments to be tokenized.
* @param delimiter
* The argument tokenizer.
*/
public ArgumentTokenizer(final String arguments, final char delimiter) {
this.arguments = arguments;
this.delimiter = delimiter;
}
/**
* Indicates if there are more elements.
*
* @return True if there are more elements and false if not.
*/
public boolean hasMoreElements() {
return hasMoreTokens();
}
/**
* Indicates if there are more tokens.
*
* @return True if there are more tokens and false if not.
*/
public boolean hasMoreTokens() {
if (arguments.length() > 0) {
return true;
}
return false;
}
/**
* Returns the next element.
*
* @return The next element.
*/
public Object nextElement() {
return nextToken();
}
/**
* Returns the next token.
*
* @return The next element.
*/
public String nextToken() {
int charCtr = 0;
int size = arguments.length();
int parenthesesCtr = 0;
String returnArgument = null;
// Loop until we hit the end of the arguments String.
while (charCtr < size) {
if (arguments.charAt(charCtr) == '(') {
parenthesesCtr++;
} else if (arguments.charAt(charCtr) == ')') {
parenthesesCtr--;
} else if (arguments.charAt(charCtr) == delimiter
&& parenthesesCtr == 0) {
returnArgument = arguments.substring(0, charCtr);
arguments = arguments.substring(charCtr + 1);
break;
}
charCtr++;
}
if (returnArgument == null) {
returnArgument = arguments;
arguments = "";
}
return returnArgument;
}
}

View File

@@ -0,0 +1,63 @@
package com.fibo.ddp.common.utils.util.runner.jeval;
/**
* Contains constants used by classes in this package.
*/
public class EvaluationConstants {
/**
* The single quote character.
*/
public static final char SINGLE_QUOTE = '\'';
/**
* The double quote character.
*/
public static final char DOUBLE_QUOTE = '"';
/**
* The open brace character.
*/
public static final char OPEN_BRACE = '{';
/**
* The closed brace character.
*/
public static final char CLOSED_BRACE = '}';
/**
* The pound sign character.
*/
public static final char POUND_SIGN = '#';
/**
* The open variable string.
*/
public static final String OPEN_VARIABLE = String.valueOf(POUND_SIGN)
+ String.valueOf(OPEN_BRACE);
/**
* The closed brace string.
*/
public static final String CLOSED_VARIABLE = String.valueOf(CLOSED_BRACE);
/**
* The true value for a Boolean string.
*/
public static final String BOOLEAN_STRING_TRUE = "1.0";
/**
* The false value for a Boolean string.
*/
public static final String BOOLEAN_STRING_FALSE = "0.0";
/**
* The comma character.
*/
public static final char COMMA = ',';
/**
* The function argument separator.
*/
public static final char FUNCTION_ARGUMENT_SEPARATOR = COMMA;
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
/**
* This exception is thrown when an error occurs during the evaluation process.
*/
public class EvaluationException extends Exception {
private static final long serialVersionUID = -3010333364122748053L;
/**
* This constructor takes a custom message as input.
*
* @param message
* A custom message for the exception to display.
*/
public EvaluationException(String message) {
super(message);
}
/**
* This constructor takes an exception as input.
*
* @param exception
* An exception.
*/
public EvaluationException(Exception exception) {
super(exception);
}
/**
* This constructor takes an exception as input.
*
* @param message
* A custom message for the exception to display.
* @param exception
* An exception.
*/
public EvaluationException(String message, Exception exception) {
super(message, exception);
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
public class EvaluationHelper {
/**
* Replaces all old string within the expression with new strings.
*
* @param expression
* The string being processed.
* @param oldString
* The string to replace.
* @param newString
* The string to replace the old string with.
*
* @return The new expression with all of the old strings replaced with new
* strings.
*/
public static String replaceAll(final String expression,
final String oldString, final String newString) {
String replacedExpression = expression;
if (replacedExpression != null) {
int charCtr = 0;
int oldStringIndex = replacedExpression.indexOf(oldString, charCtr);
while (oldStringIndex > -1) {
// Remove the old string from the expression.
final StringBuffer buffer = new StringBuffer(replacedExpression
.substring(0, oldStringIndex)
+ replacedExpression.substring(oldStringIndex
+ oldString.length()));
// Insert the new string into the expression.
buffer.insert(oldStringIndex, newString);
replacedExpression = buffer.toString();
charCtr = oldStringIndex + newString.length();
// Determine if we need to continue to search.
if (charCtr < replacedExpression.length()) {
oldStringIndex = replacedExpression.indexOf(oldString,
charCtr);
} else {
oldStringIndex = -1;
}
}
}
return replacedExpression;
}
/**
* Determines if a character is a space or white space.
*
* @param character
* The character being evaluated.
*
* @return True if the character is a space or white space and false if not.
*/
public static boolean isSpace(final char character) {
if (character == ' ' || character == '\t' || character == '\n'
|| character == '\r' || character == '\f') {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,177 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
/**
* This class can be used to wrap the result of an expression evaluation. It
* contains useful methods for evaluating the contents of the result.
*/
public class EvaluationResult {
// The value returned from the evaluation of an expression.
private String result;
// The quote character specified in the evaluation of the expression.
private char quoteCharacter;
/**
* Constructor.
*
* @param result
* The value returned from the evaluation of an expression.
* @param quoteCharacter
* The quote character specified in the evaluation of the
* expression.
*/
public EvaluationResult(String result, char quoteCharacter) {
this.result = result;
this.quoteCharacter = quoteCharacter;
}
/**
* Returns the quote character.
*
* @return The quote character.
*/
public char getQuoteCharacter() {
return quoteCharacter;
}
/**
* Sets the quote character.
*
* @param quoteCharacter
* The quoteCharacter to set.
*/
public void setQuoteCharacter(char quoteCharacter) {
this.quoteCharacter = quoteCharacter;
}
/**
* Returns the result value.
*
* @return The result value.
*/
public String getResult() {
return result;
}
/**
* Sets the result value.
*
* @param result
* The result to set.
*/
public void setResult(String result) {
this.result = result;
}
/**
* Returns true if the result value is equal to the value of a Boolean true
* string (1.0).
*
* @return True if the result value is equal to the value of a Boolean true
* string (1.0).
*/
public boolean isBooleanTrue() {
if (result != null
&& EvaluationConstants.BOOLEAN_STRING_TRUE.equals(result)) {
return true;
}
return false;
}
/**
* Returns true if the result value is equal to the value of a Boolean false
* string (0.0).
*
* @return True if the result value is equal to the value of a Boolean false
* string (0.0).
*/
public boolean isBooleanFalse() {
if (result != null
&& EvaluationConstants.BOOLEAN_STRING_FALSE.equals(result)) {
return true;
}
return false;
}
/**
* Returns true if the result value starts with a quote character and ends
* with a quote character.
*
* @return True if the result value starts with a quote character and ends
* with a quote character.
*/
public boolean isString() {
if (result != null && result.length() >= 2) {
if (result.charAt(0) == quoteCharacter
&& result.charAt(result.length() - 1) == quoteCharacter) {
return true;
}
}
return false;
}
/**
* Returns a Double for the result value.
*
* @return A Double for the result value.
*
* @throws NumberFormatException
* Thrown if the result value is not a double.
*/
public Double getDouble() throws NumberFormatException {
return new Double(result);
}
/**
* Returns the unwrapped string for the result value. An unwrapped string is
* a string value without the quote characters that wrap the result value.
* For a string to be returned, then the first character must be a quote
* character and the last character must be a quote character. Otherwise, a
* null value is returned.
*
* @return The normal string for the result value. Null will be returned if
* the result value is not of a string type.
*/
public String getUnwrappedString() {
if (result != null && result.length() >= 2) {
if (result.charAt(0) == quoteCharacter
&& result.charAt(result.length() - 1) == quoteCharacter) {
return result.substring(1, result.length() - 1);
}
}
return null;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
import com.fibo.ddp.common.utils.util.runner.jeval.operator.Operator;
/**
* Represents an operand being processed in the expression.
*/
public class ExpressionOperand {
// The value of the operand.
private String value = null;
// The unary operator for the operand, if one exists.
private Operator unaryOperator = null;
/**
* Create a new ExpressionOperand.
*
* @param value
* The value for the new ExpressionOperand.
* @param unaryOperator
* The unary operator for this object.
*/
public ExpressionOperand(final String value, final Operator unaryOperator) {
this.value = value;
this.unaryOperator = unaryOperator;
}
/**
* Returns the value of this object.
*
* @return The value of this object.
*/
public String getValue() {
return value;
}
/**
* Returns the unary operator for this object.
*
* @return The unary operator for this object.
*/
public Operator getUnaryOperator() {
return unaryOperator;
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
import com.fibo.ddp.common.utils.util.runner.jeval.operator.Operator;
/**
* Represents an operator being processed in the expression.
*/
public class ExpressionOperator {
// The operator that this object represents.
private Operator operator = null;
// The unary operator for this object, if there is one.
private Operator unaryOperator = null;
/**
* Creates a new ExpressionOperator.
*
* @param operator
* The operator this object represents.
* @param unaryOperator
* The unary operator for this object.
*/
public ExpressionOperator(final Operator operator,
final Operator unaryOperator) {
this.operator = operator;
this.unaryOperator = unaryOperator;
}
/**
* Returns the operator for this object.
*
* @return The operator for this object.
*/
public Operator getOperator() {
return operator;
}
/**
* Returns the unary operator for this object.
*
* @return The unary operator for this object.
*/
public Operator getUnaryOperator() {
return unaryOperator;
}
}

View File

@@ -0,0 +1,368 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
import com.fibo.ddp.common.utils.util.runner.jeval.operator.Operator;
/**
* Represents an expression tree made up of a left operand, right operand,
* operator and unary operator.
*/
public class ExpressionTree {
// The left node in the tree.
private Object leftOperand = null;
// The right node in the tree.
private Object rightOperand = null;
// The operator for the two operands.
private Operator operator = null;
// The unary operator, if one exists.
private Operator unaryOperator = null;
// The Evaluator object processing this tree.
private Evaluator evaluator = null;
/**
* Creates a new ExpressionTree.
*
* @param evaluator
* The Evaluator object processing this tree.
* @param leftOperand
* The left operand to place as the left node of the tree.
* @param rightOperand
* The right operand to place as the right node of the tree.
* @param operator
* The operator to place as the operator node of the tree.
* @param unaryOperator
* The new unary operator for this tree.
*/
public ExpressionTree(final Evaluator evaluator, final Object leftOperand,
final Object rightOperand, final Operator operator,
final Operator unaryOperator) {
this.evaluator = evaluator;
this.leftOperand = leftOperand;
this.rightOperand = rightOperand;
this.operator = operator;
this.unaryOperator = unaryOperator;
}
/**
* Returns the left operand of this tree.
*
* @return The left operand of this tree.
*/
public Object getLeftOperand() {
return leftOperand;
}
/**
* Returns the right operand of this tree.
*
* @return The right operand of this tree.
*/
public Object getRightOperand() {
return rightOperand;
}
/**
* Returns the operator for this tree.
*
* @return The operator of this tree.
*/
public Operator getOperator() {
return operator;
}
/**
* Returns the unary operator for this tree.
*
* @return The unary operator of this tree.
*/
public Operator getUnaryOperator() {
return unaryOperator;
}
/**
* Evaluates the operands for this tree using the operator and the unary
* operator.
*
* @param wrapStringFunctionResults
* Indicates if the results from functions that return strings
* should be wrapped in quotes. The quote character used will be
* whatever is the current quote character for this object.
*
* @exception EvaluateException
* Thrown is an error is encountered while processing the
* expression.
*/
public String evaluate(final boolean wrapStringFunctionResults)
throws EvaluationException {
String rtnResult = null;
// Get the left operand.
String leftResultString = null;
Double leftResultDouble = null;
if (leftOperand instanceof ExpressionTree) {
leftResultString = ((ExpressionTree) leftOperand)
.evaluate(wrapStringFunctionResults);
try {
leftResultDouble = new Double(leftResultString);
leftResultString = null;
} catch (NumberFormatException exception) {
leftResultDouble = null;
}
} else if (leftOperand instanceof ExpressionOperand) {
final ExpressionOperand leftExpressionOperand = (ExpressionOperand) leftOperand;
leftResultString = leftExpressionOperand.getValue();
leftResultString = evaluator.replaceVariables(leftResultString);
// Check if the operand is a string or not. If it not a string,
// then it must be a number.
if (!evaluator.isExpressionString(leftResultString)) {
try {
leftResultDouble = new Double(leftResultString);
leftResultString = null;
} catch (NumberFormatException nfe) {
throw new EvaluationException("Expression is invalid.", nfe);
}
if (leftExpressionOperand.getUnaryOperator() != null) {
leftResultDouble = new Double(leftExpressionOperand
.getUnaryOperator().evaluate(
leftResultDouble.doubleValue()));
}
} else {
if (leftExpressionOperand.getUnaryOperator() != null) {
throw new EvaluationException("Invalid operand for "
+ "unary operator.");
}
}
} else if (leftOperand instanceof ParsedFunction) {
final ParsedFunction parsedFunction = (ParsedFunction) leftOperand;
final Function function = parsedFunction.getFunction();
String arguments = parsedFunction.getArguments();
arguments = evaluator.replaceVariables(arguments);
if (evaluator.getProcessNestedFunctions()) {
arguments = evaluator.processNestedFunctions(arguments);
}
try {
FunctionResult functionResult =
function.execute(evaluator, arguments);
leftResultString = functionResult.getResult();
if (functionResult.getType() ==
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC) {
Double resultDouble = new Double(leftResultString);
// Process a unary operator if one exists.
if (parsedFunction.getUnaryOperator() != null) {
resultDouble = new Double(parsedFunction
.getUnaryOperator().evaluate(
resultDouble.doubleValue()));
}
// Get the final result.
leftResultString = resultDouble.toString();
}
else if (functionResult.getType() ==
FunctionConstants.FUNCTION_RESULT_TYPE_STRING) {
// The result must be a string result.
if (wrapStringFunctionResults) {
leftResultString = evaluator.getQuoteCharacter()
+ leftResultString
+ evaluator.getQuoteCharacter();
}
if (parsedFunction.getUnaryOperator() != null) {
throw new EvaluationException("Invalid operand for "
+ "unary operator.");
}
}
} catch (FunctionException fe) {
throw new EvaluationException(fe.getMessage(), fe);
}
if (!evaluator.isExpressionString(leftResultString)) {
try {
leftResultDouble = new Double(leftResultString);
leftResultString = null;
} catch (NumberFormatException nfe) {
throw new EvaluationException("Expression is invalid.", nfe);
}
}
} else {
if (leftOperand != null) {
throw new EvaluationException("Expression is invalid.");
}
}
// Get the right operand.
String rightResultString = null;
Double rightResultDouble = null;
if (rightOperand instanceof ExpressionTree) {
rightResultString = ((ExpressionTree) rightOperand)
.evaluate(wrapStringFunctionResults);
try {
rightResultDouble = new Double(rightResultString);
rightResultString = null;
} catch (NumberFormatException exception) {
rightResultDouble = null;
}
} else if (rightOperand instanceof ExpressionOperand) {
final ExpressionOperand rightExpressionOperand = (ExpressionOperand) rightOperand;
rightResultString = ((ExpressionOperand) rightOperand).getValue();
rightResultString = evaluator.replaceVariables(rightResultString);
// Check if the operand is a string or not. If it not a string,
// then it must be a number.
if (!evaluator.isExpressionString(rightResultString)) {
try {
rightResultDouble = new Double(rightResultString);
rightResultString = null;
} catch (NumberFormatException nfe) {
throw new EvaluationException("Expression is invalid.", nfe);
}
if (rightExpressionOperand.getUnaryOperator() != null) {
rightResultDouble = new Double(rightExpressionOperand
.getUnaryOperator().evaluate(
rightResultDouble.doubleValue()));
}
} else {
if (rightExpressionOperand.getUnaryOperator() != null) {
throw new EvaluationException("Invalid operand for "
+ "unary operator.");
}
}
} else if (rightOperand instanceof ParsedFunction) {
final ParsedFunction parsedFunction = (ParsedFunction) rightOperand;
final Function function = parsedFunction.getFunction();
String arguments = parsedFunction.getArguments();
arguments = evaluator.replaceVariables(arguments);
if (evaluator.getProcessNestedFunctions()) {
arguments = evaluator.processNestedFunctions(arguments);
}
try {
FunctionResult functionResult =
function.execute(evaluator, arguments);
rightResultString = functionResult.getResult();
if (functionResult.getType() ==
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC) {
Double resultDouble = new Double(rightResultString);
// Process a unary operator if one exists.
if (parsedFunction.getUnaryOperator() != null) {
resultDouble = new Double(parsedFunction
.getUnaryOperator().evaluate(
resultDouble.doubleValue()));
}
// Get the final result.
rightResultString = resultDouble.toString();
}
else if (functionResult.getType() ==
FunctionConstants.FUNCTION_RESULT_TYPE_STRING) {
// The result must be a string result.
if (wrapStringFunctionResults) {
rightResultString = evaluator.getQuoteCharacter()
+ rightResultString
+ evaluator.getQuoteCharacter();
}
if (parsedFunction.getUnaryOperator() != null) {
throw new EvaluationException("Invalid operand for "
+ "unary operator.");
}
}
} catch (FunctionException fe) {
throw new EvaluationException(fe.getMessage(), fe);
}
if (!evaluator.isExpressionString(rightResultString)) {
try {
rightResultDouble = new Double(rightResultString);
rightResultString = null;
} catch (NumberFormatException nfe) {
throw new EvaluationException("Expression is invalid.", nfe);
}
}
} else if (rightOperand == null) {
// Do nothing.
} else {
throw new EvaluationException("Expression is invalid.");
}
// Evaluate the the expression.
if (leftResultDouble != null && rightResultDouble != null) {
double doubleResult = operator.evaluate(leftResultDouble
.doubleValue(), rightResultDouble.doubleValue());
if (getUnaryOperator() != null) {
doubleResult = getUnaryOperator().evaluate(doubleResult);
}
rtnResult = new Double(doubleResult).toString();
} else if (leftResultString != null && rightResultString != null) {
rtnResult = operator.evaluate(leftResultString, rightResultString);
} else if (leftResultDouble != null && rightResultDouble == null) {
double doubleResult = -1;
if (unaryOperator != null) {
doubleResult = unaryOperator.evaluate(leftResultDouble
.doubleValue());
} else {
// Do not allow numeric (left) and
// string (right) to be evaluated together.
throw new EvaluationException("Expression is invalid.");
}
rtnResult = new Double(doubleResult).toString();
} else {
throw new EvaluationException("Expression is invalid.");
}
return rtnResult;
}
}

View File

@@ -0,0 +1,62 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
import com.fibo.ddp.common.utils.util.runner.jeval.operator.Operator;
/**
* Represents the next operator in the expression to process.
*/
class NextOperator {
// The operator this object represetns.
private Operator operator = null;
// The index of the operator in the expression.
private int index = -1;
/**
* Create a new NextOperator from an operator and index.
*
* @param operator
* The operator this object represents.
* @param index
* The index of the operator in the expression.
*/
public NextOperator(final Operator operator, final int index) {
this.operator = operator;
this.index = index;
}
/**
* Returns the operator for this object.
*
* @return The operator represented by this object.
*/
public Operator getOperator() {
return operator;
}
/**
* Returns the index for this object.
*
* @return The index of the operator in the expression.
*/
public int getIndex() {
return index;
}
}

View File

@@ -0,0 +1,81 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.operator.Operator;
/**
* This class represents a function that has been parsed.
*/
public class ParsedFunction {
// The function that has been parsed.
// FIXME Make all class instance methods final if possible.
private final Function function;
// The arguments to the function.
private final String arguments;
// The unary operator for this object, if there is one.
private final Operator unaryOperator;
/**
* The constructor for this class.
*
* @param function
* The function that has been parsed.
* @param arguments
* The arguments to the function.
* @param unaryOperator
* The unary operator for this object, if there is one.
*/
public ParsedFunction(final Function function, final String arguments,
final Operator unaryOperator) {
this.function = function;
this.arguments = arguments;
this.unaryOperator = unaryOperator;
}
/**
* Returns the function that has been parsed.
*
* @return The function that has been parsed.
*/
public Function getFunction() {
return function;
}
/**
* Returns the arguments to the function.
*
* @return The arguments to the function.
*/
public String getArguments() {
return arguments;
}
/**
* Returns the unary operator for this object, if there is one.
*
* @return The unary operator for this object, if there is one.
*/
public Operator getUnaryOperator() {
return unaryOperator;
}
}

View File

@@ -0,0 +1,26 @@
package com.fibo.ddp.common.utils.util.runner.jeval;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
/**
* This interface can be implement with a custom resolver and set onto the
* Evaluator class. It will then be used to resolve variables when they are
* replaced in an expression as it gets evaluated. Varaibles resolved by the
* resolved will override any varibles that exist in the variable map of an
* Evaluator instance.
*/
public interface VariableResolver {
/**
* Returns a variable value for the specified variable name.
*
* @param variableName
* The name of the variable to return the variable value for.
*
* @return A variable value for the specified variable name. If the variable
* name can not be resolved, then null should be returned.
*
* @throws Can throw a FunctionException if needed.
*/
public String resolveVariable(String variableName) throws FunctionException;
}

View File

@@ -0,0 +1,51 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
/**
* A function that can be specified in an expression.
*/
public interface Function {
/**
* Returns the name of the function.
*
* @return The name of this function class.
*/
public String getName();
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* The arguments that will be evaluated by the function. It is up
* to the function implementation to break the string into one or
* more arguments.
*
* @return The value of the evaluated argument and its type.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException;
}

View File

@@ -0,0 +1,33 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function;
/**
* Contains constants used by classes in this package.
*/
public class FunctionConstants {
/**
* Indicates that the function result is a numeric or Boolean value.
*/
public static final int FUNCTION_RESULT_TYPE_NUMERIC = 0;
/**
* Indicates that the function result is a string value.
*/
public static final int FUNCTION_RESULT_TYPE_STRING = 1;
}

View File

@@ -0,0 +1,57 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function;
/**
* This exception is thrown when an error occurs while processing a function.
*/
public class FunctionException extends Exception {
private static final long serialVersionUID = 4767250768467137620L;
/**
* This constructor takes a custom message as input.
*
* @param message
* A custom message for the exception to display.
*/
public FunctionException(String message) {
super(message);
}
/**
* This constructor takes an exception as input.
*
* @param exception
* An exception.
*/
public FunctionException(Exception exception) {
super(exception);
}
/**
* This constructor takes an exception as input.
*
* @param message
* A custom message for the exception to display.
* @param exception
* An exception.
*/
public FunctionException(String message, Exception exception) {
super(message, exception);
}
}

View File

@@ -0,0 +1,58 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import java.util.List;
/**
* A groups of functions that can loaded at one time into an instance of
* Evaluator.
*/
public interface FunctionGroup {
/**
* Returns the name of the function group.
*
* @return The name of this function group class.
*/
public String getName();
/**
* Returns a list of the functions that are loaded by this class.
*
* @return A list of the functions loaded by this class.
*/
public List getFunctions();
/**
* Loads the functions in this function group into an instance of Evaluator.
*
* @param evaluator
* An instance of Evaluator to load the functions into.
*/
public void load(Evaluator evaluator);
/**
* Unloads the functions in this function group from an instance of
* Evaluator.
*
* @param evaluator
* An instance of Evaluator to unload the functions from.
*/
public void unload(Evaluator evaluator);
}

View File

@@ -0,0 +1,284 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function;
import com.fibo.ddp.common.utils.util.runner.jeval.ArgumentTokenizer;
import java.util.ArrayList;
/**
* This class contains many methods that are helpful when writing functions.
* Some of these methods were created to help with the creation of the math and
* string functions packaged with Evaluator.
*/
public class FunctionHelper {
/**
* This method first removes any white space at the beginning and end of the
* input string. It then removes the specified quote character from the the
* first and last characters of the string if a quote character exists in
* those positions. If quote characters are not in the first and last
* positions after the white space is trimmed, then a FunctionException will
* be thrown.
*
* @param arguments
* The arguments to trim and revove quote characters from.
* @param quoteCharacter
* The character to remove from the first and last position of
* the trimmed string.
*
* @return The arguments with white space and quote characters removed.
*
* @exception FunctionException
* Thrown if quote characters do not exist in the first and
* last positions after the white space is trimmed.
*/
public static String trimAndRemoveQuoteChars(final String arguments,
final char quoteCharacter) throws FunctionException {
String trimmedArgument = arguments;
trimmedArgument = trimmedArgument.trim();
if (trimmedArgument.charAt(0) == quoteCharacter) {
trimmedArgument = trimmedArgument.substring(1, trimmedArgument
.length());
} else {
throw new FunctionException("Value does not start with a quote.");
}
if (trimmedArgument.charAt(trimmedArgument.length() - 1) == quoteCharacter) {
trimmedArgument = trimmedArgument.substring(0, trimmedArgument
.length() - 1);
} else {
throw new FunctionException("Value does not end with a quote.");
}
return trimmedArgument;
}
/**
* This methods takes a string of input function arguments, evaluates each
* argument and creates a Double value for each argument from the result of
* the evaluations.
*
* @param arguments
* The arguments to parse.
* @param delimiter
* The delimiter to use while parsing.
*
* @return An array list of Double values found in the input string.
*
* @exception FunctionException
* Thrown if the string does not properly parse into Double
* values.
*/
public static ArrayList getDoubles(final String arguments,
final char delimiter) throws FunctionException {
ArrayList returnValues = new ArrayList();
try {
final ArgumentTokenizer tokenizer = new ArgumentTokenizer(
arguments, delimiter);
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken().trim();
returnValues.add(new Double(token));
}
} catch (Exception e) {
throw new FunctionException("Invalid values in string.", e);
}
return returnValues;
}
/**
* This methods takes a string of input function arguments, evaluates each
* argument and creates a String value for each argument from the result of
* the evaluations.
*
* @param arguments
* The arguments of values to parse.
* @param delimiter
* The delimiter to use while parsing.
*
* @return An array list of String values found in the input string.
*
* @exception FunctionException
* Thrown if the stirng does not properly parse into String
* values.
*/
public static ArrayList getStrings(final String arguments,
final char delimiter) throws FunctionException {
final ArrayList returnValues = new ArrayList();
try {
ArgumentTokenizer tokenizer = new ArgumentTokenizer(arguments,
delimiter);
while (tokenizer.hasMoreTokens()) {
final String token = tokenizer.nextToken();
returnValues.add(token);
}
} catch (Exception e) {
throw new FunctionException("Invalid values in string.", e);
}
return returnValues;
}
/**
* This methods takes a string of input function arguments, evaluates each
* argument and creates a one Integer and one String value for each argument
* from the result of the evaluations.
*
* @param arguments
* The arguments of values to parse.
* @param delimiter
* The delimiter to use while parsing.
*
* @return An array list of object values found in the input string.
*
* @exception FunctionException
* Thrown if the stirng does not properly parse into the
* proper objects.
*/
public static ArrayList getOneStringAndOneInteger(final String arguments,
final char delimiter) throws FunctionException {
ArrayList returnValues = new ArrayList();
try {
final ArgumentTokenizer tokenizer = new ArgumentTokenizer(
arguments, delimiter);
int tokenCtr = 0;
while (tokenizer.hasMoreTokens()) {
if (tokenCtr == 0) {
final String token = tokenizer.nextToken();
returnValues.add(token);
} else if (tokenCtr == 1) {
final String token = tokenizer.nextToken().trim();
returnValues.add(new Integer(new Double(token).intValue()));
} else {
throw new FunctionException("Invalid values in string.");
}
tokenCtr++;
}
} catch (Exception e) {
throw new FunctionException("Invalid values in string.", e);
}
return returnValues;
}
/**
* This methods takes a string of input function arguments, evaluates each
* argument and creates a two Strings and one Integer value for each
* argument from the result of the evaluations.
*
* @param arguments
* The arguments of values to parse.
* @param delimiter
* The delimiter to use while parsing.
*
* @return An array list of object values found in the input string.
*
* @exception FunctionException
* Thrown if the stirng does not properly parse into the
* proper objects.
*/
public static ArrayList getTwoStringsAndOneInteger(final String arguments,
final char delimiter) throws FunctionException {
final ArrayList returnValues = new ArrayList();
try {
final ArgumentTokenizer tokenizer = new ArgumentTokenizer(
arguments, delimiter);
int tokenCtr = 0;
while (tokenizer.hasMoreTokens()) {
if (tokenCtr == 0 || tokenCtr == 1) {
final String token = tokenizer.nextToken();
returnValues.add(token);
} else if (tokenCtr == 2) {
final String token = tokenizer.nextToken().trim();
returnValues.add(new Integer(new Double(token).intValue()));
} else {
throw new FunctionException("Invalid values in string.");
}
tokenCtr++;
}
} catch (Exception e) {
throw new FunctionException("Invalid values in string.", e);
}
return returnValues;
}
/**
* This methods takes a string of input function arguments, evaluates each
* argument and creates a one String and two Integers value for each
* argument from the result of the evaluations.
*
* @param arguments
* The arguments of values to parse.
* @param delimiter
* The delimiter to use while parsing.
*
* @return An array list of object values found in the input string.
*
* @exception FunctionException
* Thrown if the stirng does not properly parse into the
* proper objects.
*/
public static ArrayList getOneStringAndTwoIntegers(final String arguments,
final char delimiter) throws FunctionException {
final ArrayList returnValues = new ArrayList();
try {
final ArgumentTokenizer tokenizer = new ArgumentTokenizer(
arguments, delimiter);
int tokenCtr = 0;
while (tokenizer.hasMoreTokens()) {
if (tokenCtr == 0) {
final String token = tokenizer.nextToken().trim();
returnValues.add(token);
} else if (tokenCtr == 1 || tokenCtr == 2) {
final String token = tokenizer.nextToken().trim();
returnValues.add(new Integer(new Double(token).intValue()));
} else {
throw new FunctionException("Invalid values in string.");
}
tokenCtr++;
}
} catch (Exception e) {
throw new FunctionException("Invalid values in string.", e);
}
return returnValues;
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function;
/**
* This is a wrapper for the result value returned from a function that not only
* contains the result, but the type. All custom functions must return a
* FunctionResult.
*/
public class FunctionResult {
// The value returned from a function call.
private String result;
// The type of the result. Can be a numberic or string. Boolean values come
// back as numeric values.
private int type;
/**
* Constructor.
*
* @param result
* The result value.
* @param type
* The result type.
*
* @throws FunctionException
* Thrown if result type is invalid.
*/
public FunctionResult(String result, int type) throws FunctionException {
if (type < FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC
|| type > FunctionConstants.FUNCTION_RESULT_TYPE_STRING) {
throw new FunctionException("Invalid function result type.");
}
this.result = result;
this.type = type;
}
/**
* Returns the result value.
*
* @return The result value.
*/
public String getResult() {
return result;
}
/**
* Returns the result type.
*
* @return The result type.
*/
public int getType() {
return type;
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the absolute value of a double value. See the Math.abs(double) method in the
* JDK for a complete description of how this function works.
*/
public class Abs implements Function {
/**
* Returns the name of the function - "abs".
*
* @return The name of this function class.
*/
public String getName() {
return "abs";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The absolute value of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.abs(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the arc cosine of an angle. See the Math.ceil(double) method in the JDK for a
* complete description of how this function works.
*/
public class Acos implements Function {
/**
* Returns the name of the function - "acos".
*
* @return The name of this function class.
*/
public String getName() {
return "acos";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The arc cosine value of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.acos(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the arc sine of an angle See the Math.asin(double) method in the JDK for a
* complete description of how this function works.
*/
public class Asin implements Function {
/**
* Returns the name of the function - "asin".
*
* @return The name of this function class.
*/
public String getName() {
return "asin";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The arc sine of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.asin(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the arc tangent of an angle. See the Math.atan(double) method in the JDK for
* a complete description of how this function works.
*/
public class Atan implements Function {
/**
* Returns the name of the function - "atan".
*
* @return The name of this function class.
*/
public String getName() {
return "atan";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The arc tangent of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.atan(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,77 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function
* converts rectangular coordinates to polar. See the Math.atan2(double, double)
* method in the JDK for a complete description of how this function works.
*/
public class Atan2 implements Function {
/**
* Returns the name of the function - "atan2".
*
* @return The name of this function class.
*/
public String getName() {
return "atan2";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two double
* values and evaluated.
*
* @return The arc tangent2 value of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
ArrayList numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (numbers.size() != 2) {
throw new FunctionException("Two numeric arguments are required.");
}
try {
double argumentOne = ((Double) numbers.get(0)).doubleValue();
double argumentTwo = ((Double) numbers.get(1)).doubleValue();
result = new Double(Math.atan2(argumentOne, argumentTwo));
} catch (Exception e) {
throw new FunctionException("Two numeric arguments are required.", e);
}
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,49 @@
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.math.BigDecimal;
import java.util.ArrayList;
/**
* 计算多个数字的平均值
*/
public class Average implements Function {
@Override
public String getName() {
return "avg";
}
@Override
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
ArrayList<Double> numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
int count = numbers.size() ;
if (count < 2) {
throw new FunctionException("Two numeric arguments are required at least.");
}
double sum=0;
for (Double num : numbers) {
//为什么使用这样的方法,而不直接相加呢?
//原因是Java中的简单浮点数类型float和double不能够进行运算会出现类似如下情况
//eg:sum(1,2,3,1.2,2.0,3.6)=12.79999999999而不等于12.8
BigDecimal b1=new BigDecimal(Double.toString(sum));
BigDecimal b2=new BigDecimal(Double.toString(num));
sum=b1.add(b2).doubleValue();
}
result = new Double(sum/count);
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the ceiling value of a double value. See the Math.ceil(double) method in the
* JDK for a complete description of how this function works.
*/
public class Ceil implements Function {
/**
* Returns the name of the function - "ceil".
*
* @return The name of this function class.
*/
public String getName() {
return "ceil";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The ceiling of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.ceil(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the trigonometric cosine of an angle. See the Math.cos(double) method in the
* JDK for a complete description of how this function works.
*/
public class Cos implements Function {
/**
* Returns the name of the function - "cos".
*
* @return The name of this function class.
*/
public String getName() {
return "cos";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The cosine of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.cos(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the exponential number e (i.e., 2.718...) raised to the power of a double
* value. See the Math.exp(double) method in the JDK for a complete description
* of how this function works.
*/
public class Exp implements Function {
/**
* Returns the name of the function - "exp".
*
* @return The name of this function class.
*/
public String getName() {
return "exp";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The the value e to the argument power, where e is the base of the
* natural logarithms
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.exp(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the floor value of a double value. See the Math.floor(double) method in the
* JDK for a complete description of how this function works.
*/
public class Floor implements Function {
/**
* Returns the name of the function - "floor".
*
* @return The name of this function class.
*/
public String getName() {
return "floor";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The floor of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.floor(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,167 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.common.MD5;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationException;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* This class is a function that executes within Evaluator. The function returns
* the ceiling value of a double value. See the Math.ceil(double) method in the
* JDK for a complete description of how this function works.
*/
@Component
public class Groovy implements Function {
private static final Logger logger = LoggerFactory.getLogger(Groovy.class);
private static final ScriptEngineManager factory = new ScriptEngineManager();
public static String GROOVY_SHELL_KEY_PREFIX = "GROOVY_SHELL#";
// private RedisManager redisManager;
private static Cache<String, ScriptEngine> scriptClassCache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.expireAfterAccess(1, TimeUnit.HOURS)
.build();
/**
* Returns the name of the function - "def main".
*
* @return The name of this function class.
*/
public String getName() {
return "def main";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The ceiling of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
return null;
}
// public String execute(final String expression, Map<String, Object> data) throws EvaluationException {
// String result = null;
// try {
// ScriptEngine scriptEngine = null;
// String scriptMd5 = PYTHON_SHELL_KEY_PREFIX + MD5.GetMD5Code(expression);
// ScriptEngine value = (ScriptEngine) SerializeUtils.deserialize(redisManager.get(scriptMd5.getBytes()));
// if(value != null){
// scriptEngine = value;
// } else {
// scriptEngine = factory.getEngineByName("groovy");
// scriptEngine.eval(expression);
// redisManager.set(scriptMd5.getBytes(), SerializeUtils.serialize(scriptEngine), 120);
// }
//
// Object functionResult = ((Invocable) scriptEngine).invokeFunction("main", data);
// result = functionResult.toString();
// } catch (Exception e) {
// throw new EvaluationException("执行groovy脚本出错", e);
// }
// return result;
// }
public String execute(final String expression, Map<String, Object> data) throws EvaluationException {
String result = null;
try {
ScriptEngine scriptEngine = null;
String scriptMd5 = GROOVY_SHELL_KEY_PREFIX + MD5.GetMD5Code(expression);
ScriptEngine value = scriptClassCache.getIfPresent(scriptMd5);
if(value != null){
scriptEngine = value;
} else {
scriptEngine = factory.getEngineByName("groovy");
scriptEngine.eval(expression);
scriptClassCache.put(scriptMd5, scriptEngine);
}
Object functionResult = ((Invocable) scriptEngine).invokeFunction("main", data);
if (functionResult!=null){
result = functionResult.toString();
}
// result = functionResult.toString();
} catch (Exception e) {
throw new EvaluationException("执行groovy脚本出错", e);
}
return result;
}
@Autowired
private Python python;
public Object executeForObject(final String expression, Map<String, Object> data) throws EvaluationException {
Object result = null;
try {
ScriptEngine scriptEngine = null;
String scriptMd5 = GROOVY_SHELL_KEY_PREFIX + MD5.GetMD5Code(expression);
ScriptEngine value = scriptClassCache.getIfPresent(scriptMd5);
if(value != null){
scriptEngine = value;
} else {
scriptEngine = factory.getEngineByName("groovy");
scriptEngine.eval(expression);
scriptClassCache.put(scriptMd5, scriptEngine);
}
Object functionResult = ((Invocable) scriptEngine).invokeFunction("main", data);
if (functionResult!=null){
// if (functionResult instanceof HashMap||functionResult instanceof ArrayList){
// result = JSON.toJSONString(functionResult);
// }else
// if (functionResult instanceof String){
// result = functionResult.toString();
// }else {
// result = functionResult;
// }
result = functionResult;
}
} catch (Exception e) {
throw new EvaluationException("执行groovy脚本出错", e);
}
return result;
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function returns
* the remainder operation on two arguments as prescribed by the IEEE 754
* standard. See the Math.IEEERemainder(double, double) method in the JDK for a
* complete description of how this function works.
*/
public class IEEEremainder implements Function {
/**
* Returns the name of the function - "IEEEremainder".
*
* @return The name of this function class.
*/
public String getName() {
return "IEEEremainder";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two double
* values and evaluated.
*
* @return The the remainder operation on two arguments as prescribed by the
* IEEE 754 standard.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
ArrayList numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (numbers.size() != 2) {
throw new FunctionException("Two numeric arguments are required.");
}
try {
double argumentOne = ((Double) numbers.get(0)).doubleValue();
double argumentTwo = ((Double) numbers.get(1)).doubleValue();
result = new Double(Math.IEEEremainder(argumentOne, argumentTwo));
} catch (Exception e) {
throw new FunctionException("Two numeric arguments are required.", e);
}
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,38 @@
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* log以e为底的对数
*/
public class Ln implements Function {
@Override
public String getName() {
return "ln";
}
@Override
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.log(number)/Math.log(Math.E));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the natural logarithm (base e) of a double value. See the Math.log(double)
* method in the JDK for a complete description of how this function works.
*/
public class Log implements Function {
/**
* Returns the name of the function - "log".
*
* @return The name of this function class.
*/
public String getName() {
return "log";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The natural logarithm of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.log(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,118 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionGroup;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* A groups of functions that can loaded at one time into an instance of
* Evaluator. This group contains all of the functions located in the
* net.sourceforge.jeval.function.math package.
*/
public class MathFunctions implements FunctionGroup {
/**
* Used to store instances of all of the functions loaded by this class.
*/
private List functions = new ArrayList();
/**
* Default contructor for this class. The functions loaded by this class are
* instantiated in this constructor.
*/
public MathFunctions() {
functions.add(new Abs());
functions.add(new Acos());
functions.add(new Asin());
functions.add(new Atan());
functions.add(new Atan2());
functions.add(new Ceil());
functions.add(new Cos());
functions.add(new Exp());
functions.add(new Floor());
functions.add(new IEEEremainder());
functions.add(new Log());
functions.add(new Pow());
functions.add(new Random());
functions.add(new Rint());
functions.add(new Round());
functions.add(new Sin());
functions.add(new Sqrt());
functions.add(new Tan());
functions.add(new ToDegrees());
functions.add(new ToRadians());
functions.add(new Max());
functions.add(new Min());
functions.add(new Sum());
functions.add(new Ln());
functions.add(new Average());
functions.add(new Groovy());
}
/**
* Returns the name of the function group - "numberFunctions".
*
* @return The name of this function group class.
*/
public String getName() {
return "numberFunctions";
}
/**
* Returns a list of the functions that are loaded by this class.
*
* @return A list of the functions loaded by this class.
*/
public List getFunctions() {
return functions;
}
/**
* Loads the functions in this function group into an instance of Evaluator.
*
* @param evaluator
* An instance of Evaluator to load the functions into.
*/
public void load(final Evaluator evaluator) {
Iterator functionIterator = functions.iterator();
while (functionIterator.hasNext()) {
evaluator.putFunction((Function) functionIterator.next());
}
}
/**
* Unloads the functions in this function group from an instance of
* Evaluator.
*
* @param evaluator
* An instance of Evaluator to unload the functions from.
*/
public void unload(final Evaluator evaluator) {
Iterator functionIterator = functions.iterator();
while (functionIterator.hasNext()) {
evaluator.removeFunction(((Function) functionIterator.next())
.getName());
}
}
}

View File

@@ -0,0 +1,38 @@
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
import java.util.Collections;
/**
* 获取多个值得最大值
*/
public class Max implements Function {
@Override
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
ArrayList numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
int count = numbers.size() ;
if (count < 2) {
throw new FunctionException("Two numeric arguments are required at least.");
}
result = (Double)Collections.max(numbers);
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
@Override
public String getName() {
return "max";
}
}

View File

@@ -0,0 +1,38 @@
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
import java.util.Collections;
/**
* 获取多个值最小值
*/
public class Min implements Function {
@Override
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
ArrayList numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
int count = numbers.size() ;
if (count < 2) {
throw new FunctionException("Two numeric arguments are required at least.");
}
result = (Double)Collections.min(numbers);
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
@Override
public String getName() {
return "min";
}
}

View File

@@ -0,0 +1,79 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function returns
* the value of the first argument raised to the second power of the second
* argument. See the Math.pow(double, double) method in the JDK for a complete
* description of how this function works.
*/
public class Pow implements Function {
/**
* Returns the name of the function - "pow".
*
* @return The name of this function class.
*/
public String getName() {
return "pow";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two double
* values and evaluated.
*
* @return The value of the first argument raised to the second power of the
* second argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
ArrayList numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (numbers.size() != 2) {
throw new FunctionException("Two numeric arguments are required.");
}
try {
double argumentOne = ((Double) numbers.get(0)).doubleValue();
double argumentTwo = ((Double) numbers.get(1)).doubleValue();
result = new Double(Math.pow(argumentOne, argumentTwo));
} catch (Exception e) {
throw new FunctionException("Two numeric arguments are required.", e);
}
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,177 @@
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.common.MD5;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationException;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.python.core.PyDictionary;
import org.python.core.PyObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Component
public class Python implements Function {
private static final Logger logger = LoggerFactory.getLogger(Groovy.class);
private static final ScriptEngineManager factory = new ScriptEngineManager();
public static String PYTHON_SHELL_KEY_PREFIX = "JYTHON_SHELL#";
private static Cache<String, ScriptEngine> scriptClassCache = Caffeine.newBuilder()
.expireAfterWrite(1, TimeUnit.HOURS)
.expireAfterAccess(1, TimeUnit.HOURS)
.build();
/**
* Returns the name of the function - "def main".
*
* @return The name of this function class.
*/
@Override
public String getName() {
return "if __name__ == \"__main__\":";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The ceiling of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
@Override
public FunctionResult execute(Evaluator evaluator, String arguments) throws FunctionException {
return null;
}
public Object executeForObject(final String expression, Map<String, Object> data) throws EvaluationException {
Object result = null;
try {
ScriptEngine scriptEngine = null;
String scriptMd5 = PYTHON_SHELL_KEY_PREFIX + MD5.GetMD5Code(expression);
ScriptEngine value = scriptClassCache.getIfPresent(scriptMd5);
Object functionResult = null;
if(value != null){
scriptEngine = value;
} else {
scriptEngine = factory.getEngineByName("python");
scriptEngine.eval(expression);
scriptClassCache.put(scriptMd5, scriptEngine);
}
PyDictionary pyDictionary = new PyDictionary();
for (Map.Entry<String, Object> entry : data.entrySet()) {
pyDictionary.put(entry.getKey(),entry.getValue());
}
// PythonInterpreter interpreter = new PythonInterpreter();
// interpreter.exec(new String(expression.getBytes()));
// PyFunction python_main = interpreter.get("python_main", PyFunction.class);
// PyObject pyObject = python_main.__call__(pyDictionary);
// System.out.println(pyObject);
// String ret = pyObject.toString();
// String newStr = new String(ret.getBytes("iso8859-1"), "utf-8"); //通过new String(ret.getBytes("iso8859-1"), "utf-8")转一下就好了
// System.out.println(newStr); //newStr就不会乱码了
// System.out.println(getEncode(String.valueOf(pyObject)));
functionResult = ((Invocable) scriptEngine).invokeFunction("python_main", pyDictionary);
if (functionResult instanceof PyDictionary){
PyObject resultPy = (PyObject)functionResult;
String ret = resultPy.toString();//这里ret可能会乱码
System.out.println(ret);
}
result = functionResult;
} catch (Exception e) {
e.printStackTrace();
throw new EvaluationException("执行Python脚本出错", e);
}
return result;
}
// 这里可以提供更多地编码格式,另外由于部分编码格式是一致的所以会返回 第一个匹配的编码格式 GBK 和 GB2312
public static final String[] encodes = new String[] { "UTF-8", "GBK", "GB2312", "ISO-8859-1", "ISO-8859-2" };
/**
* 获取字符串编码格式
*
* @param str
* @return
*/
public static String getEncode(String str) {
byte[] data = str.getBytes();
byte[] b = null;
a:for (int i = 0; i < encodes.length; i++) {
try {
b = str.getBytes(encodes[i]);
if (b.length!=data.length)
continue;
for (int j = 0; j < b.length; j++) {
if (b[j] != data[j]) {
continue a;
}
}
return encodes[i];
} catch (UnsupportedEncodingException e) {
continue;
}
}
return null;
}
public static void main(String[] args) throws IOException {
// Properties props = new Properties();
//// props.put("python.home", "F:\\Java\\jython\\jython2.7.1\\Lib");
// props.put("python.console.encoding", "UTF-8");
// props.put("python.security.respectJavaAccessibility", "false");
// props.put("python.import.site", "false");
// Properties preprops = System.getProperties();
// PythonInterpreter.initialize(preprops, props, new String[0]);
// PythonInterpreter interpreter = new PythonInterpreter();
// interpreter.exec("#coding=UTF-8 \n" +
// "print('a智障v')");
// interpreter.execfile("E:\\python\\迭代求阶乘.py");
// PythonInterpreter interpreter = new PythonInterpreter();
// interpreter.exec("# -*- encoding: utf-8 -*- \na='智障'; ");
// interpreter.exec("print a;");
// interpreter.exec("print '智障';");
// String s = "python \ndef python_main(_):\n" +
// " # result 为返回结果其中内部字段解释为ruleScore规则命中时得分hitResult规则是否命中可选值为命中/未命中\n" +
// " # fieldList 为输出字段列表内部为字典表updateInputMap 为需要更新到入参的变量是一个字典表\n" +
// "\n" +
// " result = {\"ruleScore\":0,\"hitResult\":\"未命中\",\"fieldList\":[],\"updateInputMap\":{}}\n" +
// " print(_)\n" +
// " print(\"未命中\")\n" +
// " result[\"ruleScore\"] = 420\n" +
// " result[\"hitResult\"] = \"命中\"\n" +
// " return result\n" +
// "\n" +
// "if __name__ == \"__main__\":\n" +
// " python_main(params)";
// String[] inputParam = new String[2];
// inputParam[0] = "python3";
// inputParam[1] = s;
// Runtime.getRuntime().exec(s);
}
}

View File

@@ -0,0 +1,63 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* a random double value greater than or equal to 0.0 and less than 1.0. See the
* Math.random() method in the JDK for a complete description of how this
* function works.
*/
public class Random implements Function {
/**
* Returns the name of the function - "random".
*
* @return The name of this function class.
*/
public String getName() {
return "random";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* Not used.
*
* @return A random double value greater than or equal to 0.0 and less than
* 1.0.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = new Double(Math.random());
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,73 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the double value that is closest in value to the argument and is equal to a
* mathematical integer. See the Math.rint(double) method in the JDK for a
* complete description of how this function works.
*/
public class Rint implements Function {
/**
* Returns the name of the function - "rint".
*
* @return The name of this function class.
*/
public String getName() {
return "rint";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return A double value that is closest in value to the argument and is
* equal to a mathematical integer.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.rint(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the closet long to a double value. See the Math.round(double) method in the
* JDK for a complete description of how this function works.
*/
public class Round implements Function {
/**
* Returns the name of the function - "round".
*
* @return The name of this function class.
*/
public String getName() {
return "round";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return A long value that is closest to the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Long result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Long(Math.round(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the sine of an angle. See the Math.sin(double) method in the JDK for a
* complete description of how this function works.
*/
public class Sin implements Function {
/**
* Returns the name of the function - "sin".
*
* @return The name of this function class.
*/
public String getName() {
return "sin";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return The sine of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.sin(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* a square root of a double value. See the Math.sqrt(double) method in the JDK
* for a complete description of how this function works.
*/
public class Sqrt implements Function {
/**
* Returns the name of the function - "sqrt".
*
* @return The name of this function class.
*/
public String getName() {
return "sqrt";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return A square root of the argument.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.sqrt(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,47 @@
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.math.BigDecimal;
import java.util.ArrayList;
/**
* 计算多个数字的和
*/
public class Sum implements Function {
@Override
public String getName() {
return "sum";
}
@Override
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
ArrayList<Double> numbers = FunctionHelper.getDoubles(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
int count = numbers.size() ;
if (count < 2) {
throw new FunctionException("Two numeric arguments are required at least.");
}
double sum=0;
for (Double num : numbers) {
//为什么使用这样的方法,而不直接相加呢?
//原因是Java中的简单浮点数类型float和double不能够进行运算会出现类似如下情况
//eg:sum(1,2,3,1.2,2.0,3.6)=12.79999999999而不等于12.8
BigDecimal b1=new BigDecimal(Double.toString(sum));
BigDecimal b2=new BigDecimal(Double.toString(num));
sum=b1.add(b2).doubleValue();
}
result = new Double(sum);
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,71 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* trigonometric tangent of an angle. See the Math.tan(double) method in the JDK
* for a complete description of how this function works.
*/
public class Tan implements Function {
/**
* Returns the name of the function - "tan".
*
* @return The name of this function class.
*/
public String getName() {
return "tan";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return A trigonometric tangent of an angle.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.tan(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function
* converts an angle measured in radians to the equivalent angle measured in
* degrees. See the Math.toDegrees(double) method in the JDK for a complete
* description of how this function works.
*/
public class ToDegrees implements Function {
/**
* Returns the name of the function - "toDegrees".
*
* @return The name of this function class.
*/
public String getName() {
return "toDegrees";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return A measurement of the argument in degrees.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.toDegrees(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,72 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.math;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function
* converts an angle measured in degress to the equivalent angle measured in
* radians. See the Math.toRadians(double) method in the JDK for a complete
* description of how this function works.
*/
public class ToRadians implements Function {
/**
* Returns the name of the function - "toRadians".
*
* @return The name of this function class.
*/
public String getName() {
return "toRadians";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted to a double value and
* evaluated.
*
* @return A measurement of the argument in radians.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(Evaluator evaluator, String arguments)
throws FunctionException {
Double result = null;
Double number = null;
try {
number = new Double(arguments);
} catch (Exception e) {
throw new FunctionException("Invalid argument.", e);
}
result = new Double(Math.toRadians(number.doubleValue()));
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,96 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function returns
* the character at the specified index in the source string. See the
* String.charAt(int) method in the JDK for a complete description of how this
* function works.
*/
public class CharAt implements Function {
/**
* Returns the name of the function - "charAt".
*
* @return The name of this function class.
*/
public String getName() {
return "charAt";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into one string and
* one integer argument. The first argument is the source string
* and the second argument is the index. The string argument(s)
* HAS to be enclosed in quotes. White space that is not enclosed
* within quotes will be trimmed. Quote characters in the first
* and last positions of any string argument (after being
* trimmed) will be removed also. The quote characters used must
* be the same as the quote characters used by the current
* instance of Evaluator. If there are multiple arguments, they
* must be separated by a comma (",").
*
* @return A character that is located at the specified index. The value is
* returned as a string.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
String result = null;
String exceptionMessage = "One string and one integer argument "
+ "are required.";
ArrayList values = FunctionHelper.getOneStringAndOneInteger(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (values.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) values.get(0), evaluator.getQuoteCharacter());
int index = ((Integer) values.get(1)).intValue();
char[] character = new char[1];
character[0] = argumentOne.charAt(index);
result = new String(character);
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result,
FunctionConstants.FUNCTION_RESULT_TYPE_STRING);
}
}

View File

@@ -0,0 +1,93 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function
* compares two strings lexicographically. See the String.compareTo(String)
* method in the JDK for a complete description of how this function works.
*/
public class CompareTo implements Function {
/**
* Returns the name of the function - "compareTo".
*
* @return The name of this function class.
*/
public String getName() {
return "compareTo";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is the first string to compare
* and the second argument is the second string to compare. The
* string argument(s) HAS to be enclosed in quotes. White space
* that is not enclosed within quotes will be trimmed. Quote
* characters in the first and last positions of any string
* argument (after being trimmed) will be removed also. The quote
* characters used must be the same as the quote characters used
* by the current instance of Evaluator. If there are multiple
* arguments, they must be separated by a comma (",").
*
* @return Returns an integer value of zero if the strings are equal, an
* integer value less than zero if the first string precedes the
* second string or an integer value greater than zero if the first
* string follows the second string.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Integer result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
result = new Integer(argumentOne.compareTo(argumentTwo));
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,94 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function
* compares two strings lexicographically, ignoreing case considerations. See
* the String.compareTo(String) method in the JDK for a complete description of
* how this function works.
*/
public class CompareToIgnoreCase implements Function {
/**
* Returns the name of the function - "compareToIgnoreCase".
*
* @return The name of this function class.
*/
public String getName() {
return "compareToIgnoreCase";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is the first string to compare
* and the second argument is the second argument to compare. The
* string argument(s) HAS to be enclosed in quotes. White space
* that is not enclosed within quotes will be trimmed. Quote
* characters in the first and last positions of any string
* argument (after being trimmed) will be removed also. The quote
* characters used must be the same as the quote characters used
* by the current instance of Evaluator. If there are multiple
* arguments, they must be separated by a comma (",").
*
* @return Returns an integer value of zero if the strings are equal, an
* integer value less than zero if the first string precedes the
* second string or an integer value greater than zero if the first
* string follows the second string.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
Integer result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
result = new Integer(argumentOne.compareToIgnoreCase(argumentTwo));
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result.toString(),
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,92 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function
* concatenates the second string to the end of the first. See the
* String.concat(String) method in the JDK for a complete description of how
* this function works.
*/
public class Concat implements Function {
/**
* Returns the name of the function - "concat".
*
* @return The name of this function class.
*/
public String getName() {
return "concat";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is the string in which the
* second argument string will be concatenated. The string
* argument(s) HAS to be enclosed in quotes. White space that is
* not enclosed within quotes will be trimmed. Quote characters
* in the first and last positions of any string argument (after
* being trimmed) will be removed also. The quote characters used
* must be the same as the quote characters used by the current
* instance of Evaluator. If there are multiple arguments, they
* must be separated by a comma (",").
*
* @return Returns a strng that is made up the first string, followed by the
* second string.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
String result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
result = argumentOne.concat(argumentTwo);
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result,
FunctionConstants.FUNCTION_RESULT_TYPE_STRING);
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function returns
* the index within the source string of the first occurrence of the substring,
* starting at the specified index. See the String.indexOf(String, int) method
* in the JDK for a complete description of how this function works.
*/
public class Contains implements Function {
/**
* Returns the name of the function - "indexOf".
*
* @return The name of this function class.
*/
public String getName() {
return "contains";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments and one integer argument. The first argument is the
* source string, the second argument is the substring and the
* third argument is the index. The string argument(s) HAS to be
* enclosed in quotes. White space that is not enclosed within
* quotes will be trimmed. Quote characters in the first and last
* positions of any string argument (after being trimmed) will be
* removed also. The quote characters used must be the same as
* the quote characters used by the current instance of
* Evaluator. If there are multiple arguments, they must be
* separated by a comma (",").
*
* @return Returns The index at where the substring is found. If the
* substring is not found, then -1 is returned.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
String result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
if (argumentOne.contains(argumentTwo)) {
result = EvaluationConstants.BOOLEAN_STRING_TRUE;
} else {
result = EvaluationConstants.BOOLEAN_STRING_FALSE;
}
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result,
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function tests
* if the string ends with a specified suffix. See the String.endswith(String)
* method in the JDK for a complete description of how this function works.
*/
public class EndsWith implements Function {
/**
* Returns the name of the function - "endsWith".
*
* @return The name of this function class.
*/
public String getName() {
return "endsWith";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is the string to test and second
* argument is the suffix. The string argument(s) HAS to be
* enclosed in quotes. White space that is not enclosed within
* quotes will be trimmed. Quote characters in the first and last
* positions of any string argument (after being trimmed) will be
* removed also. The quote characters used must be the same as
* the quote characters used by the current instance of
* Evaluator. If there are multiple arguments, they must be
* separated by a comma (",").
*
* @return Returns "1.0" (true) if the string ends with the suffix,
* otherwise it returns "0.0" (false). The return value respresents
* a Boolean value that is compatible with the Boolean operators
* used by Evaluator.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
String result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
if (argumentOne.endsWith(argumentTwo)) {
result = EvaluationConstants.BOOLEAN_STRING_TRUE;
} else {
result = EvaluationConstants.BOOLEAN_STRING_FALSE;
}
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result,
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function tests
* one string equals another. See the String.equals(String) method in the JDK
* for a complete description of how this function works.
*/
public class Equals implements Function {
/**
* Returns the name of the function - "equals".
*
* @return The name of this function class.
*/
public String getName() {
return "equals";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is a string that will be
* compared to the second argument / string. The string
* argument(s) HAS to be enclosed in quotes. White space that is
* not enclosed within quotes will be trimmed. Quote characters
* in the first and last positions of any string argument (after
* being trimmed) will be removed also. The quote characters used
* must be the same as the quote characters used by the current
* instance of Evaluator. If there are multiple arguments, they
* must be separated by a comma (",").
*
* @return Returns "1.0" (true) if the string ends with the suffix,
* otherwise it returns "0.0" (false). The return value respresents
* a Boolean value that is compatible with the Boolean operators
* used by Evaluator.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
String result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
if (argumentOne.equals(argumentTwo)) {
result = EvaluationConstants.BOOLEAN_STRING_TRUE;
} else {
result = EvaluationConstants.BOOLEAN_STRING_FALSE;
}
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result,
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,99 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.*;
import java.util.ArrayList;
/**
* This class is a function that executes within Evaluator. The function tests
* one string equals another, but ignores case. See the
* String.equalsIgnoreCase(String) method in the JDK for a complete description
* of how this function works.
*/
public class EqualsIgnoreCase implements Function {
/**
* Returns the name of the function - "equalsIgnoreCase".
*
* @return The name of this function class.
*/
public String getName() {
return "equalsIgnoreCase";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of Evaluator.
* @param arguments
* A string argument that will be converted into two string
* arguments. The first argument is a string that will be
* compared to the second argument / string. The string
* argument(s) HAS to be enclosed in quotes. White space that is
* not enclosed within quotes will be trimmed. Quote characters
* in the first and last positions of any string argument (after
* being trimmed) will be removed also. The quote characters used
* must be the same as the quote characters used by the current
* instance of Evaluator. If there are multiple arguments, they
* must be separated by a comma (",").
*
* @return Returns "1.0" (true) if the string ends with the suffix,
* otherwise it returns "0.0" (false). The return value respresents
* a Boolean value that is compatible with the Boolean operators
* used by Evaluator.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator, final String arguments)
throws FunctionException {
String result = null;
String exceptionMessage = "Two string arguments are required.";
ArrayList strings = FunctionHelper.getStrings(arguments,
EvaluationConstants.FUNCTION_ARGUMENT_SEPARATOR);
if (strings.size() != 2) {
throw new FunctionException(exceptionMessage);
}
try {
String argumentOne = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(0), evaluator.getQuoteCharacter());
String argumentTwo = FunctionHelper.trimAndRemoveQuoteChars(
(String) strings.get(1), evaluator.getQuoteCharacter());
if (argumentOne.equalsIgnoreCase(argumentTwo)) {
result = EvaluationConstants.BOOLEAN_STRING_TRUE;
} else {
result = EvaluationConstants.BOOLEAN_STRING_FALSE;
}
} catch (FunctionException fe) {
throw new FunctionException(fe.getMessage(), fe);
} catch (Exception e) {
throw new FunctionException(exceptionMessage, e);
}
return new FunctionResult(result,
FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC);
}
}

View File

@@ -0,0 +1,78 @@
/*
* Copyright 2002-2007 Robert Breidecker.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fibo.ddp.common.utils.util.runner.jeval.function.string;
import com.fibo.ddp.common.utils.util.runner.jeval.EvaluationException;
import com.fibo.ddp.common.utils.util.runner.jeval.Evaluator;
import com.fibo.ddp.common.utils.util.runner.jeval.function.Function;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionConstants;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionException;
import com.fibo.ddp.common.utils.util.runner.jeval.function.FunctionResult;
/**
* This class is a function that executes within Evaluator. The function returns
* the result of a Evaluator compatible expression. See the
* Evaluator.evaluate(String) method for a complete description of how this
* function works.
*/
public class Eval implements Function {
/**
* Returns the name of the function - "eval".
*
* @return The name of this function class.
*/
public String getName() {
return "eval";
}
/**
* Executes the function for the specified argument. This method is called
* internally by Evaluator.
*
* @param evaluator
* An instance of evaluator.
* @param arguments
* A string expression that is compatible with Evaluator. *** THE
* STRING ARGUMENT SHOULD NOT BE ENCLOSED IN QUOTES OR THE
* EXPRESSION MAY NOT BE EVALUATED CORRECTLY.*** *** FUNCTION
* CALLS ARE VALID WITHIN THE EVAL FUNCTION. ***
*
* @return The evaluated result fot the input expression.
*
* @exception FunctionException
* Thrown if the argument(s) are not valid for this function.
*/
public FunctionResult execute(final Evaluator evaluator,
final String arguments) throws FunctionException {
String result = null;
try {
result = evaluator.evaluate(arguments, false, true);
} catch (EvaluationException ee) {
throw new FunctionException(ee.getMessage(), ee);
}
int resultType = FunctionConstants.FUNCTION_RESULT_TYPE_NUMERIC;
try {
Double.parseDouble(result);
} catch (NumberFormatException nfe) {
resultType = FunctionConstants.FUNCTION_RESULT_TYPE_STRING;
}
return new FunctionResult(result, resultType);
}
}

Some files were not shown because too many files have changed in this diff Show More