Tag Cloud

Showing posts with label juel. Show all posts
Showing posts with label juel. Show all posts

Monday, August 13, 2012

Using Expression Language

This is an example using expression language in Java



import javax.el.ValueExpression;

import junit.framework.Assert;
import junit.framework.TestCase;

import org.jlego.core.Dto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.odysseus.el.util.SimpleContext;

public class TestExpression extends TestCase {

private static final Logger log = LoggerFactory.getLogger(TestExpression.class);

public void testJuel(){
java.util.Properties properties = new java.util.Properties();
properties.put("javax.el.cacheSize", "5000");
javax.el.ExpressionFactory factory = new de.odysseus.el.ExpressionFactoryImpl(properties);

Map map= new HashMap();
map .put("data", "ali");

SimpleContext context = new SimpleContext();
context.setVariable("request", factory.createValueExpression(map, HashMap.class));
ValueExpression expr = factory.createValueExpression(context, "${request.data == 'ali'}", Object.class);

Assert.assertEquals("true", expr.getValue(context).toString());

ValueExpression expr2 = factory.createValueExpression(context, "${ (1==0) ? 'ali' : ((2==2) ? 'not not ali' : 'not ali') }", Object.class);

Assert.assertEquals("not not ali",expr2.getValue(context));
}
}

I'm using Maven, so make sure you have these dependencies:


<dependency>
<groupId>de.odysseus.juel</groupId>
<artifactId>juel</artifactId>
<version>2.1.3</version>
</dependency>

Of course JUnit as well


<dependency>
        <groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.1</version>
<scope>test</scope>
</dependency>