JSF EL Calculator bean – to overcome "coercion" errors and add functionality to EL Expressions

0

In a recent project I was working on JSF page that needed to display the result of a calculation performed on values taken from various bean properties. The beans were somewhat beyond my control, the properties were all of a numeric type so I tried an EL expression like:

<af:outputText value="#{SimpleBean.operand1 + SimpleBean.operand2}"/> 

Simple as it may seem, JSF EL Evaluation resulted in errors such as: "(Coercions) -Attempt to coerce a value of type "oracle.jbo.domain.Number" to type "java.lang.Long"". The two bean properties involved in this case were of different types. The standard EL evaluator in JSF 1.1 assumes that properties involved in numerical operations are either Long (no fraction) or Double (when a fraction is involved). If they are not one of those… too bad. 

An attempt to base the rendering expression for this outputText element on one of the operandi also failed, with same error:

<af:outputText value="#{SimpleBean.operand1 + SimpleBean.operand2}" rendered="#{SimpleBean.operand1 > 0}"/> 

Again the operation requires a numerical value and EL Evaluation goes for Long. In my case I had used the oracle.jbo.domain.Number – hence the error.

Along the same lines are requirements for operations that EL evaluation does currently not support, such as rounding numbers (for example after calculating #{operand1/operand2*100} %, you can easily end up with output like "33.3333333333 %", which is slightly overdoing it. Rounding the division result to 33.3 would be a boon, but EL cannot do it.

I have come up with a very simple class that can be used in any JSF application to overcome such challenges. Using expressions such as:

&lt;af:outputText value=&quot;#{Calculator.RESET[SimpleBean.operand1][SimpleBean.operand2].ADD.EQUALS}&quot; rendered=&quot;#{Calculator.RESET[SimpleBean.operand1].LONG.EQUALS &amp;gt; 0}&quot;/&gt;<br />&nbsp;

all the coercion problems disappear.

Using the Calculator bean, we can even create a fairly dynamic calculator, such as shown here:

Any time we change one of the operands or the operator, the outcome is immediately recalculated. The essential piece....
of JSF behind this calculator is this:

            &lt;af:inputText id=&quot;oper1&quot; label=&quot;Operand 1&quot; columns=&quot;5&quot;<br />                          value=&quot;#{SimpleBean.operand1}&quot; autoSubmit=&quot;true&quot;/&gt;<br />            &lt;af:selectOneChoice label=&quot;  &quot; value=&quot;#{SimpleBean.operator}&quot;<br />                                id=&quot;operator&quot; autoSubmit=&quot;true&quot;&gt;<br />              &lt;f:selectItem itemLabel=&quot;+&quot; itemValue=&quot;ADD&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;-&quot; itemValue=&quot;SUBSTRACT&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;*&quot; itemValue=&quot;MULTIPLY&quot;/&gt;<br />              &lt;f:selectItem itemLabel=&quot;/&quot; itemValue=&quot;DIVIDE&quot;/&gt;<br />            &lt;/af:selectOneChoice&gt;<br />            &lt;af:inputText id=&quot;oper2&quot; label=&quot;  Operand 2&quot; columns=&quot;5&quot;<br />                          value=&quot;#{SimpleBean.operand2}&quot; autoSubmit=&quot;true&quot;/&gt;<br />            &lt;af:outputLabel value=&quot;=&quot;/&gt;<br />            &lt;af:panelGroup partialTriggers=&quot;oper1&quot;&gt;<br />              &lt;af:outputText value=&quot;#{Calculator.RESET[SimpleBean.operand1][SimpleBean.operand2][SimpleBean.operator].EQUALS}&quot;<br />                             partialTriggers=&quot;oper1 operator oper2&quot;<br />                             rendered=&quot;#{Calculator.RESET[SimpleBean.operand1].LONG.EQUALS &gt; 0}&quot;/&gt;<br />            &lt;/af:panelGroup&gt;<br />&nbsp;

The one element that really does the trick if of course the outputText element. (Notice how the autoSubmit and partialTriggers attributes are used to get AJAX-style refresh whenever the operandi or operator are changed. This functionality in the Apache MyFaces Trinidad en Oracle ADF Faces JSF libraries)

To calculate a percentage and round it to 2 fractional digits, you could use:

#{Calculator.RESET[SimpleBean.operand1][SimpleBean.operand2].DIVIDE[1000].MULTIPLY.ROUND[10].DIVIDE.EQUALS}&nbsp;

The Calculator class is fairly simple. It most distinguishing feature is probably the fact that it extends the HashMap (or rather that it implements the Map interface):

package nl.amis.adffaces.matrix;<br /><br />import java.util.ArrayList;<br />import java.util.HashMap;<br />import java.util.List;<br />import oracle.jbo.domain.Number;<br /><br />public class Calculator extends HashMap {<br /><br />    private static final String reset =&quot;RESET&quot;;<br />    private static final String add =&quot;ADD&quot;;<br />    private static final String substract =&quot;SUBSTRACT&quot;;<br />    private static final String divide =&quot;DIVIDE&quot;;<br />    private static final String multiply =&quot;MULTIPLY&quot;;<br />    private static final String round =&quot;ROUND&quot;;<br />    private static final String aslong =&quot;LONG&quot;;<br />    private static final String equals =&quot;EQUALS&quot;;<br />    <br />    public List operands = new ArrayList();<br />    <br />    public Calculator() {<br />    }<br /><br />    public Object get(Object key) {<br />        boolean processed = false;<br />        if (key instanceof String) {<br />            String command = (String)key;<br />            if (reset.equalsIgnoreCase(command)) {<br />                operands = new ArrayList();<br />                return this;<br />            }<br />            if (equals.equalsIgnoreCase(command)) {<br />                processed=true;            <br />                return operands.get(operands.size()-1);<br />            }<br />            Object result = null;<br />            if (add.equalsIgnoreCase(command)) {<br />                result = add( operands.get(operands.size()-2), operands.get(operands.size()-1));<br />                processed=true;<br />            }<br />            if (substract.equalsIgnoreCase(command)) {<br />                result = substract( operands.get(operands.size()-2), operands.get(operands.size()-1));<br />                processed=true;<br />            }<br />            if (multiply.equalsIgnoreCase(command)) {<br />                result = multiply( operands.get(operands.size()-2), operands.get(operands.size()-1));<br />                processed=true;<br />            }<br />            if (divide.equalsIgnoreCase(command)) {<br />                result = divide( operands.get(operands.size()-2), operands.get(operands.size()-1));<br />                processed=true;<br />            }<br />            if (aslong.equalsIgnoreCase(command)) {<br />                result = aslong(  operands.get(operands.size()-1));<br />                operands.add(null); // since this is a one operand operation<br />                processed=true;<br />            }<br />            if (round.equalsIgnoreCase(command)) {<br />                result = round( operands.get(operands.size()-1));<br />                operands.add(null); // since this is a one operand operation<br />                processed=true;<br />            }<br />            if (result!=null) {<br />                operands.remove(operands.size()-1);<br />                operands.remove(operands.size()-1);<br />                operands.add(result);                            <br />            }                       <br />        }<br />        if (!processed)<br />          operands
.add(key);    <br />      retur
n this;<br />    }<br />    <br />    private Object add(Object o1, Object o2) {<br />        return makeNumber(o1).add(makeNumber(o2));        <br />    }<br />    private Object substract(Object o1, Object o2) {<br />        return makeNumber(o1).subtract(makeNumber(o2));        <br />    }<br />    private Object multiply(Object o1, Object o2) {<br />        return makeNumber(o1).multiply(makeNumber(o2));        <br />    }<br />    private Object divide(Object o1, Object o2) {<br />        try {<br />            return makeNumber(o1).divide(makeNumber(o2));        <br />        }<br />        catch (Exception e) {<br />            return null;<br />        }<br />    }<br />    private Object round(Object o1) {<br />        try {<br />            return makeNumber(o1).round(0);        <br />        }<br />        catch (Exception e) {<br />            return null;<br />        }<br />    }<br />    private Object aslong(Object o1) {<br />        try {<br />            return new Long(makeNumber(o1).longValue());        <br />        }<br />        catch (Exception e) {<br />            return null;<br />        }<br />    }<br />    <br />    private Number makeNumber(Object o) {<br />       try {<br />       if (o instanceof Number) return (Number)o;<br />           if (o instanceof String) return new Number((String)o);<br />           if (o instanceof Long) return new Number((Long)o);<br />           if (o instanceof Integer) return new Number((Integer)o);<br />           if (o instanceof Double) return new Number((Double)o);<br />       } catch (Exception e) {<br />           return null;<br />       }<br />       return null;<br />    }<br /><br />}<br /><br />

Note: by extending the Calculator class we can support an unlimited number of operations and functions, for formatting, string manipulation, calculations etc.

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

Comments are closed.