com.reizes.shiva.utils.CommonUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.reizes.shiva.utils.CommonUtil.java

Source

/*
 * CommonUtil.java 
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package com.reizes.shiva.utils;

import java.io.UnsupportedEncodingException;
import java.math.RoundingMode;
import java.net.IDN;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.UrlValidator;

/**
 *  
 * @author reizes
 * @since 2010.1.21
 */
public class CommonUtil {
    /**
     * Date? yyyy-mm-dd ? ? ?
     * @param date - Date
     * @return - yyyy-mm-dd
     */
    public static String getDateString(Date date) {
        if (date != null) {
            return String.format("%1$tY.%1$tm.%1$td", date);
        }

        return null;
    }

    /**
     * Date? yyyy-mm-dd ? ? ?
     * date  null ? null 
     * @param date - Date
     * @return - yyyy-mm-dd
     */
    public static String getDateStringDash(Date date) {
        if (date != null) {
            return String.format("%1$tY-%1$tm-%1$td", date);
        }

        return null;
    }

    /**
     * Date? yyyy-mm-dd ? ? ?
     * date  null ? ""(?) 
     * @param date
     * @return
     */
    public static String getDateStringDashNullToEmpty(Date date) {
        String dateString = getDateStringDash(date);
        return dateString == null ? "" : dateString;
    }

    /**
     * Date? yyyy.mm.dd HH:MM ? ? ?
     * @param date - Date
     * @return - yyyy.mm.dd HH:MM
     */
    public static String getDateTimeString(Date date) {
        if (date != null) {
            return String.format("%1$tY.%1$tm.%1$td %1$tH:%1$tM:%1$tS", date);
        }

        return null;
    }

    /**
     * Date? yyyy-mm-dd HH:MM:SS ? ? ?(24 )
     * @param date - Date
     * @return - yyyy-mm-dd HH:MM:SS
     */
    public static String getDateTimeStringDash(Date date) {
        if (date != null) {
            return String.format("%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS", date);
        }
        return null;
    }

    /**
     * Date? yyyymmdd-HHMMSS ? ? ?(24 )
     * @param date - Date
     * @return - yyyymmdd-HHMMSS
     */
    public static String getDateTimeStringNoBlank(Date date) {
        if (date != null) {
            return String.format("%1$tY%1$tm%1$td-%1$tH%1$tM%1$tS", date);
        }
        return null;
    }

