一般的なツールクラス

16064 ワード

package com.yzs.plat.process.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *   
 */
@Slf4j
public class oConvertUtils {
	public static boolean isEmpty(Object object) {
		if (object == null) {
			return (true);
		}
		if ("".equals(object)) {
			return (true);
		}
		if ("null".equals(object)) {
			return (true);
		}
		return (false);
	}
	
	public static boolean isNotEmpty(Object object) {
		if (object != null && !object.equals("") && !object.equals("null")) {
			return (true);
		}
		return (false);
	}

	public static String decode(String strIn, String sourceCode, String targetCode) {
		String temp = code2code(strIn, sourceCode, targetCode);
		return temp;
	}

	public static String StrToUTF(String strIn, String sourceCode, String targetCode) {
		strIn = "";
		try {
			strIn = new String(strIn.getBytes("ISO-8859-1"), "GBK");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strIn;

	}

	private static String code2code(String strIn, String sourceCode, String targetCode) {
		String strOut = null;
		if (strIn == null || (strIn.trim()).equals("")) {
			return strIn;
		}
		try {
			byte[] b = strIn.getBytes(sourceCode);
			for (int i = 0; i < b.length; i++) {
				System.out.print(b[i] + "  ");
			}
			strOut = new String(b, targetCode);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		return strOut;
	}

	public static int getInt(String s, int defval) {
		if (s == null || s == "") {
			return (defval);
		}
		try {
			return (Integer.parseInt(s));
		} catch (NumberFormatException e) {
			return (defval);
		}
	}

	public static int getInt(String s) {
		if (s == null || s == "") {
			return 0;
		}
		try {
			return (Integer.parseInt(s));
		} catch (NumberFormatException e) {
			return 0;
		}
	}

	public static int getInt(String s, Integer df) {
		if (s == null || s == "") {
			return df;
		}
		try {
			return (Integer.parseInt(s));
		} catch (NumberFormatException e) {
			return 0;
		}
	}

	public static Integer[] getInts(String[] s) {
		Integer[] integer = new Integer[s.length];
		if (s == null) {
			return null;
		}
		for (int i = 0; i < s.length; i++) {
			integer[i] = Integer.parseInt(s[i]);
		}
		return integer;

	}

	public static double getDouble(String s, double defval) {
		if (s == null || s == "") {
			return (defval);
		}
		try {
			return (Double.parseDouble(s));
		} catch (NumberFormatException e) {
			return (defval);
		}
	}

	public static double getDou(Double s, double defval) {
		if (s == null) {
			return (defval);
		}
		return s;
	}

	/*public static Short getShort(String s) {
		if (StringUtil.isNotEmpty(s)) {
			return (Short.parseShort(s));
		} else {
			return null;
		}
	}*/

	public static int getInt(Object object, int defval) {
		if (isEmpty(object)) {
			return (defval);
		}
		try {
			return (Integer.parseInt(object.toString()));
		} catch (NumberFormatException e) {
			return (defval);
		}
	}
	
	public static Integer getInt(Object object) {
		if (isEmpty(object)) {
			return null;
		}
		try {
			return (Integer.parseInt(object.toString()));
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public static int getInt(BigDecimal s, int defval) {
		if (s == null) {
			return (defval);
		}
		return s.intValue();
	}

	public static Integer[] getIntegerArry(String[] object) {
		int len = object.length;
		Integer[] result = new Integer[len];
		try {
			for (int i = 0; i < len; i++) {
				result[i] = new Integer(object[i].trim());
			}
			return result;
		} catch (NumberFormatException e) {
			return null;
		}
	}

	public static String getString(String s) {
		return (getString(s, ""));
	}

	/**
	 *    Unicode  
	 * @param s
	 * @return
	 */
	/*public static String escapeJava(Object s) {
		return StringEscapeUtils.escapeJava(getString(s));
	}*/
	
	public static String getString(Object object) {
		if (isEmpty(object)) {
			return "";
		}
		return (object.toString().trim());
	}

	public static String getString(int i) {
		return (String.valueOf(i));
	}

	public static String getString(float i) {
		return (String.valueOf(i));
	}

	public static String getString(String s, String defval) {
		if (isEmpty(s)) {
			return (defval);
		}
		return (s.trim());
	}

	public static String getString(Object s, String defval) {
		if (isEmpty(s)) {
			return (defval);
		}
		return (s.toString().trim());
	}

	public static long stringToLong(String str) {
		Long test = new Long(0);
		try {
			test = Long.valueOf(str);
		} catch (Exception e) {
		}
		return test.longValue();
	}

	/**
	 *     IP
	 */
	public static String getIp() {
		String ip = null;
		try {
			InetAddress address = InetAddress.getLocalHost();
			ip = address.getHostAddress();

		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		return ip;
	}

	/**
	 *               。
	 * 
	 * @param clazz
	 *                 。
	 * @return true          。
	 */
	private static boolean isBaseDataType(Class clazz) throws Exception {
		return (clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Byte.class) || clazz.equals(Long.class) || clazz.equals(Double.class) || clazz.equals(Float.class) || clazz.equals(Character.class) || clazz.equals(Short.class) || clazz.equals(BigDecimal.class) || clazz.equals(BigInteger.class) || clazz.equals(Boolean.class) || clazz.equals(Date.class) || clazz.isPrimitive());
	}

	/**
	 * @param request
	 *            IP
	 * @return IP Address
	 */
	public static String getIpAddrByRequest(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * @return   IP
	 * @throws SocketException
	 */
	public static String getRealIp() throws SocketException {
		String localip = null;//   IP,        IP    
		String netip = null;//   IP

		Enumeration netInterfaces = NetworkInterface.getNetworkInterfaces();
		InetAddress ip = null;
		boolean finded = false;//       IP
		while (netInterfaces.hasMoreElements() && !finded) {
			NetworkInterface ni = netInterfaces.nextElement();
			Enumeration address = ni.getInetAddresses();
			while (address.hasMoreElements()) {
				ip = address.nextElement();
				if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {//   IP
					netip = ip.getHostAddress();
					finded = true;
					break;
				} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {//   IP
					localip = ip.getHostAddress();
				}
			}
		}

		if (netip != null && !"".equals(netip)) {
			return netip;
		} else {
			return localip;
		}
	}

	/**
	 * java         、  、   、   
	 * 
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
		String dest = "";
		if (str != null) {
			Pattern p = Pattern.compile("\\s*|\t|\r|
"); Matcher m = p.matcher(str); dest = m.replaceAll(""); } return dest; } /** * * * @param substring * @param source * @return */ public static boolean isIn(String substring, String[] source) { if (source == null || source.length == 0) { return false; } for (int i = 0; i < source.length; i++) { String aSource = source[i]; if (aSource.equals(substring)) { return true; } } return false; } /** * Map */ public static Map getHashMap() { return new HashMap(); } /** * SET MAP * * @param str * @return */ public static Map SetToMap(Set setobj) { Map map = getHashMap(); for (Iterator iterator = setobj.iterator(); iterator.hasNext();) { Map.Entry entry = (Map.Entry) iterator.next(); map.put(entry.getKey().toString(), entry.getValue() == null ? "" : entry.getValue().toString().trim()); } return map; } public static boolean isInnerIP(String ipAddress) { boolean isInnerIp = false; long ipNum = getIpNum(ipAddress); /** * IP:A 10.0.0.0-10.255.255.255 B 172.16.0.0-172.31.255.255 C 192.168.0.0-192.168.255.255 , 127 **/ long aBegin = getIpNum("10.0.0.0"); long aEnd = getIpNum("10.255.255.255"); long bBegin = getIpNum("172.16.0.0"); long bEnd = getIpNum("172.31.255.255"); long cBegin = getIpNum("192.168.0.0"); long cEnd = getIpNum("192.168.255.255"); isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd) || ipAddress.equals("127.0.0.1"); return isInnerIp; } private static long getIpNum(String ipAddress) { String[] ip = ipAddress.split("\\."); long a = Integer.parseInt(ip[0]); long b = Integer.parseInt(ip[1]); long c = Integer.parseInt(ip[2]); long d = Integer.parseInt(ip[3]); long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d; return ipNum; } private static boolean isInner(long userIp, long begin, long end) { return (userIp >= begin) && (userIp <= end); } /** * 。 * , 。 * :hello_world->helloWorld * * @param name * * @return */ public static String camelName(String name) { StringBuilder result = new StringBuilder(); // if (name == null || name.isEmpty()) { // return ""; } else if (!name.contains("_")) { // , //update-begin--Author:zhoujf Date:20180503 for:TASK #2500 【 】 //update-begin--Author:zhoujf Date:20180503 for:TASK #2500 【 】 return name.substring(0, 1).toLowerCase() + name.substring(1).toLowerCase(); //update-end--Author:zhoujf Date:20180503 for:TASK #2500 【 】 } // String camels[] = name.split("_"); for (String camel : camels) { // 、 if (camel.isEmpty()) { continue; } // if (result.length() == 0) { // , result.append(camel.toLowerCase()); } else { // , result.append(camel.substring(0, 1).toUpperCase()); result.append(camel.substring(1).toLowerCase()); } } return result.toString(); } /** * 。 * , 。 * :hello_world,test_id->helloWorld,testId * * @param name * * @return */ public static String camelNames(String names) { if(names==null||names.equals("")){ return null; } StringBuffer sf = new StringBuffer(); String[] fs = names.split(","); for (String field : fs) { field = camelName(field); sf.append(field + ","); } String result = sf.toString(); return result.substring(0, result.length() - 1); } //update-begin--Author:zhoujf Date:20180503 for:TASK #2500 【 】 /** * 。( ) * , 。 * :hello_world->HelloWorld * * @param name * * @return */ public static String camelNameCapFirst(String name) { StringBuilder result = new StringBuilder(); // if (name == null || name.isEmpty()) { // return ""; } else if (!name.contains("_")) { // , return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase(); } // String camels[] = name.split("_"); for (String camel : camels) { // 、 if (camel.isEmpty()) { continue; } // , result.append(camel.substring(0, 1).toUpperCase()); result.append(camel.substring(1).toLowerCase()); } return result.toString(); } //update-end--Author:zhoujf Date:20180503 for:TASK #2500 【 】 /** * * @param para * @return */ public static String camelToUnderline(String para){ if(para.length()<3){ return para.toLowerCase(); } StringBuilder sb=new StringBuilder(para); int temp=0;// // for(int i=2;i clazz = object.getClass(); List fieldList = new ArrayList<>(); while (clazz != null) { fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields()))); clazz = clazz.getSuperclass(); } Field[] fields = new Field[fieldList.size()]; fieldList.toArray(fields); return fields; } /** * map key * @param list * @return */ public static List> toLowerCasePageList(List> list){ List> select = new ArrayList<>(); for (Map row : list) { Map resultMap = new HashMap<>(); Set keySet = row.keySet(); for (String key : keySet) { String newKey = key.toLowerCase(); resultMap.put(newKey, row.get(key)); } select.add(resultMap); } return select; } /** * entityList modelList * @param fromList * @param tClass * @param * @param * @return */ public static List entityListToModelList(List fromList, Class tClass){ if(fromList.isEmpty() || fromList == null){ return null; } List tList = new ArrayList<>(); for(F f : fromList){ T t = entityToModel(f, tClass); tList.add(t); } return tList; } public static T entityToModel(F entity, Class modelClass) { log.debug("entityToModel : Entity Model"); Object model = null; if (entity == null || modelClass ==null) { return null; } try { model = modelClass.newInstance(); } catch (InstantiationException e) { log.error("entityToModel : ", e); } catch (IllegalAccessException e) { log.error("entityToModel : ", e); } BeanUtils.copyProperties(entity, model); return (T)model; } /** * list * * @param list * @return true or false * list == null : true * list.size() == 0 : true */ public static boolean listIsEmpty(Collection list) { return (list == null || list.size() == 0); } /** * list * * @param list * @return true or false * list == null : false * list.size() == 0 : false */ public static boolean listIsNotEmpty(Collection list) { return !listIsEmpty(list); } }