Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
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.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Enumeration;
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 java.lang.reflect.Method;
import java.lang.reflect.Constructor;
import java.net.JarURLConnection;
import java.util.HashSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
*
* @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 {
osw.close();
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 isNumeric(String str) {
Pattern pattern = Pattern.compile("[0-9]*");
if (str.indexOf(".") > 0) {//判断是否有小数点
if (str.indexOf(".") == str.lastIndexOf(".") && str.split("\\.").length == 2) { //判断是否只有一个小数点
return pattern.matcher(str.replace(".", "")).matches();
} else {
return false;
}
} else {
return pattern.matcher(str).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();
}
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> getClassSet(String packageName) {
Set> classSet = new HashSet>();
try {
Enumeration urls = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".", "/"));
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (url != null) {
String protocol = url.getProtocol();
if (protocol.equals("file")) {
String packagePath = URLDecoder.decode(url.getFile(), "UTF-8");
addClass(classSet, packagePath, packageName);
} else if (protocol.equals("jar")) {
JarURLConnection jarURLConnection = (JarURLConnection) url.openConnection();
if (jarURLConnection != null) {
JarFile jarFile = jarURLConnection.getJarFile();
if (jarFile != null) {
Enumeration jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
String jarEntryName = jarEntry.getName();
if (jarEntryName.endsWith(".class")) {
String className = jarEntryName.substring(0, jarEntryName.lastIndexOf("."))
.replaceAll("/", ".");
try {
classSet.add(Class.forName(className, false, Thread.currentThread().getContextClassLoader()));
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
// UniversalLogHolder.e("加载类失败 loadClass->{}", ex.getMessage());
}
}
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
// UniversalLogHolder.e("查找包下的类失败{}", e.getMessage());
}
return classSet;
}
private static void addClass(Set> classSet, String packagePath, String packageName) {
File[] files = new File(packagePath).listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
return (file.isFile() && file.getName().endsWith(".class") || file.isDirectory());
}
});
for (File file : files) {
String fileName = file.getName();
if (file.isFile()) {
String className = fileName.substring(0, fileName.lastIndexOf("."));
if (!SystemUtil.isTxtEmpty(packageName)) {
className = packageName + "." + className;
// UniversalLogHolder.e("className: {}", className);
}
try {
classSet.add(Class.forName(className, false, Thread.currentThread().getContextClassLoader()));
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
// UniversalLogHolder.e("加载类失败 loadClass->{}", ex.getMessage());
}
} else {
String subPackagePath = fileName;
if (!SystemUtil.isTxtEmpty(packagePath)) {
subPackagePath = packagePath + "/" + subPackagePath;
}
String subPackageName = fileName;
if (!SystemUtil.isTxtEmpty(packageName)) {
subPackageName = packageName + "." + subPackageName;
}
addClass(classSet, subPackagePath, subPackageName);
}
}
}
/*
* 中文转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);
}
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);
}
public static boolean isAndroidEnvironment() {
try {
Class> cls = Class.forName("android.os.SystemProperties");
if (cls == null) {
return false;
}
Method methods[] = cls.getDeclaredMethods();
if (methods == null || methods.length < 1) {
return false;
}
for (Method method : methods) {
if (!"getInt".equals(method.getName())) {
continue;
}
Object intValue = method.invoke(cls, "ro.build.version.sdk", 0);
return intValue != null;
}
} catch (ClassNotFoundException e) {
return false;
} catch (IllegalArgumentException ex) {
return false;
} catch (IllegalAccessException e) {
return false;
} catch (InvocationTargetException ex) {
return false;
}
return false;
}
public static Set> loadAndroidClasses(Object context, String pkgName) {
if (isTxtEmpty(pkgName)) {
return null;
}
if (context == null) {
return null;
}
Object data = context;
Set> all_clses = null;
try {
Method method = Class.forName("android.content.Context").getMethod("getPackageCodePath");
if (method == null) {
return null;
}
Object pkgPath = method.invoke(data);
if (SystemUtil.isTxtEmpty(pkgPath + "")) {
return null;
}
//Log.d(getClass().getSimpleName(),"pkgPath--->"+pkgPath);
String dex = "dalvik.system.DexFile";
Class dex_clz = Class.forName(dex);
if (dex_clz == null) {
return null;
}
Constructor constructor = dex_clz.getConstructor(String.class);
if (constructor == null) {
return null;
}
Object dexFile = constructor.newInstance(pkgPath);
if (dexFile == null) {
return null;
}
Method method_entries = dex_clz.getMethod("entries");
if (method_entries == null) {
return null;
}
Object enumeration = method_entries.invoke(dexFile);
if (enumeration == null) {
return null;
}
//Log.d(getClass().getSimpleName(),"enumeration--->"+enumeration);
if (!(enumeration instanceof Enumeration)) {
return null;
}
Enumeration enumeration_clsses = (Enumeration) enumeration;
all_clses = new HashSet>();
while (enumeration_clsses.hasMoreElements()) {
String className = enumeration_clsses.nextElement() + "";
if (className.contains("$") || !className.startsWith(pkgName)) {
continue;
}
all_clses.add(Class.forName(className));
}
} catch (NoSuchMethodException e) {
return null;
} catch (ClassNotFoundException e) {
return null;
} catch (IllegalAccessException e) {
return null;
} catch (InvocationTargetException e) {
return null;
} catch (InstantiationException e) {
return null;
}
return all_clses;
}
}