Browse Source

工具类

wanfa99 3 years ago
parent
commit
54fc446a4a

+ 64 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/util/InterfaceConnUtils.java

@@ -0,0 +1,64 @@
+package org.jeecg.modules.system.util;
+
+import com.alibaba.fastjson.JSONArray;
+import com.alibaba.fastjson.JSONObject;
+import org.apache.commons.codec.binary.Base64;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.util.EntityUtils;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ *
+ * 接口工具类
+ * @author 隔壁老赵
+ *
+ */
+public class InterfaceConnUtils {
+
+    /**
+     * post请求-推数据
+     * @throws Exception
+     */
+    public static JSONObject doPost(JSONObject json, String url,String type) throws Exception {
+        //定义测试返回JSON
+        JSONObject onejb = new JSONObject();
+        HttpClient httpClient = new DefaultHttpClient();
+        HttpPost httpPost=new HttpPost(url);
+        httpPost.setHeader("Content-Type", "application/json");
+        String tokenCode = "sap:Cwa1QJrhfhtXbzSGZi94ydBPNQCPbmz7";
+        //使用base64进行加密
+        byte[] tokenByte = Base64.encodeBase64((tokenCode).getBytes());
+        //将加密的信息转换为string
+        String tokenStr = new String(tokenByte);
+        //Basic
+        String token = "Basic "+tokenStr;
+        //把认证信息发到header中
+        httpPost.setHeader("Authorization", "Basic "+token);
+
+        StringEntity entity;
+        entity = new StringEntity(json.toString(),"utf-8");
+        entity.setContentEncoding("utf-8");
+        entity.setContentType("application/json");
+        httpPost.setEntity(entity);
+        try {
+            //调用接口
+            HttpResponse response = httpClient.execute(httpPost);
+            //返回信息
+            String resultStr = EntityUtils.toString(response.getEntity());
+            onejb=JSONObject.parseObject(resultStr);
+
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+          return onejb;
+    }
+
+}

+ 40 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/util/JsonChangeUtils.java

@@ -0,0 +1,40 @@
+package org.jeecg.modules.system.util;
+
+import com.alibaba.fastjson.JSONObject;
+import org.springframework.stereotype.Component;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/***
+ * json转换类
+ * 赵万发
+ */
+public class JsonChangeUtils{
+
+    /**
+     * 数据库查询返回集合转换为json对象集合
+     * @param result
+     * @return
+     */
+    public static List<JSONObject> toListJson(List<Map<String, String>> result) {
+        List<JSONObject> pljf = new ArrayList<JSONObject>();// 表数据json集合
+        JSONObject jf = new JSONObject();
+        for (int i = 0; i < result.size(); i++) {
+            Map<String, String> map = result.get(i);
+            Set<String> keys = map.keySet();
+            jf = new JSONObject();
+            for (String key : keys) {
+                if(null==map.get(key)){
+                    jf.put(key, "");
+                }else{
+                    jf.put(key, map.get(key));
+                }
+            }
+            pljf.add(jf);
+        }
+        return pljf;
+    }
+}

+ 617 - 0
jeecg-boot-module-system/src/main/java/org/jeecg/modules/system/util/oConvertUtils.java

@@ -0,0 +1,617 @@
+package org.jeecg.modules.system.util;
+
+import org.apache.shiro.SecurityUtils;
+import org.jeecg.modules.system.entity.SysUser;
+
+import javax.servlet.http.HttpServletRequest;
+import java.io.UnsupportedEncodingException;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.*;
+import java.sql.Date;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * 
+ * @author  张代浩
+ *
+ */
+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) {
+		if (s == null) {
+			return null;
+		}
+		Integer[] integer = new Integer[s.length];
+		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;
+		}
+	}*/
+
+	/**
+	 * 获取当前用户
+	 * licc
+	 * @return
+	 */
+	public static SysUser getCurrentUser(){
+		return (SysUser) SecurityUtils.getSubject().getPrincipal();
+	}
+
+	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<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
+		InetAddress ip = null;
+		boolean finded = false;// 是否找到外网IP
+		while (netInterfaces.hasMoreElements() && !finded) {
+			NetworkInterface ni = netInterfaces.nextElement();
+			Enumeration<InetAddress> 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|\n");
+			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<Object, Object> getHashMap() {
+		return new HashMap<Object, Object>();
+	}
+
+	/**
+	 * SET转换MAP
+	 * 
+	 * @param str
+	 * @return
+	 */
+	public static Map<Object, Object> SetToMap(Set<Object> setobj) {
+		Map<Object, Object> map = getHashMap();
+		for (Iterator iterator = setobj.iterator(); iterator.hasNext();) {
+			Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) 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);
+	}
+	
+	/**
+	 * 将下划线大写方式命名的字符串转换为驼峰式。
+	 * 如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
+	 * 例如: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();
+	}
+	
+	/**
+	 * 将下划线大写方式命名的字符串转换为驼峰式。
+	 * 如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
+	 * 例如: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 【代码生成器】代码生成器开发一通用模板生成功能
+	/**
+	 * 将下划线大写方式命名的字符串转换为驼峰式。(首字母写)
+	 * 如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。</br>
+	 * 例如: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){
+        StringBuilder sb=new StringBuilder(para);
+        int temp=0;//定位
+        for(int i=0;i<para.length();i++){
+            if(Character.isUpperCase(para.charAt(i))){
+                sb.insert(i+temp, "_");
+                temp+=1;
+            }
+        }
+        return sb.toString().toLowerCase(); 
+	}
+
+	/**
+	 * 随机数
+	 * @param place 定义随机数的位数
+	 */
+	public static String randomGen(int place) {
+		String base = "qwertyuioplkjhgfdsazxcvbnmQAZWSXEDCRFVTGBYHNUJMIKLOP0123456789";
+		StringBuffer sb = new StringBuffer();
+		Random rd = new Random();
+		for(int i=0;i<place;i++) {
+			sb.append(base.charAt(rd.nextInt(base.length())));
+		}
+		return sb.toString();
+	}
+
+	//生成uuid
+	public static String id() {
+		String uuid = UUID.randomUUID().toString();
+		char[] ar = uuid.toCharArray();
+		StringBuilder sb = new StringBuilder();
+		for (int i = 0; i < ar.length; i++) {
+			if (ar[i] != '-') {
+				sb.append(ar[i]);
+			}
+		}
+		return sb.toString();
+	}
+
+	public static String UrlEncode(String text){
+		try {
+			text = URLEncoder.encode(text, "UTF-8");
+		}catch (Exception ex){
+			ex.printStackTrace();
+		}
+		return text;
+	}
+
+	// 数字转字符串前面补0
+	public static String getString(int num, int strLen){
+		String code = String.valueOf(num);
+		while (code.length() < strLen) {
+			code = "0" + code;
+		}
+		return code;
+
+	}
+    /**
+
+     * 字符串+1方法,该方法将其结尾的整数+1,适用于任何以整数结尾的字符串,不限格式,不限分隔符。
+     * @author 隔壁老赵
+     * @param testStr 要+1的字符串
+     * @return +1后的字符串
+     * @exception NumberFormatException
+     */
+    public static String addOne(String testStr) {
+        String[] strs = testStr.split("[^0-9]");//根据不是数字的字符拆分字符串
+        String numStr = strs[strs.length - 1];//取出最后一组数字
+        if (numStr != null && numStr.length() > 0) {//如果最后一组没有数字(也就是不以数字结尾),抛NumberFormatException异常
+            int n = numStr.length();//取出字符串的长度
+            BigDecimal num=new BigDecimal(numStr).add(new BigDecimal(1));//将该数字加一
+            String added = String.valueOf(num);
+            n = Math.min(n, added.length());
+            //拼接字符串
+            return testStr.subSequence(0, testStr.length() - n) + added;
+        } else {
+            throw new NumberFormatException();
+        }
+    }
+    public static String getId(){
+        //生成主键:12位时间+8位随机数字
+        StringBuffer b=new StringBuffer();
+        SimpleDateFormat sdf = new SimpleDateFormat();// 格式化时间
+        sdf.applyPattern("yyyyMMddHHmm");// a为am/pm的标记
+        b.append(sdf.format(new java.util.Date()));
+        Random random=new Random();
+        //随机生成数字,并添加到字符串
+        for(int i=0;i<8;i++){
+            b.append(random.nextInt(10));
+        }
+        return b.toString();
+    }
+}