All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.javaclub.monitor.util.Utils Maven / Gradle / Ivy

The newest version!
/*
 * @(#)Utils.java	2018年1月13日
 *
 * Copyright (c) 2018. All Rights Reserved.
 *
 */

package com.github.javaclub.monitor.util;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.github.javaclub.monitor.encrypt.MD5;
import com.github.javaclub.monitor.exception.BizException;
import com.github.javaclub.toolbox.ToolBox.Maps;
import com.github.javaclub.toolbox.ToolBox.Strings;
import com.github.javaclub.toolbox.ToolBox.Web;


/**
 * Utils
 *
 * @author Gerald Chen
 * @version $Id: Utils.java 2018年1月13日 12:03:34 Exp $
 */
public class Utils {
	
	static final Logger log = LoggerFactory.getLogger(Utils.class);
	
	static final String EMPTY_STRING = "";

	public static String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
		}
		return null;
	}
	
	public static boolean hasLength(CharSequence str) {
		return (str != null && str.length() > 0);
	}
	
	public static boolean hasLength(String str) {
		return hasLength((CharSequence) str);
	}
	
	public static boolean isNumeric(String str) {
		if(isBlank(str)) {
			return false;
		}
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}
	
	/**
	 * http请求,调用方法参数签名
	 */
	public static String sign(Map paramValues, 
			List ignoreParamNames, String secret) {
		StringBuilder sb = new StringBuilder();
		List paramNames = new ArrayList(paramValues.size());
		paramNames.addAll(paramValues.keySet());
		if (ignoreParamNames != null && ignoreParamNames.size() > 0) {
			for (String ignoreParamName : ignoreParamNames) {
				paramNames.remove(ignoreParamName);
			}
		}
		Collections.sort(paramNames);

		sb.append(secret);
		for (String paramName : paramNames) {
			sb.append(paramName).append(paramValues.get(paramName));
		}
		sb.append(secret);

		String sign = MD5.getMd5(sb.toString());
		return sign;
	}
	
	/**
	 * 对Map内所有value作utf8编码,拼接返回结果
	 *
	 * @param data
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String toQueryString(Map data) throws UnsupportedEncodingException {
		StringBuffer queryString = new StringBuffer();
		for (Entry pair : data.entrySet()) {
			String val = Objects.toString(pair.getValue(), EMPTY_STRING);
			if (val.startsWith("[") && val.endsWith("]")) {
				String[] array = Strings.splitArrayString(val);
				if (null != array && array.length > 0) {
					for (String str : array) {
						queryString.append(pair.getKey() + "=");
						queryString.append(URLEncoder.encode(str, "UTF-8") + "&");
					}
				}
			} else {
				queryString.append(pair.getKey() + "=");
				queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
			}
		}
		if (queryString.length() > 0) {
			queryString.deleteCharAt(queryString.length() - 1);
		}
		return queryString.toString();
	}
	
	public static String buildHttpUrl(String url, Map paramsMap) {
		String actualUrl = url;
    	if (url.indexOf("?") > 0) {
    		Map map = Maps.newHashMap();
    		actualUrl = Strings.substringBefore(url, "?");
    		String queryString = Strings.substringAfter(url, "?");
    		Map queryParams = Web.splitUrlQuery(queryString);
    		if (Maps.isNotEmpty(queryParams)) {
    			map.putAll(queryParams);
    		}
    		if (Maps.isNotEmpty(paramsMap)) {
    			map.putAll(paramsMap);
    		}
    		if (Maps.isNotEmpty(map)) {
    			try {
					String appendQuery = Utils.toQueryString(map);
					if (Strings.isNotBlank(appendQuery)) {
						actualUrl = Strings.concat(actualUrl, "?", appendQuery);
					}
				} catch (UnsupportedEncodingException e) {
					log.error("Error of buildHttpUrl: " + e.getMessage(), e);
				}
    		}
    	} else if (Maps.isNotEmpty(paramsMap)) {
    		try {
				String appendQuery = Utils.toQueryString(paramsMap);
				if (Strings.isNotBlank(appendQuery)) {
					actualUrl = Strings.concat(actualUrl, "?", appendQuery);
				}
			} catch (UnsupportedEncodingException e) {
				log.error("Error of buildHttpUrl: " + e.getMessage(), e);
			}
    	}
    	return actualUrl;
	}
	
	public static boolean isNullOrEmpty(final CharSequence cs) {
		if (null == cs) {
			return true;
		}
		return !hasLength(cs);
	}
	
	public static boolean isEmpty(String input) {
		return null == input || 0 == input.length();
	}
	
	public static boolean isNotEmpty(String input) {
		return null != input && input.length() > 0;
	}

	public static boolean isNotBlank(final CharSequence cs) {
        return !isBlank(cs);
    }
	
	public static boolean isBlank(final CharSequence cs) {
        int strLen;
        if (cs == null || (strLen = cs.length()) == 0) {
            return true;
        }
        for (int i = 0; i < strLen; i++) {
            if (Character.isWhitespace(cs.charAt(i)) == false) {
                return false;
            }
        }
        return true;
    }
	
	/**
	 * 
     * Utils.split(null)       = null
     * Utils.split("")         = []
     * Utils.split("abc def")  = ["abc", "def"]
     * Utils.split("abc  def") = ["abc", "def"]
     * Utils.split(" abc ")    = ["abc"]
     * 
* * @param str the String to parse, may be null * @return an array of parsed Strings, null if null String input */ public static String[] split(String str) { return split(str, null, -1); } /** *
     * StringUtils.split(null, *)         = null
     * StringUtils.split("", *)           = []
     * StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
     * StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
     * StringUtils.split("a:b:c", '.')    = ["a:b:c"]
     * StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
     * 
*/ public static String[] split(String str, char separatorChar) { return splitWorker(str, separatorChar, false); } /** *
     * StringUtils.split(null, *)         = null
     * StringUtils.split("", *)           = []
     * StringUtils.split("abc def", null) = ["abc", "def"]
     * StringUtils.split("abc def", " ")  = ["abc", "def"]
     * StringUtils.split("abc  def", " ") = ["abc", "def"]
     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
     * 
*/ public static String[] split(String str, String separatorChars) { return splitWorker(str, separatorChars, -1, false); } public static String[] split(String str, String separatorChars, int max) { return splitWorker(str, separatorChars, max, false); } /** * 将目标字符串以指定字符分隔后,并每个分隔的元素去除首尾空格 * * @param str 被处理字符串 * @param separatorChars 分隔字符 * @return */ public static String[] splitAndTrim(String str, String separatorChars) { List list = new ArrayList(); String[] strArray = splitWorker(str, separatorChars, -1, false); if(null != strArray && strArray.length > 0) { for (String e : strArray) { if(null == e) continue; list.add(e.trim()); } } return list.toArray(new String[0]); } /** * 以分隔符号第一次出现的地方,将字符串分隔为两部分 * * @param str 将被分隔的字符串 * @param sep 分隔符号 * @return 长度为2的字符串数组 */ public static String[] splitByFirstSeparator(String str, String sep) { String[] result = new String[2]; result[0] = substringBefore(str, sep); result[1] = substringAfter(str, sep); return result; } public static String substringBefore(String str, String separator) { if (isEmpty(str) || separator == null) { return str; } if (separator.length() == 0) { return EMPTY_STRING; } int pos = str.indexOf(separator); if (pos == -1) { return str; } return str.substring(0, pos); } public static String substringAfter(String str, String separator) { if (isEmpty(str)) { return str; } if (separator == null) { return EMPTY_STRING; } int pos = str.indexOf(separator); if (pos == -1) { return EMPTY_STRING; } return str.substring(pos + separator.length()); } public static String[] substringsBetween(String str, String open, String close) { if (str == null || isEmpty(open) || isEmpty(close)) { return null; } int strLen = str.length(); if (strLen == 0) { return new String[] {}; } int closeLen = close.length(); int openLen = open.length(); List list = new ArrayList(); int pos = 0; while (pos < (strLen - closeLen)) { int start = str.indexOf(open, pos); if (start < 0) { break; } start += openLen; int end = str.indexOf(close, start); if (end < 0) { break; } list.add(str.substring(start, end)); pos = end + closeLen; } if (list.isEmpty()) { return null; } return (String[]) list.toArray(new String [list.size()]); } public static boolean startsWithIgnoreCase(String str, String prefix) { if (str == null || prefix == null) { return false; } if (str.startsWith(prefix)) { return true; } if (str.length() < prefix.length()) { return false; } String lcStr = str.substring(0, prefix.length()).toLowerCase(); String lcPrefix = prefix.toLowerCase(); return lcStr.equals(lcPrefix); } public static boolean endsWithIgnoreCase(String str, String suffix) { if (str == null || suffix == null) { return false; } if (str.endsWith(suffix)) { return true; } if (str.length() < suffix.length()) { return false; } String lcStr = str.substring(str.length() - suffix.length()).toLowerCase(); String lcSuffix = suffix.toLowerCase(); return lcStr.equals(lcSuffix); } public static String getFormat(java.util.Date date, String parseFormat) { if (null == date) { return null; } if (null == parseFormat || "".equalsIgnoreCase(parseFormat)) { return date.toString(); } return new SimpleDateFormat(parseFormat).format(date); } public static void closeQuietly(final Closeable closeable) { try { if (closeable != null) { closeable.close(); } } catch (final IOException ioe) { // ignore } } public static void closeQuietly(final Closeable... closeables) { if (closeables == null) { return; } for (final Closeable closeable : closeables) { closeQuietly(closeable); } } public static Charset toCharset(final String charset) { return charset == null ? Charset.defaultCharset() : Charset.forName(charset); } public static String concat(Object... array) { if(null == array || 0 >= array.length) { return ""; } StringBuilder sbf = new StringBuilder(); for (Object o : array) { sbf.append(null == o ? "" : o.toString()); } return sbf.toString(); } public static String getHostName() { try { InetAddress inetAddr = InetAddress.getLocalHost(); String hostname = inetAddr.getHostName(); // 取主机名 if (isNotBlank(hostname) && !Objects.equals("localhost", hostname)) { return hostname; } return inetAddr.getCanonicalHostName(); } catch (UnknownHostException e) { System.err.println("Get serverName error:" + e.getMessage()); } return "unknow-host"; } public static String getSystemProperty(String key, String valIfNull) { String val = getSystemProperty(key); return val == null ? valIfNull : val; } public static String getSystemProperty(String property) { try { return System.getProperty(property); } catch (SecurityException ex) { // we are not allowed to look at this property System.err.println("Caught a SecurityException reading the system property '" + property + "'; the SystemUtils property value will default to null."); return null; } } /** * 必须为true */ public static void requireTrue(Boolean flag, String message) { if (null == flag || !flag) { throw new BizException(message); } } public static void requireEquals(Object a, Object b, String message) { requireTrue((a == b) || (a != null && a.equals(b)), message); } public static T requireNotNull(T obj, String message) { if (null == obj) { throw new BizException(message); } return obj; } /** * 字符串必须非空 */ public static String requireNotEmpty(String str, String message) { if(null == str || 0 >= str.trim().length()) { throw new BizException(message); } return str; } public static String readAsString(File file, String charset) throws IOException { return readAsString(new FileInputStream(file), charset); } public static String readAsString(InputStream input, String charset) throws IOException { String encoding = "UTF-8"; if (null != charset && charset.length() != 0) { encoding = charset; } BufferedReader r = new BufferedReader(new InputStreamReader(input, encoding)); StringBuffer b = new StringBuffer(); while (true) { int ch = r.read(); if (ch == -1) break; b.append((char) ch); } r.close(); return b.toString(); } public static File[] listTree(File directory, FileFilter fileFilter) { if (!(directory.exists() && directory.isDirectory())) { throw new BizException("The parameter [directory=" + directory.getAbsolutePath() + "] must be a directory file."); } List list = new ArrayList(); _listTree(list, directory, fileFilter); return (File[]) list.toArray(new File[0]); } static void _listTree(List list, File directory, FileFilter fileFilter) { File[] rootFilterdFiles = directory.listFiles(fileFilter); list.addAll(Arrays.asList(rootFilterdFiles)); File[] rootFiles = directory.listFiles(); for (int i = 0; i < rootFiles.length; i++) { File file = rootFiles[i]; if (file.isDirectory()) { _listTree(list, file, fileFilter); } } } private static String[] splitWorker(String str, char separatorChar, boolean preserveAllTokens) { // Performance tuned for 2.0 (JDK1.4) if (str == null) { return null; } int len = str.length(); if (len == 0) { return new String[0]; } List list = new ArrayList(); int i = 0, start = 0; boolean match = false; boolean lastMatch = false; while (i < len) { if (str.charAt(i) == separatorChar) { if (match || preserveAllTokens) { list.add(str.substring(start, i)); match = false; lastMatch = true; } start = ++i; continue; } lastMatch = false; match = true; i++; } if (match || (preserveAllTokens && lastMatch)) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } private static String[] splitWorker(String str, String separatorChars, int max, boolean preserveAllTokens) { // Performance tuned for 2.0 (JDK1.4) // Direct code is quicker than StringTokenizer. // Also, StringTokenizer uses isSpace() not isWhitespace() if (str == null) { return null; } int len = str.length(); if (len == 0) { return new String[0]; } List list = new ArrayList(); int sizePlus1 = 1; int i = 0, start = 0; boolean match = false; boolean lastMatch = false; if (separatorChars == null) { // Null separator means use whitespace while (i < len) { if (Character.isWhitespace(str.charAt(i))) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else if (separatorChars.length() == 1) { // Optimise 1 character case char sep = separatorChars.charAt(0); while (i < len) { if (str.charAt(i) == sep) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } else { // standard case while (i < len) { if (separatorChars.indexOf(str.charAt(i)) >= 0) { if (match || preserveAllTokens) { lastMatch = true; if (sizePlus1++ == max) { i = len; lastMatch = false; } list.add(str.substring(start, i)); match = false; } start = ++i; continue; } lastMatch = false; match = true; i++; } } if (match || (preserveAllTokens && lastMatch)) { list.add(str.substring(start, i)); } return (String[]) list.toArray(new String[list.size()]); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy