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

com.mycomm.itool.SystemUtil Maven / Gradle / Ivy

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycomm.itool;

import com.mycomm.itool.logs.TheLogger;
import com.mycomm.itool.utils.LineReader;
import com.mycomm.itool.utils.IBase64;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
//import javax.xml.bind.DatatypeConverter;

/**
 *
 * @author jw362j
 */
public class SystemUtil {

    public interface MyLogApi {

        void Log(String lgMsg);
    }

    private static final String default_charSet = "UTF-8";
    private static TheLogger logger;

    public static void setLogger(TheLogger log) {        
        logger = log;
    }

    

    public static InputStream getInputStream(String msg) {
//        logger.info("the delivery msg is:" + msg);
        if ("".equals(msg) || msg == null) {
            return null;
        }
        InputStream inputStream = null;
        try {
            inputStream = new ByteArrayInputStream(msg.getBytes(default_charSet));
        } catch (UnsupportedEncodingException e) {
            recordLog(e.getMessage());
        }
        return inputStream;
    }

    public static boolean isEmailFormat(String email) {
        if ("".equals(email) || email == null) {
            return false;
        }
        String reg = "^\\w+([-.]\\w+)*@\\w+([-]\\w+)*\\.(\\w+([-]\\w+)*\\.)*[a-z]{2,3}$";
        Pattern pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }

