Jun 052011
 

I created this library of methods, all of them static, out of my daily work on Java projects. AS I see that there is a chance to write a generic expression evaluator, I just add it to this package:

package sactosoft.common;

import java.text.CharacterIterator;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.text.StringCharacterIterator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;

//import com.raleys.dw.tlog.utils.F;
// date format could be MM/dd/yyyy, yyyy-MM-dd, ...
/**
 * @author Sactosoft
 * 
 *      
 * Date format reference
 * y:Year,                 H:Hour in day (0-23):
 * M:Month in year,        k:Hour in day (1-24):
 * w:Week in year,         K:Hour in am/pm (0-11):
 * W:Week in month,        h:Hour in am/pm (1-12):
 * D:Day in year:m,        Minute in hour:
 * d:Day in month,         s:Second in minute:
 * F:Day of week in month, S:Millisecond:
 * E:Day in week,          z:Time zone:
 * a:Am/pm marker,         Z:Time zone:
 * 
 */
public class Evaluate {

    public static final String yyyy_MM_dd = "yyyy-MM-dd";

    /**
     * Convert date to string.
     * 
     * @param date - java.util.Date
     * @param format - yyyy-MM-dd, MM/dd/yy, ...
     * @return
     */
    public static String dateToString(Date date, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(date);
    }

    /**
     * Convert string to date
     * 
     * @param date - java.util.Date
     * @param format - yyyy-MM-dd, MM/dd/yy, ...
     * @return date
     * @throws Exception
     */
    public static Date stringToDate(String date, String format) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.parse(date);
    }

    /**
     * 
     * @param date - Date text in the format defined by the next param.
     * @param format - yyyy-MM-dd, MM/dd/yy, ...
     * @return Date + 7 days
     * @throws Exception
     */
    public static String nextWeekDate(String date, String format) throws Exception {
        return addDays(date, format, 7);
    }

    public static String prevWeekDate(String date, String format) throws Exception {
        return addDays(date, format, -7);
    }

    /**
     * 
     * @param date - Date text in the format defined by the next param.
     * @param format - yyyy-MM-dd, MM/dd/yy, ...
     * @param days - Number of days to add or subtract (e.g. 2, -3)
     * @return - Evaluated date as string.
     * @throws Exception
     */
    public static String addDays(String date, String format, int days) throws Exception {
        Date d = Evaluate.stringToDate(date, format);
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        c.add(Calendar.DATE, days);
        d = c.getTime();
        return Evaluate.dateToString(d, format);
    }

    /**
     * 
     * @param date - Date text in the format defined by the next param.
     * @param format - yyyy-MM-dd, MM/dd/yy, ...
     * @return - 1=Sunday, 2=Monday, ...
     * @throws Exception
     */
    public static int dayOfWeek(String date, String format) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date1 = sdf.parse(date);
        Calendar c = Calendar.getInstance();
        c.setTime(date1);
        return c.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 
     * @param dayOfWeek - 1=Sunday, 2=Monday, ...
     * @param format - yyyy-MM-dd, MM/dd/yy, ...
     * @return The date of the provided day of week, within the current week. E.g. assume todays date is Tues Aug 26,
     *         2008, then: Evaluate.thisWeekDayOfWeekDate(2,"yyyyMMdd") would return "20080825"
     * @throws Exception
     */
    public static String thisWeekDayOfWeekDate(int dayOfWeek, String format) throws Exception {
        String date = Evaluate.dateToString(new Date(), format);
        int days = dayOfWeek - Evaluate.dayOfWeek(date, format);
        return Evaluate.addDays(date, format, days);
    }

    public static String lastDayOfWeekDate(int dayOfWeek, String dateFormat) throws Exception {
        String date = Evaluate.dateToString(new Date(), dateFormat);
        int days = Evaluate.dayOfWeek(date, dateFormat) - dayOfWeek + 7;
        days = -1 * (days % 7);
        return Evaluate.addDays(date, dateFormat, days);
    }

    /**
     * 
     * @param strings
     * @param stringToFind
     * @return the index of str in array
     */
    public static int arrayIndex(String[] strings, String stringToFind) {
        int retVal = -1;
        for (int i = 0; i < strings.length; i++) {
            if (strings[i].equalsIgnoreCase(stringToFind)) {
                return i;
            }
        }
        return retVal;
    }

    public static String arrayToString(String values[], String delimiter) {
        String retVal = values[0];
        for (int i = 1; i < values.length; i++) {
            retVal = retVal + delimiter + values[i];
        }
        return retVal;
    }

    public static int getJulianDateInt(String dateString, String format) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d = sdf.parse(dateString);
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        int jDate = c.get(Calendar.DAY_OF_YEAR);
        return jDate;
    }

    public static String getJulianDateStr(String dateString, String format) throws Exception {
        int jd = Evaluate.getJulianDateInt(dateString, format);
        return Evaluate.intToString(jd, "000");
    }

    public static String intToString(int i, String format) {
        NumberFormat nf = new DecimalFormat(format);
        String str = nf.format(i);
        return str;
    }

    public static Map sortMapOnValues(Map hmap) {
        HashMap map = new LinkedHashMap();
        List mapKeys = new ArrayList(hmap.keySet());
        List mapValues = new ArrayList(hmap.values());
        TreeSet sortedSet = new TreeSet(mapValues);
        Object[] sortedArray = sortedSet.toArray();
        int size = sortedArray.length;
        // Ascending sort
        for (int i = 0; i < size; i++) {
            map.put(mapKeys.get(mapValues.indexOf(sortedArray[i])), sortedArray[i]);
        }
        return map;
    }

    public static String escapeXMLSpecialChars(String input) {
        final StringBuffer result = new StringBuffer();
        final StringCharacterIterator iterator = new StringCharacterIterator(input);
        char character = iterator.current();

        while (character != CharacterIterator.DONE) {
            if (character == '&') {
                result.append("&");
            } else if (character == '\"') {
                result.append(""");
            } else if (character == '<') {
                result.append("<");
            } else if (character == '>') {
                result.append(">");
            } else {
                result.append(character); // char not special, just append
            }
            character = iterator.next();
        }
        return result.toString();
    }

    /*
     * String leftPaddedWithX = stringPadding("aa", 5, "X", true); String rightPaddedWithX = stringPadding("aa", 5, "X",
     * false);
     */
    public static String stringPadding(String s, int n, char c, boolean paddingLeft) {
        if (s == null) {
            return s;
        }
        int add = n - s.length(); // may overflow int size... should not be a problem in real life
        if (add <= 0) {
            return s;
        }
        StringBuffer str = new StringBuffer(s);
        char[] ch = new char[add];
        Arrays.fill(ch, c);
        if (paddingLeft) {
            str.insert(0, ch);
        } else {
            str.append(ch);
        }
        return str.toString();

    }
}