001    package railo.runtime.type.comparator;
002    
003    import java.util.Comparator;
004    
005    import railo.runtime.exp.ExpressionException;
006    import railo.runtime.exp.PageException;
007    import railo.runtime.exp.PageRuntimeException;
008    import railo.runtime.op.Caster;
009    
010    
011    /**
012     * comparator implementation, compare to numbers
013     */
014    public final class NumberComparator implements Comparator {
015    
016            private boolean isAsc;
017    
018            /**
019             * constructor of the class 
020             * @param isAsc is ascendinf or descending
021             */
022            public NumberComparator(boolean isAsc) {
023                    this.isAsc=isAsc;
024            }
025            
026            @Override
027            public int compare(Object oLeft, Object oRight) {
028                    try {
029                            if(isAsc) return compareObjects(oLeft, oRight);
030                            return compareObjects(oRight, oLeft);
031                    } catch (PageException e) {
032                            throw new PageRuntimeException(new ExpressionException("can only sort arrays with simple values",e.getMessage()));
033                    }
034            }
035            
036            private int compareObjects(Object oLeft, Object oRight) throws PageException {
037                    double left=Caster.toDoubleValue(oLeft);
038                    double right=Caster.toDoubleValue(oRight);
039                    if(left < right)return -1;
040                    return left > right ? 1 : 0;
041                    
042            }
043    }