All Downloads are FREE. Search and download functionalities are using the official Maven repository.

commons.box.app.TextToken Maven / Gradle / Ivy

The newest version!
package commons.box.app;

import commons.box.util.Beans;
import commons.box.util.Strs;

import java.util.function.BiFunction;

/**
 * 

创建作者:xingxiuyi

*

版权所属:xingxiuyi

*/ public class TextToken { private static final AppLog LOG = AppLog.get(TextToken.class); /** * 文本变量解析开始 */ public static final String QS_OPEN = "${"; // 用于表达式解析过程 /** * 文本变量解析结束 */ public static final String QS_CLOSE = "}"; private final String openToken; private final String closeToken; private final BiFunction handler; public TextToken(BiFunction handler) { this(QS_OPEN, QS_CLOSE, handler); } public TextToken(String openToken, String closeToken, BiFunction handler) { this.openToken = openToken; this.closeToken = closeToken; this.handler = handler; } /** * 基于属性获取方式的表达式解析 * * @param * @return */ public static TextToken inst() { return new TextToken<>(TextToken::handleObjectValue); } /** * 基于属性获取方式的表达式解析 * * @param openToken * @param closeToken * @param * @return */ public static TextToken inst(String openToken, String closeToken) { return new TextToken<>(openToken, closeToken, TextToken::handleObjectValue); } public static String handleObjectValue(C context, String token) { if (context == null) return ""; try { Object o = Beans.get(context, token); if (o == null) return ""; return Strs.toString(o); } catch (Throwable e) { if (LOG.isDebugEnabled()) LOG.debug("无法解析目标属性 {} 原始上下文={}", token, context); } return ""; } /** * 解析字符串 * * @param text * @return */ public String parse(String text) { return this.parse(null, text); } /** * 带上下文解析条件的解析过程 * * @param context * @param text * @return */ public String parse(T context, String text) { StringBuilder builder = new StringBuilder(); if (text != null && text.length() > 0) { char[] src = text.toCharArray(); int offset = 0; int start = text.indexOf(this.openToken, offset); while (start > -1) { if (start > 0 && src[start - 1] == '\\') { builder.append(src, offset, start - 1).append(this.openToken); offset = start + this.openToken.length(); } else { int end = text.indexOf(this.closeToken, start); if (end == -1) { builder.append(src, offset, src.length - offset); offset = src.length; } else { builder.append(src, offset, start - offset); offset = start + this.openToken.length(); String content = new String(src, offset, end - offset); builder.append(this.handler.apply(context, content)); offset = end + this.closeToken.length(); } } start = text.indexOf(openToken, offset); } if (offset < src.length) { builder.append(src, offset, src.length - offset); } } return builder.toString(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy