Home » Java » Enterprise Java » Playing with ANTLR4, Primefaces extensions for Code Mirror and web-based DSLs

About Leonardo Shikida

Leonardo is a Systems Analyst and Java Senior Developer at IBM (The postings on his site are his own and don't necessarily represent IBM's positions, strategies or opinions.)

Playing with ANTLR4, Primefaces extensions for Code Mirror and web-based DSLs

DSLs are cool things, but it wasn’t clear to me what they were good for.

Then I realized they are good for:

  • get rid of complex UIs

which means

  • faster way to do things

That’s it.  I’ve came to this conclusion when I read this blog.

If your user is techie and are not afraid of a SQL-like syntax way of doing things, DSLs are great specially if

  • you have syntax highlight
  • you have code completion

Otherwise, DSLs kinda sucks.

So, I had to present some proof of concept to a client. He has fuzzy requirements and it’s not easy to extract exactly what his team needs (they need a lot of things and he’s very busy), so a DSL can help a lot in this process because people are forced to think exactly what they need when they face a grammar (even a small one).

So I went with these technologies:

Unfortunately, I could not reuse the grammar in both tools. Actually, I could not find any solution that could do that. At least for a web-based JSF solution. And there was no time to learn. So I had to hack a little.

First, we need the grammar. ANTLR4 is way better than ANTLR3 because now the wiring code is done via visitors and listeners. No more java code inside the grammar. That’s great and much easier to work with.

So you can have a grammar like this

grammar Grammar;
    language = Java;
@lexer::header {
  package parsers;

@parser::header {
  package parsers;
eval     :     expr EOF;
expr    :    'JOB' (jobName)? type 'TARGET' targetList ('START' startExpr)?
    :    'AT' cronTerm
    |    'AFTER' timeAmount timeUnits;
timeAmount: INT;   
jobName: STRING;   
targetList: STRING (',' STRING)*;   
type    :    deleteUser
    |    createUser;

deleteUser: opDelete userName;
createUser: opCreate userName;
opDelete: 'DELETE';
opCreate: 'CREATE';
userName: STRING;
cronTerm: '!'? (INT | '-' | '/' | '*' | '>' | '<')+;

    :    'MINUTES'
    |    'HOURS'
    |    'DAYS'
    |    'WEEKS'
    |    'MONTHS';

WS  :   [ \t\r\n]+ -> skip;

    :  '"' ( ESC_SEQ | ~('\\'|'"') )* '"'

HEX_DIGIT : ('0'..'9'|'a'..'f'|'A'..'F') ;

    :   '\\' ('b'|'t'|'n'|'f'|'r'|'\"'|'\''|'\\')
    |   OCTAL_ESC

    :   '\\' ('0'..'3') ('0'..'7') ('0'..'7')
    |   '\\' ('0'..'7') ('0'..'7')
    |   '\\' ('0'..'7')


ID  :    ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'0'..'9'|'_')*

INT :    '0'..'9'+

To compile your grammar, try

public static void main(String[] args) {
        String[] arg0 = {"-visitor","/pathto/Grammar.g4"};

Then ANTLR will generate the classes for you.

In our case, we want to visit the parse tree and retrieve the values we want. We do this extending the generated abstract class.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

import org.antlr.v4.runtime.tree.ErrorNode;

import bsh.EvalError;
import bsh.Interpreter;

public class MyLoader2 extends GrammarBaseVisitor<Void> {

    private String jobName,cronTerm,timeUnits,userName,jobType;
    private List<String> targetList;
    private boolean now,errorFound;
    private int timeAmount;   
    private Interpreter bsh = new Interpreter();
    private String eval(String s) throws EvaluationException{
        try {
            if (!s.startsWith("\"")){
                return s;
            bsh.eval("String s="+s);
            return (String)bsh.eval("s");
        } catch (EvalError e) {
            throw new EvaluationException(s);
    public Void visitTimeAmount(TimeAmountContext ctx) {
            this.timeAmount = Integer.parseInt(ctx.getText());
        }catch(java.lang.NumberFormatException nfe){
            throw new InvalidTimeAmountException(ctx.getText());

        return super.visitTimeAmount(ctx);
    public Void visitUserName(UserNameContext ctx) {
        this.userName = eval(ctx.getText());
        return super.visitUserName(ctx);
    public Void visitCronTerm(CronTermContext ctx) {
        this.cronTerm = eval(ctx.getText());
        return super.visitCronTerm(ctx);
    public Void visitTimeUnits(TimeUnitsContext ctx) {
        this.timeUnits = ctx.getText();
        return super.visitTimeUnits(ctx);
    public Void visitTargetList(TargetListContext ctx) {
        this.targetList = toStringList(ctx.getText());
        return super.visitTargetList(ctx);
    public Void visitJobName(JobNameContext ctx) {
        this.jobName = eval(ctx.getText());
        return super.visitJobName(ctx);
    public Void visitOpCreate(OpCreateContext ctx) {
        this.jobType = ctx.getText();
        return super.visitOpCreate(ctx);
    public Void visitOpDelete(OpDeleteContext ctx) {
        this.jobType = ctx.getText();
        return super.visitOpDelete(ctx);
    private List<String> toStringList(String text) {
        List<String> l = new ArrayList<String>();
        StringTokenizer st = new StringTokenizer(text," ,");
        return l;
    private Map<String, String> toMapList(String text) throws InvalidItemsException, InvalidKeyvalException {
        Map<String, String> m = new HashMap<String, String>();
        if (text == null || text.trim().length() == 0){
            return m;
        String[] items = text.split(",");
        if (items.length == 0){
            throw new InvalidItemsException();
        for(String item:items){
            String[] keyval = item.split("=");
            if (keyval.length == 2){
                m.put(keyval[0], keyval[1]);
                throw new InvalidKeyvalException(keyval.length);
        return m;
    public String getJobName() {
        return jobName;
    public String getCronTerm() {
        return cronTerm;
    public String getTimeUnits() {
        return timeUnits;
    public String getUserName() {
        return userName;
    public String getJobType() {
        return jobType;
    public List<String> getTargetList() {
        return targetList;
    public boolean isNow() {
        return now;
    public int getTimeAmount() {
        return timeAmount;
    public Void visitOpNow(OpNowContext ctx) {
        this.now = ctx.getText().equals("NOW");
        return super.visitOpNow(ctx);
    public boolean isErrorFound() {
        return errorFound;
    public Void visitErrorNode(ErrorNode node) {
        this.errorFound = true;
        return super.visitErrorNode(node);

Notice the beanshell interpreter being used to evaluate a string like “xyz” to be xyz. This is specially useful for strings that contains escaped quotes and characteres inside.

So, you have your grammar and your visitor / loader bean, then we can test it:

private static MyLoader getLoader(String str){
    ANTLRInputStream input = new ANTLRInputStream(str);
    GrammarLexer lexer = new GrammarLexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    GrammarParser parser = new GrammarParser(tokens);
    ParseTree tree = parser.eval();
    MyLoader loader = new MyLoader();
    return loader;

public static void main(String[] args){
    MyLoader loader = getLoader("JOB \"jobName\" CREATE \"myuser\" TARGET \"site1\",\"site2\" START AFTER 1 DAY");

Great. Now it’s the hack. Code Mirror has support for custom grammars, but it’s not present in the JSF Primefaces extension. So I’ve opened the resources-codemirror-1.2.0.jar, opened the /META-INF/resources/primefaces-extensions/codemirror/mode/modes.js file, formatted it (so I could read it) and I’ve just chosen the simplest language to be my new custom sintax highlighter!

I renamed this one

}, "xml"), CodeMirror.defineMIME("text/x-markdown", "markdown"), CodeMirror.defineMode("mylanguage", function (e) {
    var t = e.indentUnit,
        n, i = r(["site", "type", "targetList"]),
}), CodeMirror.defineMIME("text/x-mylanguage", "mylanguage"), CodeMirror.defineMode("ntriples", function () {(...) 

those guys in uppercase in the “s = r” are tokens that will be highlighted, while those one in the “i = r” are tokens that won’t be highlighted. Why do we want both? Because the second type is the “placeholder”, I mean, we’ll use them for the autocomplete stuff.

well, then your JSF xhtml page will look like this

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"

<h:form id="form">
    extraKeys="{ 'Ctrl-Space': function(cm) { PF('myCodeMirror').complete(); }}"/> 
<p:commandButton value="Verify" action="#{myMB.verify}" />

now, we need the autocomplete stuff. It’s the boring part. You have to do most of the completion stuff manually, because there’s no context information (remember, I don’t have time to learn…), so the quick and dirty way to do it is like this

in myMB

    public List<String> complete(final CompleteEvent event) {
        try {
            return this.myEJB.complete(event.getToken());
        } catch (Exception e) {
            jsfUtilEJB.addErrorMessage(e,"Could not complete");
            return null;

in myEJB

private static final String    SITE    = "site_";
public List<String> complete(String token) throws Exception {
    if (token == null || token.trim().length() == 0){
        return null;
        List<String> suggestions = new ArrayList<String>();
            //first search variables
            case "targetlist":
                for(String v:TARGETS){
            case "site":
                List<Site> allSites = this.baseService.getSiteDAO().getAll();
                for(Site s:allSites){
            case "type":
                suggestions.add("DELETE \"userName\"");
                suggestions.add("CREATE \"userName\"");
            case "AT":
                suggestions.add("AT \"cronExpression\"");
                suggestions.add("AT \"0 * * * * * * *\"");
            case "AFTER":
                for(int a:AMOUNTS){
                    for(String u:UNITS){
                        if (a == 1){
                            suggestions.add("AFTER"+" "+a+" "+u);
                            suggestions.add("AFTER"+" "+a+" "+u+"S");
            case "TARGET":
                for(String v:TARGETS){
                    suggestions.add("TARGET "+v+"");   
            case "JOB":
                suggestions.add("JOB \"jobName\" \ntype \nTARGET targetlist \nSTART");
            case "START":
                suggestions.add("START AT \"cronExpression\"");
                suggestions.add("START AT \"0 * * * * * * *\"");
                for(int a:AMOUNTS){
                    for(String u:UNITS){
                        if (a == 1){
                            suggestions.add("START AFTER"+" "+a+" "+u);
                            suggestions.add("START AFTER"+" "+a+" "+u+"S");
                suggestions.add("START NOW");
            case "DELETE":
                suggestions.add("DELETE \"userName\"");
            case "CREATE":
                suggestions.add("CREATE \"userName\"");

                if (token.startsWith(SITE)){
                    List<Site> matchedSites = this.baseService.getSiteDAO().getByPattern(token.substring(SITE.length())+"*");
                    for(Site s:matchedSites){
                    //then search substrings
                    for(String kw:KEYWORDS){
                        if (kw.toLowerCase().startsWith(token.toLowerCase())){
        }//end switch
        //remove dups and sort
        Set<String> ts = new TreeSet<String>(suggestions);           
        return new ArrayList<String>(ts);

private static final int[] AMOUNTS = {1,5,10};
private static final String[] UNITS = {"MINUTE","HOUR","DAY","WEEK","MONTH"};
private static final String[] TARGETS = {"site"};

 * KEYWORDS are basic suggestions
private static final String[] KEYWORDS = {"AT","AFTER","CREATE","MINUTES","HOURS","TARGET","MONTHS","JOB","DAYS","DELETE","START","WEEKS"};

so the autocomplete stuff for keywords will just show you fields and more keywords, while the “placeholders” (remember those lowercase keywords in the codemirror javascript from the jar?) are completed with dynamic values retrieved from the DB, for actual values. Also, you can use partial strings to retrieve those ones that start with a substring, like this:


of course, pattern-like searches in JPA can be performed like this:

public abstract class GenericDAO<E> {
    protected EntityManager entityManager;
    private Class<E> clazz;
    private EntityType<E> pClass;

    public GenericDAO(EntityManager entityManager) {
        this.entityManager = entityManager;
    ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
    this.clazz = (Class<E>) genericSuperclass.getActualTypeArguments()[0];

    EntityManagerFactory emf = this.entityManager.getEntityManagerFactory();
    Metamodel metamodel = emf.getMetamodel();
    this.pClass = metamodel.entity(clazz);

    public List<E> getByPattern(String pattern) {
        pattern = pattern.replace("?", "_").replace("*", "%");
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<E> q = cb.createQuery(clazz);
        Root<E> entity = q.from(clazz);
        SingularAttribute<E, String> singularAttribute = (SingularAttribute<E, String>) pClass.getDeclaredSingularAttribute(getNameableField(clazz));
        Path<String> path = entity.get(singularAttribute);
        q.where(cb.like(path, pattern));
        TypedQuery<E> tq = entityManager.createQuery(q);
        List<E> all = tq.getResultList();
        return all;

    private String getNameableField(Class<E> clazz) {
        for(Field f : clazz.getDeclaredFields()) {
            for(Annotation a : f.getAnnotations()) {
                if(a.annotationType() == Nameable.class) {
                    return f.getName();
        return null;

where Nameable is an annotation for your entity classes:

public @interface Nameable {

Use it to annotate a single column from your entity class, a String one. Like this:

@Table([email protected](columnNames={"name"}))
public class Site implements Serializable {
    private static final long serialVersionUID = 8008732613898597654L;
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

And the “verify” button, of course, just get your script and pushes into the loader.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....



Leave a Reply

Your email address will not be published. Required fields are marked *


Want to take your Java skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • Spring Interview QnA
  • Multithreading & Concurrency QnA
  • JPA Minibook
  • JVM Troubleshooting Guide
  • Advanced Java
  • Java Interview QnA
  • Java Design Patterns