From 8f080054ffa6d61aa66aceac4d3b7ae42e48551a Mon Sep 17 00:00:00 2001 From: 王彬 Date: Thu, 25 Jul 2019 15:45:20 +0800 Subject: [PATCH] first submit --- build.gradle | 38 ++++++++++++++++++++++++++------------ src/main/java/com/taover/util/UtilCollection.java | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilDate.java | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilEncrypt.java | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilExcel.java | 324 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilHttpByOkHttp.java | 189 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilLog.java | 74 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilObject.java | 245 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilPinyin.java | 63 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilRegex.java | 162 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilRemoteShellExe.java | 121 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilResultInfo.java | 55 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilString.java | 180 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/main/java/com/taover/util/UtilTemplate.java | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 14 files changed, 1694 insertions(+), 12 deletions(-) create mode 100644 src/main/java/com/taover/util/UtilCollection.java create mode 100644 src/main/java/com/taover/util/UtilDate.java create mode 100644 src/main/java/com/taover/util/UtilEncrypt.java create mode 100644 src/main/java/com/taover/util/UtilExcel.java create mode 100644 src/main/java/com/taover/util/UtilHttpByOkHttp.java create mode 100644 src/main/java/com/taover/util/UtilLog.java create mode 100644 src/main/java/com/taover/util/UtilObject.java create mode 100644 src/main/java/com/taover/util/UtilPinyin.java create mode 100644 src/main/java/com/taover/util/UtilRegex.java create mode 100644 src/main/java/com/taover/util/UtilRemoteShellExe.java create mode 100644 src/main/java/com/taover/util/UtilResultInfo.java create mode 100644 src/main/java/com/taover/util/UtilString.java create mode 100644 src/main/java/com/taover/util/UtilTemplate.java diff --git a/build.gradle b/build.gradle index 5f5ae9f..698392c 100644 --- a/build.gradle +++ b/build.gradle @@ -8,23 +8,37 @@ plugins { // Apply the java-library plugin to add support for Java Library - id 'java-library' + id 'java' + id 'eclipse' + id 'application' } -dependencies { - // This dependency is exported to consumers, that is to say found on their compile classpath. - api 'org.apache.commons:commons-math3:3.6.1' - - // This dependency is used internally, and not exposed to consumers on their own compile classpath. - implementation 'com.google.guava:guava:23.0' +jar.enabled = true +group = 'com.taover.util' +mainClassName = 'com.taover.util.UtilString' - // Use JUnit test framework - testImplementation 'junit:junit:4.12' +dependencies { + compile( + "org.apache.poi:poi:3.16", + "org.apache.poi:poi-excelant:3.16", + "log4j:log4j:1.2.17", + "commons-logging:commons-logging:1.2", + "ch.ethz.ganymed:ganymed-ssh2:build210", + "org.apache.velocity:velocity:1.6.4", + "com.squareup.okhttp3:okhttp:3.14.1", + "com.belerweb:pinyin4j:2.5.1" + ) } -// In this section you declare where to find the dependencies of your project repositories { - // Use jcenter for resolving your dependencies. - // You can declare any Maven/Ivy/file repository here. jcenter() } + +task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource +} + +artifacts { + archives sourcesJar +} diff --git a/src/main/java/com/taover/util/UtilCollection.java b/src/main/java/com/taover/util/UtilCollection.java new file mode 100644 index 0000000..df14b16 --- /dev/null +++ b/src/main/java/com/taover/util/UtilCollection.java @@ -0,0 +1,68 @@ +package com.taover.util; + +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UtilCollection{ + + public static Map listToMap(List elements, String keyFieldName){ + Map result = new HashMap(); + if(elements==null || keyFieldName==null || keyFieldName.isEmpty()){ + return null; + } + for(int i=0; i data, String key){ + if(data == null){ + return null; + } + Object value = data.get(key); + if(value == null){ + return null; + }else{ + if(value.getClass().isArray()){ + return String.valueOf(Array.get(value, 0)); + }else{ + return String.valueOf(value); + } + } + } + + public static void main(String args[]){ + List data = new ArrayList(); + data.add(new TestColl("1","2")); + data.add(new TestColl("3","4")); + data.add(new TestColl("5","6")); + Map temp = UtilCollection.listToMap(data, "a"); + System.out.println(temp.get("1")); + } +} + +class TestColl { + String a; + String b; + public TestColl(String a, String b){ + this.a = a; + this.b = b; + } +} diff --git a/src/main/java/com/taover/util/UtilDate.java b/src/main/java/com/taover/util/UtilDate.java new file mode 100644 index 0000000..82aa14a --- /dev/null +++ b/src/main/java/com/taover/util/UtilDate.java @@ -0,0 +1,59 @@ +package com.taover.util; + +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; + +public class UtilDate { + public static String getWeekCnByIndex(int index){ + String weekDay[] = new String[]{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"}; + return weekDay[index]; + } + + /** + * 计算周开始时间,gap=0表示当前周,gap=-1表示上一周,依次类推 + * @param gap + * @return + */ + public static Date getDateWeekBegin(int gap){ + Date result = new Date(); + Calendar currCal = Calendar.getInstance(); + currCal.setWeekDate(currCal.getWeekYear(), currCal.get(Calendar.WEEK_OF_YEAR)+gap, Calendar.MONDAY); + result = currCal.getTime(); + return result; + } + + /** + * 计算周开始时间,gap=0表示当前周,gap=-1表示上一周,依次类推 + * @param gap + * @return + */ + public static Date getDateWeekSome(int gap, int someWeekDay){ + Date result = new Date(); + Calendar currCal = Calendar.getInstance(); + currCal.setWeekDate(currCal.getWeekYear(), currCal.get(Calendar.WEEK_OF_YEAR)+gap, someWeekDay); + result = currCal.getTime(); + return result; + } + + /** + * 计算月开始时间,gap=0表示当前月,gap=-1表示上一月,依次类推 + * @param gap + * @return + */ + public static Date getDateMonthBegin(int gap){ + Date result = new Date(); + Calendar currCal = Calendar.getInstance(); + currCal.set(currCal.get(Calendar.YEAR), currCal.get(Calendar.MONTH)+gap, 1); + result = currCal.getTime(); + return result; + } + + public static void main(String args[]){ + SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); + //System.out.println(sdf.format(getDateMonthBegin(-1))); + DecimalFormat dFormat=new DecimalFormat("#.00"); + System.out.println(dFormat.format((Double.valueOf("2.123123123")/123.212*100))); + } +} diff --git a/src/main/java/com/taover/util/UtilEncrypt.java b/src/main/java/com/taover/util/UtilEncrypt.java new file mode 100644 index 0000000..e3d5eb1 --- /dev/null +++ b/src/main/java/com/taover/util/UtilEncrypt.java @@ -0,0 +1,56 @@ +package com.taover.util; + +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; + +public class UtilEncrypt { + + public static String MD5Lower32(String sourceStr) { + String result = ""; + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + md.update(sourceStr.getBytes()); + byte b[] = md.digest(); + int i; + StringBuffer buf = new StringBuffer(""); + for (int offset = 0; offset < b.length; offset++) { + i = b[offset]; + if (i < 0) + i += 256; + if (i < 16) + buf.append("0"); + buf.append(Integer.toHexString(i)); + } + result = buf.toString(); + } catch (NoSuchAlgorithmException e) { + System.out.println(e); + } + return result; + } + + private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1"; + /** + * hmac sha1 + * @param src + * @param key + * @return + */ + public static byte[] hmacSha1(byte[] key, byte[] src) { + try { + SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM); + Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM); + mac.init(signingKey); + return mac.doFinal(src); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static void main(String[] args) { + System.out.println(MD5Lower32("Lexi@1799")+"6591"); + System.out.println(MD5Lower32("adf8d8f44072dfae10ca8d11d060bf406591")); + } +} diff --git a/src/main/java/com/taover/util/UtilExcel.java b/src/main/java/com/taover/util/UtilExcel.java new file mode 100644 index 0000000..7528048 --- /dev/null +++ b/src/main/java/com/taover/util/UtilExcel.java @@ -0,0 +1,324 @@ +package com.taover.util; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.poi.hssf.usermodel.HSSFCell; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.hssf.util.HSSFColor; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +public class UtilExcel { + private final static String excel2003L =".xls"; //2003- 版本的excel + private final static String excel2007U =".xlsx"; //2007+ 版本的excel + + private final static int maxExcelRowNum = 5000; + private final static int maxExcelColumnNum = 50; + + /** + * 描述:根据文件后缀,自适应上传文件的版本 + * @param inStr,fileName + * @return + * @throws Exception + */ + private static Workbook getWorkbook(String filePath, boolean isRead) throws Exception{ + Workbook wb = null; + if(isRead){ + File tempFile = new File(filePath); + if(!tempFile.exists()){ + throw new Exception("需要读取的文件不存在!"); + } + } + String fileType = filePath.substring(filePath.lastIndexOf(".")); + if(excel2003L.equals(fileType)){ + if(isRead){ + wb = new HSSFWorkbook(new FileInputStream(filePath)); //2003- + }else{ + wb = new HSSFWorkbook(); //2003- + } + }else if(excel2007U.equals(fileType)){ + if(isRead){ + wb = new XSSFWorkbook(new FileInputStream(filePath)); //2007+ + }else{ + wb = new XSSFWorkbook(); //2007+ + } + }else{ + throw new Exception("解析的文件格式有误!"); + } + return wb; + } + + /** + * 创建并保存excel表 + * @param sheetName + * @param data + * @param path + */ + public static File saveExcelFromListString(String sheetName, List data, String path){ + Log log = LogFactory.getLog(UtilExcel.class); + Workbook wb = null; + try { + wb = UtilExcel.getWorkbook(path, false); + } catch (Exception e1) { + e1.printStackTrace(); + log.error(e1.getStackTrace().toString()+"保存excel文件失败,失败原因不能获取Workbook对象!msg="+e1.getMessage()); + return null; + } + //创建Excel工作簿对象 + Sheet sheet = wb.createSheet(sheetName);//创建Excel工作表对象 + for(int i=0; i> data, String path){ + Log log =LogFactory.getLog(UtilExcel.class); + Workbook wb = null; + try { + wb = UtilExcel.getWorkbook(path, false); + } catch (Exception e1) { + e1.printStackTrace(); + log.error(e1.getStackTrace().toString()+"保存excel文件失败,失败原因不能获取Workbook对象!msg="+e1.getMessage()); + return; + } + //创建Excel工作簿对象 + Sheet sheet = wb.createSheet(sheetName);//创建Excel工作表对象 + for(int i=0; i dataRow = data.get(i); + if(dataRow != null){ + for(int j=0; j> data, String path, List backColorList){ + Log log =LogFactory.getLog(UtilExcel.class); + Workbook wb = null; + try { + wb = UtilExcel.getWorkbook(path, false); + } catch (Exception e1) { + e1.printStackTrace(); + log.error(e1.getStackTrace().toString()+"保存excel文件失败,失败原因不能获取Workbook对象!msg="+e1.getMessage()); + return; + } + Map cellStyleMap = new HashMap(); + Sheet sheet = wb.createSheet(sheetName);//创建Excel工作表对象 + for(int i=0; i dataRow = data.get(i); + Short backColor = backColorList.get(i); + CellStyle style = cellStyleMap.get(backColor); + if(style == null){ + style = wb.createCellStyle(); + style.setFillPattern(style.SOLID_FOREGROUND); + cellStyleMap.put(backColor, style); + } + if(backColor != null){ + style.setFillForegroundColor(backColor.shortValue()); + } + if(dataRow != null){ + for(int j=0; j> readExcel(String filepath){ + File file = new File(filepath); + List> result = new ArrayList>(); + if(!file.exists()){ + return result; + } + Log log = LogFactory.getLog(UtilExcel.class); + Workbook wb = null; + try { + wb = UtilExcel.getWorkbook(filepath, true); + } catch (Exception e1) { + e1.printStackTrace(); + log.error(e1.getStackTrace().toString()+"保存excel文件失败,失败原因不能获取Workbook对象!msg="+e1.getMessage()); + return new ArrayList>(); + } + //创建Excel工作簿对象 + DecimalFormat df = new DecimalFormat("0"); + Sheet sheet = wb.getSheetAt(wb.getActiveSheetIndex()); + int start = sheet.getFirstRowNum(); + int end = sheet.getLastRowNum(); + if(end > UtilExcel.maxExcelRowNum){ + end = UtilExcel.maxExcelRowNum; + } + for(int i=start; i dataRow = new ArrayList(); + int lastCellNum = row.getLastCellNum(); + if(lastCellNum > UtilExcel.maxExcelColumnNum){ + lastCellNum = UtilExcel.maxExcelColumnNum; + } + for(int j=0; j> data = UtilExcel.readExcel(filepath); + List styleList = new ArrayList(); + for(int i=0; i headers) throws Exception { + //http头信息拼装 + Request request = getRequestBuilder(url, headers).get().build(); + + return getHttpClient(url).newCall(request).execute().body().string(); + } + + public static String sendPostForm(String url, final Map headers, final Map params) throws Exception { + //请求体信息 + RequestBody requestBody = getReqeustBody(params); + + //http头信息拼装 + Request request = getRequestBuilder(url, headers).post(requestBody).build(); + + return getHttpClient(url).newCall(request).execute().body().string(); + } + + public static String sendPutForm(String url, final Map headers, final Map params) throws Exception { + //请求体信息 + RequestBody requestBody = getReqeustBody(params); + + //http头信息拼装 + Request request = getRequestBuilder(url, headers).put(requestBody).build(); + + return getHttpClient(url).newCall(request).execute().body().string(); + } + + public static String sendPostString(String url, final Map headers, final String content) throws Exception{ + //请求体 + RequestBody requestBody = getReqeustBody(content); + + //http头信息拼装 + Request request = getRequestBuilder(url, headers).post(requestBody).build(); + + return getHttpClient(url).newCall(request).execute().body().string(); + } + + public static String sendDelete(String url, final Map headers) throws Exception { + //http头信息拼装 + Request request = getRequestBuilder(url, headers).delete().build(); + + return getHttpClient(url).newCall(request).execute().body().string(); + } + + private static OkHttpClient getHttpClient(String url){ + if(url.trim().toLowerCase().startsWith("https")){ + return buildOkHttpClientForHttps(); + }else{ + return new OkHttpClient(); + } + } + + private static RequestBody getReqeustBody(Map params){ + //表单信息拼装 + FormBody.Builder builder = new FormBody.Builder(Charset.forName("UTF-8")); + if(params != null) { + for(Map.Entry entry: params.entrySet()) { + Object tempValue = entry.getValue(); + if(tempValue.getClass().isArray()){ + String[] tempValueArr = (String[])tempValue; + for(int i=0; i headers){ + //http头信息拼装 + Request.Builder requestBuilder = new Request.Builder().url(url); + if(headers != null){ + for(Map.Entry entry: headers.entrySet()) { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + return requestBuilder; + } + + private static OkHttpClient buildOkHttpClientForHttps() { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.connectTimeout(30, TimeUnit.SECONDS) + .readTimeout(30, TimeUnit.SECONDS) + .writeTimeout(30,TimeUnit.SECONDS) + .retryOnConnectionFailure(true) + .sslSocketFactory(getTrustedSSLSocketFactory()) + .hostnameVerifier(DO_NOT_VERIFY); + return builder.build(); + } + + static TrustManager[] trustAllCerts = new TrustManager[]{ + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + X509Certificate[] x509Certificates = new X509Certificate[0]; + return x509Certificates; + } + + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + } + }; + + static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + private static SSLSocketFactory getTrustedSSLSocketFactory() { + try { + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + return sc.getSocketFactory(); + } catch (KeyManagementException | NoSuchAlgorithmException e) { + e.printStackTrace(); + return null; + } + } + + public static void main(String args[]){ + String contactSsid = "lM4AeZSizgFROR/OAHmUos4BUTkf"; + try { + contactSsid = URLEncoder.encode(contactSsid, "UTF-8"); + } catch (UnsupportedEncodingException e1) { + e1.printStackTrace(); + } + String url = "https://ssep.umsapi.com/api/v1/contacts/"+contactSsid+"/messages"; + System.out.println(url); + + Map headerData = new HashMap(); + headerData.put("ss-token", "lsQUPZA2rxyckfmOD5gfnPAo9Qa6N1/EEESotlOah3t2392ZZkrhOofNAZF5zlyUrDS1Y29tLnNvbmdzaHUud2ViYXBwLnYx"); + + Map paramData = new HashMap(); + paramData.put("kind", "text"); + paramData.put("content", "小伙子 干得漂亮"); + + try { + //System.out.println(UtilHttpByOkHttp.sendPostForm(url, headerData, paramData)); + System.out.println(UtilHttpByOkHttp.sendGet("https://ssep.umsapi.com/api/v2/openapi/querycontacts?appid=songshuyun-ifun×tamp=1562239191&signature=967fd77a24cbbce872bc1506a0187983", null)); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } +} diff --git a/src/main/java/com/taover/util/UtilLog.java b/src/main/java/com/taover/util/UtilLog.java new file mode 100644 index 0000000..048bdb6 --- /dev/null +++ b/src/main/java/com/taover/util/UtilLog.java @@ -0,0 +1,74 @@ +package com.taover.util; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + +public class UtilLog { + private static Map logByClassName = new HashMap(); + + /** + * 输出日志文本 + * @param message + * @param infoClass + */ + public static void infoForMessage(String message, Class infoClass){ + String className = infoClass.getName(); + Log log = logByClassName.get(infoClass.getName()); + if(log == null){ + log = LogFactory.getLog(infoClass); + if(log == null){ + return; + } + logByClassName.put(className, log); + } + log.info(message); + } + + /** + * 输出日志Exception内容 + * @param e + * @param infoClass + */ + public static String infoForException(Exception e, Class infoClass){ + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + UtilLog.infoForMessage(sw.toString(), infoClass); + return sw.toString(); + } + + /** + * 输出文本内容 + * @param message + * @param infoClass + */ + public static void errorForMessage(String message, Class infoClass){ + String className = infoClass.getName(); + Log log = logByClassName.get(infoClass.getName()); + if(log == null){ + log = LogFactory.getLog(infoClass); + if(log == null){ + return; + } + logByClassName.put(className, log); + } + log.error(message); + } + + /** + * 输出日志Exception信息 + * @param e + * @param infoClass + */ + public static String errorForException(Exception e, Class infoClass){ + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw)); + UtilLog.errorForMessage(sw.toString(), infoClass); + return sw.toString(); + } +} diff --git a/src/main/java/com/taover/util/UtilObject.java b/src/main/java/com/taover/util/UtilObject.java new file mode 100644 index 0000000..b8a5356 --- /dev/null +++ b/src/main/java/com/taover/util/UtilObject.java @@ -0,0 +1,245 @@ +package com.taover.util; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; + +public class UtilObject { + /** + * 将源对象source字段赋值到对象dest字段,条件1字段名相同,条件2字段类型相同; + * 注:source与dest可以是两个没有关系的类,不接受基本封装类型,例如Integer + * @param source + * @param dest + * @param allowNull + * @param exceptFieldNameArray + * @return 如果source==dest或者source==null或者dest==null,则返回false + */ + public static Object fieldCopy(Object source, Object dest, boolean allowNull, String exceptFieldNameArray[], boolean isNewInstance){ + //引用检查 + if(source==null || dest==null || source==dest){ + return null; + } + + //获取Field数组 + Field[] sourceField = source.getClass().getDeclaredFields(); + Field[] destField = dest.getClass().getDeclaredFields(); + + //获取目标对象 + String[] destFieldNameArray = new String[destField.length]; + String[] destFieldTypeArray = new String[destField.length]; + for(int i=0; i hello_word + * @param source + * @param isCopyNull + * @param exceptFieldNameArray + * @return + */ + public static List objecFieldToListToLowerCase(Object source, boolean isCopyNull, String exceptFieldNameArray[]){ + List result = new ArrayList(); + //参数检验 + if(source == null){ + return result; + } + + //获取Field数组 + Field[] sourceField = source.getClass().getDeclaredFields(); + //遍历源field数组,处理源field数组 + for(int i=0; i fieldToArray(Object source, boolean allowNull, String exceptFieldNameArray[]){ + List result = new ArrayList(); + //参数检验 + if(source == null){ + return result; + } + + //获取Field数组 + Field[] sourceField = source.getClass().getDeclaredFields(); + //遍历源field数组,处理源field数组 + for(int i=0; i www.zuidaima.com + * @create 2012-11-15 下午4:54:42 + */ +public class UtilRegex { + + /** + * 验证Email + * @param email email地址,格式:zhangsan@zuidaima.com,zhangsan@xxx.com.cn,xxx代表邮件服务商 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkEmail(String email) { + String regex = "[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?"; + return Pattern.matches(regex, email); + } + + /** + * 验证身份证号码 + * @param idCard 居民身份证号码15位或18位,最后一位可能是数字或字母 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkIdCard(String idCard) { + String regex = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$"; + return Pattern.matches(regex,idCard); + } + + /** + * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港)) + * @param mobile 移动、联通、电信运营商的号码段 + *

移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡) + *、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)

