001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.type.comparator;
020
021import java.util.Comparator;
022
023import lucee.runtime.exp.ExpressionException;
024import lucee.runtime.exp.PageException;
025import lucee.runtime.exp.PageRuntimeException;
026import lucee.runtime.op.Caster;
027
028
029/**
030 * comparator implementation to compare textes
031 */
032public final class TextComparator implements Comparator {
033        
034        private boolean isAsc;
035        private boolean ignoreCase;
036
037        /**
038         * constructor of the class
039         * @param isAsc ascending or desending
040         * @param ignoreCase ignore case or not
041         */
042        public TextComparator(boolean isAsc, boolean ignoreCase) {
043                this.isAsc=isAsc;
044                this.ignoreCase=ignoreCase;
045        }
046        
047        @Override
048        public int compare(Object oLeft, Object oRight) {
049                try {
050                        if(isAsc) return compareObjects(oLeft, oRight);
051                        return compareObjects(oRight, oLeft);
052                } 
053                catch (PageException e) {
054                        throw new PageRuntimeException(new ExpressionException("can only sort arrays with simple values",e.getMessage()));
055                }
056        }
057        
058        private int compareObjects(Object oLeft, Object oRight) throws PageException {
059                if(ignoreCase)return Caster.toString(oLeft).compareToIgnoreCase(Caster.toString(oRight));
060                return Caster.toString(oLeft).compareTo(Caster.toString(oRight));
061        }
062
063}