提交 f56d1315 编写于 作者: Q qiao tian

(1)增加超时方法:TimeOutExceptionTest,

(2)安全审核方法:InvokeSecurityRiskMethodsTest,
(3)区分异常类型:ThrowExceptionTest
上级 087632f8
......@@ -6,7 +6,7 @@
<groupId>com.alibaba</groupId>
<artifactId>QLExpress</artifactId>
<packaging>jar</packaging>
<version>3.2.2</version>
<version>3.2.3-SNAPSHOT</version>
<name>QLExpress</name>
<description>QLExpress is a powerful, lightweight, dynamic language for the Java platform aimed at improving developers’ productivity in different business scenes.</description>
<url>https://github.com/alibaba/QLExpress</url>
......
package com.ql.util.express;
import com.ql.util.express.exception.QLException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
......@@ -10,7 +12,7 @@ public class DefaultExpressResourceLoader implements IExpressResourceLoader {
InputStream in = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(expressName);
if (in == null) {
throw new Exception("不能找到表达式文件:" + expressName);
throw new QLException("不能找到表达式文件:" + expressName);
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder builder = new StringBuilder();
......
package com.ql.util.express;
import com.ql.util.express.exception.QLException;
import java.lang.reflect.Array;
/**
......@@ -15,7 +17,7 @@ public class DynamicParamsUtil {
//参数定义不符合动态参数形式 || 用户自定义不支持 || 用户传入的参数不符合
if(!maybeDynamicParams || !supportDynamicParams || !maybeDynamicParams(context,list,delaredParamsClasses)){
if(delaredParamsClasses.length != list.length){
throw new Exception("定义的参数长度与运行期传入的参数长度不一致");
throw new QLException("定义的参数长度与运行期传入的参数长度不一致");
}
params = new Object[list.length];
for (int i = 0; i < list.length; i++) {
......@@ -45,7 +47,7 @@ public class DynamicParamsUtil {
}
}
}else {
throw new Exception("定义的参数长度与运行期传入的参数长度不一致");
throw new QLException("定义的参数长度与运行期传入的参数长度不一致");
}
return params;
......
......@@ -4,6 +4,7 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.FunctionInstructionSet;
......@@ -28,7 +29,7 @@ public class ExpressLoader {
throws Exception {
synchronized (expressInstructionSetCache) {
if (expressInstructionSetCache.containsKey(expressName)) {
throw new Exception("表达式定义重复:" + expressName);
throw new QLException("表达式定义重复:" + expressName);
}
expressInstructionSetCache.put(expressName, set);
}
......@@ -38,7 +39,7 @@ public class ExpressLoader {
String expressString) throws Exception {
InstructionSet parseResult = null;
if (expressInstructionSetCache.containsKey(expressName)) {
throw new Exception("表达式定义重复:" + expressName);
throw new QLException("表达式定义重复:" + expressName);
}
synchronized (expressInstructionSetCache) {
parseResult = this.creator.parseInstructionSet(expressString);
......
......@@ -4,6 +4,10 @@ import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.ql.util.express.config.QLExpressTimer;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.exception.QLTimeOutException;
import com.ql.util.express.instruction.op.*;
import com.ql.util.express.parse.*;
import com.ql.util.express.rule.Condition;
......@@ -454,11 +458,11 @@ public class ExpressRunner {
}
NodeType realNodeType = this.manager.findNodeType(realKeyWordName);
if(realNodeType == null){
throw new Exception("关键字:" + realKeyWordName +"不存在");
throw new QLException("关键字:" + realKeyWordName +"不存在");
}
boolean isExist = this.operatorManager.isExistOperator(realNodeType.getName());
if(isExist == false && errorInfo != null){
throw new Exception("关键字:" + realKeyWordName +"是通过指令来实现的,不能设置错误的提示信息,errorInfo 必须是 null");
throw new QLException("关键字:" + realKeyWordName +"是通过指令来实现的,不能设置错误的提示信息,errorInfo 必须是 null");
}
if(isExist == false || errorInfo == null){
//不需要新增操作符号,只需要建立一个关键子即可
......@@ -540,31 +544,53 @@ public class ExpressRunner {
return InstructionSetRunner.executeOuter(this,instructionSets,this.loader,context, errorList,
isTrace,isCatchException,aLog,false);
}
/**
* 执行一段文本
* @param expressString 程序文本
* @param context 执行上下文
* @param errorList 输出的错误信息List
* @param isCache 是否使用Cache中的指令集
* @param isTrace 是否输出详细的执行指令信息
* @return
* @throws Exception
*/
/**
* 执行一段文本
* @param expressString 程序文本
* @param context 执行上下文
* @param errorList 输出的错误信息List
* @param isCache 是否使用Cache中的指令集
* @param isTrace 是否输出详细的执行指令信息
* @param timeoutMillis 超时毫秒时间
* @return
* @throws Exception
*/
public Object execute(String expressString, IExpressContext<String,Object> context,
List<String> errorList, boolean isCache, boolean isTrace,long timeoutMillis) throws Exception {
//设置超时毫秒时间
QLExpressTimer.setTimer(timeoutMillis);
try {
return this.execute(expressString, context, errorList, isCache, isTrace, null);
}finally {
QLExpressTimer.reset();
}
}
/**
* 执行一段文本
* @param expressString 程序文本
* @param context 执行上下文
* @param errorList 输出的错误信息List
* @param isCache 是否使用Cache中的指令集
* @param isTrace 是否输出详细的执行指令信息
* @return
* @throws Exception
*/
public Object execute(String expressString, IExpressContext<String,Object> context,
List<String> errorList, boolean isCache, boolean isTrace) throws Exception {
List<String> errorList, boolean isCache, boolean isTrace) throws Exception {
return this.execute(expressString, context, errorList, isCache, isTrace, null);
}
/**
* 执行一段文本
* @param expressString 程序文本
* @param context 执行上下文
* @param errorList 输出的错误信息List
* @param isCache 是否使用Cache中的指令集
* @param isTrace 是否输出详细的执行指令信息
* @param aLog 输出的log
* @return
* @throws Exception
*/
/**
* 执行一段文本
* @param expressString 程序文本
* @param context 执行上下文
* @param errorList 输出的错误信息List
* @param isCache 是否使用Cache中的指令集
* @param isTrace 是否输出详细的执行指令信息
* @param aLog 输出的log
* @return
* @throws Exception
*/
public Object execute(String expressString, IExpressContext<String,Object> context,
List<String> errorList, boolean isCache, boolean isTrace, Log aLog)
throws Exception {
......@@ -663,19 +689,25 @@ public class ExpressRunner {
*/
public InstructionSet parseInstructionSet(String text)
throws Exception {
Map<String,String> selfDefineClass = new HashMap<String,String> ();
for(ExportItem item : this.loader.getExportInfo()){
if(item.getType().equals(InstructionSet.TYPE_CLASS)){
selfDefineClass.put(item.getName(), item.getName());
try {
Map<String, String> selfDefineClass = new HashMap<String, String>();
for (ExportItem item : this.loader.getExportInfo()) {
if (item.getType().equals(InstructionSet.TYPE_CLASS)) {
selfDefineClass.put(item.getName(), item.getName());
}
}
}
ExpressNode root = this.parse.parse(this.rootExpressPackage,text, isTrace,selfDefineClass);
InstructionSet result = createInstructionSet(root, "main");
if (this.isTrace && log.isDebugEnabled()) {
log.debug(result);
ExpressNode root = this.parse.parse(this.rootExpressPackage, text, isTrace, selfDefineClass);
InstructionSet result = createInstructionSet(root, "main");
if (this.isTrace && log.isDebugEnabled()) {
log.debug(result);
}
return result;
}catch (QLCompileException e){
throw e;
}catch (Exception e){
throw new QLCompileException("编译异常:\n"+text,e);
}
return result;
}
/**
* 输出全局定义信息
......@@ -719,7 +751,7 @@ public class ExpressRunner {
Stack<ForRelBreakContinue> forStack = new Stack<ForRelBreakContinue>();
createInstructionSetPrivate(result, forStack, root, true);
if (forStack.size() > 0) {
throw new Exception("For处理错误");
throw new QLCompileException("For处理错误");
}
}
......
package com.ql.util.express;
import com.ql.util.express.config.QLExpressRunStrategy;
import com.ql.util.express.exception.QLException;
import org.apache.commons.beanutils.PropertyUtils;
import java.lang.reflect.*;
......@@ -514,7 +515,7 @@ public class ExpressUtil {
while (m.find()) {
int index = Integer.parseInt(m.group().substring(1)) - 1;
if (index < 0 || index >= parameters.length) {
throw new Exception("设置的参数位置$" + (index + 1) + "超过了范围 "
throw new QLException("设置的参数位置$" + (index + 1) + "超过了范围 "
+ parameters.length);
}
m.appendReplacement(sb, " " + parameters[index].toString() + " ");
......
......@@ -8,6 +8,8 @@ import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import com.ql.util.express.config.QLExpressTimer;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.detail.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
......@@ -200,7 +202,7 @@ public class InstructionSet implements Serializable{
}
}
if (environmen.getDataStackSize() > 1) {
throw new Exception("在表达式执行完毕后,堆栈中还存在多个数据");
throw new QLException("在表达式执行完毕后,堆栈中还存在多个数据");
}
CallResult result = OperateDataCacheManager.fetchCallResult(environmen.getReturnValue(), environmen.isExit());
return result;
......@@ -209,9 +211,7 @@ public class InstructionSet implements Serializable{
Instruction instruction =null;
try {
while (environmen.programPoint < this.instructionList.length) {
// if (environmen.isExit() == true) {
// return;
// }
QLExpressTimer.assertTimeOut();
instruction = this.instructionList[environmen.programPoint];
instruction.setLog(aLog);// 设置log
instruction.execute(environmen, errorList);
......
......@@ -3,6 +3,7 @@ package com.ql.util.express;
import java.util.HashMap;
import java.util.Map;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.OperateDataCacheManager;
public class InstructionSetContext implements IExpressContext<String,Object> {
......@@ -57,7 +58,7 @@ public class InstructionSetContext implements IExpressContext<String,Object> {
}
public void addSymbol(String varName,Object aliasNameObject) throws Exception{
if(this.symbolTable.containsKey(varName)){
throw new Exception("变量" + varName + "已经存在,不能重复定义,也不能再从函数内部 exprot ");
throw new QLException("变量" + varName + "已经存在,不能重复定义,也不能再从函数内部 exprot ");
}
this.symbolTable.put(varName,aliasNameObject);
}
......
......@@ -2,6 +2,7 @@ package com.ql.util.express;
import java.util.List;
import com.ql.util.express.config.QLExpressTimer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
......@@ -14,6 +15,10 @@ public class InstructionSetRunner {
boolean isTrace,boolean isCatchException,
Log aLog,boolean isSupportDynamicFieldName) throws Exception{
try{
//开始计时
QLExpressTimer.startTimer();
OperateDataCacheManager.push(runner);
return execute(runner,sets, loader, aContext, errorList, isTrace, isCatchException,true, aLog,isSupportDynamicFieldName);
}finally{
......
package com.ql.util.express;
import com.ql.util.express.exception.QLException;
/**
* 数据类型定义
* @author qhlhl2010@gmail.com
......@@ -48,7 +50,7 @@ public class OperateData implements java.io.Serializable {
public final Object getObject(InstructionSetContext context) throws Exception {
if(this.type != null && this.type.equals(void.class)){
throw new Exception("void 不能参与任何操作运算,请检查使用在表达式中使用了没有返回值的函数,或者分支不完整的if语句");
throw new QLException("void 不能参与任何操作运算,请检查使用在表达式中使用了没有返回值的函数,或者分支不完整的if语句");
}
return getObjectInner(context);
}
......
package com.ql.util.express;
import com.ql.util.express.config.QLExpressRunStrategy;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.OperateDataCacheManager;
import com.ql.util.express.instruction.op.OperatorBase;
......@@ -24,7 +25,7 @@ public abstract class Operator extends OperatorBase {
}
Object result = this.executeInner(parameters);
if (result != null && result.getClass().equals(OperateData.class)) {
throw new Exception("操作符号定义的返回类型错误:" + this.getAliasName());
throw new QLException("操作符号定义的返回类型错误:" + this.getAliasName());
}
if (result == null) {
//return new OperateData(null,null);
......@@ -37,6 +38,43 @@ public abstract class Operator extends OperatorBase {
public abstract Object executeInner(Object[] list) throws Exception;
/**
* 进行对象是否相等的比较
* @param op1
* @param op2
* @return
* @throws Exception
*/
public static boolean objectEquals(Object op1, Object op2) throws Exception{
if (op1 == null && op2 == null) {
return true;
}
if (op1 == null || op2 == null) {
return false;
}
//Character的值比较
if(op1 instanceof Character || op2 instanceof Character){
int compareResult = 0;
if (op1 instanceof Character && op2 instanceof Character) {
return ((Character) op1).equals((Character) op2);
}else if (op1 instanceof Number) {
compareResult = OperatorOfNumber.compareNumber((Number) op1, (int) ((Character) op2).charValue());
return compareResult==0;
} else if (op2 instanceof Number) {
compareResult = OperatorOfNumber.compareNumber((int) ((Character) op1).charValue(), (Number) op2);
return compareResult==0;
}
}
//数值的值比较
if (op1 instanceof Number && op2 instanceof Number) {
//数字比较
int compareResult = OperatorOfNumber.compareNumber((Number) op1, (Number) op2);
return compareResult==0;
}
//调用原始Object的比较
return op1.equals(op2);
}
/**
* 进行对象比较
*
......@@ -65,7 +103,7 @@ public abstract class Operator extends OperatorBase {
} else if (op2 instanceof Number) {
compareResult = OperatorOfNumber.compareNumber((int) ((Character) op1).charValue(), (Number) op2);
} else {
throw new Exception(op1 + "和" + op2 + "不能执行compare 操作");
throw new QLException(op1 + "和" + op2 + "不能执行compare 操作");
}
} else if (op1 instanceof Number && op2 instanceof Number) {
//数字比较
......@@ -78,7 +116,7 @@ public abstract class Operator extends OperatorBase {
} else if ((op1 instanceof Date) && (op2 instanceof Date)) {
compareResult = ((Date) op1).compareTo((Date) op2);
} else
throw new Exception(op1 + "和" + op2 + "不能执行compare 操作");
throw new QLException(op1 + "和" + op2 + "不能执行compare 操作");
return compareResult;
}
......
package com.ql.util.express;
import com.ql.util.express.exception.QLException;
import java.math.BigDecimal;
/**
......@@ -217,7 +219,7 @@ class NormalNumberOperator {
if(type == NumberType.NUMBER_TYPE_FLOAT) return op1.floatValue() + op2.floatValue();
if(type == NumberType.NUMBER_TYPE_DOUBLE) return op1.doubleValue() + op2.doubleValue();
if(type == NumberType.NUMBER_TYPE_BIGDECIMAL) return new BigDecimal(op1.toString()).add(new BigDecimal(op2.toString()));
throw new Exception("不支持的对象执行了\"+\"操作");
throw new QLException("不支持的对象执行了\"+\"操作");
}
......@@ -233,7 +235,7 @@ class NormalNumberOperator {
if(type == NumberType.NUMBER_TYPE_FLOAT) return op1.floatValue() - op2.floatValue();
if(type == NumberType.NUMBER_TYPE_DOUBLE) return op1.doubleValue() - op2.doubleValue();
if(type == NumberType.NUMBER_TYPE_BIGDECIMAL) return new BigDecimal(op1.toString()).subtract(new BigDecimal(op2.toString()));
throw new Exception("不支持的对象执行了\"-\"操作");
throw new QLException("不支持的对象执行了\"-\"操作");
}
public static Number multiplyNormal(Number op1,Number op2) throws Exception {
......@@ -247,7 +249,7 @@ class NormalNumberOperator {
if(type == NumberType.NUMBER_TYPE_FLOAT) return op1.floatValue() * op2.floatValue();
if(type == NumberType.NUMBER_TYPE_DOUBLE) return op1.doubleValue() * op2.doubleValue();
if(type == NumberType.NUMBER_TYPE_BIGDECIMAL) return new BigDecimal(op1.toString()).multiply(new BigDecimal(op2.toString()));
throw new Exception("不支持的对象执行了\"*\"操作");
throw new QLException("不支持的对象执行了\"*\"操作");
}
public static Number divideNormal(Number op1,Number op2) throws Exception{
int type1 = OperatorOfNumber.getSeq(op1.getClass());
......@@ -260,7 +262,7 @@ class NormalNumberOperator {
if(type == NumberType.NUMBER_TYPE_FLOAT) return op1.floatValue() / op2.floatValue();
if(type == NumberType.NUMBER_TYPE_DOUBLE) return op1.doubleValue() / op2.doubleValue();
if(type == NumberType.NUMBER_TYPE_BIGDECIMAL) return new BigDecimal(op1.toString()).divide(new BigDecimal(op2.toString()), BigDecimal.ROUND_HALF_UP);
throw new Exception("不支持的对象执行了\"/\"操作");
throw new QLException("不支持的对象执行了\"/\"操作");
}
......@@ -272,7 +274,7 @@ class NormalNumberOperator {
if(type == NumberType.NUMBER_TYPE_SHORT) return op1.shortValue() % op2.shortValue();
if(type == NumberType.NUMBER_TYPE_INT) return op1.intValue() % op2.intValue();
if(type == NumberType.NUMBER_TYPE_LONG) return op1.longValue() % op2.longValue();
throw new Exception("不支持的对象执行了\"mod\"操作");
throw new QLException("不支持的对象执行了\"mod\"操作");
}
}
......
package com.ql.util.express;
import com.ql.util.express.exception.QLException;
public final class RunEnvironment {
private static int INIT_DATA_LENTH = 15;
......@@ -136,13 +137,13 @@ public final class RunEnvironment {
public OperateData[] popArrayBackUp(InstructionSetContext context,int len) throws Exception {
int start = point - len + 1;
if(start <0){
throw new Exception("堆栈溢出,请检查表达式是否错误");
throw new QLException("堆栈溢出,请检查表达式是否错误");
}
OperateData[] result = new OperateData[len];
for (int i = 0 ; i < len; i++) {
result[i] = this.dataContainer[start + i];
if(void.class.equals(result[i].getType(context))){
throw new Exception("void 不能参与任何操作运算,请检查使用在表达式中使用了没有返回值的函数,或者分支不完整的if语句");
throw new QLException("void 不能参与任何操作运算,请检查使用在表达式中使用了没有返回值的函数,或者分支不完整的if语句");
}
}
point = point - len;
......
package com.ql.util.express.config;
import com.ql.util.express.exception.QLSecurityRiskException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
/**
* ExpressRunner设置全局生效的配置,直接使用静态方法控制
*/
public class QLExpressRunStrategy {
/**
* 预防空指针
*/
private static boolean avoidNullPointer = false;
public static boolean isAvoidNullPointer() {
......@@ -14,4 +24,40 @@ public class QLExpressRunStrategy {
public static void setAvoidNullPointer(boolean avoidNullPointer) {
QLExpressRunStrategy.avoidNullPointer = avoidNullPointer;
}
/**
* 禁止调用不安全的方法
*/
private static boolean forbiddenInvokeSecurityRiskMethods = false;
public static boolean isForbiddenInvokeSecurityRiskMethods() {
return forbiddenInvokeSecurityRiskMethods;
}
public static void setForbiddenInvokeSecurityRiskMethods(boolean forbiddenInvokeSecurityRiskMethods) {
QLExpressRunStrategy.forbiddenInvokeSecurityRiskMethods = forbiddenInvokeSecurityRiskMethods;
}
private static List<String>securityRiskMethods = new ArrayList<String>();
static{
securityRiskMethods.add(System.class.getName()+"."+"exit");//系统退出
securityRiskMethods.add(Runtime.getRuntime().getClass().getName()+".exec");//运行脚本命令
}
public static void addSecurityRiskMethod(Class clazz, String methodName )
{
QLExpressRunStrategy.securityRiskMethods.add(clazz.getName()+"."+methodName);
}
public static void assertBlackMethod(Method m) throws QLSecurityRiskException {
if(forbiddenInvokeSecurityRiskMethods && m!=null){
if(securityRiskMethods.contains(m.getDeclaringClass().getName()+"."+m.getName())) {
throw new QLSecurityRiskException("使用QLExpress调用了不安全的系统方法:" + m.toString());
}
}
}
}
package com.ql.util.express.config;
import com.ql.util.express.exception.QLTimeOutException;
import java.sql.SQLTimeoutException;
/**
* @Author: tianqiao@taobao.com
* @Date: 2019/6/17 4:12 PM
*/
public class QLExpressTimer {
private static ThreadLocal<Boolean> NEED_TIMER = new ThreadLocal<Boolean>(){
@Override
protected Boolean initialValue() {
return false;
}
};
private static ThreadLocal<Long> TIME_OUT_MILLIS = new ThreadLocal<Long>(){};
private static ThreadLocal<Long> START_TIME = new ThreadLocal<Long>(){};
private static ThreadLocal<Long> END_TIME = new ThreadLocal<Long>(){};
/**
* 设置计时器
* @param timeoutMillis 超时时间
* @return
*/
public static void setTimer(long timeoutMillis)
{
NEED_TIMER.set(true);
TIME_OUT_MILLIS.set(timeoutMillis);
}
/**
* 开始计时
* @return
*/
public static void startTimer()
{
if(NEED_TIMER.get()) {
long t = System.currentTimeMillis();
START_TIME.set(t);
END_TIME.set(t+TIME_OUT_MILLIS.get());
}
}
/**
* 断言是否超时
* @throws QLTimeOutException
*/
public static void assertTimeOut() throws QLTimeOutException {
if(NEED_TIMER.get() && System.currentTimeMillis()>END_TIME.get()){
throw new QLTimeOutException("运行QLExpress脚本的下一条指令将超过了限定时间:" + TIME_OUT_MILLIS.get() + "ms");
}
}
public static boolean hasExpired()
{
if(NEED_TIMER.get() && System.currentTimeMillis()>END_TIME.get()){
return true;
}
return false;
}
public static void reset()
{
if(NEED_TIMER.get()) {
START_TIME.remove();
END_TIME.remove();
NEED_TIMER.remove();
TIME_OUT_MILLIS.remove();
}
}
}
package com.ql.util.express.exception;
/**
* 非QLExpress框架捕获的业务系统代码的异常
* @Author: tianqiao@taobao.com
* @Date: 2019/6/18 2:13 PM
*/
public class QLBizException extends Exception {
public QLBizException() {
}
public QLBizException(String message) {
super(message);
}
public QLBizException(String message, Throwable cause) {
super(message, cause);
}
}
package com.ql.util.express.exception;
/**
* 编译器的异常信息
* @Author: tianqiao@taobao.com
* @Date: 2019/6/18 2:13 PM
*/
public class QLCompileException extends Exception {
public QLCompileException() {
}
public QLCompileException(String message) {
super(message);
}
public QLCompileException(String message, Throwable cause) {
super(message, cause);
}
}
package com.ql.util.express.exception;
/**
* QLExpress的框架执行过程中捕获的异常
* @Author: tianqiao@taobao.com
* @Date: 2019/6/18 2:13 PM
*/
public class QLException extends Exception {
public QLException() {
}
public QLException(String message) {
super(message);
}
public QLException(String message, Throwable cause) {
super(message, cause);
}
}
package com.ql.util.express.exception;
/**
* 系统安全相关异常(比如调用操作系统命令等)
* @Author: tianqiao@taobao.com
* @Date: 2019/6/18 10:36 AM
*/
public class QLSecurityRiskException extends QLException {
public QLSecurityRiskException() {
}
public QLSecurityRiskException(String message) {
super(message);
}
}
package com.ql.util.express.exception;
/**
* 设置了timeoutMills造成的超时异常
* @Author: tianqiao@taobao.com
* @Date: 2019/6/18 10:36 AM
*/
public class QLTimeOutException extends QLException {
public QLTimeOutException() {
}
public QLTimeOutException(String message) {
super(message);
}
}
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.detail.InstructionOperator;
import com.ql.util.express.instruction.op.OperatorBase;
import com.ql.util.express.parse.ExpressNode;
......@@ -16,11 +17,11 @@ public class CastInstructionFactory extends InstructionFactory{
OperatorBase op = aCompile.getOperatorFactory().newInstance(node);
ExpressNode[] children = node.getChildren();
if(children.length ==0){
throw new Exception("扩展类型不存在");
throw new QLException("扩展类型不存在");
}else if(children.length > 2) {
throw new Exception("扩展操作只能有一个类型为Class的操作数");
throw new QLException("扩展操作只能有一个类型为Class的操作数");
}else if(children[0].getNodeType().isEqualsOrChild("CONST_CLASS") == false){
throw new Exception("扩展操作只能有一个类型为Class的操作数,当前的数据类型是:" + children[0].getNodeType().getName());
throw new QLException("扩展操作只能有一个类型为Class的操作数,当前的数据类型是:" + children[0].getNodeType().getName());
}
for(int i =0;i < children.length;i++){
......
......@@ -5,6 +5,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.ExpressUtil;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.instruction.detail.InstructionOperator;
import com.ql.util.express.instruction.op.OperatorBase;
import com.ql.util.express.parse.ExpressNode;
......@@ -25,7 +26,7 @@ class DefineInstructionFactory extends InstructionFactory{
node.getLeftChildren().remove(i);
tempStr = tempStr +"[]";
}else{
throw new Exception("不正确的类型定义");
throw new QLCompileException("不正确的类型定义");
}
}
if(arrayDimeCount > 0){
......
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.instruction.detail.InstructionOperator;
import com.ql.util.express.instruction.op.OperatorBase;
import com.ql.util.express.instruction.op.OperatorField;
......@@ -22,7 +23,7 @@ public class FieldCallInstructionFactory extends InstructionFactory {
//处理属性名称
if(children[1].getNodeType().getName().equalsIgnoreCase("CONST_STRING") == false){
throw new Exception("对象属性名称不是字符串常量:" + children[1] );
throw new QLCompileException("对象属性名称不是字符串常量:" + children[1] );
}
String fieldName = (String)children[1].getObjectValue();
......
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.instruction.detail.InstructionCloseNewArea;
import com.ql.util.express.instruction.detail.InstructionGoTo;
import com.ql.util.express.instruction.detail.InstructionGoToWithCondition;
......@@ -15,12 +16,12 @@ public class ForInstructionFactory extends InstructionFactory {
Stack<ForRelBreakContinue> forStack, ExpressNode node,boolean isRoot)
throws Exception {
if(node.getChildren().length < 2){
throw new Exception("for 操作符至少需要2个操作数 " );
throw new QLCompileException("for 操作符至少需要2个操作数 " );
}else if(node.getChildren().length > 2){
throw new Exception("for 操作符最多只有2个操作数 " );
throw new QLCompileException("for 操作符最多只有2个操作数 " );
}
if(node.getChildren()[0].getChildren()!= null && node.getChildren()[0].getChildren().length > 3){
throw new Exception("循环语句的设置不合适:" + node.getChildren()[0]);
throw new QLCompileException("循环语句的设置不合适:" + node.getChildren()[0]);
}
//生成作用域开始指令
result.addInstruction(new InstructionOpenNewArea().setLine(node.getLine()));
......
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.opdata.OperateDataLocalVar;
import com.ql.util.express.parse.ExpressNode;
......@@ -13,7 +14,7 @@ public class FunctionInstructionFactory extends InstructionFactory {
throws Exception {
ExpressNode[] children = node.getChildren();
if(children.length != 3){
throw new Exception("funciton 操作符需要3个操作数 " );
throw new QLException("funciton 操作符需要3个操作数 " );
}
String functionName =children[0].getValue();
ExpressNode[] varDefines = children[1].getChildren();
......@@ -29,7 +30,7 @@ public class FunctionInstructionFactory extends InstructionFactory {
while(point<varDefines.length){
if(varDefines[point].isTypeEqualsOrChild("def") == false){
throw new Exception("function的参数定义错误," + varDefines[point] + "不是一个Class");
throw new QLException("function的参数定义错误," + varDefines[point] + "不是一个Class");
}
Class<?> varClass = (Class<?>)varDefines[point].getChildren()[0].getObjectValue();
String varName = varDefines[point].getChildren()[1].getValue();
......
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.instruction.detail.InstructionGoTo;
import com.ql.util.express.instruction.detail.InstructionGoToWithCondition;
import com.ql.util.express.parse.ExpressNode;
......@@ -14,9 +15,9 @@ public class IfInstructionFactory extends InstructionFactory {
throws Exception {
ExpressNode[] oldChildren = node.getChildren();
if(oldChildren.length < 2){
throw new Exception("if 操作符至少需要2个操作数 " );
throw new QLCompileException("if 操作符至少需要2个操作数 " );
}else if(oldChildren.length > 5){
throw new Exception("if 操作符最多只有5个操作数 " );
throw new QLCompileException("if 操作符最多只有5个操作数 " );
}
ExpressNode[] children = new ExpressNode[3];
int point = 0;
......
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.detail.InstructionCallMacro;
import com.ql.util.express.instruction.detail.InstructionLoadAttr;
import com.ql.util.express.parse.ExpressNode;
......@@ -19,7 +20,7 @@ public class LoadAttrInstructionFactory extends InstructionFactory {
}else{
result.addInstruction(new InstructionLoadAttr(node.getValue()).setLine(node.getLine()));
if(node.getChildren().length >0){
throw new Exception("表达式设置错误");
throw new QLException("表达式设置错误");
}
}
return false;
......
......@@ -4,6 +4,7 @@ import java.util.Stack;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.detail.InstructionOperator;
import com.ql.util.express.instruction.op.OperatorBase;
import com.ql.util.express.instruction.op.OperatorMethod;
......@@ -21,7 +22,7 @@ public class MethodCallInstructionFactory extends InstructionFactory {
returnVal = returnVal || tmpHas;
//处理方法名称
if(children[1].getNodeType().getName().equalsIgnoreCase("CONST_STRING") == false){
throw new Exception("对象方法名称不是字符串常量:" + children[1] );
throw new QLException("对象方法名称不是字符串常量:" + children[1] );
}
String methodName = (String)children[1].getObjectValue();
//处理方法参数
......
......@@ -2,6 +2,7 @@ package com.ql.util.express.instruction.detail;
import java.util.List;
import com.ql.util.express.exception.QLException;
import org.apache.commons.logging.Log;
import com.ql.util.express.ArraySwap;
......@@ -59,7 +60,7 @@ public class InstructionCallSelfDefineFunction extends Instruction{
Object function = environment.getContext().getSymbol(functionName);
if (function == null || function instanceof InstructionSet == false) {
throw new Exception(getExceptionPrefix()+"在Runner的操作符定义和自定义函数中都没有找到\""
throw new QLException(getExceptionPrefix()+"在Runner的操作符定义和自定义函数中都没有找到\""
+ this.functionName + "\"的定义");
}
InstructionSet functionSet = (InstructionSet)function;
......
......@@ -4,6 +4,7 @@ import java.util.List;
import com.ql.util.express.OperateData;
import com.ql.util.express.RunEnvironment;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.OperateDataCacheManager;
public class InstructionGoToWithCondition extends Instruction{
......@@ -37,7 +38,7 @@ public class InstructionGoToWithCondition extends Instruction{
}else if(o instanceof Boolean){
r = ((Boolean)o).booleanValue();
}else{
throw new Exception(getExceptionPrefix()+"指令错误:" + o + " 不是Boolean");
throw new QLException(getExceptionPrefix()+"指令错误:" + o + " 不是Boolean");
}
if (r == this.condition) {
if (environment.isTrace() && log.isDebugEnabled()) {
......
......@@ -2,6 +2,8 @@ package com.ql.util.express.instruction.detail;
import java.util.List;
import com.ql.util.express.exception.QLBizException;
import com.ql.util.express.exception.QLException;
import org.apache.commons.logging.Log;
import com.ql.util.express.ArraySwap;
......@@ -44,9 +46,11 @@ public class InstructionOperator extends Instruction{
OperateData result = this.operator.execute(environment.getContext(), parameters, errorList);
environment.push(result);
environment.programPointAddOne();
}catch (Exception e){
throw new Exception(getExceptionPrefix(),e);
}
}catch (QLException e){
throw new QLException(getExceptionPrefix(),e);
}catch (Throwable t){
throw new QLBizException(getExceptionPrefix(),t);
}
}
public String toString(){
String result = "OP : " + this.operator.toString() + " OPNUMBER[" + this.opDataNumber +"]";
......
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
/**
* 处理 And,Or操作
......@@ -32,7 +33,7 @@ public class OperatorAnd extends Operator {
r1 = ((Boolean) o1).booleanValue();
}else{
String msg = "没有定义类型" + o1 + "和" + o2 + " 的 " + this.name + "操作";
throw new Exception(msg);
throw new QLException(msg);
}
if(o2 == null){
r2 = false;
......@@ -40,7 +41,7 @@ public class OperatorAnd extends Operator {
r2 = ((Boolean) o2).booleanValue();
}else{
String msg = "没有定义类型" + o1 + "和" + o2 + " 的 " + this.name + "操作";
throw new Exception(msg);
throw new QLException(msg);
}
boolean result = r1 && r2;
return Boolean.valueOf(result);
......
......@@ -3,6 +3,7 @@ package com.ql.util.express.instruction.op;
import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.OperateDataCacheManager;
import com.ql.util.express.instruction.opdata.OperateDataArrayItem;
......@@ -19,11 +20,11 @@ public class OperatorArray extends OperatorBase {
public OperateData executeInner(InstructionSetContext context, ArraySwap list) throws Exception {
OperateData p0 = list.get(0);
if(p0 == null || p0.getObject(context) == null){
throw new Exception("对象为null,不能执行数组相关操作");
throw new QLException("对象为null,不能执行数组相关操作");
}
Object tmpObject = p0.getObject(context);
if( tmpObject.getClass().isArray() == false){
throw new Exception("对象:"+ tmpObject.getClass() +"不是数组,不能执行相关操作" );
throw new QLException("对象:"+ tmpObject.getClass() +"不是数组,不能执行相关操作" );
}
int index = ((Number)list.get(1).getObject(context)).intValue();
OperateData result = OperateDataCacheManager.fetchOperateDataArrayItem((OperateData)p0,index);
......
......@@ -16,6 +16,7 @@ import com.ql.util.express.ArraySwap;
import com.ql.util.express.ExpressUtil;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.opdata.OperateDataAttr;
/**
......@@ -141,7 +142,7 @@ class OperatorFunction extends OperatorBase {
}
public OperateData executeInner(InstructionSetContext context, ArraySwap list) throws Exception {
throw new Exception("还没有实现");
throw new QLException("还没有实现");
}
}
......@@ -159,7 +160,7 @@ class OperatorReturn extends OperatorBase{
}
public OperateData executeInner(InstructionSetContext parent) throws Exception {
throw new Exception("return 是通过特殊指令来实现的,不能支持此方法");
throw new QLException("return 是通过特殊指令来实现的,不能支持此方法");
}
}
class OperatorCall extends OperatorBase{
......@@ -172,7 +173,7 @@ class OperatorCall extends OperatorBase{
this.errorInfo = aErrorInfo;
}
public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {
throw new Exception("call 是通过特殊指令来实现的,不能支持此方法");
throw new QLException("call 是通过特殊指令来实现的,不能支持此方法");
}
}
......@@ -186,7 +187,7 @@ class OperatorBreak extends OperatorBase{
this.errorInfo = aErrorInfo;
}
public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {
throw new Exception("OperatorBreak 是通过特殊指令来实现的,不能支持此方法");
throw new QLException("OperatorBreak 是通过特殊指令来实现的,不能支持此方法");
}
}
class OperatorContinue extends OperatorBase{
......@@ -199,7 +200,7 @@ class OperatorContinue extends OperatorBase{
this.errorInfo = aErrorInfo;
}
public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {
throw new Exception("OperatorContinue 是通过特殊指令来实现的,不能支持此方法");
throw new QLException("OperatorContinue 是通过特殊指令来实现的,不能支持此方法");
}
}
......@@ -215,7 +216,7 @@ class OperatorFor extends OperatorBase {
}
public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {
throw new Exception("cache 是通过特殊指令来实现的,不能支持此方法");
throw new QLException("cache 是通过特殊指令来实现的,不能支持此方法");
}
}
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
import java.util.Arrays;
......@@ -23,7 +24,7 @@ public class OperatorBit extends Operator {
return ~(((Number) list[0]).longValue());
}
}else{
throw new Exception("取反操作符 ~ 参数不合法:"+ Arrays.toString(list));
throw new QLException("取反操作符 ~ 参数不合法:"+ Arrays.toString(list));
}
}
if( this.name.equals("&")){
......@@ -33,7 +34,7 @@ public class OperatorBit extends Operator {
}
return (((Number)list[0]).longValue())&(((Number)list[1]).longValue());
}else{
throw new Exception("按位与操作符 & 两边的参数不合法:"+ Arrays.toString(list));
throw new QLException("按位与操作符 & 两边的参数不合法:"+ Arrays.toString(list));
}
}
if( this.name.equals("|")){
......@@ -43,7 +44,7 @@ public class OperatorBit extends Operator {
}
return (((Number)list[0]).longValue())|(((Number)list[1]).longValue());
}else{
throw new Exception("按位或操作符 | 两边的参数不合法:"+ Arrays.toString(list));
throw new QLException("按位或操作符 | 两边的参数不合法:"+ Arrays.toString(list));
}
}
if( this.name.equals("^")){
......@@ -53,7 +54,7 @@ public class OperatorBit extends Operator {
}
return (((Number)list[0]).longValue())^(((Number)list[1]).longValue());
}else{
throw new Exception("按位异或操作符 ^ 两边的参数不合法:"+ Arrays.toString(list));
throw new QLException("按位异或操作符 ^ 两边的参数不合法:"+ Arrays.toString(list));
}
}
if( this.name.equals("<<")){
......@@ -63,7 +64,7 @@ public class OperatorBit extends Operator {
}
return (((Number)list[0]).longValue())<<(((Number)list[1]).longValue());
}else{
throw new Exception("左移操作符 << 两边的参数不合法:"+ Arrays.toString(list));
throw new QLException("左移操作符 << 两边的参数不合法:"+ Arrays.toString(list));
}
}
if( this.name.equals(">>")){
......@@ -73,9 +74,9 @@ public class OperatorBit extends Operator {
}
return (((Number)list[0]).longValue())>>(((Number)list[1]).longValue());
}else{
throw new Exception("右移操作符 >> 两边的参数不合法:"+ Arrays.toString(list));
throw new QLException("右移操作符 >> 两边的参数不合法:"+ Arrays.toString(list));
}
}
throw new Exception("不支持的位运算操作符:"+ Arrays.toString(list));
throw new QLException("不支持的位运算操作符:"+ Arrays.toString(list));
}
}
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
/**
/**
* 处理比较操作符号
*/
public class OperatorEqualsLessMore extends Operator {
......@@ -28,26 +29,18 @@ public class OperatorEqualsLessMore extends Operator {
public static boolean executeInner(String opStr, Object obj1, Object obj2)
throws Exception {
if (obj1 == null && obj2 == null) {
if (opStr.equals("==")) {
return true;
} else if (opStr.equals("!=") || opStr.equals("<>")) {
return false;
} else {
throw new Exception("两个空操作数不能执行这个操作:" + opStr);
}
} else if (obj1 == null || obj2 == null) {
if (opStr.equals("==")) {
return false;
} else if (opStr.equals("!=") || opStr.equals("<>")) {
return true;
} else {
throw new Exception("空操作数不能执行这个操作:" + opStr);
}
}
int i = Operator.compareData(obj1, obj2);
if(opStr.equals("==")){
return Operator.objectEquals(obj1, obj2);
}
if(opStr.equals("!=")||opStr.equals("<>")){
return !Operator.objectEquals(obj1, obj2);
}
//进行其他大小比较操作
if (obj1 == null || obj2 == null){
throw new QLException("空操作数无法进行数字比较操作:left = " + obj1+",right = "+ obj2);
}
int i = Operator.compareData(obj1, obj2);
boolean result = false;
if (i > 0) {
if (opStr.equals(">") || opStr.equals(">=") || opStr.equals("!=")
......
......@@ -4,6 +4,7 @@ import com.ql.util.express.ArraySwap;
import com.ql.util.express.ExpressUtil;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.exception.QLException;
public class OperatorEvaluate extends OperatorBase {
public OperatorEvaluate(String name) {
......@@ -24,7 +25,7 @@ public class OperatorEvaluate extends OperatorBase {
Class<?> sourceType = op2.getType(parent);
if (targetType != null) {
if (ExpressUtil.isAssignable(targetType, sourceType) == false) {
throw new Exception("赋值时候,类型转换错误:"
throw new QLException("赋值时候,类型转换错误:"
+ ExpressUtil.getClassName(sourceType) + " 不能转换为 "
+ ExpressUtil.getClassName(targetType));
}
......
......@@ -4,6 +4,8 @@ import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.parse.ExpressNode;
public class OperatorFactory {
......@@ -81,11 +83,11 @@ public class OperatorFactory {
@SuppressWarnings("unchecked")
public void addOperatorWithAlias(String aAliasName,String name,String errorInfo) throws Exception{
if (this.operator.containsKey(name) == false){
throw new Exception(name + " 不是系统级别的操作符号,不能设置别名");
throw new QLException(name + " 不是系统级别的操作符号,不能设置别名");
}else{
OperatorBase orgiOperator = this.operator.get(name);
if(orgiOperator == null){
throw new Exception(name + " 不能被设置别名");
throw new QLException(name + " 不能被设置别名");
}
OperatorBase destOperator = null;
if (orgiOperator instanceof CanClone) {
......@@ -97,10 +99,10 @@ public class OperatorFactory {
constructor = (Constructor<OperatorBase>) opClass
.getConstructor(String.class, String.class,String.class);
} catch (Exception e) {
throw new Exception(name + " 不能被设置别名:" + e.getMessage());
throw new QLException(name + " 不能被设置别名:" + e.getMessage());
}
if (constructor == null) {
throw new Exception(name + " 不能被设置别名");
throw new QLException(name + " 不能被设置别名");
}
destOperator = constructor.newInstance(aAliasName, name,errorInfo);
}
......@@ -129,13 +131,13 @@ public class OperatorFactory {
op = operator.get(opItem.getValue());
}
if (op == null)
throw new Exception("没有为\"" + opItem.getValue() + "\"定义操作符处理对象");
throw new QLCompileException("没有为\"" + opItem.getValue() + "\"定义操作符处理对象");
return op;
}
public OperatorBase newInstance(String opName) throws Exception {
OperatorBase op = operator.get(opName);
if (op == null){
throw new Exception("没有为\"" + opName + "\"定义操作符处理对象");
throw new QLCompileException("没有为\"" + opName + "\"定义操作符处理对象");
}
return op;
}
......
......@@ -3,6 +3,7 @@ package com.ql.util.express.instruction.op;
import com.ql.util.express.ArraySwap;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.exception.QLException;
public class OperatorIf extends OperatorBase {
public OperatorIf(String aName) {
......@@ -17,15 +18,15 @@ public class OperatorIf extends OperatorBase {
public OperateData executeInner(InstructionSetContext parent, ArraySwap list) throws Exception {
if(list.length <2){
throw new Exception("\"" + this.aliasName + "\"操作至少要两个操作数");
throw new QLException("\"" + this.aliasName + "\"操作至少要两个操作数");
}
Object obj = list.get(0).getObject(parent);
if (obj == null) {
String msg ="\"" + this.aliasName + "\"的判断条件不能为空";
throw new Exception(msg);
throw new QLException(msg);
} else if ((obj instanceof Boolean) == false) {
String msg = "\"" + this.aliasName + "\"的判断条件 必须是 Boolean,不能是:";
throw new Exception(msg + obj.getClass().getName());
throw new QLException(msg + obj.getClass().getName());
} else {
if (((Boolean)obj).booleanValue() == true){
return list.get(1);
......
......@@ -5,6 +5,7 @@ import java.util.List;
import com.ql.util.express.Operator;
import com.ql.util.express.config.QLExpressRunStrategy;
import com.ql.util.express.exception.QLException;
public class OperatorIn extends Operator {
public OperatorIn(String aName) {
......@@ -26,10 +27,10 @@ public class OperatorIn extends Operator {
}
// 对象为空,不能执行方法
String msg = "对象为空,不能执行方法:";
throw new Exception(msg + this.name);
throw new QLException(msg + this.name);
} else if (((obj instanceof Number) || (obj instanceof String)) == false) {
String msg = "对象类型不匹配,只有数字和字符串类型才才能执行 in 操作,当前数据类型是:";
throw new Exception(msg + obj.getClass().getName());
throw new QLException(msg + obj.getClass().getName());
} else if(list.length == 2 && (list[1].getClass().isArray() || list[1] instanceof List)){
if(obj.equals(list[1]) == true){
return true;
......
......@@ -7,6 +7,7 @@ import com.ql.util.express.ExpressUtil;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.config.QLExpressRunStrategy;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.OperateDataCacheManager;
import com.ql.util.express.instruction.opdata.OperateClass;
import com.ql.util.express.instruction.opdata.OperateDataVirClass;
......@@ -41,7 +42,7 @@ public class OperatorMethod extends OperatorBase {
}
// 对象为空,不能执行方法
String msg = "对象为空,不能执行方法:";
throw new Exception(msg + this.methodName);
throw new QLException(msg + this.methodName);
} else {
Class<?>[] types = new Class[list.length - 1];
Class<?>[] orgiTypes = new Class[list.length - 1];
......@@ -69,8 +70,14 @@ public class OperatorMethod extends OperatorBase {
m = ExpressUtil.findMethodWithCache((Class<?>) obj, this.methodName,
types, true, true);
} else {
m = ExpressUtil.findMethodWithCache(obj.getClass(), this.methodName,
types, true, false);
if(obj instanceof Class){
m = ExpressUtil.findMethodWithCache((Class<?>) obj, this.methodName,
types, true, true);
}
if(m==null) {
m = ExpressUtil.findMethodWithCache(obj.getClass(), this.methodName,
types, true, false);
}
}
if(m == null){
types = new Class[]{ArrayClass};
......@@ -97,9 +104,11 @@ public class OperatorMethod extends OperatorBase {
}
}
s.append(")");
throw new Exception(s.toString());
throw new QLException(s.toString());
}
//阻止调用不安全的方法
QLExpressRunStrategy.assertBlackMethod(m);
if (p0 instanceof OperateClass) {// 调用静态方法
boolean oldA = m.isAccessible();
m.setAccessible(true);
......
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
public class OperatorMinMax extends Operator {
public OperatorMinMax(String name) {
......@@ -9,7 +10,7 @@ public class OperatorMinMax extends Operator {
public Object executeInner(Object[] list) throws Exception {
if (list.length == 0){
throw new Exception("操作数异常");
throw new QLException("操作数异常");
}
Object result = list[0];
......
......@@ -7,6 +7,7 @@ import com.ql.util.express.ArraySwap;
import com.ql.util.express.ExpressUtil;
import com.ql.util.express.InstructionSetContext;
import com.ql.util.express.OperateData;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.OperateDataCacheManager;
public class OperatorNew extends OperatorBase {
......@@ -51,7 +52,7 @@ public class OperatorNew extends OperatorBase {
s.append(types[i].getName());
}
s.append(")");
throw new Exception(s.toString());
throw new QLException(s.toString());
}
tmpObj = c.newInstance(objs);
......
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
public class OperatorNot extends Operator {
public OperatorNot(String name) {
......@@ -19,7 +20,7 @@ public class OperatorNot extends Operator {
throws Exception {
Object result = null;
if (op == null){
throw new Exception("null 不能执行操作:" + this.getAliasName());
throw new QLException("null 不能执行操作:" + this.getAliasName());
}
if (Boolean.class.equals(op.getClass()) == true) {
boolean r = !((Boolean) op).booleanValue();
......@@ -28,7 +29,7 @@ public class OperatorNot extends Operator {
//
String msg = "没有定义类型" + op.getClass().getName() + " 的 " + this.name
+ "操作";
throw new Exception(msg);
throw new QLException(msg);
}
return result;
}
......
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
public class OperatorOr extends Operator {
public OperatorOr(String name) {
......@@ -27,7 +28,7 @@ public class OperatorOr extends Operator {
r1 = ((Boolean) o1).booleanValue();
}else{
String msg = "没有定义类型" + o1 + "和" + o2 + " 的 " + this.name + "操作";
throw new Exception(msg);
throw new QLException(msg);
}
if(o2 == null){
r2 = false;
......@@ -35,7 +36,7 @@ public class OperatorOr extends Operator {
r2 = ((Boolean) o2).booleanValue();
}else{
String msg = "没有定义类型" + o1 + "和" + o2 + " 的 " + this.name + "操作";
throw new Exception(msg);
throw new QLException(msg);
}
boolean result = r1 || r2;
return Boolean.valueOf(result);
......
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
public class OperatorPrint extends Operator {
public OperatorPrint(String name) {
......@@ -13,7 +14,7 @@ public class OperatorPrint extends Operator {
}
public Object executeInner(Object[] list) throws Exception {
if (list.length != 1 ){
throw new Exception("操作数异常,有且只能有一个操作数");
throw new QLException("操作数异常,有且只能有一个操作数");
}
System.out.print(list[0]);
return null;
......
package com.ql.util.express.instruction.op;
import com.ql.util.express.Operator;
import com.ql.util.express.exception.QLException;
public class OperatorPrintln extends Operator {
public OperatorPrintln(String name) {
......@@ -13,7 +14,7 @@ public class OperatorPrintln extends Operator {
}
public Object executeInner(Object[] list) throws Exception {
if (list.length != 1 ){
throw new Exception("操作数异常,有且只能有一个操作数");
throw new QLException("操作数异常,有且只能有一个操作数");
}
System.out.println(list[0]);
return null;
......
......@@ -2,6 +2,7 @@ package com.ql.util.express.instruction.opdata;
import java.util.List;
import com.ql.util.express.exception.QLException;
import org.apache.commons.logging.Log;
import com.ql.util.express.InstructionSet;
......@@ -39,7 +40,7 @@ public class OperateDataVirClass extends OperateDataAttr{
parent.getExpressRunner(),parent,parent.getExpressLoader(),parent.isSupportDynamicFieldName());
Object functionSet = parent.getSymbol(this.name);
if (functionSet == null || functionSet instanceof InstructionSet == false) {
throw new Exception("没有找到自定义对象\"" + this.name + "\"");
throw new QLException("没有找到自定义对象\"" + this.name + "\"");
}
this.virClassInstructionSet = (InstructionSet)functionSet;
......@@ -56,7 +57,7 @@ public class OperateDataVirClass extends OperateDataAttr{
public OperateData callSelfFunction(String functionName,OperateData[] parameters) throws Exception{
Object function = this.context.getSymbol(functionName);
if (function == null || function instanceof InstructionSet == false) {
throw new Exception("在VClass:"+ this.name +"中没有定义函数\"" + functionName + "\"");
throw new QLException("在VClass:"+ this.name +"中没有定义函数\"" + functionName + "\"");
}
InstructionSet functionSet = (InstructionSet)function;
......@@ -99,7 +100,7 @@ public class OperateDataVirClass extends OperateDataAttr{
return result;
}
}else{
throw new Exception("不支持的数据类型:" + o.getClass().getName());
throw new QLException("不支持的数据类型:" + o.getClass().getName());
}
}
public void setValue(String name,Object value) throws Exception{
......@@ -107,7 +108,7 @@ public class OperateDataVirClass extends OperateDataAttr{
if(o instanceof OperateData){
((OperateData)o).setObject(context,value);
}else{
throw new Exception("不支持的数据类型:" + o.getClass().getName());
throw new QLException("不支持的数据类型:" + o.getClass().getName());
}
}
public Class<?> getValueType(Object name) throws Exception{
......@@ -115,7 +116,7 @@ public class OperateDataVirClass extends OperateDataAttr{
if(o instanceof OperateData){
return ((OperateData)o).getType(context);
}else{
throw new Exception("不支持的数据类型:" + o.getClass().getName());
throw new QLException("不支持的数据类型:" + o.getClass().getName());
}
}
public Object getObjectInner(InstructionSetContext context) {
......
......@@ -4,6 +4,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import com.ql.util.express.exception.QLCompileException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
......@@ -30,9 +31,9 @@ public class QLPattern {
}
if(result == null || result.getMatchSize() == 0){
throw new Exception("程序错误,不满足语法规范,没有匹配到合适的语法,最大匹配致[0:" + (maxMatchPoint.longValue()-1) +"]");
throw new QLCompileException("程序错误,不满足语法规范,没有匹配到合适的语法,最大匹配致[0:" + (maxMatchPoint.longValue()-1) +"]");
}else if(result != null && result.getMatchSize() != 1){
throw new Exception("程序错误,不满足语法规范,必须有一个根节点:" + pattern + ",最大匹配致[0:" + (maxMatchPoint.longValue()-1) +"]");
throw new QLCompileException("程序错误,不满足语法规范,必须有一个根节点:" + pattern + ",最大匹配致[0:" + (maxMatchPoint.longValue()-1) +"]");
}
return result;
}
......@@ -85,7 +86,7 @@ public class QLPattern {
resultDetail = findMatchStatementWithAddRootOptimizeStack(staticParams,pattern.nodeType.getPatternNode(),pointDetail,false,deep);
if(pattern.targetNodeType != null && resultDetail != null && resultDetail.getMatchSize() >0){
if(resultDetail.getMatchSize() > 1){
throw new Exception("设置了类型转换的语法,只能有一个根节点");
throw new QLCompileException("设置了类型转换的语法,只能有一个根节点");
}
resultDetail.getMatchs().get(0).targetNodeType = pattern.targetNodeType;
}
......@@ -135,7 +136,7 @@ public class QLPattern {
pointAnd = tempResultAnd.getMatchLastIndex();
if (item.isTreeRoot == true && tempResultAnd.getMatchSize() >0) {
if (tempResultAnd.getMatchSize() > 1) {
throw new Exception("根节点的数量必须是1");
throw new QLCompileException("根节点的数量必须是1");
}
if (root == null) {
QLMatchResultTree tempTree = tempResultAnd.getMatchs().get(0);
......@@ -192,7 +193,7 @@ public class QLPattern {
}
}else{
throw new Exception("不正确的类型:" + pattern.matchMode.toString());
throw new QLCompileException("不正确的类型:" + pattern.matchMode.toString());
}
if(tempResult == null){
......@@ -214,7 +215,7 @@ public class QLPattern {
lastPoint = tempResult.getMatchLastIndex();
if(pattern.isTreeRoot == true){
if(tempResult.getMatchSize() > 1){
throw new Exception("根节点的数量必须是1");
throw new QLCompileException("根节点的数量必须是1");
}
if(tempList.size() == 0){
tempList.addAll(tempResult.getMatchs());
......
......@@ -3,6 +3,7 @@ package com.ql.util.express.match;
import java.util.ArrayList;
import java.util.List;
import com.ql.util.express.exception.QLCompileException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
......@@ -95,7 +96,7 @@ public class QLPatternNode{
protected QLPatternNode(INodeTypeManager aManager,String aName,String aOrgiContent) throws Exception{
this(aManager,aName,aOrgiContent,false,1);
// if(this.toString().equals(aOrgiContent)==false){
//throw new Exception("语法定义解析后的结果与原始值不一致,原始值:"+ aOrgiContent + " 解析结果:" + this.toString());
//throw new QLCompileException("语法定义解析后的结果与原始值不一致,原始值:"+ aOrgiContent + " 解析结果:" + this.toString());
//log.error(("语法定义解析后的结果与原始值不一致,原始值:"+ aOrgiContent + " 解析结果:" + this.toString()));
// }
}
......@@ -146,7 +147,7 @@ public class QLPatternNode{
}else if(orgStr.charAt(i) == '$'){
if (this.matchMode != MatchMode.NULL
&& this.matchMode != MatchMode.AND) {
throw new Exception("不正确的模式串,在一个匹配模式中不能|,$并存,请使用字串模式:"
throw new QLCompileException("不正确的模式串,在一个匹配模式中不能|,$并存,请使用字串模式:"
+ orgStr);
}
children.add(new QLPatternNode(this.nodeTypeManager,"ANONY_PATTERN",tempStr, false,this.level + 1));
......@@ -155,7 +156,7 @@ public class QLPatternNode{
}else if(orgStr.charAt(i) == '|'){
if (this.matchMode != MatchMode.NULL
&& this.matchMode != MatchMode.OR) {
throw new Exception("不正确的模式串,在一个匹配模式中不能|,$并存,请使用字串模式:"
throw new QLCompileException("不正确的模式串,在一个匹配模式中不能|,$并存,请使用字串模式:"
+ orgStr);
}
children.add(new QLPatternNode(this.nodeTypeManager,"ANONY_PATTERN",tempStr, false,this.level + 1));
......@@ -170,7 +171,7 @@ public class QLPatternNode{
}
// 处理没有()的内容
if (count > 0) {
throw new Exception("不正确的模式串,(没有找到对应的):" + orgStr);
throw new QLCompileException("不正确的模式串,(没有找到对应的):" + orgStr);
}
if(this.children.size() > 0){
......
......@@ -3,6 +3,7 @@ package com.ql.util.express.parse;
import java.util.ArrayList;
import java.util.List;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.match.IDataNode;
import com.ql.util.express.match.INodeType;
......@@ -55,7 +56,7 @@ public class ExpressNode implements IDataNode{
}
public ExpressNode(NodeType aType,String aValue,String aOrgiValue,Object aObjectValue,NodeType aTreeType,int aLine,int aCol,int wordIndex) throws Exception{
if(aType == null){
throw new Exception(aValue + " 没有找到对应的节点类型");
throw new QLCompileException(aValue + " 没有找到对应的节点类型");
}
this.nodeType = aType;
this.treeType = aTreeType;
......
......@@ -6,6 +6,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ql.util.express.exception.QLCompileException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
......@@ -179,7 +180,7 @@ public class ExpressParse {
point = point + 1;
}else if(firstChar =='"'){
if(lastChar !='"' || tempWord.length() <2){
throw new Exception("没有关闭的字符串:" + tempWord);
throw new QLCompileException("没有关闭的字符串:" + tempWord);
}
tempWord = tempWord.substring(1,tempWord.length() -1);
tempType =nodeTypeManager.findNodeType("CONST_STRING");
......@@ -188,7 +189,7 @@ public class ExpressParse {
point = point + 1;
}else if(firstChar =='\''){
if(lastChar !='\'' || tempWord.length() <2){
throw new Exception("没有关闭的字符:" + tempWord);
throw new QLCompileException("没有关闭的字符:" + tempWord);
}
tempWord = tempWord.substring(1,tempWord.length() -1);
......@@ -392,12 +393,12 @@ public class ExpressParse {
QLMatchResult result = QLPattern.findMatchStatement(this.nodeTypeManager, this.nodeTypeManager
.findNodeType("PROGRAM").getPatternNode(), tempList,0);
if(result == null){
throw new Exception("语法匹配失败");
throw new QLCompileException("语法匹配失败");
}
if(result.getMatchLastIndex() < tempList.size()){
int maxPoint = result.getMatchLastIndex();
ExpressNode tempNode = tempList.get(maxPoint);
throw new Exception("还有单词没有完成语法匹配:" + result.getMatchLastIndex() +"["+ tempNode.getValue() + ":line=" + tempNode.getLine() + ",col=" + tempNode.getCol() +"] 之后的单词 \n" + express);
throw new QLCompileException("还有单词没有完成语法匹配:" + result.getMatchLastIndex() +"["+ tempNode.getValue() + ":line=" + tempNode.getLine() + ",col=" + tempNode.getCol() +"] 之后的单词 \n" + express);
}
result.getMatchs().get(0).buildExpressNodeTree();
ExpressNode root =(ExpressNode)result.getMatchs().get(0).getRef();
......
......@@ -9,7 +9,7 @@ public class Word {
public Word(String aWord,int aLine,int aCol){
this.word = aWord;
this.line = aLine;
this.col = aCol - aWord.length() + 1;
this.col = aCol;
}
public String toString(){
return this.word;// + "[" + this.line + "," + this.col + "]";
......
package com.ql.util.express.parse;
import com.ql.util.express.exception.QLCompileException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
......@@ -31,6 +33,8 @@ public class WordSplit
List<Word> list = new ArrayList<Word>();
int i= 0;
int point = 0;
// 当前行第一个字符相对脚本起点的偏移量offset
int currentLineOffset = 0;
while(i<str.length()){
c = str.charAt(i);
if (c=='"' || c=='\''){//字符串处理
......@@ -40,7 +44,7 @@ public class WordSplit
index = str.indexOf(c,index + 1);
}
if (index < 0)
throw new Exception("字符串没有关闭");
throw new QLCompileException("字符串没有关闭");
String tempDealStr = str.substring(i,index + 1);
//处理 \\,\"的情况
String tmpResult = "";
......@@ -48,17 +52,17 @@ public class WordSplit
while(tmpPoint >=0 ){
tmpResult = tmpResult + tempDealStr.substring(0,tmpPoint);
if(tmpPoint == tempDealStr.length() -1){
throw new Exception("字符串中的" + "\\错误:" + tempDealStr);
throw new QLCompileException("字符串中的" + "\\错误:" + tempDealStr);
}
tmpResult = tmpResult + tempDealStr.substring(tmpPoint + 1 ,tmpPoint + 2);
tempDealStr = tempDealStr.substring(tmpPoint + 2);
tmpPoint = tempDealStr.indexOf("\\");
}
tmpResult = tmpResult + tempDealStr;
list.add(new Word(tmpResult,line,i));
list.add(new Word(tmpResult,line,i - currentLineOffset + 1));
if (point < i ){
list.add(new Word(str.substring(point,i),line,i));
list.add(new Word(str.substring(point,i),line,point - currentLineOffset + 1));
}
i = index + 1;
point = i;
......@@ -66,10 +70,11 @@ public class WordSplit
i = i + 1; //小数点的特殊处理
}else if(c == ' ' ||c =='\r'|| c =='\n'||c=='\t'||c=='\u000C'){
if (point < i ){
list.add(new Word(str.substring(point,i),line,i));
list.add(new Word(str.substring(point,i),line,point - currentLineOffset + 1));
}
if(c =='\n'){
line = line + 1;
line = line + 1;
currentLineOffset = i + 1;
}
i = i + 1;
point = i;
......@@ -79,9 +84,9 @@ public class WordSplit
int length = s.length();
if(i + length <= str.length() && str.substring(i, i+length).equals(s)){
if (point < i ){
list.add(new Word(str.substring(point,i),line,i));
list.add(new Word(str.substring(point,i),line,point - currentLineOffset + 1));
}
list.add(new Word(str.substring(i, i+length),line,i+length));
list.add(new Word(str.substring(i, i+length),line,i - currentLineOffset + 1));
i = i + length;
point = i;
isFind = true;
......@@ -94,7 +99,7 @@ public class WordSplit
}
}
if (point < i) {
list.add(new Word(str.substring(point, i), line, i));
list.add(new Word(str.substring(point, i), line, point - currentLineOffset + 1));
}
Word result[] = new Word[list.size()];
......
package com.ql.util.express.bugfix;
import com.ql.util.express.ExpressRunner;
import org.junit.Test;
/**
* @author bingo 2019-05-01
*/
public class ErrorColumnTest {
/**
* 之前的错误:java.lang.Exception: 还有单词没有完成语法匹配:22[if:line=9,col=69] 之后的单词
* 修改后错误:java.lang.Exception: 还有单词没有完成语法匹配:22[if:line=9,col=12] 之后的单词
*
* @throws Exception
*/
@Test
public void test() throws Exception {
try {
String expressName = "bugfix/error-column";
ExpressRunner expressRunner = new ExpressRunner(false, true);
expressRunner.loadExpress(expressName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.ql.util.express.bugfix;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import com.ql.util.express.config.QLExpressRunStrategy;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.exception.QLSecurityRiskException;
import com.ql.util.express.exception.QLTimeOutException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class InvokeSecurityRiskMethodsTest {
@Before
public void before()
{
QLExpressRunStrategy.setForbiddenInvokeSecurityRiskMethods(true);
}
@After
public void after()
{
QLExpressRunStrategy.setForbiddenInvokeSecurityRiskMethods(false);
}
private static String[] expressList = new String[]{
"System.exit(1);",
"for(i=1;i<10;i++){\nRuntime.getRuntime().exec('echo 1+1');}"
};
@Test
public void test() throws Exception {
ExpressRunner runner = new ExpressRunner();
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
for(String express : expressList) {
try {
Object r = runner.execute(express, context, null, true, false, 1000);
System.out.println(r);
throw new Exception("没有捕获到不安全的方法");
} catch (QLException e) {
System.out.println(e.getCause());
}
}
}
}
......@@ -3,6 +3,9 @@ package com.ql.util.express.bugfix;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.IExpressContext;
import com.ql.util.express.exception.QLBizException;
import com.ql.util.express.exception.QLCompileException;
import com.ql.util.express.exception.QLException;
import org.junit.Assert;
import org.junit.Test;
......@@ -12,41 +15,94 @@ import org.junit.Test;
public class ThrowExceptionTest {
public String testParseLong(String a) throws Exception {
try {
return Long.valueOf(a).toString();
}catch (Exception e) {
// e.printStackTrace();
throw new Exception("Exception happened!",e);
return Long.valueOf(a).toString();
}
public void runExpress(String exp) throws Exception {
ExpressRunner runner = new ExpressRunner();
IExpressContext<String, Object> context = new DefaultContext<String, Object>();
Object result = runner.execute(exp, context, null, false, false);
System.out.println(result);
}
@Test
public void testQLCompileException() throws Exception {
String[] expList = new String[]{
"a = 0;\nfor(i=0;){a=a+1;}return a;",
"1a>1"
};
for(String exp : expList) {
try {
runExpress(exp);
} catch (QLCompileException e) {
System.out.println("捕获QLCompileException类型的异常成功.");
System.out.println(e.getCause());
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("捕获到系统异常");
}
}
}
@Test
public void testException()
{
try {
ExpressRunner runner = new ExpressRunner();
String exp = "a = new com.ql.util.express.bugfix.ThrowExceptionTest();a.testParseLong('11112LL')";
IExpressContext<String, Object> context = new DefaultContext<String, Object>();
Object result = runner.execute(exp, context, null, false, false);
System.out.println(result);
}catch (Exception e){
// e.printStackTrace();
String keywords = "run QlExpress Exception at line 1";
String exceptionString = e.toString();
Assert.assertTrue(exceptionString.contains(keywords));
public void testQLException() throws Exception {
String[] expList = new String[]{
"a>1",
"a = new com.ql.util.express.bugfix.ThrowExceptionTest();a.testParseLong2('11112LL')"
};
for(String exp : expList) {
try {
runExpress(exp);
} catch (QLException e) {
System.out.println("捕获QLException类型的异常成功.");
System.out.println(e.getCause());
// e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
throw new Exception("捕获到系统异常");
}
}
}
keywords = "java.lang.reflect.InvocationTargetException";
exceptionString = e.getCause().toString();
Assert.assertTrue(exceptionString.contains(keywords));
keywords = "Exception happened";
exceptionString = e.getCause().getCause().toString();
Assert.assertTrue(exceptionString.contains(keywords));
keywords = "java.lang.NumberFormatException";
exceptionString = e.getCause().getCause().getCause().toString();
Assert.assertTrue(exceptionString.contains(keywords));
@Test
public void testQLBizException() throws Exception {
String[] expList = new String[]{
"a = new com.ql.util.express.bugfix.ThrowExceptionTest();a.testParseLong('11112LL')"
};
for(String exp : expList) {
try {
runExpress(exp);
} catch (QLBizException e) {
System.out.println("捕获到QLBizException业务系统异常成功.");
System.out.println(e.getCause());
System.out.println(e.getCause().getCause());
// e.printStackTrace();
String keywords = "run QlExpress Exception at line 1";
String exceptionString = e.toString();
Assert.assertTrue(exceptionString.contains(keywords));
keywords = "java.lang.reflect.InvocationTargetException";//反射调用的异常,无法避免
exceptionString = e.getCause().toString();
Assert.assertTrue(exceptionString.contains(keywords));
keywords = "java.lang.NumberFormatException";
exceptionString = e.getCause().getCause().toString();
Assert.assertTrue(exceptionString.contains(keywords));
} catch (Exception e) {
e.printStackTrace();
throw new Exception("捕获到系统异常");
}
}
}
}
......@@ -66,4 +66,65 @@ public class ArrayTest {
}
System.out.println(expressContext);
}
@Test
public void testArrayField() throws Exception {
ExpressRunner runner = new ExpressRunner(false,true);
String[] expressList = new String[]{
"(args[0]).test.code",
"System.out.println(args[0].code)"
};
for(String express :expressList){
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
Args[] args = new Args[2];
args[0]= new Args();
args[0].setCode("parent");
Args child = new Args();
child.setCode("child");
args[0].setTest(child);
context.put("args",args);
runner.execute(express,context,null,true,false);
}
}
@Test
public void testFunction2() throws Exception {
ExpressRunner runner = new ExpressRunner();
String exp = "this.println((args[0]));";
String[] args = {"123","456"};
IExpressContext<String, Object> context = new DefaultContext<String, Object>();
((DefaultContext<String, Object>) context).put("args", args);
((DefaultContext<String, Object>) context).put("this",new ArrayTest());
Object result = runner.execute(exp,context,null,false,false);
}
public void println(String x) {
System.out.println("println(String x)");
}
public void println(Object x) {
System.out.println("println(Object x)");
}
public class Args{
private Args test;
private String code;
public Args getTest() {
return test;
}
public void setTest(Args test) {
this.test = test;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
}
package com.ql.util.express.test;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import org.junit.Assert;
import org.junit.Test;
public class PreloadExpressTest {
@Test
public void preloadExpress() throws Exception {
ExpressRunner runner = new ExpressRunner();
runner.loadMutilExpress(null,
"function add(int a, int b){return a+b;} \n" +
"function sub(int a, int b){return a-b;}");
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
context.put("m", 1);
context.put("n", 1);
Object object = runner.execute("add(m,n)+sub(2,-2)", context, null, true, false);
System.out.println(object);
Assert.assertTrue((Integer)object==6);
}
}
package com.ql.util.express.test;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import org.junit.Test;
public class StaticMethodTest {
@Test
public void testStaticMethod() throws Exception {
String expressArray[] = new String[]{
"StaticUtils.ITEM_DIM_MASTER",
"StaticUtils.isVirtualSCItem(1L)",
StaticUtils.class.getName()+".ITEM_DIM_MASTER",
StaticUtils.class.getName()+".isVirtualSCItem(1L)"
};
ExpressRunner runner = new ExpressRunner(false,true);
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
context.put("StaticUtils", StaticUtils.class);
for(String express : expressArray) {
Object r = runner.execute(express, context, null, false,
true);
System.out.println(r);
}
}
public static class StaticUtils {
public static long ITEM_DIM_MASTER = 0x01;
public static long ITEM_DIM_VIRTUAL = 0x02;
public static boolean isVirtualSCItem (
Long itemDim) {
return itemDim != null && (itemDim & 0x0f) == ITEM_DIM_VIRTUAL;
}
}
}
package com.ql.util.express.test;
import com.ql.util.express.DefaultContext;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.exception.QLTimeOutException;
import org.junit.Test;
/**
* @Author: tianqiao@taobao.com
* @Date: 2019/6/18 10:52 AM
*/
public class TimeOutExceptionTest {
private static String[] expressList = new String[]{
"sum=0;for(i=0;i<1000000000;i++){sum=sum+i;}return sum;",
"for(i=1;i<10;i++){System.out.println('loop time:'+i);Thread.sleep(3000);}"
};
@Test
public void test() throws Exception {
ExpressRunner runner = new ExpressRunner();
DefaultContext<String, Object> context = new DefaultContext<String, Object>();
for(String express : expressList) {
try {
Object r = runner.execute(express, context, null, true, false, 1000);
System.out.println(r);
throw new Exception("没有捕获到超时异常");
} catch (QLTimeOutException e) {
System.out.println(e);
}
}
}
}
if (a != null) {
return a;
}
if (b != null) {
return b;
}
c = a + b ;if (c != null {
return c;
}
/** println("<> result:" + (2 <> 3)); **/
return "a b c all is null";
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册