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.
fu-hsi-service/src/main/java/com/supervision/utils/CalculationUtil.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));
}
}