com.hemou.android.util.StrUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.hemou.android.util.StrUtils.java

Source

/*
 * Copyright 2014 hemou Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hemou.android.util;

import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.Log;
import android.webkit.URLUtil;

import com.hemou.android.core.cons.AppCons;
import com.hemou.component.saripaar.Rules;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.util.StringUtils;
import org.springframework.web.util.UriTemplate;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import static android.text.format.DateUtils.*;
import static com.eagleyes.social.SysCons.*;

/**
 * Utilities for dealing with dates and times
 */
public class StrUtils {

    /**
     * Get relative time for date
     * 
     * @param date
     * @return relative time
     */
    public static CharSequence getRelativeTime(final Date date) {
        if (date == null)
            return "--";
        long now = System.currentTimeMillis();
        if (Math.abs(now - date.getTime()) > 60000)
            return DateUtils.getRelativeTimeSpanString(date.getTime(), now, MINUTE_IN_MILLIS,
                    FORMAT_SHOW_DATE | FORMAT_SHOW_YEAR | FORMAT_NUMERIC_DATE);
        else
            return "";
    }

    public static String convertTime(long time) {
        Date date = new Date(time);
        Format format = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
        return format.format(date);
    }

    /**
     * {@link https://en.wikipedia.org/wiki/List_of_time_zones_by_country}
     * @param time
     * @return
     */
    public static String convertTimeWithTimeZome(long time) {

        Calendar cal = Calendar.getInstance();
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        cal.setTimeInMillis(time);
        return (cal.get(Calendar.YEAR) + " " + (cal.get(Calendar.MONTH) + 1) + " " + cal.get(Calendar.DAY_OF_MONTH)
                + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE));

    }

    public static String obj2Str(Object obj) {
        String str;
        try {
            str = new ObjectMapper().writeValueAsString(obj);
        } catch (Exception e) {
            Log.w("Obj2Str", "Can not convert for?" + e.getMessage() + "");
            str = obj == null ? "null" : obj.toString();
        }
        return str;
    }

    public static <K> K str2Obj(String str, TypeReference<K> type) {
        try {
            return new ObjectMapper().readValue(str, type);
        } catch (Exception e) {
            Log.w("Str2Obj", "Can not convert " + str + " to class ?" + type.getType() + "");
            e.printStackTrace();
        }
        return null;
    }

    public static <K> K str2Obj(String str, Class<K> cls) {
        try {
            return new ObjectMapper().readValue(str, cls);
        } catch (Exception e) {
            Log.w("Str2Obj", "Can not convert " + str + " to class ?" + cls.getSimpleName() + "");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * ???
     * 
     * @param chinese
     *            
     * @return 
     */
    public static String getPinyin(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString();
    }

    public static boolean isValidUrl(String url) {
        return URLUtil.isValidUrl(url);
    }

    public static boolean isLegalUrl(String str) {
        boolean isRight = true;
        try {
            new URL(str);
        } catch (MalformedURLException e) {
            isRight = false;
        } finally {
            if (!isRight) {
                try {
                    new URL("http://" + str);
                } catch (MalformedURLException e) {
                    isRight = false;
                }
                isRight = true;
            }
        }
        return isRight;
    }

    public static String toUri(String url, Object... urlVariables) {
        try {
            UriTemplate uriTemplate = new UriTemplate(url);
            URI expanded = uriTemplate.expand(urlVariables);
            return expanded.toURL().toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    public static String arrayToCommaDelimitedString(String[] arr) {
        StringBuilder sb = new StringBuilder();
        if (arr != null) {
            for (String itm : arr)
                if (!TextUtils.isEmpty(itm))
                    sb.append(itm + ",");
            if (sb.length() == 0)
                return "";
            return sb.deleteCharAt(sb.length() - 1).toString();
        } else
            return "";
    }

    public static String replaceUrlWithPlus(String url) {
        // 1. ?
        // 2. ?????(???)
        if (url != null) {
            return url.replaceAll("http://(.)*?/", "").replaceAll("[.:/,%?&=]", "+").replaceAll("[+]+", "+");
        }
        return null;
    }

    /**
     * ??<b> ??
     * 
     * @param size
     * @return
     */
    public static String formatFileSize(long size) {
        StringBuilder sb = new StringBuilder();
        String u = null;
        double tmpSize = 0;
        if (size < KB) {
            sb.append(size).append("B");
            return sb.toString();
        } else if (size < MB) {
            tmpSize = getSize(size, KB);
            u = "KB";
        } else if (size < GB) {
            tmpSize = getSize(size, MB);
            u = "MB";
        } else {
            tmpSize = getSize(size, GB);
            u = "GB";
        }
        return sb.append(twodot(tmpSize)).append(u).toString();
    }

    /**
     * ??????mkm
     * 
     * @param value
     * @return
     */
    public static String formatDist(double value) {
        if (value <= 0)
            return "";
        else if (value < 1)
            return String.valueOf((int) (value * 1000)) + "m";
        else
            return String.valueOf(((int) (value * 100) / 100.0)) + "km";
    }

    public static boolean isIllegalAcnt(String acnt) {

        return TextUtils.isEmpty(acnt) || (acnt.matches(AppCons.REG_PHONE_NUM) && acnt.matches(Rules.REGEX_EMAIL));
    }

    public static boolean isIllegalDynamicToken(String token) {
        return TextUtils.isEmpty(token) || !token.matches(AppCons.REG_DYNAMIC_TOKEN);
    }

    public static boolean isIllegalPswd(String pswd) {
        return TextUtils.isEmpty(pswd) || pswd.matches(AppCons.REG_CHAR) || pswd.matches(AppCons.REG_NUM)
                || pswd.length() < AppCons.MIN_PSWD_LEN;
    }

    /**
    * ???
    * 
    * @param d
    * @return
    */
    public static String twodot(double d) {
        return String.format("%.2f", d);
    }

    public static double getSize(long size, long u) {
        return (double) size / (double) u;
    }

    public static boolean isEmpties(String... itms) {
        if (itms == null || itms.length <= 0)
            throw new IllegalArgumentException();
        for (String itm : itms)
            if (StringUtils.isEmpty(itm))
                return true;
        return false;
    }
}