The visitor way is as always one way to go. If you want to get the parenthesis depth, you could stick with:
public void visit(Parenthesis parenthesis)
To get the ouput you want, is a little bit trickier. I implemented a simple example only taking ANDs and ORs into account. I do not use the ExpressionVisitorAdapter, but the ExpressionDeParser which is responsible for Expression printing. This way you can modify the generated output to your needs.
public static void main(String args[]) throws JSQLParserException {
Expression expr = CCJSqlParserUtil.parseCondExpression("(a=1 AND (b=2 OR (c=3 AND d=4))) OR e=2");
StringBuilder b = new StringBuilder();
expr.accept(new ExpressionDeParser(null, b) {
int depth = 0;
@Override
public void visit(Parenthesis parenthesis) {
if (parenthesis.isNot()) {
getBuffer().append("NOT");
}
depth++;
parenthesis.getExpression().accept(this);
depth--;
}
@Override
public void visit(OrExpression orExpression) {
visitBinaryExpr(orExpression, "OR");
}
@Override
public void visit(AndExpression andExpression) {
visitBinaryExpr(andExpression, "AND");
}
private void visitBinaryExpr(BinaryExpression expr, String operator) {
if (expr.isNot()) {
getBuffer().append("NOT");
}
if (!(expr.getLeftExpression() instanceof OrExpression)
&& !(expr.getLeftExpression() instanceof AndExpression)
&& !(expr.getLeftExpression() instanceof Parenthesis)) {
getBuffer().append(StringUtils.repeat("-", depth)).append(">");
}
expr.getLeftExpression().accept(this);
getBuffer().append("\n").append(StringUtils.repeat("-", depth)).append(">");
getBuffer().append(operator).append("\n");
if (!(expr.getRightExpression() instanceof OrExpression)
&& !(expr.getRightExpression() instanceof AndExpression)
&& !(expr.getRightExpression() instanceof Parenthesis)) {
getBuffer().append(StringUtils.repeat("-", depth)).append(">");
}
expr.getRightExpression().accept(this);
}
});
System.out.println(b);
}
As you can see, the parenthesis visitor changes the depth. The hard part is within visitBinaryExpression
. The complex instanceof logic derives from using the And/OrExpression for output. Since for one text line multiple calls to visitBinaryExpression
could happen, the indent has to be done from the most outer part.
If you would like to improve the printing of an JSqlParser parsed statement your updates should go to the deparsers.