    public static String getMD5(byte[] source) {
        String sour = new String(source);
//        log.info("the input parameter for md5 is:"+sour);
        String s = null;
        char hexDigits[] = { // 用来将字节转换成 16 进制表示的字符
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
            md.update(source);
            byte tmp[] = md.digest();          // MD5 的计算结果是一个 128 位的长整数,
            // 用字节表示就是 16 个字节
            char str[] = new char[16 * 2];   // 每个字节用 16 进制表示的话,使用两个字符,
            // 所以表示成 16 进制需要 32 个字符
            int k = 0;                                // 表示转换结果中对应的字符位置
            for (int i = 0; i < 16; i++) {          // 从第一个字节开始,对 MD5 的每一个字节
                // 转换成 16 进制字符的转换
                byte byte0 = tmp[i];                 // 取第 i 个字节
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];  // 取字节中高 4 位的数字转换,
                // >>> 为逻辑右移,将符号位一起右移
                str[k++] = hexDigits[byte0 & 0xf];            // 取字节中低 4 位的数字转换
            }
            s = new String(str);                                 // 换后的结果转换为字符串

        } catch (Exception e) {
            recordLog(e.getMessage());
        }
//        logger.info("the md5 string value for '" + sour + "' is:" + s);
        return s;
    }

    public static boolean isPasswordValid(String password) {
        boolean result = true;
        if ("".equals(password) || password == null) {
            return false;
        }
        if (password.length() < 6) {
            return false;
        }
        if (password.startsWith("asd")) {
            result = false;
        }

        return result;
    }

    public static String getMACAddress(String ip) {
        String str;
        String macAddress = "";
        try {
            Process p = Runtime.getRuntime().exec("nbtstat -A " + ip);
            InputStreamReader ir = new InputStreamReader(p.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (int i = 1; i < 100; i++) {
                str = input.readLine();
                if (str != null) {
                    if (str.indexOf("MAC Address") > 1) {
                        macAddress = str.substring(
                                str.indexOf("MAC Address") + 14, str.length());
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return macAddress;
    }

    public static void WriteIntoFile(String fileFullPath, String content) {
        WriteIntoFile(fileFullPath, content, null);
    }

    @SuppressWarnings({"UnusedAssignment"})
    public static void WriteIntoFile(String fileFullPath, String content, String charSet) {
        charSet = (charSet == null || "".equals(charSet)) ? default_charSet : charSet;
        if ("".equals(fileFullPath) || "".equals(content) || content == null || fileFullPath == null) {
            recordLog("File content or file path is null,give up!");
            return;
        }
        //write into the file
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        try {
            fos = new FileOutputStream(fileFullPath);
            osw = new OutputStreamWriter(fos, charSet);
            osw.write(content);
            osw.flush();
        } catch (Exception e) {
            recordLog(e.getMessage());
        } finally {
            try {
                if(osw != null )osw.close();
                if(fos != null )fos.close();
            } catch (IOException e) {
                recordLog(e.getMessage());
            }
        }
        recordLog("File update seccussfully!");
    }

    public static void WriteIntoFile(String fileFullPath, byte[] content) {
        WriteIntoFile(fileFullPath, content, null);
    }

    @SuppressWarnings({"UnusedAssignment"})
    public static void WriteIntoFile(String fileFullPath, byte[] content, String charSet) {
        charSet = (charSet == null || "".equals(charSet)) ? default_charSet : charSet;
        if ("".equals(fileFullPath) || content == null || fileFullPath == null) {
            recordLog("File content or file path is null,give up!");
            return;
        }
        //write into the file
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(fileFullPath);

            fos.write(content);
            fos.flush();
        } catch (Exception e) {
            recordLog(e.getMessage());
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                recordLog(e.getMessage());
            }
        }
        recordLog("File update seccussfully!");
    }

    public static String ReadFile(String fileFullPath, String charSet, String[] allowed_file_postfix_list) {
        String extentsion = getExtensionName(fileFullPath);
        extentsion = extentsion.toLowerCase();
        if (!isContainItem(extentsion, allowed_file_postfix_list)) {
            return "bad file extention type!";
        }
        return ReadFromFile(fileFullPath, charSet);
    }

    public static String ReadFromFile(String fileFullPath) {
        return ReadFromFile(fileFullPath, null);
    }

    public static String ReadFromFile(String fileFullPath, String charSet) {
        charSet = (charSet == null || "".equals(charSet)) ? default_charSet : charSet;
        StringBuilder sb = new StringBuilder();
        if ("".equals(fileFullPath) || fileFullPath == null) {
            sb.append("文件不存在:").append(fileFullPath);
            return sb.toString();
        }

        File file = new File(fileFullPath);
        if (!file.exists()) {
            sb.append("文件不存在:").append(fileFullPath);
            return sb.toString();
        }
        Reader reader = null;
        try {
            // 一次读一个字符
            reader = new InputStreamReader(new FileInputStream(fileFullPath), charSet);
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                sb.append((char) tempchar);
            }
            reader.close();
        } catch (Exception e) {
            sb.append("file error:").append(e.getMessage());
        }
        if ("".equals(sb.toString())) {
            return "file content is empty!";
        }

        return sb.toString();
    }

    public static boolean isContainItem(String filename, String[] items) {
        boolean result = false;
        if (items == null || items.length < 1) {
            return result;
        }
        for (String name : items) {
            if (name.equals(filename)) {
                result = true;
                break;
            }
        }
        return result;
    }

    public static String[] StringArrayMerge(String[] strArray1, String[] strArray2) {
        String[] targetArray = null;
        if (strArray1 == null && strArray2 == null) {
            return targetArray;
        }
        if (strArray1 != null || strArray2 != null) {
            int targetLength = (strArray1 == null ? 0 : strArray1.length) + (strArray2 == null ? 0 : strArray2.length);
            if (targetLength == 0) {
                return targetArray;
            }
            targetArray = new String[targetLength];
            int index = 0;

            if (strArray1 != null && strArray1.length > 0) {
                for (String tem_a1 : strArray1) {
                    targetArray[index] = tem_a1;
                    index++;
                }
            }
            if (strArray2 != null && strArray2.length > 0) {
                for (String tem_a2 : strArray2) {
                    targetArray[index] = tem_a2;
                    index++;
                }
            }
        }
        return targetArray;
    }

    /* 
     * Java文件操作 获取文件扩展名 
     * 
     *  Created on: 2011-8-2 
     *      Author: blueeagle 
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /* 
     * Java文件操作 获取不带扩展名的文件名 
     * 
     *  Created on: 2011-8-2 
     *      Author: blueeagle 
     */
    public static String getFileNameNoPostFix(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static String getQueryStringItem(String qstring, String keyItem) {
        String result = null;
        if ("".equals(qstring) || qstring == null || "".equals(keyItem) || keyItem == null) {
            return result;
        }
        String[] qs = qstring.split("&");
        if (qs == null || qs.length < 1) {
            return result;
        }
        for (String s : qs) {
            String[] s_ = s.split("=");
            if (s_ != null && s_.length == 2) {
                if (keyItem.equals(s_[0])) {
                    result = s_[1];
                    break;
                }
            }
        }
        return result;

    }

    public static Map urlStringToMap(String urlString) {
        if (urlString == null || "".equals(urlString)) {
            return null;
        }
        if (!urlString.contains("=")) {
            return null;
        }
        
        if (urlString.contains("#")) {
             if (!urlString.contains("?")){
                 urlString = urlString.substring(urlString.indexOf("#") + 1);
             }
        }
        
        if (urlString.contains("?")) {
            urlString = urlString.substring(urlString.indexOf("?") + 1);
        }
        
        
        Map parameters = null;
        if (!urlString.contains("&")) {
            //only one key-value pair
            String kvs[] = urlString.split("=");
            if (kvs.length == 2) {
                parameters = new HashMap();
                parameters.put(kvs[0], kvs[1]);
            }
            return parameters;
        }

        String[] pairs = urlString.split("&");
        if (pairs == null || pairs.length == 0) {
            return null;
        }
        parameters = new HashMap();
        for (String items : pairs) {
            if (items == null || "".equals(items)) {
                continue;
            }
            String kv_temp[] = items.split("=");
            if (kv_temp == null || kv_temp.length != 2) {
                continue;
            }
            String k_tmp = kv_temp[0];
            String v_tmp = kv_temp[1];
            try {
                k_tmp = URLDecoder.decode(k_tmp, default_charSet);
                v_tmp = URLDecoder.decode(v_tmp, default_charSet);
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(SystemUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
            parameters.put(k_tmp, v_tmp);
        }

        return parameters;
    }

    public static String mapToUrlString(Map parameters) {
        if (parameters == null || parameters.isEmpty()) {
            return null;
        }
        Set keys = parameters.keySet();
        StringBuilder sb = new StringBuilder();
        for (String key : keys) {
            if (key == null || "".equals(key)) {
                continue;
            }

            String value = parameters.get(key);
            if (value == null || "".equals(value)) {
                continue;
            }
            try {
                key = URLEncoder.encode(key, default_charSet);
                value = URLEncoder.encode(value, default_charSet);
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(SystemUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
            sb.append(key).append("=").append(value).append("&");
        }
        sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }

    public static boolean isNumberString(String target) {
        boolean result = false;
        if ("".equals(target) || target == null) {
            return result;
        }
        return Pattern.compile("[0-9]*").matcher(target).matches();
    }

    public static boolean isNumber(String[] nums) {
        boolean result = true;
        if (nums == null || nums.length == 0) {
            return false;
        }
        for (String item : nums) {
            if (item != null && !"".equals(item)) {
                if (!SystemUtil.isNumberString(item)) {
                    result = false;
                    break;
                }
            }
        }
        return result;
    }

    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                    + Character.digit(s.charAt(i + 1), 16));
        }
        return data;
    }

    public static String byteArraytoHex(byte[] buf) {
        StringBuilder strbuf = new StringBuilder(buf.length * 2);
        int i;
        for (i = 0; i < buf.length; i++) {
            if (((int) buf[i] & 0xff) < 0x10) {
                strbuf.append("0");
            }
            strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
        }
        return strbuf.toString();
    }

    /**
     *
     * String hexStr = "01DFAF09CC6F39281C81332A1E1FD25F"; byte[] b =
     * SystemUhexStringToByteArray(hexStr); log.debug("the length of byte is:" +
     * b.length); for (byte x : b) { int p = new Byte(x).intValue(); p = p<0 ?
     * p+256: p; log.debug("" + p); } @param input @param logTag
     *
     * @param input
     * @param logTag
     */
    public static void printByteArrayToUchar(byte[] input, String logTag) {
        logTag = logTag == null || "".equals(logTag) ? "SystemUtilLog" : logTag;
        if (input == null || input.length <= 0) {
            recordLog(logTag + ":input bytes are null in printByteArrayToUchar!");
            return;
        }
        for (byte x : input) {
            int p = new Byte(x).intValue();
            p = p < 0 ? p + 256 : p;
            recordLog(logTag + ":" + p);
        }
    }

    public static Set> getClasses(String pack) {

        try {
            // 第一个class类的集合
            Set> classes = new LinkedHashSet>();
            // 是否循环迭代
            boolean recursive = true;
            // 获取包的名字 并进行替换
            String packageName = pack;
            String packageDirName = packageName.replace('.', '/');
            // 定义一个枚举的集合 并进行循环来处理这个目录下的things
            Enumeration dirs;

            dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
            // 循环迭代下去
            while (dirs.hasMoreElements()) {
                // 获取下一个元素
                URL url = dirs.nextElement();
                // 得到协议的名称
                String protocol = url.getProtocol();
                // 如果是以文件的形式保存在服务器上
                if ("file".equals(protocol)) {
                    System.err.println("file类型的扫描");
                    // 获取包的物理路径
                    String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
                    // 以文件的方式扫描整个包下的文件 并添加到集合中
                    findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
                }
            }

            return classes;
        } catch (IOException ex) {
            recordLog(ex.getMessage());
            return null;
        }
    }

    /**
     * 以文件的形式来获取包下的所有Class
     *
     * @param packageName
     * @param packagePath
     * @param recursive
     * @param classes
     */
    private static void findAndAddClassesInPackageByFile(String packageName,
            String packagePath, final boolean recursive, Set> classes) {
        // 获取此包的目录 建立一个File
        File dir = new File(packagePath);
        // 如果不存在或者 也不是目录就直接返回
        if (!dir.exists() || !dir.isDirectory()) {
            // log.warn("用户定义包名 " + packageName + " 下没有任何文件");
            return;
        }
        // 如果存在 就获取包下的所有文件 包括目录
        File[] dirfiles = dir.listFiles(new FileFilter() {
            // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
            @Override
            public boolean accept(File file) {
                return (recursive && file.isDirectory())
                        || (file.getName().endsWith(".class"));
            }
        });
        // 循环所有文件
        for (File file : dirfiles) {
            // 如果是目录 则继续扫描
            if (file.isDirectory()) {
                findAndAddClassesInPackageByFile(packageName + "."
                        + file.getName(), file.getAbsolutePath(), recursive,
                        classes);
            } else {
                // 如果是java类文件 去掉后面的.class 只留下类名
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    // 添加到集合中去
                    //classes.add(Class.forName(packageName + '.' + className));
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
                } catch (ClassNotFoundException e) {
                    // log.error("添加用户自定义视图类错误 找不到此类的.class文件");
                    recordLog(e.getMessage());
                }
            }
        }
    }

    /*
     * 中文转unicode编码
     */
    public static String cn2Unicode(final String gbString) {
        char[] utfBytes = gbString.toCharArray();
        String unicodeBytes = "";
        for (int i = 0; i < utfBytes.length; i++) {
            String hexB = Integer.toHexString(utfBytes[i]);
            if (hexB.length() <= 2) {
                hexB = "00" + hexB;
            }
            unicodeBytes = unicodeBytes + "\\u" + hexB;
        }
        return unicodeBytes;
    }

    /*
     * unicode编码转中文
    unicode编码必须为6位长度 如果不足则在前面补0 ,如4E03 补为004E03
     */
    public static String Unicode2cn(final String dataStr) {

        int start = 0;
        int end = 0;
        final StringBuffer buffer = new StringBuffer();
        while (start > -1) {
            end = dataStr.indexOf("\\u", start + 2);
            String charStr = "";
            if (end == -1) {
                charStr = dataStr.substring(start + 2, dataStr.length());
            } else {
                charStr = dataStr.substring(start + 2, end);
            }
            char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
            buffer.append(new Character(letter).toString());
            start = end;
        }
        return buffer.toString();
    }

    private static boolean isChineseCharacter(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION) {
            return true;
        }
        return false;
    }

    public static String encodeToBase64(String value) {
        if (value == null || "".equals(value) || value.length() <= 0) {
            return null;
        }
        String result = null;
        try {
            result = new String(IBase64.encode(value));
        } catch (UnsupportedEncodingException ex) {
            recordLog(ex.getMessage());
        }
        return result;
    }

    public static String decodeFromBase64(String value) {
        if (value == null || "".equals(value) || value.length() <= 0) {
            return null;
        }
        byte[] decodedValue = null;  
        try {
            decodedValue = IBase64.decode(value);
        } catch (UnsupportedEncodingException ex) {
            recordLog(ex.getMessage());
        }
        return new String(decodedValue, StandardCharsets.UTF_8);
    }

    public static String base64Decode(String value) {
        return decodeFromBase64(value);
    }

    public static String base64Encode(String value) {
        return encodeToBase64(value);
    }

    public static void readFileByEachLine(String filePath, LineReader lineReader) {
        if (filePath == null || "".equals(filePath) || lineReader == null) {
            recordLog("filePath is null or lineReader is null!");
            return;
        }
        File fAccount = new File(filePath);
        if (fAccount == null || !fAccount.exists()) {
            recordLog("filePath does not exists!");
            return;
        }
        BufferedReader br = null;
        try {
            Reader reader = new InputStreamReader(new FileInputStream(filePath), StandardCharsets.UTF_8);
            br = new BufferedReader(reader);

            String readLine = "";
            recordLog("Reading file using Buffered Reader");
            while ((readLine = br.readLine()) != null) {
                if (readLine == null || "".equals(readLine)) {
                    continue;
                }
                lineReader.OnRead(readLine);
            }
        } catch (IOException e) {
            recordLog("error:" + e.getMessage());
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (Throwable t) {
                    recordLog("error in initAccountList:" + t.getMessage());
                }
            }
        }
    }

    public enum InternetStatus {
        SUCCESS, FAILED
    }

    public interface MyInternetDetecter {
        void onInternetStatus(InternetStatus status);
    }    

    /* @author sichard
     * @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
     * @return
     */
    public static void ping(String web_host, MyInternetDetecter detecter, TheLogger logHelper) {

        String result = null;
        try {
            String ip = "www.google.com";// ping 的地址,可以换成任何一种可靠的外网 
            if (web_host != null) {
                ip = web_host;
            }
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次 
            // 读取ping的内容,可以不加 
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuilder stringBuffer = new StringBuilder();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content).append("\n");
            }
            if (logHelper != null) {
                logHelper.debug( "result content : " + stringBuffer.toString());
            }
            // ping的状态 
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                if (detecter != null) {
                    detecter.onInternetStatus(InternetStatus.SUCCESS);
                }
                return;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException:" + e.getMessage();
        } catch (InterruptedException e) {
            result = "InterruptedException:" + e.getMessage();
        } finally {
            if (logHelper != null) {
                logHelper.debug( "result = " + result);
            }
        }
        if (detecter != null) {
            detecter.onInternetStatus(InternetStatus.FAILED);
        }
    }

    public static boolean isTxtEmpty(String txt) {
        if ("".equals(txt) || txt == null) {
            return true;
        }
        return false;
    }

    private static void recordLog(String lgMsg) {
        if (logger == null) {
            return;
        }
        logger.debug(lgMsg);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy