com.github.aidensuen.mongo.parsing.GenericTokenParser Maven / Gradle / Ivy
package com.github.aidensuen.mongo.parsing;
import com.github.aidensuen.mongo.util.MongoCommandUtil;
public class GenericTokenParser {
private final String openToken;
private final String closeToken;
private final TokenHandler handler;
public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
this.openToken = openToken;
this.closeToken = closeToken;
this.handler = handler;
}
public String parse(String text) {
if (text == null || text.isEmpty()) {
return "";
}
// search open token
int start = text.indexOf(openToken, 0);
if (start == -1) {
return text;
}
char[] src = text.toCharArray();
int openTokenCount = 0;
int closeTokenCount = 0;
int offset = 0;
final StringBuilder builder = new StringBuilder();
StringBuilder expression = null;
while (start > -1) {
if (start > 0 && src[start - 1] == '\\') {
// this open token is escaped. remove the backslash and continue.
builder.append(src, offset, start - offset - 1).append(openToken);
offset = start + openToken.length();
} else {
openTokenCount += 1;
// found open token. let's search close token.
if (expression == null) {
expression = new StringBuilder();
} else {
expression.setLength(0);
}
builder.append(src, offset, start - offset);
offset = start + openToken.length();
int end = text.indexOf(closeToken, offset);
boolean counted = false;
while (end > -1) {
if (end > offset && src[end - 1] == '\\') {
// this close token is escaped. remove the backslash and continue.
expression.append(src, offset, end - offset - 1).append(closeToken);
offset = end + closeToken.length();
end = text.indexOf(closeToken, offset);
} else {
closeTokenCount += 1;
expression.append(src, offset, end - offset);
offset = end + closeToken.length();
}
if (!counted) {
// search open token in expression
String exp = expression.toString();
int i = (exp.length() - exp.replace(openToken, "").length()) / openToken.length();
openTokenCount += i;
counted = true;
}
if (openTokenCount == closeTokenCount) {
counted = false;
break;
} else {
expression.append(closeToken);
}
end = text.indexOf(closeToken, offset);
}
if (end == -1) {
// close token was not found.
builder.append(src, start, src.length - start);
offset = src.length;
} else {
String parsed = handler.handleToken(expression.toString().trim(), openTokenCount);
//parse again for parse child expression
//example: #{name != null ? 'name: #{name}':''}
String parseSec = parse(parsed);
while (!parsed.equals(parseSec)) {
parsed = parseSec;
parseSec = parse(parsed);
}
builder.append(parsed);
offset = end + closeToken.length();
}
}
openTokenCount = closeTokenCount = 0;
start = text.indexOf(openToken, offset);
}
if (offset < src.length) {
builder.append(src, offset, src.length - offset);
}
return MongoCommandUtil.converteJsonToCommandStr(builder.toString());
}
}