You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
76 lines
2.6 KiB
Java
76 lines
2.6 KiB
Java
package com.supervision.utils;
|
|
|
|
import org.springframework.expression.ExpressionParser;
|
|
import org.springframework.expression.spel.standard.SpelExpressionParser;
|
|
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
|
|
|
import java.util.Set;
|
|
|
|
import static com.supervision.common.constant.IndexRuleConstants.LOGIC_AND;
|
|
import static com.supervision.common.constant.IndexRuleConstants.LOGIC_OR;
|
|
|
|
public class CalculationUtil {
|
|
|
|
/**
|
|
* 计算表达式结果
|
|
*
|
|
* @param leftOperand 左操作数
|
|
* @param operator 操作符
|
|
* @param rightOperand 右操作数
|
|
* @return 计算结果
|
|
*/
|
|
public static boolean evaluateExpression(String leftOperand, String operator, String rightOperand) {
|
|
// 构建表达式
|
|
String expression = leftOperand + " " + operator + " " + rightOperand;
|
|
|
|
// 初始化SpEL解析器
|
|
ExpressionParser parser = new SpelExpressionParser();
|
|
StandardEvaluationContext context = new StandardEvaluationContext();
|
|
|
|
// 计算结果
|
|
return Boolean.TRUE.equals(parser.parseExpression(expression).getValue(context, Boolean.class));
|
|
}
|
|
|
|
/**
|
|
* 计算布尔值集合的逻辑运算结果
|
|
*
|
|
* @param booleanSet 布尔值集合
|
|
* @param logic 逻辑运算符
|
|
* @return 计算结果
|
|
*/
|
|
public static boolean calculateBooleanSet(Set<Boolean> booleanSet, String logic) {
|
|
// 判断是否为空
|
|
if (booleanSet == null || booleanSet.isEmpty()) {
|
|
throw new IllegalArgumentException("Boolean set cannot be null or empty");
|
|
}
|
|
|
|
// 判断是"且"还是"或"
|
|
String operator;
|
|
if (LOGIC_AND.equals(logic)) {
|
|
operator = " and ";
|
|
} else if (LOGIC_OR.equals(logic)) {
|
|
operator = " or ";
|
|
} else {
|
|
throw new IllegalArgumentException("Invalid logic value, use 1 for AND, 2 for OR.");
|
|
}
|
|
|
|
// 构建表达式
|
|
StringBuilder expressionBuilder = new StringBuilder();
|
|
boolean first = true;
|
|
for (Boolean bool : booleanSet) {
|
|
if (!first) {
|
|
expressionBuilder.append(operator);
|
|
}
|
|
expressionBuilder.append(bool);
|
|
first = false;
|
|
}
|
|
|
|
// 初始化SpEL解析器
|
|
ExpressionParser parser = new SpelExpressionParser();
|
|
StandardEvaluationContext context = new StandardEvaluationContext();
|
|
|
|
// 计算结果
|
|
return Boolean.TRUE.equals(parser.parseExpression(expressionBuilder.toString()).getValue(context, Boolean.class));
|
|
}
|
|
}
|