+ *

联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)

+ *

电信的号段:133、153、180(未启用)、189

+ * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkMobile(String mobile) { + String regex = "\\d{3}-\\d{8}|\\d{4}-\\{7,8}|\\d{11}"; + return Pattern.matches(regex,mobile); + } + + /** + * 验证固定电话号码 + * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 + *

国家(地区) 代码 :标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字, + * 数字之后是空格分隔的国家(地区)代码。

+ *

区号(城市代码):这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— + * 对不使用地区或城市代码的国家(地区),则省略该组件。

+ *

电话号码:这包含从 0 到 9 的一个或多个数字

+ * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkPhone(String phone) { + String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; + return Pattern.matches(regex, phone); + } + + /** + * 验证整数(正整数和负整数) + * @param digit 一位或多位0-9之间的整数 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkDigit(String digit) { + String regex = "^-?[1-9]\\d*$"; + return Pattern.matches(regex,digit); + } + + /** + * 验证整数和浮点数(正负整数和正负浮点数) + * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkDecimals(String decimals) { + String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; + return Pattern.matches(regex,decimals); + } + + /** + * 验证空白字符 + * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkBlankSpace(String blankSpace) { + String regex = "\\s+"; + return Pattern.matches(regex,blankSpace); + } + + /** + * 验证中文 + * @param chinese 中文字符 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkChinese(String chinese) { + String regex = "^[\u4e00-\u9fa5]+$"; + return Pattern.matches(regex,chinese); + } + + /** + * 验证日期(年月日) + * @param birthday 日期,格式:1992-09-03,或1992.09.03 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkBirthday(String birthday) { + String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; + return Pattern.matches(regex,birthday); + } + + /** + * 验证URL地址 + * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkURL(String url) { + String regex = "[a-zA-z]+://[^\\s]*"; + return Pattern.matches(regex, url); + } + + /** + *
+     * 获取网址 URL 的一级域名
+     * http://www.zuidaima.com/share/1550463379442688.htm ->> zuidaima.com
+     * 
+ * + * @param url + * @return + */ + public static String getDomain(String url) { + Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); + // 获取完整的域名 + // Pattern p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); + Matcher matcher = p.matcher(url); + matcher.find(); + return matcher.group(); + } + /** + * 匹配中国邮政编码 + * @param postcode 邮政编码 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkPostcode(String postcode) { + String regex = "[1-9]\\d{5}(?!\\d)"; + return Pattern.matches(regex, postcode); + } + + /** + * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小) + * @param ipAddress IPv4标准地址 + * @return 验证成功返回true,验证失败返回false + */ + public static boolean checkIpAddress(String ipAddress) { + String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; + return Pattern.matches(regex, ipAddress); + } + + public static void main(String args[]){ + System.out.println(checkMobile("13621051230")); + } +} diff --git a/src/main/java/com/taover/util/UtilRemoteShellExe.java b/src/main/java/com/taover/util/UtilRemoteShellExe.java new file mode 100644 index 0000000..e0bafca --- /dev/null +++ b/src/main/java/com/taover/util/UtilRemoteShellExe.java @@ -0,0 +1,121 @@ +package com.taover.util; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; + +import ch.ethz.ssh2.ChannelCondition; +import ch.ethz.ssh2.Connection; +import ch.ethz.ssh2.Session; +import ch.ethz.ssh2.StreamGobbler; + +public class UtilRemoteShellExe { + + private Connection conn; + /** 远程机器IP */ + private String ip; + /** 用户名 */ + private String osUsername; + /** 密码 */ + private String password; + private String charset = Charset.defaultCharset().toString(); + + private static final int TIME_OUT = 1000 * 5; + + /** + * 构造函数 + * @param ip + * @param usr + * @param pasword + */ + public UtilRemoteShellExe(String ip, String usr, String pasword) { + this.ip = ip; + this.osUsername = usr; + this.password = pasword; + } + + + /** + * 登录 + * @return + * @throws IOException + */ + private boolean login() throws IOException { + conn = new Connection(ip); + conn.connect(); + return conn.authenticateWithPassword(osUsername, password); + } + + /** + * 执行脚本 + * + * @param cmds + * @return + * @throws Exception + */ + public int exec(String cmds) throws Exception { + InputStream stdOut = null; + InputStream stdErr = null; + String outStr = ""; + String outErr = ""; + int ret = -1; + try { + if (login()) { + // Open a new {@link Session} on this connection + Session session = conn.openSession(); + + // Execute a command on the remote machine. + session.execCommand(cmds); + + stdOut = new StreamGobbler(session.getStdout()); + outStr = processStream(stdOut, charset); + + stdErr = new StreamGobbler(session.getStderr()); + outErr = processStream(stdErr, charset); + + session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT); + + System.out.println("SHELL PRINT INFO=" + outStr); + System.out.println("SHELL PRINT ERROR=" + outErr); + + ret = session.getExitStatus(); + + session.close(); + } else { + throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略 + } + } finally { + if (conn != null) { + conn.close(); + } + stdOut.close(); + stdErr.close(); + } + return ret; + } + + /** + * @param in + * @param charset + * @return + * @throws IOException + * @throws UnsupportedEncodingException + */ + private String processStream(InputStream in, String charset) throws Exception { + byte[] buf = new byte[1024]; + StringBuilder sb = new StringBuilder(); + while (in.read(buf) != -1) { + sb.append(new String(buf, charset)); + } + return sb.toString(); + } + + public static void main(String args[]) throws Exception { + UtilRemoteShellExe executor = new UtilRemoteShellExe("47.93.114.120", "wangbin", "wangbin"); + // 执行myTest.sh 参数为java Know dummy + System.out.println(executor.exec("sh /home/wangbin/taover-vbote/boot.sh")); +// System.out.println(executor.exec("cd taover-vbote")); +// System.out.println(executor.exec("pwd")); + } +} \ No newline at end of file diff --git a/src/main/java/com/taover/util/UtilResultInfo.java b/src/main/java/com/taover/util/UtilResultInfo.java new file mode 100644 index 0000000..fb45cd9 --- /dev/null +++ b/src/main/java/com/taover/util/UtilResultInfo.java @@ -0,0 +1,55 @@ +package com.taover.util; + +public class UtilResultInfo { + public static final String SUCCESS ="success"; + public static final String FAIL ="fail"; + public static final String NOT_AUTHORIZED ="not_authorized"; + + public static ResultInfo getResultSuccessMessage(String error){ + return getResult(UtilResultInfo.SUCCESS, error, null); + } + + public static ResultInfo getResultFailureMessage(String error){ + return getResult(UtilResultInfo.FAIL, error, null); + } + + public static ResultInfo getResultSuccessMessage(String error, Object data){ + return getResult(UtilResultInfo.SUCCESS, error, data); + } + + public static ResultInfo getResultFailureMessage(String error, Object data){ + return getResult(UtilResultInfo.FAIL, error, data); + } + + public static ResultInfo getResult(String code, String error, Object data){ + ResultInfo result = new ResultInfo(); + result.setCode(code); + result.setData(data); + result.setError(error); + return result; + } +} + +class ResultInfo { + private String code; + private String error; + private Object data; + public String getCode() { + return code; + } + public void setCode(String code) { + this.code = code; + } + public String getError() { + return error; + } + public void setError(String error) { + this.error = error; + } + public Object getData() { + return data; + } + public void setData(Object data) { + this.data = data; + } +} diff --git a/src/main/java/com/taover/util/UtilString.java b/src/main/java/com/taover/util/UtilString.java new file mode 100644 index 0000000..7827a1f --- /dev/null +++ b/src/main/java/com/taover/util/UtilString.java @@ -0,0 +1,180 @@ +package com.taover.util; + +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class UtilString { + /** + * 在compares字符数组查找pattern字符串,找到则返回字串在数组中的索引,未找到返回-1 + * @param pattern + * @param compares + * @return + */ + public static int getStringIndex(String pattern, String compares[]){ + //参数检验 + if(pattern==null || compares==null){ + return -1; + } + + //循环遍历compares + for(int i=0; iLong.MAX_VALUE || value0; --i){ + long baseDiv = (long) Math.pow(10, i-1); + long baseRand = (long) Math.pow(10, i); + long currentDigit = value % baseRand / baseDiv; + if(currentDigit == 0){ + result = result + preffixChar; + }else{ + result = result + currentDigit; + } + } + return result; + } + + /** + * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空,则返回空字符串。
+ * 例如:HelloWorld->HELLO_WORLD + * @param name 转换前的驼峰式命名的字符串 + * @return 转换后下划线大写方式命名的字符串 + */ + public static String underscoreName(String name) { + StringBuilder result = new StringBuilder(); + if (name != null && name.length() > 0) { + // 将第一个字符处理成大写 + result.append(name.substring(0, 1).toUpperCase()); + // 循环处理其余字符 + for (int i = 1; i < name.length(); i++) { + String s = name.substring(i, i + 1); + // 在大写字母前添加下划线 + if (Character.isUpperCase(s.charAt(0)) && Character.isLetter(s.charAt(0))) { + result.append("_"); + } + // 其他字符直接转成大写 + result.append(s.toUpperCase()); + } + } + return result.toString(); + } + + /** + * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。
+ * 例如: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("_")) { + // 不含下划线,仅将首字母小写 + return name.substring(0, 1).toLowerCase() + name.substring(1); + } + // 用下划线将原始字符串分割 + 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(); + } + + /** + * 将idstring转换为integer数组 + * @param ids + * @param splitStr + * @return + */ + public static Integer[] transIdStringToArray(String ids, String splitStr){ + String idArray[] = ids.split(splitStr); + List idList = new ArrayList(); + for(int i=0; i data){ + //初始化 + VelocityEngine ve = new VelocityEngine(); + Properties p = new Properties(); + p.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem"); + p.put("runtime.log.logsystem.log4j.category", "velocity"); + p.put("runtime.log.logsystem.log4j.logger", "velocity"); + p.put(VelocityEngine.INPUT_ENCODING, "UTF-8"); + p.put(VelocityEngine.OUTPUT_ENCODING, "UTF-8"); + p.put(VelocityEngine.ENCODING_DEFAULT, "UTF-8"); + p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + try { + ve.init(p); + } catch (Exception e) { + StringWriter sw = new StringWriter(); + e.printStackTrace(new PrintWriter(sw, true)); + Log log = LogFactory.getLog(UtilTemplate.class); + log.error(sw.toString()); + } + //取得VelocityContext对象 + VelocityContext context = new VelocityContext(); + //向context中放入要在模板中用到的数据对象 + if(data != null){ + Set keySet = data.keySet(); + Iterator iter = keySet.iterator(); + while(iter.hasNext()){ + String key = iter.next(); + context.put(key, data.get(key)); + } + } + //选择要用到的模板 + if( !ve.resourceExists(templateClassPath) ){ + return null; + } + Template template; + StringWriter sw = new StringWriter(); + try { + template = ve.getTemplate(templateClassPath, "UTF-8"); + //合并输出 + template.merge( context, sw); + } catch (Exception e) { + StringWriter swE = new StringWriter(); + e.printStackTrace(new PrintWriter(swE, true)); + Log log = LogFactory.getLog(UtilTemplate.class); + log.error(sw.toString()); + } + return sw.toString(); + } +} -- libgit2 0.21.2