    /**
     * ?    ?  ? ?. ? 00:00:00  
     * adjustAmount ? -?  + ? ?, 0 ?  ?  
     */
    public static Date getAdjustDayResetTime(Date date, int adjustAmount) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.add(Calendar.DATE, adjustAmount);
        return cal.getTime();
    }

    /**
     *  ?    .
     */
    public static Date getMinus1Day(Date date) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, -1);
        return cal.getTime();
    }

    /**
     *  ?  ?  .
     */
    public static Date getPlus1Day(Date date) {
        if (date == null) {
            return null;
        }
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, 1);
        return cal.getTime();
    }

    /**
     * inputFormatStr ? ?  Date (yyyy-MM-dd) (yyyyMM)
     */
    public static Date getDateFromStr(String inputDate, String inputFormatStr) {
        java.text.SimpleDateFormat formatterInput = new java.text.SimpleDateFormat(inputFormatStr);
        try {
            return formatterInput.parse(inputDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * HTML   ? ? escape 
     * @param str -
     * @param length - ? ? ?
     * @return - ? String
     */
    public static String getAbbrHTMLString(String str, int length) {
        return StringEscapeUtils.escapeHtml(StringUtils.abbreviate(str, length));
    }

    /**
     * StringEscapeUtils.escapeHtml wrapping
     * @param str -
     * @return -
     */
    public static String escapeHtml(String str) {
        if (str == null) {
            return null;
        }

        return StringUtils.replace(StringEscapeUtils.escapeHtml(str), "\n", "<br/>");
    }

    /**
     * StringEscapeUtils.escapeJavaScript wrapping
     * @param str -
     * @return -
     */
    public static String escapeJavaScript(String str) {
        if (str == null) {
            return null;
        }

        return StringEscapeUtils.escapeJavaScript(str);
    }

    /**
     * URLEncoder.encode wrapping
     * @param uri -
     * @return -
     * @throws UnsupportedEncodingException -
     */
    public static String encodeURI(String uri) throws UnsupportedEncodingException {
        if (uri == null) {
            return null;
        }

        return URLEncoder.encode(uri, "UTF-8");
    }

    /**
     * URLDecoder.decode wrapping
     * @param uri -
     * @return -
     * @throws UnsupportedEncodingException -
     */
    public static String decodeURI(String uri) throws UnsupportedEncodingException {
        if (uri == null) {
            return null;
        }

        return URLDecoder.decode(uri, "UTF-8");
    }

    /**
     * apache codec Base64 encoding
     * @param str -
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encodeBase64(String str) throws UnsupportedEncodingException {
        return Base64.encodeBase64URLSafeString(str.getBytes("UTF-8"));
    }

    /**
     * apache codec Base64 decoding
     * @param str
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String decodeBase64(String str) throws UnsupportedEncodingException {
        return new String(Base64.decodeBase64(str), "UTF-8");
    }

    public static String md5(String data) {
        return DigestUtils.md5Hex(data);
    }

    /**
     * @param str  String
     * @return null ? ?
     */
    public static String enforceNotNull(String str) {
        return str == null ? "" : str;
    }

    /**
     * @param num  ?
     * @return null ? 0
     */
    public static String enforceNotNull(Integer num) {
        return num == null ? "0" : Integer.toString(num);
    }

    /**
     * @param num  ?
     * @return null ? 0
     */
    public static String enforceNotNull(Long num) {
        return num == null ? "0" : Long.toString(num);
    }

    /**
     * @param num  ?
     * @return null ? 0.0
     */
    public static String enforceNotNull(Double num) {
        return num == null ? "0.0" : Double.toString(num);
    }

    /**
     * @param num  
     * @return null ? ?
     */
    public static String enforceNotNull(Date date) {
        return getDateStringDashNullToEmpty(date);
    }

    /**
     * ?   . ? null ? size  0? null 
     * @param list ? 
     */
    public static Object popFromList(List<?> list) {
        Object lastItem = null;
        if (list != null && list.size() > 0) {
            lastItem = list.get(list.size() - 1);
        }
        return lastItem;
    }

    /**
     * API ?  path ? 
     * path  null ? null 
     * @param path  
     * @return "||" -> ">", ?  "^>" -> ""  replace
     */
    public static String getDirPathForApi(String path) {
        if (path == null) {
            return null;
        }
        String dispPath = path.replace("||", ">");
        dispPath = dispPath.replaceFirst("^>", "");
        return dispPath;
    }

    /**
     * ??? 100  ? ?? ? (  ?)
     *  ? null ? 0 ? 0.0 ( API   )
     * @param input  ?
     * @return ? ? ? ?
     */
    public static String div100(Long input) {
        if (input == null || input == 0) {
            return "0.0";
        }
        Double fl = input / 100d;
        DecimalFormat df = new DecimalFormat("#.##");
        df.setRoundingMode(RoundingMode.FLOOR);
        return df.format(fl);
    }

    /**
     * end ? ? ? ? .
     * @param start
     * @param end
     * @return
     */
    public static long daysBetweenTime(long start, long end) {
        if (start > end) {
            return -1;
        }
        long term = end - start;
        return term / (1000 * 60 * 60 * 24);
    }

    /**
     * ?   (  ?)
     * @param input
     * @return
     */
    public static String decimalPointTwo(Float input) {
        if (input == null || input == 0) {
            return "0.0";
        }
        DecimalFormat df = new DecimalFormat("#.##");
        df.setRoundingMode(RoundingMode.FLOOR);
        return df.format(input);
    }

    /**
     * ?   (  ?)
     * @param input
     * @return
     */
    public static String decimalPointTwo(Double input) {
        if (input == null || input == 0) {
            return "0.0";
        }
        DecimalFormat df = new DecimalFormat("#.##");
        df.setRoundingMode(RoundingMode.FLOOR);
        return df.format(input);
    }

    /**
     * http  https URL ??  
     * @param url
     * @return
     * @throws MalformedURLException 
     */
    public static boolean isValidHttpUrl(String url) {
        if (url.length() > 255) { // 255?  url ?  ?
            return false;
        }

        String[] schemes = { "http", "https" };
        UrlValidator urlValidator = new UrlValidator(schemes);
        if (urlValidator.isValid(url)) {
            return true;
        }

        // ?   ??  
        URL urlTemp;
        try {
            urlTemp = new URL(url);
        } catch (MalformedURLException e) {
            return false;
        }
        String forUnicodeUrl = urlTemp.getProtocol() + "://" + IDN.toASCII(urlTemp.getHost());
        if (urlValidator.isValid(forUnicodeUrl)) {
            // ???  http://.com  www      ? 
            return true;
        }

        String regex = "([a-zA-Z0-9-.\\-&/%=?:#$(),.+;~\\_]+)"; // ?  ??  
        if (urlTemp.getHost().startsWith("\"")) {
            // ?? ? ??  ? URL
            return false;
        } else if (urlTemp.getHost().startsWith(".")) {
            // ?? ? ??  ? URL
            return false;
        } else if (urlTemp.getProtocol().startsWith("http") && urlTemp.getHost().matches(regex)) {
            return true;
        }

        return false;
    }

    /**
     * url   . www 
     * ? url ? ? ??   ?? ""  ? 
     * @param url
     * @return
     */
    public static String getUrlHost(String url) {
        String hostName = "";
        try {
            hostName = new URL(url).getHost();
            if (hostName.startsWith("www.")) {
                hostName = hostName.substring(4);
            }
        } catch (Exception e) {
        }
        return hostName;
    }

    /**
     * ? ?? URL ?  ?? ?? ?. www.   ?.
     * @param url1
     * @param url2
     * @return
     */
    public static boolean isEqualHost(String url1, String url2) {
        return CommonUtil.getUrlHost(url1).equals(CommonUtil.getUrlHost(url2));
    }

    public static String newlineToBR(String str) {
        return StringUtils.replace(str, "\n", "<BR/>");
    }
}