1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
|
public class ScriptEngine {
public Map<String, String> getStrVariables() { return strVariables; }
private Map<String, String> strVariables = new HashMap<>();
public Map<String, Number> getNumbervariables() { return numbervariables; }
private Map<String, Number> numbervariables = new HashMap<>();
public interface ParseCallBack { void onPrint(String text);
void onError(Throwable error);
String onEachContent(String content); }
public PrintLabelModel evaluate(String script, ParseCallBack parseCallBack) { PrintLabelModel model = new PrintLabelModel(); try { script = script.replace("\r\n", "\n");
String[] split = script.split("\n"); line: for (String currentLine : split) { if (isComment(currentLine)) { continue; } for_block: for (String block : currentLine.split(";")) { if (isComment(block)) { break for_block; } // 解析整数变量 // Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][a-zA-Z0-9_]*)\\s*=\\s*(.+)$");
// Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][\\w\\u4e00-\\u9fa5]*)\\s*=\\s*(\"[^\"]+\"|[^\\s]+)$"); // Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][\\w\\u4e00-\\u9fa5]*)\\s*=\\s*(\"[^\"]+\"|[^\\s]+)$"); // Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][\\w\\u4e00-\\u9fa5]*)\\s*\\t=\\t(\"[^\"]+\"|[^\\s]+)$", Pattern.DOTALL); // Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][\\w\\u4e00-\\u9fa5]*)\\s*=\\s*(\"[^\"]+\"|[^\\s]+)$"); // Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][\\w]*)\\s*=\\s*(\"[^\"]+\"|[^\\s]+)$"); Pattern varPattern = Pattern.compile("^([$]?[a-zA-Z][\\w]*)\\s*=\\s*(\"[^\"]+\"|[^\\s]+)$"); // Pattern varPattern = Pattern.compile("^([a-zA-Z][a-zA-Z0-9_]*)\\s*=\\s*([a-zA-Z0-9+*-\\/()]+)$"); // Pattern varPattern = Pattern.compile("^([a-z]+)\\s*=\\s*([a-z0-9+*-\\/()]+)$"); // Pattern varPattern = Pattern.compile("(\\w+)\\s*=\\s*(\\d+)"); // block = Pattern.quote(block); Matcher varMatcher = varPattern.matcher(block);
boolean isVar = false; while (varMatcher.find()) { String varName = varMatcher.group(1); String value = varMatcher.group(2);
if (value.startsWith("\"") && value.endsWith("\"")) { String convertValue = evaluateString(value); strVariables.put(varName, convertValue); } else if (value.matches("\\d+") || value.matches("\\d+\\.\\d+") || value.matches("[+-]?\\d+\\.?\\d*[eE][+-]?\\d+")) { Number number = evaluateNumber(value); numbervariables.put(varName, number); } else { if (!value.startsWith("\"") && (value.contains("+") || value.contains("-") || value.contains("*") || value.contains("/"))) { Number number = evaluateNumber(value); numbervariables.put(varName, number); } else { String convertValue = evaluateString(value); strVariables.put(varName, convertValue); } } isVar = true; } if (isVar) { continue; } /*else if (block.trim().endsWith("\"") && block.contains("=")) { int i = block.indexOf("="); int start = block.indexOf("\"",i); int end = block.lastIndexOf("\""); if (i >= 0 && start > 0 && start < end && end > i) { String varName = block.substring(0, i); String value = block.substring(start+1, end); String convertValue = evaluateString(value); strVariables.put(varName, convertValue); } }*/ // 解析函数调用 Pattern funcPattern = Pattern.compile("(\\w+)\\((.*)\\)"); Matcher funcMatcher = funcPattern.matcher(block); if (funcMatcher.matches()) { String funcName = funcMatcher.group(1); String[] args = funcMatcher.group(2).split(",");
if (funcName.equals("label") && args.length > 3) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue(); if (x < 0 || y < 0) { x = 0; y = 0; }
String label = evaluateString(args[2].trim()); String text = evaluateString(args[3].trim());
PrintLabelModel.TextLeftRight printLabelModel = new PrintLabelModel.TextLeftRight(x, y, label, parseCallBack != null ? parseCallBack.onEachContent(text) : text); int fontSize = args.length > 4 ? evaluateNumber(args[4].trim()).intValue() : printLabelModel.fontSize; int limitRight = args.length > 5 ? evaluateNumber(args[5].trim()).intValue() : 0; if (limitRight > x && limitRight > 2) { printLabelModel.limitRight = limitRight; } if (fontSize > 5) { printLabelModel.fontSize = fontSize; } model.infos.add(printLabelModel); } else if (funcName.equals("return")) { return model; } else if (funcName.equals("print")) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < args.length; i++) { String str;
String arg = args[i]; String varValue = getVarValue(arg); if (varValue != null) { str = varValue; } else if (arg.contains("\"") || arg.contains("#")) { str = evaluateString(args[i]); } else if (arg.matches(".*?\\d+") || arg.matches("\\d+\\.\\d+") || arg.matches("[+-]?\\d+\\.?\\d*[eE][+-]?\\d+")) { str = evaluateNumber(args[i]).toString();
} else { str = arg; } sb.append(str); if (i != args.length - 1) { sb.append(" "); }
} if (parseCallBack != null) { parseCallBack.onPrint(sb.toString()); }
} else if (funcName.equals("wait") && args.length > 0) {
int x = evaluateNumber(args[0].trim()).intValue(); if (x > 0) { try { Thread.sleep(x); } catch (InterruptedException e) { // throw new RuntimeException(e); } } } else if (funcName.equals("draw") && args.length > 1) { if (args.length >= 4) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue(); int width = evaluateNumber(args[2].trim()).intValue(); int height = evaluateNumber(args[3].trim()).intValue(); // int drawWidth = args.length > 5 ? evaluateNumber(args[5].trim()).intValue() : model.drawWidth; if (x >= 0 && y >= 0) {
model.x = x; model.y = y; } if (width > 0 && height > 0) {
model.imgWidth = width; model.imgHeight = height; } /* if (drawWidth > 15) { model.drawWidth = drawWidth; }*/ } else {
int width = evaluateNumber(args[0].trim()).intValue(); int height = evaluateNumber(args[1].trim()).intValue(); if (width > 0 && height > 0) {
model.imgWidth = width; model.imgHeight = height; }
} } else if (funcName.equals("page") && args.length > 1) { int width = evaluateNumber(args[0].trim()).intValue(); int height = evaluateNumber(args[1].trim()).intValue(); model.printerHeight = width; model.printerWidth = height; } else if (funcName.equals("text") && args.length > 2) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue(); if (x < 0 || y < 0) { x = 0; y = 0; } String text = evaluateString(args[2].trim()); PrintLabelModel.Text printLabelModel = new PrintLabelModel.Text(x, y, parseCallBack != null ? parseCallBack.onEachContent(text) : text); int fontSize = args.length > 3 ? evaluateNumber(args[3].trim()).intValue() : printLabelModel.fontsize; int limitRight = args.length > 4 ? evaluateNumber(args[4].trim()).intValue() : 0; if (fontSize <= 0 || limitRight < 0) { fontSize = 15; limitRight = 2; } printLabelModel.fontsize = fontSize; printLabelModel.limitRight = limitRight; model.infos.add(printLabelModel); } else if (funcName.equals("qrcode") && args.length > 3) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue(); if (x < 0 || y < 0) { x = 0; y = 0; } int size = evaluateNumber(args[2].trim()).intValue(); String text = evaluateString(args[3].trim()); boolean showText = args.length > 4 ? evaluateBoolean(args[4].trim()) : false; PrintLabelModel.QRCode printLabelModel = new PrintLabelModel.QRCode(x, y, size, parseCallBack != null ? parseCallBack.onEachContent(text) : text, showText); model.infos.add(printLabelModel); } else if (funcName.equals("border") || (funcName.equals("box")) && args.length > 4) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue();
int width = evaluateNumber(args[2].trim()).intValue(); int height = evaluateNumber(args[3].trim()).intValue(); int border = evaluateNumber(args[4].trim()).intValue(); if (x < 0 || y < 0) { x = 0; y = 0; } if (width <= 0 || height <= 0) { width = 30; height = 30; } boolean showText = args.length > 5 ? evaluateBoolean(args[5].trim()) : false; PrintLabelModel.Box printLabelModel = new PrintLabelModel.Box(x, y, width, height, border, showText); model.infos.add(printLabelModel); } else if (funcName.equals("line") && args.length > 4) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue(); int endx = evaluateNumber(args[2].trim()).intValue(); int endy = evaluateNumber(args[3].trim()).intValue(); int size = evaluateNumber(args[4].trim()).intValue(); if (x < 0 || y < 0 || endx < 0 || endy < 0) { x = 0; y = 0; endx = 10; endy = 10; } PrintLabelModel.Line printLabelModel = new PrintLabelModel.Line(x, y, endx, endy, size); model.infos.add(printLabelModel); } else if (funcName.equals("barcode") && args.length > 4) { int x = evaluateNumber(args[0].trim()).intValue(); int y = evaluateNumber(args[1].trim()).intValue(); int width = evaluateNumber(args[2].trim()).intValue(); int height = evaluateNumber(args[3].trim()).intValue(); if (width <= 0 || height <= 0) { width = 400; height = 100; } String text = evaluateString(args[4].trim()); PrintLabelModel.BarCode printLabelModel = new PrintLabelModel.BarCode(x, y, width, height, parseCallBack != null ? parseCallBack.onEachContent(text) : text); int fontSize = args.length > 5 ? evaluateNumber(args[5].trim()).intValue() : printLabelModel.fontsize; boolean showText = args.length > 6 ? evaluateBoolean(args[6].trim()) : false;
int leftMargin = args.length > 7 ? evaluateNumber(args[7].trim()).intValue() : -1; int topMargin = args.length > 8 ? evaluateNumber(args[8].trim()).intValue() : -1;
/* if (leftMargin < 0 && topMargin < 0) { // leftMargin=0 continue; }*/ printLabelModel.showText = showText; printLabelModel.fontsize = fontSize; if (leftMargin != -1) { printLabelModel.textMarginLeft = leftMargin; } if (topMargin != -1) { printLabelModel.textMarginTop = topMargin; } model.infos.add(printLabelModel); } } }
} } catch (Throwable e) { parseCallBack.onError(e); }
return model; }
private String getVarValue(String value) { String s = strVariables.get(value); if (s == null) { Number number = numbervariables.get(value); if (number == null) { return null; } return number.toString();
} return s; }
private boolean isStr(String arg) { if (arg.startsWith("\"") && arg.endsWith("\"")) { return true; } else { return false; } }
private static boolean isComment(String currentLine) { if (currentLine == null || currentLine.trim().length() == 0 || currentLine.startsWith("#") || currentLine.startsWith("//") || currentLine.startsWith("--")) { return true; } return false; }
private String evaluateIntTwo(String expression) { // 如果是变量,替换为变量的值 if (strVariables.containsKey(expression)) { return strVariables.get(expression); }
// 如果是数字,直接转换为整数 try { return Integer.parseInt(expression) + ""; } catch (NumberFormatException e) { // 如果不是数字,尝试解析表达式 Pattern exprPattern = Pattern.compile("(\\w+)\\s*([\\+\\-\\*\\/])\\s*(\\w+)"); Matcher exprMatcher = exprPattern.matcher(expression); if (exprMatcher.matches()) { int left = evaluateInt2(exprMatcher.group(1).trim()); int right = evaluateInt2(exprMatcher.group(3).trim()); switch (exprMatcher.group(2).trim()) { case "+": return String.valueOf(left + right); case "-": return String.valueOf(left - right); case "*": return String.valueOf(left * right); case "/": return String.valueOf(left / right); } } }
return String.valueOf(0); }
private Number evaluateNumber(String expression) { // 如果是变量,替换为变量的值 if (numbervariables.containsKey(expression)) { return numbervariables.get(expression); }
// 如果是数字,直接转换为整数或浮点数 try { if (expression.contains("+") || expression.contains("-") || expression.contains("*") || expression.contains("/")) { // 如果不是数值,尝试解析表达式 Pattern exprPattern = Pattern.compile("(\\w+)([\\+\\-\\*\\/])(\\w+)([\\+\\-\\*\\/])?(\\w+)?([\\+\\-\\*\\/])?(\\w+)?"); Matcher exprMatcher = exprPattern.matcher(expression); if (exprMatcher.matches()) { String trim = exprMatcher.group(1).trim(); Number result = evaluateNumber(trim); BigInteger bigIntegerResult = result instanceof BigInteger ? (BigInteger) result : null; BigDecimal bigDecimalResult = result instanceof BigDecimal ? (BigDecimal) result : null; for (int i = 2; i <= exprMatcher.groupCount(); i += 2) { String group = exprMatcher.group(i);//第三个的时候这里为空 if (group == null) { continue; } String operator = group.trim(); String group1 = exprMatcher.group(i + 1); String operand = group1.trim(); Number value = evaluateNumber(operand); if (bigIntegerResult != null) { // 如果都是整数,使用整数计算 BigInteger intOperand = (BigInteger) value; switch_: switch (operator) { case "+": bigIntegerResult = bigIntegerResult.add(intOperand); break switch_; case "-": bigIntegerResult = bigIntegerResult.subtract(intOperand); break switch_; case "*": bigIntegerResult = bigIntegerResult.multiply(intOperand); case "/": bigIntegerResult = bigIntegerResult.divide(intOperand); break switch_; }
} else { BigDecimal doubleOperand = (BigDecimal) value;//.doubleValue();// Double.parseDouble(value.toString()); switch_: switch (operator) { case "+": bigDecimalResult = bigDecimalResult.add(doubleOperand); break switch_; case "-": bigDecimalResult = bigDecimalResult.subtract(doubleOperand); break switch_; case "*": bigDecimalResult = bigDecimalResult.multiply(doubleOperand); case "/": bigDecimalResult = bigDecimalResult.divide(doubleOperand); break switch_; }
} } result = bigDecimalResult != null ? bigDecimalResult : bigIntegerResult; return new BigInteger(String.valueOf(result)); } } else { if (expression.matches("\\d+")) { return new BigInteger(expression); } else if (expression.matches("\\d+\\.\\d+")) { return new BigDecimal(expression); // return String.valueOf(Double.parseDouble(expression)); } else if (expression.matches("[+-]?\\d+\\.?\\d*[eE][+-]?\\d+")) { // return String.valueOf(Double.parseDouble(expression)); return new BigDecimal(expression); } else { return new BigDecimal(expression); // return String.valueOf(Double.parseDouble(expression)); } } } catch (Throwable e) { return new BigInteger("0"); } return new BigInteger("0");
}
// 辅助方法,执行加法运算 private Number add(Number a, Number b) { if (a instanceof Float || b instanceof Float) { return a.floatValue() + b.floatValue(); } else { return a.intValue() + b.intValue(); } }
// 辅助方法,执行减法运算 private Number subtract(Number a, Number b) { if (a instanceof Float || b instanceof Float) { return a.floatValue() - b.floatValue(); } else { return a.intValue() - b.intValue(); } }
// 辅助方法,执行乘法运算 private Number multiply(Number a, Number b) { if (a instanceof Float || b instanceof Float) { return a.floatValue() * b.floatValue(); } else { return a.intValue() * b.intValue(); } }
// 辅助方法,执行除法运算 private Number divide(Number a, Number b) { if (a instanceof Float || b instanceof Float) { return a.floatValue() / b.floatValue(); } else { return a.intValue() / b.intValue(); } }
private int evaluateInt2(String expression) { // 如果是变量,替换为变量的值 if (numbervariables.containsKey(expression)) { return numbervariables.get(expression).intValue(); }
// 如果是数字,直接转换为整数 try { return Integer.parseInt(expression); } catch (NumberFormatException e) { // 如果不是数字,尝试解析表达式 Pattern exprPattern = Pattern.compile("(\\w+)([\\+\\-\\*\\/])(\\w+)([\\+\\-\\*\\/])?(\\w+)?([\\+\\-\\*\\/])?(\\w+)?"); Matcher exprMatcher = exprPattern.matcher(expression); if (exprMatcher.matches()) { int result = evaluateInt2(exprMatcher.group(1).trim()); for (int i = 2; i <= exprMatcher.groupCount(); i += 2) { String operator = exprMatcher.group(i).trim(); String operand = exprMatcher.group(i + 1).trim(); int value = evaluateInt2(operand); switch (operator) { case "+": result += value; break; case "-": result -= value; break; case "*": result *= value; break; case "/": result /= value; break; } } return result; } }
return 0; }
private String evaluateString(String expression) { // 如果是变量,替换为变量的值 if (strVariables.containsKey(expression)) { return strVariables.get(expression); } if (numbervariables.containsKey(expression)) { return String.valueOf(numbervariables.get(expression).intValue()); }
// 如果是字符串,去掉引号 if (expression.startsWith("\"") && expression.endsWith("\"")) { if (expression.contains("+\"")) { StringBuffer sb = new StringBuffer(); expression = expression.substring(1, expression.length() - 1); String[] split = expression.split(",\""); for (String s : split) { sb.append(s); } return sb.toString(); } return expression.substring(1, expression.length() - 1); }
return expression; }
private boolean evaluateBoolean(String expression) { // 如果是变量,替换为变量的值 if (numbervariables.containsKey(expression)) { return numbervariables.get(expression).intValue() != 0; }
// 如果是布尔值,直接转换为布尔型 if (expression.equalsIgnoreCase("true")) { return true; } else if (expression.equalsIgnoreCase("false")) { return false; }
return false; }
}
|