Jun 052011
 

A very tolerant time string parser.

package sactosoft.common;

public class MilitaryTimeParser {
    String timeString;

    String hh = "00";

    String mm = "00";

    String ss = "00";

    private boolean isValid = true;

    public MilitaryTimeParser() {
    }

    public MilitaryTimeParser(String timeString) {
        this.setTimeString(timeString);
    }

    public void setTimeString(String timeString) {
        this.timeString = timeString;
        parseTime();
    }

    public String getTimeString() {
        return this.hh + this.mm + this.ss;
    }

    public String getTimeString(String dlm) {
        return this.hh + dlm + this.mm + dlm + this.ss;
    }

    private void parseTime() {
        // the extrac 00 guard against the case when the user enter 8 digits
        String[] tt = { "00", "00", "00", "00" };
        String t = this.timeString.replaceAll("[^0-9]", " ").trim().replaceAll(" +", " ").replaceAll("[^0-9]", ":");
        if (t.contains(":")) {
            for (int i = 0; i < t.split(":").length; i++) {
                tt[i] = t.split(":")[i];
                tt[i] = "0".substring(tt[i].length() - 1) + tt[i];
            }
        } else {
            int timeLen = t.length();
            // pad the string to even number of digits
            String pad = "0".substring(0, timeLen - (timeLen / 2) * 2);
            t = pad + t;
            timeLen = t.length();
            for (int i = 0; i < t.length() / 2; i++) {
                tt[i] = t.substring(i * 2, (i + 1) * 2);
            }
        }

        this.hh = tt[0];
        this.mm = tt[1];
        this.ss = tt[2];
        if ((Integer.parseInt(this.hh) > 24) || (Integer.parseInt(this.mm) > 59) || (Integer.parseInt(this.ss) > 59)) {
            this.isValid = false;
        }
    }

    public boolean isValidTime() {
        return this.isValid;
    }

    /**
     * @return the hh
     */
    public String getHH() {
        return this.hh;
    }

    /**
     * @return the mm
     */
    public String getMM() {
        return this.mm;
    }

    /**
     * @return the ss
     */
    public String getSS() {
        return this.ss;
    }
}

Jun 052011
 
package sactosoft.filedecompressor;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class FileDecompressor {
    static final int BUFFER = 2048;

    public static final boolean UseFolderNames = true;

    public static void decompress(String inputFile, String outputPath, boolean useFolderNames) throws Exception {
        inputFile = inputFile.trim().replace('\\', '/');
        outputPath = getOutputPath(inputFile, outputPath);

        BufferedInputStream is = null;

        if (inputFile.toLowerCase().endsWith("gz")) {
            GZIPInputStream gzis = new GZIPInputStream(new FileInputStream(inputFile));
            is = new BufferedInputStream(gzis);
            String outputFile = outputPath + "/"
                    + inputFile.substring(inputFile.lastIndexOf('/') + 1, inputFile.length() - 3);
            createOutFile(is, outputFile);
        } else {
            ZipEntry entry;
            ZipFile zipfile = new ZipFile(inputFile);
            Enumeration e = zipfile.entries();

            while (e.hasMoreElements()) {
                entry = (ZipEntry) e.nextElement();
                String outputFileName;
                if (useFolderNames) {
                    outputFileName = entry.getName();
                } else {
                    outputFileName = entry.getName().replace('\\', '/');
                    if (outputFileName.contains("/")) {
                        outputFileName = outputFileName.substring(outputFileName.lastIndexOf('/') + 1);
                    }
                }
                is = new BufferedInputStream(zipfile.getInputStream(entry));
                createOutFile(is, outputFileName);
            }
        }

    }

    // -----
    private static String getOutputPath(String inputFile, String outputPath) {
        if (outputPath == null) {
            // inputFile = inputFile.trim().replace('\\', '/');
            String inputPath = inputFile.substring(0, inputFile.lastIndexOf("/"));
            outputPath = inputPath;
        } else {
            outputPath = outputPath.trim().replace('\\', '/');
            if (outputPath.endsWith("/")) {
                outputPath = outputPath.substring(0, outputPath.length() - 1);
            }
        }
        return outputPath;
    }

    private static void createOutFile(BufferedInputStream is, String outputFile) throws Exception {
        BufferedOutputStream dest = null;
        int count;
        byte data[] = new byte[BUFFER];
        FileOutputStream fos = new FileOutputStream(outputFile);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = is.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
        is.close();
    }
}
Jun 052011
 

Very useful for logging and debugging.

package sactosoft.beanviewer;

import java.lang.reflect.Method;

/**
 * Displays an object propeties as property=value
 * 
 * 
 * Need to make it display object properties recursivly 
 * Usage: BeanViewer.view(object)
 * 
 * 
 * @author sactosoft
 * 
 */
public class BeanViewer {
    public static void view(Object obj) {
        Class c = obj.getClass();
        Method[] m = c.getMethods();
        for (int i = 0; i < m.length; i++) {
            String mName = m[i].getName();
            if (mName.startsWith("get")) {
                Class[] parameterTypes = m[i].getParameterTypes();
                if (parameterTypes.length == 0) {
                    Object result = null;
                    try {
                        result = m[i].invoke(obj, parameterTypes);
                    } catch (Exception e) {
                        System.out.println("BeanViewer failed. ");
                        e.printStackTrace();
                    }
                    System.out.print(mName.substring(3) + "=" + result + " | ");
                }
            }
        }
        System.out.println("");
    }
}
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();

    }
}