com.sfs.Formatter.java Source code

Java tutorial

Introduction

Here is the source code for com.sfs.Formatter.java

Source

/*******************************************************************************
 * Copyright (c) 2009 David Harrison.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v3.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/gpl-3.0.html
 *
 * Contributors:
 *     David Harrison - initial API and implementation
 ******************************************************************************/
package com.sfs;

import java.text.SimpleDateFormat;
import java.text.Format;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.Locale;
import java.math.BigDecimal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.jvnet.inflector.Noun;

/**
 * The Class Formatter.
 */
public class Formatter {

    /** The Constant WEEKS_IN_MONTH. */
    private static final double WEEKS_IN_MONTH = 4.3;

    /**
     * Instantiates a new formatter.
     */
    protected Formatter() {
        throw new UnsupportedOperationException();
    }

    /**
     * To currency.
     *
     * @param value the value
     *
     * @return the string
     */
    public static String toCurrency(final double value) {
        String currency = "";
        NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);
        currency = currencyFormatter.format(value);
        return currency;
    }

    /**
     * To currency.
     *
     * @param value the value
     * @param denomination the denomination
     *
     * @return the string
     */
    public static String toCurrency(final double value, final String denomination) {
        String currency = toCurrency(value);

        if (value < 0) {
            // If a negative get rid of first two string values (($)
            currency = "-" + denomination + currency.substring(2);
            // Drop the ) at the end
            currency = currency.substring(0, currency.length() - 1);
        } else {
            // Otherwise just drop the $ from the front
            currency = denomination + currency.substring(1);
        }
        return currency;
    }

    /**
     * To percent.
     *
     * @param value the value
     * @param decimalPlaces the decimal places
     * @param suffix the suffix
     *
     * @return the string
     */
    public static String toPercent(final double value, final int decimalPlaces, final String suffix) {

        final int multiplier = 100;

        String percent = String.valueOf(round(value * multiplier, decimalPlaces));

        // If it ends with .0 then remove the tail
        if (percent.endsWith(".0")) {
            percent = StringUtils.replace(percent, ".0", "");
        }

        if (StringUtils.isNotBlank(suffix)) {
            percent += suffix;
        }
        return percent;
    }

    /**
     * Format the percentage.
     *
     * @param value the value
     * @return the string
     */
    public static String toPercentage(final double value, final String suffix) {

        String percent = String.valueOf(value);

        if (percent.indexOf(".") > 0) {
            while (percent.endsWith("0")) {
                percent = percent.substring(0, percent.length() - 1);
            }
            if (percent.endsWith(".")) {
                percent = percent.substring(0, percent.length() - 1);
            }
        }

        if (StringUtils.isNotBlank(suffix)) {
            percent += suffix;
        }
        return percent;
    }

    /**
     * Convert boolean.
     *
     * @param value the value
     *
     * @return the string
     */
    public static String convertBoolean(final boolean value) {
        return convertBoolean(value, "Yes", "No");
    }

    /**
     * Convert boolean.
     *
     * @param value the value
     * @param trueValue the true value
     * @param falseValue the false value
     *
     * @return the string
     */
    public static String convertBoolean(final boolean value, final String trueValue, final String falseValue) {
        String outcome = "";
        if (value) {
            outcome = trueValue;
        } else {
            outcome = falseValue;
        }
        return outcome;
    }

    /**
     * Convert boolean.
     *
     * @param value the value
     *
     * @return the string
     */
    public static String convertBoolean(final String value) {
        if (value != null) {
            if (value.compareToIgnoreCase("true") == 0) {
                return "Yes";
            }
        }
        return "No";
    }

    /**
     * Convert date.
     *
     * @param date the date
     *
     * @return the string
     */
    public static String convertDate(final Date date) {
        String strDate = "";
        if (date != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("MMM d, yyyy");
            strDate = dateFormat.format(date);
        }
        return strDate;
    }

    /**
     * Convert date time.
     *
     * @param date the date
     *
     * @return the string
     */
    public static String convertDateTime(final Date date) {
        String strDate = "";
        if (date != null) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM yyyy ' at ' h:mm aaa");
            strDate = dateFormat.format(date);
        }
        return strDate;
    }

    /**
     * Conventional date.
     *
     * @param date the date
     *
     * @return the string
     */
    public static String conventionalDate(final Date date) {
        return numericDate(date, "dd/MM/yyyy");
    }

    /**
     * Conventional date.
     *
     * @param date the date
     * @param generateCurrent the generate current
     *
     * @return the string
     */
    public static String conventionalDate(final Date date, final boolean generateCurrent) {
        Date returnDate = date;
        if (date == null && generateCurrent) {
            returnDate = Calendar.getInstance().getTime();
        }
        return conventionalDate(returnDate);
    }

    /**
     * Numeric date.
     *
     * @param date the date
     *
     * @return the string
     */
    public static String numericDate(final Date date) {
        return numericDate(date, null);
    }

    /**
     * Numeric date.
     *
     * @param date the date
     * @param generateCurrent the generate current
     *
     * @return the string
     */
    public static String numericDate(final Date date, final boolean generateCurrent) {
        Date returnDate = date;
        if (date == null && generateCurrent) {
            returnDate = Calendar.getInstance().getTime();
        }
        return numericDate(returnDate);
    }

    /**
     * Numeric date.
     *
     * @param date the date
     * @param format the format
     *
     * @return the string
     */
    public static String numericDate(final Date date, final String format) {
        String strDate = "";
        String dateFormat = "dd.MM.yyyy";
        if (StringUtils.isNotBlank(format)) {
            dateFormat = format;
        }
        if (date != null) {
            Format formatter = new SimpleDateFormat(dateFormat);
            strDate = formatter.format(date);
        }
        return strDate;
    }

    /**
     * Gets the phone.
     *
     * @param countryCode the country code
     * @param areaCode the area code
     * @param phoneNumber the phone number
     *
     * @return the phone
     */
    public static String getPhone(final String countryCode, final String areaCode, final String phoneNumber) {
        StringBuffer phone = new StringBuffer();

        if (StringUtils.isNotBlank(countryCode) && !StringUtils.equals(countryCode, "0")) {
            phone.append("(");
            phone.append(countryCode);
            phone.append(") ");
        }
        if (StringUtils.isNotBlank(areaCode) && !StringUtils.equals(areaCode, "0")) {
            phone.append(areaCode);
            phone.append("-");
        }
        if (StringUtils.isNotBlank(phoneNumber)) {
            phone.append(phoneNumber);
        }
        return phone.toString();
    }

    /**
     * Gets the numeric phone.
     *
     * @param countryCode the country code
     * @param areaCode the area code
     * @param phoneNumber the phone number
     *
     * @return the numeric phone
     */
    public static String getNumericPhone(final int countryCode, final int areaCode, final String phoneNumber) {
        StringBuffer phone = new StringBuffer();

        int intPhoneNumber = 0;
        try {
            intPhoneNumber = Integer.parseInt(phoneNumber);
        } catch (NumberFormatException nfe) {
            intPhoneNumber = 0;
        }

        if (intPhoneNumber == 0 && StringUtils.isNotBlank(phoneNumber)) {
            // An integer has not been parsed, but a phone number
            // has been supplied. This means it probably contains
            // some non-numeric characters.
            Pattern pattern = Pattern.compile("[^\\d]");
            Matcher match = pattern.matcher(phoneNumber);
            String onlyDigits = match.replaceAll("");

            try {
                intPhoneNumber = Integer.parseInt(onlyDigits);
            } catch (NumberFormatException nfe) {
                intPhoneNumber = 0;
            }
        }

        // Build the phone numeric string
        phone.append("+");
        phone.append(countryCode);
        phone.append(" ");
        phone.append(areaCode);
        phone.append(" ");
        phone.append(intPhoneNumber);

        return phone.toString();
    }

    /**
     * Gets the value.
     *
     * @param value the value
     * @param decimalPlaces the decimal places
     *
     * @return the value
     */
    public static String getValue(final double value, final int decimalPlaces) {
        String result = "";

        double roundedValue = round(value, decimalPlaces);

        if (roundedValue != 0) {
            // Cast to a string
            if (decimalPlaces == 0) {
                int rounded = (int) roundedValue;
                result = String.valueOf(rounded);
            } else {
                result = String.valueOf(roundedValue);
            }
        }
        return result;
    }

    /**
     * Round.
     *
     * @param value the value
     * @param decimalPlaces the decimal places
     *
     * @return the double
     */
    public static double round(final double value, final int decimalPlaces) {
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }

    /**
     * If value.
     *
     * @param textValue the text value
     *
     * @return the string
     */
    public static String ifValue(final String textValue) {
        return ifValue(textValue, null, null);
    }

    /**
     * If value.
     *
     * @param intValue the int value
     *
     * @return the string
     */
    public static String ifValue(final int intValue) {
        String text = "";
        if (intValue > 0) {
            text = ifValue(String.valueOf(intValue), null, null);
        }
        return text;
    }

    /**
     * If value.
     *
     * @param textValue the text value
     * @param prefix the prefix
     * @param suffix the suffix
     *
     * @return the string
     */
    public static String ifValue(final String textValue, final String prefix, final String suffix) {

        final StringBuffer returnValue = new StringBuffer();

        if (StringUtils.isNotBlank(textValue)) {
            if (prefix != null) {
                returnValue.append(prefix);
            }

            returnValue.append(textValue);

            if (suffix != null) {
                returnValue.append(suffix);
            }
        }
        return returnValue.toString();
    }

    /**
     * File size.
     *
     * @param bytes the bytes
     *
     * @return the string
     */
    public static String fileSize(final long bytes) {

        String filesize = "";

        final int maxBytes = 1024;
        final double dbMaxBytes = 1024.0;

        if (bytes < maxBytes) {
            DecimalFormat formatter = new DecimalFormat("#,##0");
            filesize = formatter.format((double) bytes) + " bytes";
        } else if (bytes < maxBytes * maxBytes) {
            DecimalFormat formatter = new DecimalFormat("#,##0.0");
            filesize = formatter.format((double) bytes / dbMaxBytes) + " kb";
        } else if (bytes < maxBytes * maxBytes * maxBytes) {
            DecimalFormat formatter = new DecimalFormat("#,##0.0");
            filesize = formatter.format((double) bytes / (dbMaxBytes * dbMaxBytes)) + " mb";
        } else {
            DecimalFormat formatter = new DecimalFormat("#,##0.0");
            filesize = formatter.format((double) bytes / (dbMaxBytes * dbMaxBytes * dbMaxBytes)) + " gb";
        }
        return filesize;
    }

    /**
     * To plural.
     *
     * @param noun the noun
     *
     * @return the string
     */
    public static String toPlural(final String noun) {
        String plural = "";
        if (noun != null) {
            plural = Noun.pluralOf(noun);
        }
        return plural;
    }

    /**
     * Gets the whole months based on the number of weeks supplied.
     *
     * @param weeks the weeks value
     * @return the whole months
     */
    public static int getWholeMonths(final int weeks) {

        double months = Formatter.round(weeks / WEEKS_IN_MONTH, 0);

        return (int) months;
    }

    /**
     * Gets the whole weeks based on the number of months supplied.
     *
     * @param months the months value
     * @return the whole weeks
     */
    public static int getWholeWeeks(final int months) {

        double weeks = Formatter.round(months * WEEKS_IN_MONTH, 0);

        return (int) weeks;
    }

    /**
     * Gets the part number of months based on the number of weeks supplied.
     *
     * @param weeks the weeks value
     * @return the part months
     */
    public static int getPartMonths(final int weeks) {

        BigDecimal bd = new BigDecimal(weeks / WEEKS_IN_MONTH);
        bd = bd.setScale(0, BigDecimal.ROUND_DOWN);

        return (int) bd.intValue();
    }

    /**
     * Gets the part number of weeks based on the number of weeks supplied.
     *
     * @param weeks the weeks value
     * @return the part weeks
     */
    public static int getPartWeeks(final int weeks) {

        int partMonths = Formatter.getPartMonths(weeks);

        int partWeeks = weeks - (int) Formatter.round(partMonths * WEEKS_IN_MONTH, 0);

        return partWeeks;
    }

    /**
     * Gets a formatted string for the number of weeks supplied.
     *
     * @param weeks the weeks value
     * @return the formatted string
     */
    public static String getFormattedDuration(final int weeks) {

        StringBuffer sb = new StringBuffer();

        int partMonths = Formatter.getPartMonths(weeks);
        int partWeeks = Formatter.getPartWeeks(weeks);

        if (partMonths > 0) {
            sb.append(partMonths);
            sb.append(" month");
            if (partMonths > 1) {
                sb.append("s");
            }
        }

        if (partWeeks > 0) {
            if (sb.length() > 0) {
                sb.append(", ");
            }
            sb.append(partWeeks);
            sb.append(" week");
            if (partWeeks > 1) {
                sb.append("s");
            }
        }
        return sb.toString();
    }

}