Java常用公共工具记录

转载于:https://blog.csdn.net/Evankaka/article/details/72614601

1、日期处理工具

  1. import java.text.SimpleDateFormat;
  2. import java.util.Calendar;
  3. import java.util.Date;
  4. /**
  5. * 日期常用格式转换
  6. */
  7. public class DateTimeUtil {
  8. static {
  9. ymdhmsFormat = new SimpleDateFormat( "yyyyMMddHHmmss");
  10. ymdhmsFormat2 = new SimpleDateFormat( "yyyyMMdd HH:mm:ss");
  11. ymdFormat = new SimpleDateFormat( "yyyyMMdd");
  12. ymdFormat2 = new SimpleDateFormat( "yyyy-MM-dd");
  13. hmsFormat = new SimpleDateFormat( "HHmmss");
  14. ymFormat = new SimpleDateFormat( "yyyyMM");
  15. c = Calendar.getInstance();
  16. }
  17. private static SimpleDateFormat ymdhmsFormat;
  18. private static SimpleDateFormat ymdhmsFormat2;
  19. private static SimpleDateFormat ymdFormat;
  20. private static SimpleDateFormat ymdFormat2;
  21. private static SimpleDateFormat hmsFormat;
  22. private static SimpleDateFormat ymFormat; //年月
  23. private static Calendar c;
  24. public static Date dateOnly(Date date) {
  25. return yyyyMMddToDate(parseToyyyyMMdd(date));
  26. }
  27. /**
  28. * 转换为 yyyyMMddHHmmss格式
  29. */
  30. public static String parseToyyyyMMddHHmmss(Date date) {
  31. if (date == null) {
  32. return null;
  33. }
  34. return ymdhmsFormat.format(date);
  35. }
  36. /**
  37. * 转换为 yyyyMMdd HH:mm:ss格式
  38. */
  39. public static String parseToyyyyMMddHHmmss2(Date date) {
  40. if (date == null) {
  41. return null;
  42. }
  43. return ymdhmsFormat2.format(date);
  44. }
  45. /**
  46. * 转换为HHmmss格式
  47. */
  48. public static String parseToHHmmss(Date date) {
  49. if (date == null) {
  50. return null;
  51. }
  52. return hmsFormat.format(date);
  53. }
  54. /**
  55. * 转换为yyyyMMdd格式
  56. */
  57. public static String parseToyyyyMMdd(Date date) {
  58. if (date == null) {
  59. return null;
  60. }
  61. return ymdFormat.format(date);
  62. }
  63. /**
  64. * 转换为yyyyMM格式
  65. */
  66. public static int parseToyyyyMM(Date date) {
  67. if (date == null) {
  68. return 0;
  69. }
  70. return Integer.valueOf(ymFormat.format(date));
  71. }
  72. public static Date yyyyMMddHHmmssToDate(String yyyyMMddHHmmss) {
  73. try {
  74. return ymdhmsFormat.parse(yyyyMMddHHmmss);
  75. }
  76. catch (Exception e) {
  77. return null;
  78. }
  79. }
  80. public static Date yyyyMMddToDate(String yyyyMMdd) {
  81. try {
  82. return ymdFormat.parse(yyyyMMdd);
  83. }
  84. catch (Exception e) {
  85. return null;
  86. }
  87. }
  88. public static Date yyyyMMToDate(String yyyyMM) {
  89. try {
  90. return ymFormat.parse(yyyyMM);
  91. }
  92. catch (Exception e) {
  93. return null;
  94. }
  95. }
  96. /**
  97. * yyyy-MM-dd转换成date
  98. * @author linbingwen
  99. * @since 2016年4月14日
  100. * @param yyyyMMdd2
  101. * @return
  102. */
  103. public static Date yyyyMMddToDate2(String yyyyMMdd2) {
  104. try {
  105. return ymdFormat2.parse(yyyyMMdd2);
  106. }
  107. catch (Exception e) {
  108. return null;
  109. }
  110. }
  111. public static Date HHmmssToDate(String HHmmss) {
  112. try {
  113. return hmsFormat.parse(HHmmss);
  114. }
  115. catch (Exception e) {
  116. return null;
  117. }
  118. }
  119. public static Date getDate(Date srcDate, Integer daysToAdd) {
  120. c.setTime(srcDate);
  121. c.add(Calendar.DATE, daysToAdd); // number of days to add
  122. return c.getTime();
  123. }
  124. public static Date yyyyMMddHHmmssToDate2(String yyyyMMddHHmmss) {
  125. try {
  126. return ymdhmsFormat2.parse(yyyyMMddHHmmss);
  127. }
  128. catch (Exception e) {
  129. return null;
  130. }
  131. }
  132. public static final int daysBetween(Date early, Date late) {
  133. java.util.Calendar calst = java.util.Calendar.getInstance();
  134. java.util.Calendar caled = java.util.Calendar.getInstance();
  135. calst.setTime(early);
  136. caled.setTime(late);
  137. // 设置时间为0时
  138. calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
  139. calst.set(java.util.Calendar.MINUTE, 0);
  140. calst.set(java.util.Calendar.SECOND, 0);
  141. caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
  142. caled.set(java.util.Calendar.MINUTE, 0);
  143. caled.set(java.util.Calendar.SECOND, 0);
  144. // 得到两个日期相差的天数
  145. int days = (( int) (caled.getTime().getTime() / 1000) - ( int) (calst.getTime().getTime() / 1000)) / 3600 / 24;
  146. return days;
  147. }
  148. public static Date getNextDayOfWeek(Date date, int dayOfWeek) {
  149. if (dayOfWeek == 0) {
  150. dayOfWeek = 7;
  151. }
  152. if (dayOfWeek > 7 || dayOfWeek < 1) {
  153. throw new RuntimeException( "星期:" + dayOfWeek + "不存在");
  154. }
  155. Calendar cal = Calendar.getInstance();
  156. cal.setTime(date);
  157. while ( true) {
  158. int day = cal.get(Calendar.DAY_OF_WEEK);
  159. if (preWeekDay(day) == dayOfWeek) {
  160. return cal.getTime();
  161. }
  162. cal.add(Calendar.DATE, 1);
  163. }
  164. }
  165. public static Date getNextMonthDate(Date date, int nextMonthDate) {
  166. Calendar cal = Calendar.getInstance();
  167. cal.setTime(date);
  168. int day = cal.get(Calendar.DATE);
  169. if (day <= nextMonthDate) {
  170. cal.set(Calendar.DATE, nextMonthDate);
  171. }
  172. else {
  173. cal.set(Calendar.DATE, 1);
  174. cal.add(Calendar.MONTH, 1);
  175. cal.set(Calendar.DATE, nextMonthDate);
  176. }
  177. return cal.getTime();
  178. }
  179. public static int nextWeekDay(int day) {
  180. if (day == 7) {
  181. return 1;
  182. }
  183. else {
  184. return day++;
  185. }
  186. }
  187. public static int preWeekDay(int day) {
  188. if (day == 1) {
  189. return 7;
  190. }
  191. else {
  192. return day - 1;
  193. }
  194. }
  195. /**
  196. * 计算两个日期相差的天数
  197. * @param beginDate 【YYYYMMDD】
  198. * @param endDate 【YYYYMMDD】
  199. * @return Integer
  200. * @author linbingwen
  201. * @since 2015年7月21日
  202. */
  203. public static long diffDate(Date beginDate,Date endDate){
  204. Calendar theCa1= Calendar.getInstance();
  205. Calendar theCa2= Calendar.getInstance();
  206. theCa1.setTime(beginDate);
  207. theCa2.setTime(endDate);
  208. long between_days=(theCa2.getTimeInMillis()-theCa1.getTimeInMillis())/( 1000* 3600* 24);
  209. return between_days;
  210. }
  211. /**
  212. * 分钟差
  213. * @Title: diffMinute 
  214. * @Description: TODO
  215. * @author : liuqiuyun
  216. * @param @param beginDate
  217. * @param @param endDate
  218. * @param @return    设定文件 
  219. * @return long    返回类型 
  220. * @throws 
  221. */
  222. public static long diffMinute(Date beginDate,Date endDate){
  223. Calendar theCa1= Calendar.getInstance();
  224. Calendar theCa2= Calendar.getInstance();
  225. theCa1.setTime(beginDate);
  226. theCa2.setTime(endDate);
  227. long between_minutes=(theCa2.getTimeInMillis()-theCa1.getTimeInMillis())/( 1000* 60);
  228. return between_minutes;
  229. }
  230. /**
  231. * 获取月份差第一天
  232. * @Title: getMonthFirstDate 
  233. * @Description: TODO
  234. * @author : liuqiuyun
  235. * @param @param date
  236. * @param @param monthToAdd
  237. * @param @param minOrMax 月初还是月末
  238. * @param @return    设定文件 
  239. * @return Date    返回类型 
  240. * @throws 
  241. */
  242. public static Date getMonthFirstDate(Date date,int monthToAdd, String minOrMax) {
  243. Calendar calendar = Calendar.getInstance();
  244. calendar.setTime(date);
  245. calendar.add(Calendar.MONTH, monthToAdd);
  246. if(minOrMax.equals( "min")){
  247. calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
  248. } else if(minOrMax.equals( "max")){
  249. calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
  250. }
  251. return calendar.getTime();
  252. }
  253. public static long getLastMonth(Date date) {
  254. Date lastDate = getMonthFirstDate(date,- 1, "min");
  255. long lastMonth = parseToyyyyMM(lastDate);
  256. return lastMonth;
  257. }
  258. public static void main(String[] args) throws InterruptedException {
  259. // Calendar cal = Calendar.getInstance();
  260. // System.out.println(" cal.get(Calendar.DAY_OF_WEEK);:" + cal.get(Calendar.DAY_OF_WEEK));
  261. // System.out.println(" cal.get(Calendar.DAY_OF_WEEK_IN_MONTH);:" + cal.get(Calendar.DAY_OF_WEEK_IN_MONTH));
  262. //
  263. // System.out.println(getNextDayOfWeek(cal.getTime(), 0));
  264. // System.out.println(getNextDayOfWeek(cal.getTime(), 7));
  265. // System.out.println(getNextDayOfWeek(cal.getTime(), 1));
  266. // System.out.println(getNextDayOfWeek(cal.getTime(), 2));
  267. //
  268. // System.out.println(getNextMonthDate(cal.getTime(), 0));
  269. // System.out.println(parseToyyyyMMdd(getNextMonthDate(cal.getTime(), 15)));
  270. System.out.println(parseToyyyyMMdd(getMonthFirstDate(yyyyMMddToDate( "20160618"),- 1, "max")));
  271. // System.out.println(yyyyMMddToDate2("2012-09-01"));
  272. //
  273. // Date start = new Date();
  274. // System.out.println(start);
  275. // Thread.sleep(60*1000*5+1000);
  276. // Date end = new Date();
  277. // System.out.println(end);
  278. // System.out.println(diffMinute(start,end));
  279. }
  280. }
2、http请求处理工具

  1. import java.io.ByteArrayInputStream;
  2. import sun.misc.BASE64Decoder;
  3. import sun.misc.BASE64Encoder;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.HttpURLConnection;
  10. import java.net.Proxy;
  11. import java.net.URL;
  12. import java.security.SecureRandom;
  13. import java.security.cert.CertificateException;
  14. import java.security.cert.X509Certificate;
  15. import java.util.Map;
  16. import javax.net.ssl.HostnameVerifier;
  17. import javax.net.ssl.HttpsURLConnection;
  18. import javax.net.ssl.KeyManager;
  19. import javax.net.ssl.SSLContext;
  20. import javax.net.ssl.SSLSession;
  21. import javax.net.ssl.TrustManager;
  22. import javax.net.ssl.X509TrustManager;
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25. //import com.lz.common.util.http.FileItem;
  26. public class HttpClientUtil {
  27. private static Logger logger = LoggerFactory
  28. .getLogger(HttpClientUtil.class);
  29. public static void main(String[] args) {
  30. HttpURLConnection conn = null;
  31. InputStream ins = null;
  32. try {
  33. // String boundary = System.currentTimeMillis() + "";
  34. // String ctype = "multipart/form-data;boundary=" + boundary;
  35. // conn = HttpClientUtil
  36. // .getConnection(
  37. // null,
  38. // new URL(
  39. // "http://10.75.201.68:8888/cfile/file/image?imageId=group2/M00/05/64/CkvJo1cQVPyATVbKACIyO0-AKoo7735712"),
  40. // "GET", ctype, null);
  41. // conn.setConnectTimeout(1000);
  42. // conn.setReadTimeout(5000);
  43. byte[] bytes = downLoadFile( "http://10.75.201.68:8888/cfile/file/image?imageId=group2/M00/05/64/CkvJo1cQVPyATVbKACIyO0-AKoo7735712");
  44. InputStream inputStream = new ByteArrayInputStream(bytes);
  45. // ins = conn.getInputStream();
  46. File file = new File( "D:/6.docx");
  47. FileOutputStream fot = new FileOutputStream(file);
  48. com.slob.util.io.IOUtil.inputStreamToOutputStream(inputStream, fot);
  49. } catch (Exception e) {
  50. }
  51. }
  52. public static byte[] downLoadFile(String url) throws IOException {
  53. HttpURLConnection conn = null;
  54. InputStream ins = null;
  55. byte[] bytes = null;
  56. try {
  57. String boundary = System.currentTimeMillis() + "";
  58. String ctype = "multipart/form-data;boundary=" + boundary;
  59. conn = HttpClientUtil.getConnection( null, new URL(url), "GET", ctype, null);
  60. conn.setConnectTimeout( 1000);
  61. conn.setReadTimeout( 5000);
  62. ins = conn.getInputStream();
  63. bytes = readBytes(ins);
  64. return bytes;
  65. } catch (Exception e) {
  66. throw new RuntimeException(e);
  67. } finally {
  68. if (ins != null) {
  69. ins.close();
  70. }
  71. if (conn != null) {
  72. conn.disconnect();
  73. }
  74. }
  75. }
  76. public static String uploadFile(String url, String fieldName,
  77. String fileName, InputStream ips, ResponseProcess respProcess)
  78. throws IOException {
  79. HttpURLConnection conn = null;
  80. OutputStream out = null;
  81. try {
  82. String boundary = System.currentTimeMillis() + "";
  83. String ctype = "multipart/form-data;boundary=" + boundary;
  84. conn = HttpClientUtil.getConnection( null, new URL(url), "POST",
  85. ctype, null);
  86. conn.setConnectTimeout( 1000);
  87. conn.setReadTimeout( 5000);
  88. out = conn.getOutputStream();
  89. byte[] entryBoundaryBytes = ( "\r\n--" + boundary + "\r\n")
  90. .getBytes( "UTF-8");
  91. out.write(entryBoundaryBytes);
  92. byte[] data = new byte[ 1024 * 1024];
  93. int size = ips.read(data);
  94. byte[] fileBytes = getFileEntry(fieldName, fileName,
  95. getMimeType(data), "UTF-8");
  96. out.write(fileBytes);
  97. while (size > 0) {
  98. out.write(data, 0, size);
  99. size = ips.read(data);
  100. }
  101. byte[] endBoundaryBytes = ( "\r\n--" + boundary + "--\r\n")
  102. .getBytes( "UTF-8");
  103. out.write(endBoundaryBytes);
  104. return respProcess.processResponse(conn);
  105. } catch (Exception e) {
  106. throw new RuntimeException(e);
  107. } finally {
  108. if (out != null) {
  109. out.close();
  110. }
  111. if (conn != null) {
  112. conn.disconnect();
  113. }
  114. }
  115. }
  116. // public static String doPost(Proxy proxy, String url, String requestType,
  117. // Map<String, String> params,
  118. // Map<String, FileItem> fileParams, String charset, int connectTimeout, int
  119. // readTimeout,
  120. // Map<String, String> headerMap, ResponseProcess respProcess) throws
  121. // IOException {
  122. //
  123. // String boundary = System.currentTimeMillis() + "";
  124. // HttpURLConnection conn = null;
  125. // OutputStream out = null;
  126. // String rsp = null;
  127. // try {
  128. // try {
  129. // String ctype = "multipart/form-data;boundary=" + boundary;
  130. // conn = getConnection(proxy, new URL(url), requestType, ctype, headerMap);
  131. // conn.setConnectTimeout(connectTimeout);
  132. // conn.setReadTimeout(readTimeout);
  133. // }
  134. // catch (IOException e) {
  135. // logger.error(url, e);
  136. // throw e;
  137. // }
  138. //
  139. // try {
  140. // out = conn.getOutputStream();
  141. //
  142. // byte[] entryBoundaryBytes = ("\r\n--" + boundary +
  143. // "\r\n").getBytes(charset);
  144. //
  145. // if (params != null) {
  146. // // 文本
  147. // Set<Entry<String, String>> textEntrySet = params.entrySet();
  148. // for (Entry<String, String> textEntry : textEntrySet) {
  149. // byte[] textBytes = getTextEntry(textEntry.getKey(), textEntry.getValue(),
  150. // charset);
  151. // out.write(entryBoundaryBytes);
  152. // out.write(textBytes);
  153. // }
  154. // }
  155. //
  156. // // 文件
  157. // if (fileParams != null) {
  158. // Set<Entry<String, FileItem>> fileEntrySet = fileParams.entrySet();
  159. // for (Entry<String, FileItem> fileEntry : fileEntrySet) {
  160. // FileItem fileItem = fileEntry.getValue();
  161. // if (fileItem.getContent() == null) {
  162. // continue;
  163. // }
  164. // byte[] fileBytes = getFileEntry(fileEntry.getKey(),
  165. // fileItem.getFileName(),
  166. // fileItem.getMimeType(), charset);
  167. // out.write(entryBoundaryBytes);
  168. // out.write(fileBytes);
  169. // out.write(fileItem.getContent());
  170. // }
  171. // }
  172. //
  173. // byte[] endBoundaryBytes = ("\r\n--" + boundary +
  174. // "--\r\n").getBytes(charset);
  175. // out.write(endBoundaryBytes);
  176. // rsp = respProcess.processResponse(conn);
  177. // }
  178. // catch (IOException e) {
  179. // logger.error(url, e);
  180. // throw e;
  181. // }
  182. // }
  183. // finally {
  184. // if (out != null) {
  185. // out.close();
  186. // }
  187. // if (conn != null) {
  188. // conn.disconnect();
  189. // }
  190. // }
  191. //
  192. // return rsp;
  193. // }
  194. public static String doGet(Proxy proxy, String url, String charset,
  195. ResponseProcess respProcess) throws IOException {
  196. if (url == null) {
  197. return "";
  198. }
  199. HttpURLConnection conn = null;
  200. String rsp = null;
  201. try {
  202. String ctype = "application/x-www-form-urlencoded;charset="
  203. + charset;
  204. conn = getConnection(proxy, new URL(url), "GET", ctype, null);
  205. rsp = respProcess.processResponse(conn);
  206. } catch (IOException e) {
  207. logger.error(url, e);
  208. throw e;
  209. } finally {
  210. if (conn != null) {
  211. conn.disconnect();
  212. }
  213. }
  214. return rsp;
  215. }
  216. private static class DefaultTrustManager implements X509TrustManager {
  217. public X509Certificate[] getAcceptedIssuers() {
  218. return null;
  219. }
  220. public void checkClientTrusted(X509Certificate[] chain, String authType)
  221. throws CertificateException {
  222. }
  223. public void checkServerTrusted(X509Certificate[] chain, String authType)
  224. throws CertificateException {
  225. }
  226. }
  227. public static HttpURLConnection getConnection(Proxy proxy, URL url,
  228. String method, String ctype, Map<String, String> headerMap)
  229. throws IOException {
  230. HttpURLConnection conn = null;
  231. if ( "https".equals(url.getProtocol())) {
  232. SSLContext ctx = null;
  233. try {
  234. ctx = SSLContext.getInstance( "TLS");
  235. ctx.init( new KeyManager[ 0],
  236. new TrustManager[] { new DefaultTrustManager() },
  237. new SecureRandom());
  238. } catch (Exception e) {
  239. throw new IOException(e);
  240. }
  241. HttpsURLConnection connHttps;
  242. if (proxy != null) {
  243. connHttps = (HttpsURLConnection) url.openConnection(proxy);
  244. } else {
  245. connHttps = (HttpsURLConnection) url.openConnection();
  246. }
  247. connHttps.setSSLSocketFactory(ctx.getSocketFactory());
  248. connHttps.setHostnameVerifier( new HostnameVerifier() {
  249. public boolean verify(String hostname, SSLSession session) {
  250. return true;
  251. }
  252. });
  253. conn = connHttps;
  254. } else {
  255. if (proxy != null) {
  256. conn = (HttpURLConnection) url.openConnection(proxy);
  257. } else {
  258. conn = (HttpURLConnection) url.openConnection();
  259. }
  260. }
  261. conn.setRequestMethod(method);
  262. conn.setDoInput( true);
  263. conn.setDoOutput( true);
  264. conn.setRequestProperty( "Accept",
  265. "text/xml,text/javascript,text/html,application/json");
  266. conn.setRequestProperty( "User-Agent", "java");
  267. conn.setRequestProperty( "Content-Type", ctype);
  268. if (headerMap != null) {
  269. for (Map.Entry<String, String> entry : headerMap.entrySet()) {
  270. conn.setRequestProperty(entry.getKey(), entry.getValue());
  271. }
  272. }
  273. return conn;
  274. }
  275. private static byte[] getTextEntry(String fieldName, String fieldValue,
  276. String charset) throws IOException {
  277. StringBuilder entry = new StringBuilder();
  278. entry.append( "Content-Disposition:form-data;name=\"");
  279. entry.append(fieldName);
  280. entry.append( "\"\r\nContent-Type:text/plain\r\n\r\n");
  281. entry.append(fieldValue);
  282. return entry.toString().getBytes(charset);
  283. }
  284. private static byte[] getFileEntry(String fieldName, String fileName,
  285. String mimeType, String charset) throws IOException {
  286. StringBuilder entry = new StringBuilder();
  287. entry.append( "Content-Disposition:form-data;name=\"");
  288. entry.append(fieldName);
  289. entry.append( "\";filename=\"");
  290. entry.append(fileName);
  291. entry.append( "\"\r\nContent-Type:");
  292. entry.append(mimeType);
  293. entry.append( "\r\n\r\n");
  294. return entry.toString().getBytes(charset);
  295. }
  296. public static interface ResponseProcess {
  297. String processResponse(HttpURLConnection conn);
  298. };
  299. public static String getMimeType(byte[] bytes) {
  300. String suffix = getFileSuffix(bytes);
  301. String mimeType;
  302. if ( "JPG".equals(suffix)) {
  303. mimeType = "image/jpeg";
  304. } else if ( "GIF".equals(suffix)) {
  305. mimeType = "image/gif";
  306. } else if ( "PNG".equals(suffix)) {
  307. mimeType = "image/png";
  308. } else if ( "BMP".equals(suffix)) {
  309. mimeType = "image/bmp";
  310. } else {
  311. mimeType = "application/octet-stream";
  312. }
  313. return mimeType;
  314. }
  315. /**
  316. * 获取文件的真实后缀名。目前只支持JPG, GIF, PNG, BMP四种图片文件。
  317. *
  318. * @param bytes
  319. * 文件字节流
  320. * @return JPG, GIF, PNG or null
  321. */
  322. public static String getFileSuffix(byte[] bytes) {
  323. if (bytes == null || bytes.length < 10) {
  324. return null;
  325. }
  326. if (bytes[ 0] == 'G' && bytes[ 1] == 'I' && bytes[ 2] == 'F') {
  327. return "GIF";
  328. } else if (bytes[ 1] == 'P' && bytes[ 2] == 'N' && bytes[ 3] == 'G') {
  329. return "PNG";
  330. } else if (bytes[ 6] == 'J' && bytes[ 7] == 'F' && bytes[ 8] == 'I'
  331. && bytes[ 9] == 'F') {
  332. return "JPG";
  333. } else if (bytes[ 0] == 'B' && bytes[ 1] == 'M') {
  334. return "BMP";
  335. } else {
  336. return null;
  337. }
  338. }
  339. public static byte[] readBytes(InputStream in) throws IOException {
  340. byte[] temp = new byte[in.available()];
  341. byte[] result = new byte[ 0];
  342. int size = 0;
  343. while ((size = in.read(temp)) != - 1) {
  344. byte[] readBytes = new byte[size];
  345. System.arraycopy(temp, 0, readBytes, 0, size);
  346. result = mergeArray(result,readBytes);
  347. }
  348. return result;
  349. }
  350. public static byte[] mergeArray( byte[]... a) {
  351. // 合并完之后数组的总长度
  352. int index = 0;
  353. int sum = 0;
  354. for ( int i = 0; i < a.length; i++) {
  355. sum = sum + a[i].length;
  356. }
  357. byte[] result = new byte[sum];
  358. for ( int i = 0; i < a.length; i++) {
  359. int lengthOne = a[i].length;
  360. if(lengthOne== 0){
  361. continue;
  362. }
  363. // 拷贝数组
  364. System.arraycopy(a[i], 0, result, index, lengthOne);
  365. index = index + lengthOne;
  366. }
  367. return result;
  368. }
  369. }

3、图像处理工具

  1. import java.awt.image.BufferedImage;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.MalformedURLException;
  10. import java.net.URL;
  11. import javax.imageio.ImageIO;
  12. import sun.misc.BASE64Decoder;
  13. import sun.misc.BASE64Encoder;
  14. /**
  15. *
  16. * 功能概要:图片处理工具类
  17. *
  18. * @author linbingwen
  19. * @since 2016年3月30日
  20. */
  21. public class ImageUtil {
  22. /**
  23. * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
  24. *
  25. * @author linbingwen
  26. * @since 2016年3月30日
  27. * @param imgFilePath 图片路径
  28. * @return base64编码的字符串
  29. * @throws IOException
  30. */
  31. public static String imageToBase64(String imgFilePath) throws IOException {
  32. byte[] data = null;
  33. InputStream in = null;
  34. try {
  35. in = new FileInputStream(imgFilePath);
  36. data = new byte[in.available()]; // 读取图片字节数组
  37. in.read(data);
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. } finally {
  41. if (in != null) {
  42. in.close();
  43. }
  44. }
  45. BASE64Encoder encoder = new BASE64Encoder(); // 对字节数组Base64编码
  46. return encoder.encode(data); // 返回Base64编码过的字节数组字符串
  47. }
  48. /**
  49. * 对字节数组字符串进行Base64解码并生成图片
  50. *
  51. * @author linbingwen
  52. * @since 2016年3月30日
  53. * @param imgStr base64编码的数据
  54. * @param imgFilePath 要保存的图片路径
  55. * @param imgFileName 要保存的图片名
  56. * @return
  57. * @throws IOException
  58. */
  59. public static Boolean base64ToImage(String base64, String imgFilePath,String imgFileName) throws IOException {
  60. if (base64 == null) {
  61. return null;
  62. }
  63. BASE64Decoder decoder = new BASE64Decoder();
  64. OutputStream out = null;
  65. try {
  66. byte[] bytes = decoder.decodeBuffer(base64); // Base64解码
  67. for ( int i = 0; i < bytes.length; ++i) {
  68. if (bytes[i] < 0) { // 调整异常数据
  69. bytes[i] += 256;
  70. }
  71. }
  72. InputStream input = new ByteArrayInputStream(bytes);
  73. out = new FileOutputStream(imgFilePath + imgFileName); // 生成jpeg图片
  74. out.write(bytes);
  75. out.flush();
  76. return true;
  77. } catch (Exception e) {
  78. return false;
  79. } finally {
  80. if (out != null) {
  81. out.close();
  82. }
  83. }
  84. }
  85. /**
  86. * 将base64编码的字符串转成InputStream
  87. * @author linbingwen
  88. * @since 2016年3月30日
  89. * @param base64
  90. * @return InputStream
  91. */
  92. public static InputStream base64ToInputStream(String base64) {
  93. if (base64 == null) {
  94. return null;
  95. }
  96. BASE64Decoder decoder = new BASE64Decoder();
  97. try {
  98. byte[] bytes = decoder.decodeBuffer(base64); // Base64解码
  99. for ( int i = 0; i < bytes.length; ++i) {
  100. if (bytes[i] < 0) { // 调整异常数据
  101. bytes[i] += 256;
  102. }
  103. }
  104. InputStream input = new ByteArrayInputStream(bytes);
  105. return input;
  106. } catch (Exception e) {
  107. return null;
  108. }
  109. }
  110. /**
  111. * 将网络图片进行Base64位编码
  112. * @author linbingwen
  113. * @since 2016年3月30日
  114. * @param imageUrl 图片的url路径,如http://.....xx.jpg
  115. * @return 返回Base64编码过的字节数组字符串
  116. * @throws IOException
  117. */
  118. public static String imageUrlToBase64(String imageUrl) throws IOException {
  119. ByteArrayOutputStream outputStream = null;
  120. try {
  121. URL url = new URL(imageUrl);
  122. BufferedImage bufferedImage = ImageIO.read(url);
  123. outputStream = new ByteArrayOutputStream();
  124. ImageIO.write(bufferedImage, "jpg", outputStream);
  125. } catch (MalformedURLException e1) {
  126. e1.printStackTrace();
  127. } catch (IOException e) {
  128. e.printStackTrace();
  129. } finally {
  130. if (outputStream != null) {
  131. outputStream.close();
  132. }
  133. }
  134. BASE64Encoder encoder = new BASE64Encoder(); // 对字节数组Base64编码
  135. return encoder.encode(outputStream.toByteArray());
  136. }
  137. /**
  138. *
  139. * @author linbingwen
  140. * @since 2016年4月13日
  141. * @param imageUrl 图片url
  142. * @param imageType 图片格式 如 jpg/bmp/png
  143. * @return
  144. * @throws IOException
  145. */
  146. public static byte[] imageUrlToBytes(String imageUrl,String imageType) throws IOException {
  147. ByteArrayOutputStream outputStream = null;
  148. byte[] bytes = null;
  149. try {
  150. URL url = new URL(imageUrl);
  151. BufferedImage bufferedImage = ImageIO.read(url);
  152. outputStream = new ByteArrayOutputStream();
  153. ImageIO.write(bufferedImage, imageType, outputStream);
  154. bytes = outputStream.toByteArray();
  155. } catch (MalformedURLException e1) {
  156. e1.printStackTrace();
  157. } catch (IOException e) {
  158. e.printStackTrace();
  159. } finally {
  160. if (outputStream != null) {
  161. outputStream.close();
  162. }
  163. }
  164. return bytes;
  165. }
  166. public static void main(String[] args) throws IOException {
  167. String imgFilePath = "D:\\";
  168. String ttString = imageUrlToBase64( "http://10.75.201.68:8888/cfile/file/image?imageId=group2/M00/05/25/CkvJolb5nIOAcHMZAADU5zn6AlI7014866");
  169. base64ToImage(ttString, imgFilePath, "44.bmp");
  170. urlBase64ToFile( "http://10.75.201.68:8888/cfile/file/image?imageId=group2/M00/05/97/CkvJo1dxbqKAEBqzAARHjfpHsPk7518600");
  171. }
  172. /**
  173. * @author linbingwen
  174. * @since 2016年6月28日
  175. * @param string
  176. */
  177. private static void urlBase64ToFile(String string) {
  178. }
  179. }

4、JSON转换处理工具

  1. /**
  2. * 功能概要:java与json转换工具类
  3. *
  4. * @author linbingwen
  5. * @since 2016年4月20日
  6. */
  7. import java.text.SimpleDateFormat;
  8. import java.util.ArrayList;
  9. import java.util.Collection;
  10. import java.util.Date;
  11. import java.util.HashMap;
  12. import java.util.Iterator;
  13. import java.util.List;
  14. import java.util.Map;
  15. import net.sf.ezmorph.MorpherRegistry;
  16. import net.sf.ezmorph.object.DateMorpher;
  17. import net.sf.json.JSONArray;
  18. import net.sf.json.JSONObject;
  19. import net.sf.json.JsonConfig;
  20. import net.sf.json.processors.JsonValueProcessor;
  21. import net.sf.json.util.JSONUtils;
  22. import net.sf.json.xml.XMLSerializer;
  23. public class JsonUtil {
  24. private static String YYYY_MM_DD = "yyyy-MM-dd";
  25. private static String YYYY_MM_DD_HH_MM_ss = "yyyy-MM-dd HH:mm:ss";
  26. private static String HH_MM_ss = "HH-mm-ss";
  27. private static String YYYYMMDD = "yyyyMMdd";
  28. private static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
  29. private static String HHMMss = "HHmmss";
  30. /**
  31. * 设置日期转换格式
  32. */
  33. static {
  34. //注册器
  35. MorpherRegistry mr = JSONUtils.getMorpherRegistry();
  36. //可转换的日期格式,即Json串中可以出现以下格式的日期与时间
  37. DateMorpher dm = new DateMorpher( new String[] { YYYY_MM_DD,
  38. YYYY_MM_DD_HH_MM_ss, HH_MM_ss, YYYYMMDD,
  39. YYYYMMDDHHMMSS, HHMMss});
  40. mr.registerMorpher(dm);
  41. }
  42. /**
  43. * 从json串转换成实体对象
  44. * @param jsonObjStr e.g. {'name':'get','dateAttr':'2009-11-12'}
  45. * @param clazz Person.class
  46. * @return
  47. */
  48. public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz) {
  49. return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz);
  50. }
  51. /**
  52. * 从json串转换成实体对象,并且实体集合属性存有另外实体Bean
  53. * @param jsonObjStr e.g. {'data':[{'name':'get'},{'name':'set'}]}
  54. * @param clazz e.g. MyBean.class
  55. * @param classMap e.g. classMap.put("data", Person.class)
  56. * @return Object
  57. */
  58. public static Object getDtoFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {
  59. return JSONObject.toBean(JSONObject.fromObject(jsonObjStr), clazz, classMap);
  60. }
  61. /**
  62. * 把一个json数组串转换成普通数组
  63. * @param jsonArrStr e.g. ['get',1,true,null]
  64. * @return Object[]
  65. */
  66. public static Object[] getArrFromJsonArrStr(String jsonArrStr) {
  67. return JSONArray.fromObject(jsonArrStr).toArray();
  68. }
  69. /**
  70. * 把一个json数组串转换成实体数组
  71. * @param jsonArrStr e.g. [{'name':'get'},{'name':'set'}]
  72. * @param clazz e.g. Person.class
  73. * @return Object[]
  74. */
  75. public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz) {
  76. JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
  77. Object[] objArr = new Object[jsonArr.size()];
  78. for ( int i = 0; i < jsonArr.size(); i++) {
  79. objArr[i] = JSONObject.toBean(jsonArr.getJSONObject(i), clazz);
  80. }
  81. return objArr;
  82. }
  83. /**
  84. * 把一个json数组串转换成实体数组,且数组元素的属性含有另外实例Bean
  85. * @param jsonArrStr e.g. [{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]
  86. * @param clazz e.g. MyBean.class
  87. * @param classMap e.g. classMap.put("data", Person.class)
  88. * @return Object[]
  89. */
  90. public static Object[] getDtoArrFromJsonArrStr(String jsonArrStr, Class clazz,
  91. Map classMap) {
  92. JSONArray array = JSONArray.fromObject(jsonArrStr);
  93. Object[] obj = new Object[array.size()];
  94. for ( int i = 0; i < array.size(); i++) {
  95. JSONObject jsonObject = array.getJSONObject(i);
  96. obj[i] = JSONObject.toBean(jsonObject, clazz, classMap);
  97. }
  98. return obj;
  99. }
  100. /**
  101. * 把一个json数组串转换成存放普通类型元素的集合
  102. * @param jsonArrStr e.g. ['get',1,true,null]
  103. * @return List
  104. */
  105. public static List getListFromJsonArrStr(String jsonArrStr) {
  106. JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
  107. List list = new ArrayList();
  108. for ( int i = 0; i < jsonArr.size(); i++) {
  109. list.add(jsonArr.get(i));
  110. }
  111. return list;
  112. }
  113. /**
  114. * 把一个json数组串转换成集合,且集合里存放的为实例Bean
  115. * @param jsonArrStr e.g. [{'name':'get'},{'name':'set'}]
  116. * @param clazz
  117. * @return List
  118. */
  119. public static List getListFromJsonArrStr(String jsonArrStr, Class clazz) {
  120. JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
  121. List list = new ArrayList();
  122. for ( int i = 0; i < jsonArr.size(); i++) {
  123. list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz));
  124. }
  125. return list;
  126. }
  127. /**
  128. * 把一个json数组串转换成集合,且集合里的对象的属性含有另外实例Bean
  129. * @param jsonArrStr e.g. [{'data':[{'name':'get'}]},{'data':[{'name':'set'}]}]
  130. * @param clazz e.g. MyBean.class
  131. * @param classMap e.g. classMap.put("data", Person.class)
  132. * @return List
  133. */
  134. public static List getListFromJsonArrStr(String jsonArrStr, Class clazz, Map classMap) {
  135. JSONArray jsonArr = JSONArray.fromObject(jsonArrStr);
  136. List list = new ArrayList();
  137. for ( int i = 0; i < jsonArr.size(); i++) {
  138. list.add(JSONObject.toBean(jsonArr.getJSONObject(i), clazz, classMap));
  139. }
  140. return list;
  141. }
  142. /**
  143. * 把json对象串转换成map对象
  144. * @param jsonObjStr e.g. {'name':'get','int':1,'double',1.1,'null':null}
  145. * @return Map
  146. */
  147. public static Map getMapFromJsonObjStr(String jsonObjStr) {
  148. JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);
  149. Map map = new HashMap();
  150. for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
  151. String key = (String) iter.next();
  152. map.put(key, jsonObject.get(key));
  153. }
  154. return map;
  155. }
  156. /**
  157. * 把json对象串转换成map对象,且map对象里存放的为其他实体Bean
  158. * @param jsonObjStr e.g. {'data1':{'name':'get'},'data2':{'name':'set'}}
  159. * @param clazz e.g. Person.class
  160. * @return Map
  161. */
  162. public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz) {
  163. JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);
  164. Map map = new HashMap();
  165. for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
  166. String key = (String) iter.next();
  167. map.put(key, JSONObject.toBean(jsonObject.getJSONObject(key), clazz));
  168. }
  169. return map;
  170. }
  171. /**
  172. * 把json对象串转换成map对象,且map对象里存放的其他实体Bean还含有另外实体Bean
  173. * @param jsonObjStr e.g. {'mybean':{'data':[{'name':'get'}]}}
  174. * @param clazz e.g. MyBean.class
  175. * @param classMap e.g. classMap.put("data", Person.class)
  176. * @return Map
  177. */
  178. public static Map getMapFromJsonObjStr(String jsonObjStr, Class clazz, Map classMap) {
  179. JSONObject jsonObject = JSONObject.fromObject(jsonObjStr);
  180. Map map = new HashMap();
  181. for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
  182. String key = (String) iter.next();
  183. map.put(key, JSONObject
  184. .toBean(jsonObject.getJSONObject(key), clazz, classMap));
  185. }
  186. return map;
  187. }
  188. /**
  189. * 把实体Bean、Map对象、数组、列表集合转换成Json串
  190. * @param obj
  191. * @return
  192. * @throws Exception String
  193. */
  194. public static String getJsonStr(Object obj) {
  195. String jsonStr = null;
  196. //Json配置
  197. // JsonConfig jsonCfg = new JsonConfig();
  198. //
  199. // //注册日期处理器
  200. // jsonCfg.registerJsonValueProcessor(java.util.Date.class,
  201. // new JsonDateValueProcessor(YYYY_MM_DD_HH_MM_ss));
  202. if (obj == null) {
  203. return "{}";
  204. }
  205. if (obj instanceof Collection || obj instanceof Object[]) {
  206. jsonStr = JSONArray.fromObject(obj).toString();
  207. } else {
  208. jsonStr = JSONObject.fromObject(obj).toString();
  209. }
  210. return jsonStr;
  211. }
  212. /**
  213. * 把json串、数组、集合(collection map)、实体Bean转换成XML
  214. * XMLSerializer API:
  215. * http://json-lib.sourceforge.net/apidocs/net/sf/json/xml/XMLSerializer.html
  216. * 具体实例请参考:
  217. * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
  218. * http://json-lib.sourceforge.net/xref-test/net/sf/json/xml/TestXMLSerializer_writes.html
  219. * @param obj
  220. * @return
  221. * @throws Exception String
  222. */
  223. public static String getXMLFromObj(Object obj) {
  224. XMLSerializer xmlSerial = new XMLSerializer();
  225. //Json配置
  226. JsonConfig jsonCfg = new JsonConfig();
  227. //注册日期处理器
  228. jsonCfg.registerJsonValueProcessor(java.util.Date.class,
  229. new JsonDateValueProcessor(YYYY_MM_DD_HH_MM_ss));
  230. if ((String.class.isInstance(obj) && String.valueOf(obj).startsWith( "["))
  231. || obj.getClass().isArray() || Collection.class.isInstance(obj)) {
  232. JSONArray jsonArr = JSONArray.fromObject(obj, jsonCfg);
  233. return xmlSerial.write(jsonArr);
  234. } else {
  235. JSONObject jsonObj = JSONObject.fromObject(obj, jsonCfg);
  236. return xmlSerial.write(jsonObj);
  237. }
  238. }
  239. /**
  240. * 从XML转json串
  241. * @param xml
  242. * @return String
  243. */
  244. public static String getJsonStrFromXML(String xml) {
  245. XMLSerializer xmlSerial = new XMLSerializer();
  246. return String.valueOf(xmlSerial.read(xml));
  247. }
  248. }
  249. /**
  250. *
  251. * 功能概要:json日期值处理器实现
  252. *
  253. * @author linbingwen
  254. * @since 2016年4月20日
  255. */
  256. class JsonDateValueProcessor implements JsonValueProcessor {
  257. private String format = "yyyy-MM-dd HH-mm-ss";
  258. public JsonDateValueProcessor() {
  259. }
  260. public JsonDateValueProcessor(String format) {
  261. this.format = format;
  262. }
  263. public Object processArrayValue(Object value, JsonConfig jsonConfig) {
  264. return process(value, jsonConfig);
  265. }
  266. public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {
  267. return process(value, jsonConfig);
  268. }
  269. private Object process(Object value, JsonConfig jsonConfig) {
  270. if (value instanceof Date) {
  271. String str = new SimpleDateFormat(format).format((Date) value);
  272. return str;
  273. }
  274. return value == null ? null : value.toString();
  275. }
  276. public String getFormat() {
  277. return format;
  278. }
  279. public void setFormat(String format) {
  280. this.format = format;
  281. }
  282. }

5、邮件发送处理工具

  1. import java.util.Properties;
  2. import javax.activation.DataHandler;
  3. import javax.activation.FileDataSource;
  4. import javax.mail.Address;
  5. import javax.mail.BodyPart;
  6. import javax.mail.Message;
  7. import javax.mail.Multipart;
  8. import javax.mail.PasswordAuthentication;
  9. import javax.mail.Session;
  10. import javax.mail.Transport;
  11. import javax.mail.internet.InternetAddress;
  12. import javax.mail.internet.MimeBodyPart;
  13. import javax.mail.internet.MimeMessage;
  14. import javax.mail.internet.MimeMultipart;
  15. import javax.mail.internet.MimeUtility;
  16. import org.slf4j.Logger;
  17. import org.slf4j.LoggerFactory;
  18. public class MailSendUtil {
  19. private static Logger logger = LoggerFactory.getLogger(MailSendUtil.class);
  20. private MimeMessage mimeMsg; // MIME邮件对象
  21. private Session session; // 邮件会话对象
  22. private Properties props; // 系统属性
  23. private boolean needAuth = false; // smtp是否需要认证
  24. private String username; // smtp认证用户名
  25. private String password; // smtp认证用户密码
  26. private Multipart mp; // 含标题,邮件内容,附件
  27. /**
  28. * Constructor
  29. *
  30. * @param smtp
  31. * 邮件发送服务器
  32. */
  33. public MailSendUtil(String smtp) {
  34. setSmtpHost(smtp);
  35. createMimeMessage();
  36. }
  37. /**
  38. * 设置邮件发送服务器
  39. *
  40. * @param hostName
  41. * String
  42. */
  43. public void setSmtpHost(String hostName) {
  44. logger.info( "设置系统属性:mail.smtp.host = " + hostName);
  45. if (props == null)
  46. props = System.getProperties(); // 获得系统属性对象
  47. props.put( "mail.smtp.host", hostName); // 设置SMTP主机
  48. }
  49. /**
  50. * 创建MIME邮件对象
  51. *
  52. * @return
  53. */
  54. public boolean createMimeMessage() {
  55. try {
  56. logger.info( "准备获取邮件会话对象!");
  57. session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
  58. protected PasswordAuthentication getPasswordAuthentication() {
  59. return new PasswordAuthentication(username, password);
  60. }
  61. }); // 获得邮件会话对象
  62. }
  63. catch (Exception e) {
  64. logger.error( "获取邮件会话对象时发生错误!" + e);
  65. return false;
  66. }
  67. logger.info( "准备创建MIME邮件对象!");
  68. try {
  69. mimeMsg = new MimeMessage(session); // 创建MIME邮件对象
  70. mp = new MimeMultipart();
  71. return true;
  72. }
  73. catch (Exception e) {
  74. logger.error( "创建MIME邮件对象失败!" + e);
  75. return false;
  76. }
  77. }
  78. /**
  79. * 设置SMTP是否需要验证
  80. *
  81. * @param need
  82. */
  83. public void setNeedAuth(boolean need) {
  84. logger.info( "设置smtp身份认证:mail.smtp.auth = " + need);
  85. if (props == null)
  86. props = System.getProperties();
  87. if (need) {
  88. props.put( "mail.smtp.auth", "true");
  89. }
  90. else {
  91. props.put( "mail.smtp.auth", "false");
  92. }
  93. }
  94. /**
  95. * 设置用户名和密码
  96. *
  97. * @param name
  98. * @param pass
  99. */
  100. public void setNamePass(String name, String pass) {
  101. username = name;
  102. password = pass;
  103. }
  104. /**
  105. * 设置邮件主题
  106. *
  107. * @param mailSubject
  108. * @return
  109. */
  110. public boolean setSubject(String mailSubject) {
  111. logger.info( "设置邮件主题!");
  112. try {
  113. mimeMsg.setSubject(mailSubject);
  114. return true;
  115. }
  116. catch (Exception e) {
  117. logger.error( "设置邮件主题发生错误!");
  118. return false;
  119. }
  120. }
  121. /**
  122. * 设置邮件正文
  123. *
  124. * @param mailBody
  125. * String
  126. */
  127. public boolean setBody(String mailBody) {
  128. try {
  129. BodyPart bp = new MimeBodyPart();
  130. bp.setContent( "" + mailBody, "text/html;charset=GBK");
  131. mp.addBodyPart(bp);
  132. return true;
  133. }
  134. catch (Exception e) {
  135. logger.error( "设置邮件正文时发生错误!" + e);
  136. return false;
  137. }
  138. }
  139. /**
  140. * 添加附件
  141. *
  142. * @param filename
  143. * String
  144. */
  145. public boolean addFileAffix(String filename) {
  146. if (filename == null) {
  147. return true;
  148. }
  149. logger.info( "增加邮件附件:" + filename);
  150. try {
  151. BodyPart bp = new MimeBodyPart();
  152. FileDataSource fileds = new FileDataSource(filename);
  153. bp.setDataHandler( new DataHandler(fileds));
  154. bp.setFileName(MimeUtility.encodeText(fileds.getName()));
  155. mp.addBodyPart(bp);
  156. return true;
  157. }
  158. catch (Exception e) {
  159. logger.error( "增加邮件附件:" + filename + "发生错误!" + e);
  160. return false;
  161. }
  162. }
  163. /**
  164. * 设置发信人
  165. *
  166. * @param from
  167. * String
  168. */
  169. public boolean setFrom(String from) {
  170. logger.info( "设置发信人!");
  171. try {
  172. mimeMsg.setFrom( new InternetAddress(from)); // 设置发信人
  173. return true;
  174. }
  175. catch (Exception e) {
  176. return false;
  177. }
  178. }
  179. /**
  180. * 设置收信人
  181. *
  182. * @param to
  183. * String
  184. */
  185. public boolean setTo(String to) {
  186. logger.info( "设置收件人:" + to);
  187. if (to == null)
  188. return false;
  189. try {
  190. mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
  191. return true;
  192. }
  193. catch (Exception e) {
  194. return false;
  195. }
  196. }
  197. /**
  198. * 设置抄送人
  199. *
  200. * @param copyto
  201. * String
  202. */
  203. public boolean setCopyTo(String copyto) {
  204. if (copyto == null)
  205. return false;
  206. try {
  207. mimeMsg.setRecipients(Message.RecipientType.CC, (Address[]) InternetAddress.parse(copyto));
  208. return true;
  209. }
  210. catch (Exception e) {
  211. return false;
  212. }
  213. }
  214. /**
  215. * 发送邮件
  216. */
  217. public boolean sendOut() {
  218. try {
  219. mimeMsg.setContent(mp);
  220. mimeMsg.saveChanges();
  221. logger.info( "正在发送邮件....");
  222. Transport transport = session.getTransport( "smtp");
  223. transport.connect((String) props.get( "mail.smtp.host"), username, password);
  224. transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
  225. // transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.CC));
  226. // Transport.send(mimeMsg);
  227. logger.info( "发送邮件成功!");
  228. transport.close();
  229. return true;
  230. }
  231. catch (Exception e) {
  232. logger.error( "邮件发送失败!" + e);
  233. return false;
  234. }
  235. }
  236. /**
  237. * 调用sendOut方法完成邮件发送
  238. *
  239. * @param smtp
  240. * @param from
  241. * @param to
  242. * @param subject
  243. * @param content
  244. * @param username
  245. * @param password
  246. * @return boolean
  247. */
  248. public static boolean send(String smtp, String from, String to, String subject, String content, String username, String password) {
  249. MailSendUtil theMail = new MailSendUtil(smtp);
  250. theMail.setNeedAuth( true); // 需要验证
  251. if (!theMail.setSubject(subject))
  252. return false;
  253. if (!theMail.setBody(content))
  254. return false;
  255. if (!theMail.setTo(to))
  256. return false;
  257. if (!theMail.setFrom(from))
  258. return false;
  259. theMail.setNamePass(username, password);
  260. if (!theMail.sendOut())
  261. return false;
  262. return true;
  263. }
  264. /**
  265. * 调用sendOut方法完成邮件发送,带抄送
  266. *
  267. * @param smtp
  268. * @param from
  269. * @param to
  270. * @param copyto
  271. * @param subject
  272. * @param content
  273. * @param username
  274. * @param password
  275. * @return boolean
  276. */
  277. public static boolean sendAndCc(String smtp, String from, String to, String copyto, String subject, String content, String username, String password) {
  278. MailSendUtil theMail = new MailSendUtil(smtp);
  279. theMail.setNeedAuth( true); // 需要验证
  280. if (!theMail.setSubject(subject))
  281. return false;
  282. if (!theMail.setBody(content))
  283. return false;
  284. if (!theMail.setTo(to))
  285. return false;
  286. if (!theMail.setCopyTo(copyto))
  287. return false;
  288. if (!theMail.setFrom(from))
  289. return false;
  290. theMail.setNamePass(username, password);
  291. if (!theMail.sendOut())
  292. return false;
  293. return true;
  294. }
  295. /**
  296. * 调用sendOut方法完成邮件发送,带附件
  297. *
  298. * @param smtp
  299. * @param from
  300. * @param to
  301. * @param subject
  302. * @param content
  303. * @param username
  304. * @param password
  305. * @param filename
  306. * 附件路径
  307. * @return
  308. */
  309. public static boolean send(String smtp, String from, String to, String subject, String content, String username, String password, String filename) {
  310. MailSendUtil theMail = new MailSendUtil(smtp);
  311. theMail.setNeedAuth( true); // 需要验证
  312. logger.info( "发送邮件至:{} " + to);
  313. if (!theMail.setSubject(subject))
  314. return false;
  315. if (!theMail.setBody(content))
  316. return false;
  317. if (!theMail.addFileAffix(filename))
  318. return false;
  319. if (!theMail.setTo(to))
  320. return false;
  321. if (!theMail.setFrom(from))
  322. return false;
  323. theMail.setNamePass(username, password);
  324. if (!theMail.sendOut())
  325. return false;
  326. return true;
  327. }
  328. /**
  329. * 调用sendOut方法完成邮件发送,带附件和抄送
  330. *
  331. * @param smtp
  332. * @param from
  333. * @param to
  334. * @param copyto
  335. * @param subject
  336. * @param content
  337. * @param username
  338. * @param password
  339. * @param filename
  340. * @return
  341. */
  342. public static boolean sendAndCc(String smtp, String from, String to, String copyto, String subject, String content, String username, String password, String filename) {
  343. MailSendUtil theMail = new MailSendUtil(smtp);
  344. theMail.setNeedAuth( true); // 需要验证
  345. if (!theMail.setSubject(subject))
  346. return false;
  347. if (!theMail.setBody(content))
  348. return false;
  349. if (!theMail.addFileAffix(filename))
  350. return false;
  351. if (!theMail.setTo(to))
  352. return false;
  353. if (!theMail.setCopyTo(copyto))
  354. return false;
  355. if (!theMail.setFrom(from))
  356. return false;
  357. theMail.setNamePass(username, password);
  358. if (!theMail.sendOut())
  359. return false;
  360. return true;
  361. }
  362. public static void main(String[] args) {
  363. String smtp = "10.75.210.10";
  364. String from = "test1@xxxxx";
  365. String to = "liuqiuyun@xxxx";
  366. String subject = "管理系统";
  367. String content = "邮件内容";
  368. String username = "test1";
  369. String password = "Password1";
  370. String filename = "D:\\file\\ces\\INT_MMS_SETTLE_20150211_0001.DATA";
  371. try {
  372. MailSendUtil.send(smtp, from, to, subject, content, username, password, filename);
  373. }
  374. catch (Exception e) {
  375. e.printStackTrace();
  376. }
  377. }
  378. }

6、SFTP处理工具

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Vector;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import com.lz.lsf.exception.BusinessException;

/**
 * 
 * 功能概要:SFTP客户端
 * 
 * @author linbingwen
 * @since  2015年8月5日
 */
public class SftpClient {

    private String m_host = "127.0.0.1";

    private int m_port = 22;

    private String m_username = "ctsUser";

    private String m_password = "ctsUser";

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private Channel m_channel = null;

    public SftpClient(String host, int Port, String userName, String password) {
        this.m_host = host;
        this.m_port = Port;
        this.m_username = userName;
        this.m_password = password;
    }

    public void reConnect() {
        try {
            this.connect();
        }
        catch (Exception e) {
            logger.warn("m_channel disconnect fail!", e);
        }
    }

    public void connect() {
        JSch jsch = new JSch();
        try {
            jsch.getSession(m_username, m_host, m_port);
            Session sshSession = jsch.getSession(m_username, m_host, m_port);
            logger.info("username:" + m_username + ", host:" + m_host + ",port:" + m_port);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(config);
            logger.debug("StrictHostKeyChecking", "no");
            sshSession.setPassword(m_password);
            sshSession.connect();
            logger.debug("Session connected.");
            m_channel = sshSession.openChannel("sftp");
            logger.debug("Opening Channel.");
            m_channel.connect();
            logger.info("Connected to {} success! ", m_host);
        }
        catch (JSchException e) {
            logger.error("connected to " + m_host + "Fail! ");
            throw new BusinessException(CommonErrorCode.ERROR_CONNECT_SFTP_FAIL, e, "connected to " + m_host + "Fail! ");
        }
    }

    public void disConnect() {
        try {
            if (m_channel == null)
                return;

            synchronized (m_channel) {
                if (m_channel.getSession().isConnected())
                    m_channel.getSession().disconnect();
            }

            m_channel.disconnect();

        }
        catch (JSchException e) {
            logger.warn("m_channel disconnect fail!", e);
        }
        finally {
            if (m_channel != null)
                m_channel = null;
        }
    }

    public boolean isTryConnect() {
        int tryConnectCount = 0;
        try {
            while (true) {
                tryConnectCount++;
                if (m_channel.getSession().isConnected())
                    return true;
                else {
                    if (tryConnectCount >= 3)
                        return false;
                    else {
                        this.reConnect();
                    }
                }
            }
        }
        catch (JSchException e) {
            logger.warn("m_channel isConnected fail!", e);
            return false;
        }
    }

    /**
     * 上传文件
     * 
     * @param directoryName
     *            上传的目录
     * @param uploadFileName
     *            要上传的文件
     * @param sftp
     * @throws SftpException
     * @throws FileNotFoundException
     * @throws JSchException
     */
    public void upload(String remotePathDirName, String uploadFileName) {
        ChannelSftp sftp = (ChannelSftp) m_channel;
        if (!this.isTryConnect()) {
            logger.error("尝试连接SFTP服务器失败!");
           throw new BusinessException(CommonErrorCode.ERROR_CONNECT_SFTP_FAIL);
        }
        try {
            sftp.cd(remotePathDirName);
            File uploadFile = new File(uploadFileName);
            sftp.put(new FileInputStream(uploadFile), uploadFile.getName());
            logger.debug("Upload file:{} to remote dir:{}", uploadFileName, remotePathDirName);
        }
        catch (FileNotFoundException e) {
            logger.error("download remote path({})FileNotFound{}", remotePathDirName, uploadFileName);
            throw new BusinessException(CommonErrorCode.NOT_EXISTS_PATH_SFTP_REMOTE, e, "FileNotFound:" + uploadFileName);
        }
        catch (SftpException e) {
            logger.error("download remote path({}) not exists!{}", remotePathDirName, e);
            throw new BusinessException(CommonErrorCode.NOT_EXISTS_PATH_SFTP_REMOTE, e, "remote path:" + remotePathDirName);
        }
    }

    public void uploadBatch(String directoryName, List<String> fileNameList) {
        for (String fileName : fileNameList) {
            this.upload(directoryName, fileName);
        }
    }

    /**
     * 下载文件
     * 
     * @param directoryName
     *            下载目录
     * @param downloadFileName
     *            下载的文件
     * @param saveFileName
     *            存在本地的路径
     * @param sftp
     * @throws SftpException
     * @throws FileNotFoundException
     * @throws JSchException
     */
    public void download(String remotePathDirName, String localPathDirName, String downloadFileName) {
        ChannelSftp sftp = (ChannelSftp) m_channel;
        if (!this.isTryConnect()) {
            logger.error("尝试连接SFTP服务器失败!");
          //  throw new BusinessException(ActErrorCode.ERROR_CONNECT_SFTP_FAIL);
        }
        try {
            sftp.cd(remotePathDirName);
            File saveFile = new File(localPathDirName + "//" + downloadFileName);
            sftp.get(downloadFileName, new FileOutputStream(saveFile));
            logger.debug("Download file:{} save as {}", downloadFileName, localPathDirName + "//" + downloadFileName);
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
            logger.error("download remote path{}//{}", remotePathDirName, downloadFileName);
            throw new BusinessException(CommonErrorCode.NOT_FINDFIELS_REMOTE_PATH, e, "FileNotFound:" + downloadFileName);
        }
        catch (SftpException e) {
            logger.error("download remote path({}) fail!{}", remotePathDirName + downloadFileName, e);
            throw new BusinessException(CommonErrorCode.NOT_EXISTS_PATH_SFTP_REMOTE, e, "remote path:" + remotePathDirName);
        }
    }

    public void downloadBatch(String directoryName, String localPathDirName, List<String> downloadFileNameList) {
        for (String fileName : downloadFileNameList) {
            this.download(directoryName, localPathDirName, fileName);
        }
    }

    public boolean isFileExists(String remotePathDirName) {
        ChannelSftp sftp = (ChannelSftp) m_channel;
        if (!this.isTryConnect()) {
            logger.error("尝试连接SFTP服务器失败!");
            throw new BusinessException(CommonErrorCode.ERROR_CONNECT_SFTP_FAIL);
        }
        try {
            Vector<LsEntry> filesName = sftp.ls(remotePathDirName);
            return filesName.size() > 0;
        }
        catch (SftpException e) {
            logger.warn("download remote path({}) not exists!{}", remotePathDirName, e);
            return false;
        }
    }

    /**
     * 删除文件
     * 
     * @param directory
     *            要删除文件所在目录
     * @param deleteFileName
     *            要删除的文件
     * @param sftp
     * @throws SftpException
     * @throws JSchException
     */
    public void delete(String directory, String deleteFileName) throws SftpException, JSchException {
        ChannelSftp sftp = (ChannelSftp) m_channel;
        if (!this.isTryConnect()) {
            logger.error("尝试连接SFTP服务器失败!");
           throw new BusinessException(CommonErrorCode.ERROR_CONNECT_SFTP_FAIL);
        }
        sftp.cd(directory);
        sftp.rm(deleteFileName);
        logger.info("Delete file:{} from remote dir:{}", deleteFileName, directory);
    }

    /**
     * 列出目录下的文件
     * 
     * @param directoryName
     *            要列出的目录
     * @param sftp
     * @return
     * @throws SftpException
     * @throws JSchException
     */
    @SuppressWarnings("unchecked")
    public Vector<LsEntry> listFiles(String directoryName) throws SftpException, JSchException {
        ChannelSftp sftp = (ChannelSftp) m_channel;
        if (!this.isTryConnect()) {
            logger.error("尝试连接SFTP服务器失败!");
           throw new BusinessException(CommonErrorCode.ERROR_CONNECT_SFTP_FAIL);
        }
        Vector<LsEntry> filesName = sftp.ls(directoryName);
        return filesName;
    }

    /**
     * 列出目录下符合要求的文件
     * 
     * @param directoryName
     *            要列出的目录
     * @param reg
     *            文件名前缀
     * @param postfix
     *            文件名后缀(格式)
     * @return
     * @throws SftpException
     * @throws JSchException
     */
    @SuppressWarnings("unchecked")
    public Vector<LsEntry> listFiles(String remotePathDirName, String reg, String postfix) {
        ChannelSftp sftp = (ChannelSftp) m_channel;
        if (!this.isTryConnect()) {
            logger.error("尝试连接SFTP服务器失败!");
           throw new BusinessException(CommonErrorCode.ERROR_CONNECT_SFTP_FAIL);
        }
        Vector<LsEntry> filesName;
        try {
            filesName = sftp.ls(remotePathDirName);
            Vector<LsEntry> filterFilesName = new Vector<LsEntry>();
            for (LsEntry lsEntry : filesName) {
                if (lsEntry.getFilename().indexOf(reg) > -1 && lsEntry.getFilename().endsWith(postfix)) {
                    filterFilesName.add(lsEntry);
                }
            }
            return filterFilesName;
        }
        catch (SftpException e) {
            logger.error("download remote path({}) not exists!{}", remotePathDirName, e);
            throw new BusinessException(CommonErrorCode.NOT_EXISTS_PATH_SFTP_REMOTE, e, "remote path" + remotePathDirName);
        }
	
    }

}

7、class工具

  1. import java.lang.reflect.Field;
  2. import java.lang.reflect.InvocationTargetException;
  3. import java.lang.reflect.Method;
  4. import java.lang.reflect.ParameterizedType;
  5. import java.lang.reflect.Type;
  6. import java.math.BigDecimal;
  7. import java.util.Date;
  8. import java.util.HashSet;
  9. import java.util.Set;
  10. import org.apache.commons.beanutils.BeanUtils;
  11. import com.lz.lsf.util.StringUtil;
  12. public class ClassUtil {
  13. static Set<Class> privateTypes = new HashSet<Class>();
  14. static {
  15. privateTypes.add( int.class);
  16. privateTypes.add( double.class);
  17. privateTypes.add( long.class);
  18. privateTypes.add( float.class);
  19. privateTypes.add( boolean.class);
  20. privateTypes.add(Integer.class);
  21. privateTypes.add(Double.class);
  22. privateTypes.add(Long.class);
  23. privateTypes.add(Float.class);
  24. privateTypes.add(String.class);
  25. privateTypes.add(Date.class);
  26. privateTypes.add(Boolean.class);
  27. }
  28. public static Class<?> getFieldGenricType(Field field, int index) {
  29. String signature = field.toGenericString();
  30. return getGenericeType(signature, index);
  31. }
  32. private static Class<?> getGenericeType(String signature, int index) {
  33. String genericStr = signature.substring(signature.indexOf( "<") + 1, signature.indexOf( ">"));
  34. String[] types = genericStr.split( ",");
  35. if (types.length > 0 && types.length > index) {
  36. try {
  37. return Class.forName(types[index]);
  38. }
  39. catch (ClassNotFoundException e) {
  40. throw new RuntimeException(e);
  41. }
  42. }
  43. else {
  44. return null;
  45. }
  46. }
  47. /**
  48. * 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
  49. *
  50. * @param clazz
  51. * clazz The class to introspect
  52. * @param index
  53. * the Index of the generic ddeclaration,start from 0.
  54. * @return the index generic declaration, or Object.class if cannot be determined
  55. */
  56. @SuppressWarnings( "unchecked")
  57. public static Class<?> getSuperClassGenricType( final Class clazz, final int index) {
  58. Class<?> ret = null;
  59. // 返回表示此 Class 所表示的实体(类、接口、基本类型或 void)的直接超类的 Type。
  60. Type genType = clazz.getGenericSuperclass();
  61. ret = getGenericType(genType, index);
  62. if (ret == null) {
  63. for (Type t : clazz.getGenericInterfaces()) {
  64. ret = getGenericType(t, index);
  65. if (ret != null) {
  66. break;
  67. }
  68. }
  69. }
  70. return ret;
  71. }
  72. private static Class<?> getGenericType(Type type, int index) {
  73. if (!(type instanceof ParameterizedType)) {
  74. return null;
  75. }
  76. // 返回表示此类型实际类型参数的 Type 对象的数组。
  77. Type[] params = ((ParameterizedType) type).getActualTypeArguments();
  78. if (index >= params.length || index < 0) {
  79. return null;
  80. }
  81. if (!(params[index] instanceof Class)) {
  82. return null;
  83. }
  84. return (Class) params[index];
  85. }
  86. public static String getSetterMethod(String attrName) {
  87. String fst = attrName.substring( 0, 1).toUpperCase();
  88. attrName = fst + attrName.substring( 1);
  89. return "set" + attrName;
  90. }
  91. public static void setObjectValue(Object obj, String fieldName, Object value) {
  92. try {
  93. String methodName = getSetterMethod(fieldName);
  94. Method method = findMethod(obj.getClass(), methodName, String.class);
  95. if (method != null) {
  96. method.invoke(obj, value);
  97. }
  98. else {
  99. Field field = obj.getClass().getDeclaredField(fieldName);
  100. if (field != null) {
  101. field.setAccessible( true);
  102. field.set(obj, value);
  103. }
  104. else {
  105. throw new RuntimeException( "no field or set method found for field:" + fieldName);
  106. }
  107. }
  108. }
  109. catch (Exception e) {
  110. throw new RuntimeException(e);
  111. }
  112. }
  113. public static boolean isPriovateType(Class type) {
  114. return privateTypes.contains(type);
  115. }
  116. public static Object getPrivateTypeValue(Class type, String value) {
  117. if (String.class == type) {
  118. return value;
  119. }
  120. else if ( int.class == type) {
  121. return StringUtil.isEmpty(value) ? 0 : Integer.parseInt(value);
  122. }
  123. else if ( double.class == type) {
  124. return StringUtil.isEmpty(value) ? 0 : Double.parseDouble(value);
  125. }
  126. else if ( long.class == type) {
  127. return StringUtil.isEmpty(value) ? 0 : Long.parseLong(value);
  128. }
  129. else if ( float.class == type) {
  130. return StringUtil.isEmpty(value) ? 0 : Float.parseFloat(value);
  131. }
  132. else if (Integer.class == type) {
  133. return StringUtil.isEmpty(value) ? 0 : Integer.valueOf(value);
  134. }
  135. else if (Double.class == type) {
  136. return StringUtil.isEmpty(value) ? 0 : Double.valueOf(value);
  137. }
  138. else if (Long.class == type) {
  139. return StringUtil.isEmpty(value) ? 0 : Long.valueOf(value);
  140. }
  141. else if (Float.class == type) {
  142. return StringUtil.isEmpty(value) ? 0 : Float.valueOf(value);
  143. }
  144. else if (BigDecimal.class == type) {
  145. return StringUtil.isEmpty(value) ? BigDecimal.ZERO : BigDecimal.valueOf(Double.valueOf(value));
  146. }
  147. else if ( boolean.class == type || Boolean.class == type) {
  148. return StringUtil.isEmpty(value) ? false : Boolean.valueOf(value);
  149. }
  150. else {
  151. return null;
  152. }
  153. }
  154. public static void main(String[] args) {
  155. System.out.println( Boolean.valueOf( "true"));
  156. System.out.println( Boolean.valueOf( "false"));
  157. String[] sp = "|1|2|||| ".split( "\\|");
  158. System.out.println(sp);
  159. System.out.println( "|1|2||||".endsWith( "|"));
  160. }
  161. public static Method findMethod(Class<?> clazz, String methodName, Class<?> paramType) {
  162. Method ret = null;
  163. try {
  164. ret = clazz.getMethod(methodName, paramType);
  165. }
  166. catch (Exception e) {
  167. if (paramType.getSuperclass() != null) {
  168. ret = findMethod(clazz, methodName, paramType.getSuperclass());
  169. }
  170. if (ret == null) {
  171. for (Class _clazz : paramType.getInterfaces()) {
  172. ret = findMethod(clazz, methodName, _clazz);
  173. if (ret != null) {
  174. break;
  175. }
  176. }
  177. }
  178. }
  179. return ret;
  180. }
  181. @SuppressWarnings( "unchecked")
  182. public static <T> T cloneInstance(T obj) {
  183. T ret;
  184. try {
  185. ret = (T) BeanUtils.cloneBean(obj);
  186. }
  187. catch (Exception e) {
  188. throw new RuntimeException( "clone instance failed!", e);
  189. }
  190. return ret;
  191. }
  192. }

8、GET/POST请求工具
  1. import java.io.IOException;
  2. import java.util.ArrayList;
  3. import java.util.Date;
  4. import java.util.HashMap;
  5. import java.util.List;
  6. import java.util.Map;
  7. import org.apache.commons.lang3.StringUtils;
  8. import org.apache.http.Consts;
  9. import org.apache.http.HttpResponse;
  10. import org.apache.http.NameValuePair;
  11. import org.apache.http.client.CookieStore;
  12. import org.apache.http.client.config.RequestConfig;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.HttpGet;
  15. import org.apache.http.client.methods.HttpPost;
  16. import org.apache.http.impl.client.BasicCookieStore;
  17. import org.apache.http.impl.client.CloseableHttpClient;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.impl.cookie.BasicClientCookie;
  20. import org.apache.http.message.BasicNameValuePair;
  21. import org.apache.http.util.EntityUtils;
  22. import org.junit.Test;
  23. import org.slf4j.Logger;
  24. import org.slf4j.LoggerFactory;
  25. public class HttpClientUtil {
  26. static CookieStore cookieStore = null;
  27. private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
  28. public static void main(String[] args) {
  29. Map<String, String> map = new HashMap<String, String>();
  30. map.put( "pageIndex", "1");
  31. map.put( "pageSize", "20");
  32. String result = HttpClientUtil.post( "http://xxxxx/xxx/operator/menu/findByPage.json", map);
  33. logger.info( "post result:" + result);
  34. map = new HashMap<String, String>();
  35. map.put( "pageNumber", "1");
  36. map.put( "pageSize", "20");
  37. result = HttpClientUtil.get( "http://xxx/ftc-ump-mid/xxx/dict/condition.json", map);
  38. logger.info( "get result:" + result);
  39. }
  40. @Test
  41. public void postTest() {
  42. Map<String, String> map = new HashMap<String, String>();
  43. map.put( "pageIndex", "1");
  44. map.put( "pageSize", "20");
  45. String result = HttpClientUtil.post( "http:/xxxxx/findByPage.json", map);
  46. logger.info( "result:" + result);
  47. }
  48. @Test
  49. public void getTest() {
  50. Map<String, String> map = new HashMap<String, String>();
  51. map.put( "pageNumber", "1");
  52. map.put( "pageSize", "20");
  53. String result = HttpClientUtil.get( "http://xxxxor/dict/condition.json", map);
  54. logger.info( "result:" + result);
  55. }
  56. /**
  57. * 获取cookie的内容
  58. *
  59. * @param ck
  60. * @param name
  61. * @return
  62. */
  63. public static String retriveCkValue(String ck, String name) {
  64. if (StringUtils.isBlank(ck) || StringUtils.isBlank(name)) {
  65. return "";
  66. }
  67. final String delimChar = name + "=";
  68. int delimBegin = ck.indexOf(delimChar);
  69. if (delimBegin < 0) {
  70. return "";
  71. }
  72. String val = null;
  73. int delimEnd = ck.indexOf( ';', delimBegin);
  74. if (delimEnd < 0) {
  75. val = ck.substring(delimBegin + delimChar.length()).trim();
  76. } else {
  77. val = ck.substring(delimBegin + delimChar.length(), delimEnd).trim();
  78. }
  79. int idx = val.indexOf( '?');
  80. if (idx > 0) {
  81. val = val.substring( 0, idx);
  82. }
  83. return val;
  84. }
  85. /**
  86. * 将cookie保存到静态变量中供后续调用
  87. *
  88. * @param httpResponse
  89. */
  90. public static void setCookieStore(HttpResponse httpResponse) {
  91. logger.info( "-------setCookieStore---------");
  92. if (httpResponse.getFirstHeader( "Set-Cookie") != null) {
  93. cookieStore = new BasicCookieStore();
  94. org.apache.http.Header[] cookies = httpResponse.getHeaders( "Set-Cookie");
  95. // Expires=Fri, 14-Apr-2017 09:42:26 GMT;
  96. for ( int j = 0; j < cookies.length; j++) {
  97. String content = cookies[j].getValue();
  98. String cookName = content.substring( 0, content.indexOf( "="));
  99. String cookNameContent = retriveCkValue(content, cookName);
  100. String domain = retriveCkValue(content, "Domain");
  101. String path = retriveCkValue(content, "Path");
  102. String time = retriveCkValue(content, "Expires");
  103. Date expires = new Date(time);
  104. BasicClientCookie cookie = new BasicClientCookie(cookName, cookNameContent);
  105. cookie.setDomain(domain);
  106. cookie.setPath(path);
  107. cookie.setExpiryDate(expires);
  108. cookieStore.addCookie(cookie);
  109. logger.info(cookName + ":{},domain:{},path:{},expires", cookNameContent, domain, path, expires);
  110. }
  111. }
  112. }
  113. /**
  114. * 模拟登陆
  115. *
  116. * @param client
  117. * @return
  118. */
  119. private static String login(CloseableHttpClient client) {
  120. String path = "http://xxxxxx/operator.json";
  121. Map<String, String> params = new HashMap<String, String>();
  122. params.put( "userId", "ITADMIN2");
  123. params.put( "password", "123456");
  124. List<NameValuePair> list = new ArrayList<NameValuePair>();
  125. if (params != null && !params.isEmpty()) {
  126. for (Map.Entry<String, String> entry : params.entrySet()) {
  127. list.add( new BasicNameValuePair(entry.getKey(), entry.getValue()));
  128. }
  129. }
  130. HttpResponse httpResponse = null;
  131. try {
  132. // 实现将请求的参数封装到表单中,即请求体中
  133. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, Consts.UTF_8);
  134. // 使用post方式提交数据
  135. HttpPost httpPost = new HttpPost(path);
  136. int connectionTimeout = 15000;
  137. int soTimeout = 15000;
  138. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout).setSocketTimeout(soTimeout).build();
  139. httpPost.setConfig(requestConfig);
  140. httpPost.setEntity(entity);
  141. httpResponse = client.execute(httpPost);
  142. // 获取服务器端返回的状态码和输入流,将输入流转换成字符串
  143. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  144. // setCookieStore(httpResponse); // 设置cookie
  145. return EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
  146. }
  147. } catch (Exception e) {
  148. e.printStackTrace();
  149. } finally {
  150. if (httpResponse != null) {
  151. try {
  152. EntityUtils.consume(httpResponse.getEntity());
  153. } catch (IOException e) {
  154. e.printStackTrace();
  155. }
  156. }
  157. }
  158. return "";
  159. }
  160. /**
  161. * 模拟get
  162. *
  163. * @param path
  164. * @param params
  165. * @param encode
  166. * @return
  167. */
  168. public static String get(String path, Map<String, String> params) {
  169. List<NameValuePair> list = new ArrayList<NameValuePair>();
  170. if (params != null && !params.isEmpty()) {
  171. for (Map.Entry<String, String> entry : params.entrySet()) {
  172. list.add( new BasicNameValuePair(entry.getKey(), entry.getValue()));
  173. }
  174. }
  175. HttpResponse httpResponse = null;
  176. CloseableHttpClient client = null;
  177. try {
  178. // 实现将请求的参数封装到表单中,即请求体中
  179. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, Consts.UTF_8);
  180. // 转换为键值对
  181. String str = EntityUtils.toString(entity);
  182. // 使用get方式提交数据
  183. HttpGet httpGet = new HttpGet(path + "?" + str);
  184. int connectionTimeout = 15000;
  185. int soTimeout = 15000;
  186. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout).setSocketTimeout(soTimeout).build();
  187. httpGet.setConfig(requestConfig);
  188. // 执行get请求,并获取服务器端的响应HttpResponse
  189. client = HttpClients.createDefault();
  190. // if (cookieStore != null) {
  191. // client =
  192. // HttpClients.custom().setDefaultCookieStore(cookieStore).build();
  193. // } else {
  194. // client = HttpClients.createDefault();
  195. // login(client);
  196. // }
  197. login(client);
  198. httpResponse = client.execute(httpGet);
  199. // 获取服务器端返回的状态码和输入流,将输入流转换成字符串
  200. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  201. return EntityUtils.toString(httpResponse.getEntity(), Consts.UTF_8);
  202. }
  203. } catch (Exception e) {
  204. e.printStackTrace();
  205. } finally {
  206. if (httpResponse != null) {
  207. try {
  208. EntityUtils.consume(httpResponse.getEntity());
  209. } catch (IOException e) {
  210. logger.error( "", e);
  211. }
  212. }
  213. if (client != null) {
  214. try {
  215. client.close();
  216. } catch (IOException e) {
  217. logger.error( "", e);
  218. }
  219. }
  220. }
  221. return "";
  222. }
  223. /**
  224. * 模拟post
  225. *
  226. * @param path
  227. * @param params
  228. * @param encode
  229. * @return
  230. */
  231. public static String post(String path, Map<String, String> params) {
  232. List<NameValuePair> list = new ArrayList<NameValuePair>();
  233. if (params != null && !params.isEmpty()) {
  234. for (Map.Entry<String, String> entry : params.entrySet()) {
  235. list.add( new BasicNameValuePair(entry.getKey(), entry.getValue()));
  236. }
  237. }
  238. HttpResponse httpResponse = null;
  239. CloseableHttpClient client = null;
  240. try {
  241. // 实现将请求的参数封装到表单中,即请求体中
  242. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "utf-8");
  243. // 使用post方式提交数据
  244. HttpPost httpPost = new HttpPost(path);
  245. int connectionTimeout = 15000;
  246. int soTimeout = 15000;
  247. RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout).setSocketTimeout(soTimeout).build();
  248. httpPost.setConfig(requestConfig);
  249. httpPost.setEntity(entity);
  250. // 执行post请求,并获取服务器端的响应HttpResponse
  251. HttpClients.createDefault();
  252. login(client);
  253. // if (cookieStore != null) {
  254. // client =
  255. // HttpClients.custom().setDefaultCookieStore(cookieStore).build();
  256. // } else {
  257. // client = HttpClients.createDefault();
  258. // login(client);
  259. // }
  260. httpResponse = client.execute(httpPost);
  261. // 获取服务器端返回的状态码和输入流,将输入流转换成字符串
  262. if (httpResponse.getStatusLine().getStatusCode() == 200) {
  263. return EntityUtils.toString(httpResponse.getEntity(), "utf-8");
  264. }
  265. } catch (Exception e) {
  266. logger.error( "", e);
  267. } finally {
  268. if (httpResponse != null) {
  269. try {
  270. EntityUtils.consume(httpResponse.getEntity());
  271. } catch (IOException e) {
  272. logger.error( "", e);
  273. }
  274. }
  275. if (client != null) {
  276. try {
  277. client.close();
  278. } catch (IOException e) {
  279. logger.error( "", e);
  280. }
  281. }
  282. }
  283. return "";
  284. }
  285. }

9、ES处理工具

  1. import com.alibaba.fastjson.JSONObject;
  2. import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
  3. import org.elasticsearch.action.bulk.BulkRequestBuilder;
  4. import org.elasticsearch.action.bulk.BulkResponse;
  5. import org.elasticsearch.action.count.CountRequestBuilder;
  6. import org.elasticsearch.action.count.CountResponse;
  7. import org.elasticsearch.action.delete.DeleteRequestBuilder;
  8. import org.elasticsearch.action.delete.DeleteResponse;
  9. import org.elasticsearch.action.get.GetResponse;
  10. import org.elasticsearch.action.index.IndexRequest;
  11. import org.elasticsearch.action.index.IndexRequestBuilder;
  12. import org.elasticsearch.action.index.IndexResponse;
  13. import org.elasticsearch.action.search.SearchRequestBuilder;
  14. import org.elasticsearch.action.search.SearchResponse;
  15. import org.elasticsearch.action.search.SearchType;
  16. import org.elasticsearch.action.update.UpdateRequest;
  17. import org.elasticsearch.action.update.UpdateResponse;
  18. import org.elasticsearch.client.Requests;
  19. import org.elasticsearch.client.transport.TransportClient;
  20. import org.elasticsearch.common.lang3.StringUtils;
  21. import org.elasticsearch.common.settings.ImmutableSettings;
  22. import org.elasticsearch.common.settings.Settings;
  23. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  24. import org.elasticsearch.common.xcontent.XContentBuilder;
  25. import org.elasticsearch.index.query.FilterBuilder;
  26. import org.elasticsearch.index.query.QueryBuilder;
  27. import org.elasticsearch.search.SearchHit;
  28. import org.elasticsearch.search.SearchHits;
  29. import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
  30. import org.slf4j.Logger;
  31. import org.slf4j.LoggerFactory;
  32. import java.util.ArrayList;
  33. import java.util.HashMap;
  34. import java.util.List;
  35. import java.util.Map;
  36. public class ESClient {
  37. private static final Logger log = LoggerFactory.getLogger(ESClient.class);
  38. private TransportClient client;
  39. public ESClient() {
  40. this.init();
  41. }
  42. private void close() {
  43. if ( this.client != null) {
  44. this.client.close();
  45. }
  46. }
  47. @Override
  48. public void finalize() throws Throwable {
  49. this.close();
  50. super.finalize();
  51. }
  52. private void init() {
  53. try {
  54. Settings settings = ImmutableSettings.settingsBuilder().loadFromClasspath( "elasticsearch.yml")
  55. .put( "client.transport.sniff", true).build();
  56. this.client = new TransportClient(settings);
  57. int port = settings.getAsInt( "client.transport.port", 9900);
  58. String[] ips = settings.getAsArray( "client.transport.ip");
  59. for (String ip : ips) {
  60. log.info( "the ip is:" + ip);
  61. client.addTransportAddress( new InetSocketTransportAddress(ip, port));
  62. }
  63. log.info( "es连接成功:{},{}", client, JSONObject.toJSONString(client.listedNodes()));
  64. } catch (Exception e) {
  65. if (client != null) {
  66. client.close();
  67. }
  68. log.error( "连接es失败!", e);
  69. }
  70. }
  71. public void createIndex(String index) throws Exception {
  72. client.admin().indices().prepareCreate(index).execute().actionGet();
  73. }
  74. /**
  75. * 为一种类型建立mapping
  76. *
  77. * @param index 索引名,相当于关系型数据库的库名
  78. * @param type 文档类型,相当于关系型数据库的表名
  79. * @param builder mapping内容, 格式 { "properties": { "fieldName1": { "type":
  80. * "string", "analyzer": "ik" }, "fieldName2": { "type":
  81. * "string", "index": "not_analyzed" } } }
  82. */
  83. public void mappingDoc(String index, String type, XContentBuilder builder)
  84. throws Exception {
  85. // XContentBuilder builder = XContentFactory.jsonBuilder()
  86. // .startObject()
  87. // .startObject("properties")
  88. // .startObject("province")
  89. // .field("type", "string")
  90. // //.field("store", "yes")
  91. // .field("analyzer","ik")
  92. // .field("index","analyzed")
  93. // //.field("indexAnalyzer", "ik")
  94. // //.field("searchAnalyzer", "ik")
  95. // .endObject()
  96. // .endObject()
  97. // .endObject();
  98. PutMappingRequest mapping = Requests.putMappingRequest(index)
  99. .type(type).source(builder);
  100. client.admin().indices().putMapping(mapping).actionGet();
  101. }
  102. /**
  103. * 为一份文档建立索引,采用自生成id
  104. *
  105. * @param index 索引名,相当于关系型数据库的库名
  106. * @param type 文档类型,相当于关系型数据库的表名
  107. * @param json json格式的数据集
  108. * @return
  109. */
  110. public IndexResponse indexDoc(String index, String type, String json) throws Exception {
  111. IndexRequestBuilder builder = client.prepareIndex(index, type);
  112. IndexResponse response = builder.setSource(json)
  113. .execute()
  114. .actionGet();
  115. return response;
  116. }
  117. /**
  118. * 为一份文档建立索引,采用自生成id
  119. *
  120. * @param index 索引名,相当于关系型数据库的库名
  121. * @param type 文档类型,相当于关系型数据库的表名
  122. * @param kvMap 键值对形式的数据集
  123. * @return
  124. */
  125. public IndexResponse indexDoc(String index, String type, Map<String, Object> kvMap)
  126. throws Exception {
  127. IndexRequestBuilder builder = client.prepareIndex(index, type);
  128. IndexResponse response = builder.setSource(kvMap)
  129. .execute()
  130. .actionGet();
  131. return response;
  132. }
  133. /**
  134. * 为一份文档建立索引
  135. *
  136. * @param index 索引名,相当于关系型数据库的库名
  137. * @param type 文档类型,相当于关系型数据库的表名
  138. * @param id 文档id
  139. * @param json json格式的数据集
  140. * @return
  141. */
  142. public IndexResponse indexDoc(String index, String type, String id, String json)
  143. throws Exception {
  144. IndexRequestBuilder builder = client.prepareIndex(index, type, id);
  145. IndexResponse response = builder.setSource(json)
  146. .execute()
  147. .actionGet();
  148. return response;
  149. }
  150. /**
  151. * 为一份文档建立索引
  152. *
  153. * @param index 索引名,相当于关系型数据库的库名
  154. * @param type 文档类型,相当于关系型数据库的表名
  155. * @param id 文档id
  156. * @param kvMap 键值对形式的数据集
  157. * @return
  158. */
  159. public IndexResponse indexDoc(String index, String type, String id, Map<String, Object> kvMap)
  160. throws Exception {
  161. IndexRequestBuilder builder = client.prepareIndex(index, type, id);
  162. IndexResponse response = builder.setSource(kvMap)
  163. .execute()
  164. .actionGet();
  165. return response;
  166. }
  167. /**
  168. * 为多份文档建立索引,采用自生成id
  169. *
  170. * @param index 索引名,相当于关系型数据库的库名
  171. * @param type 文档类型,相当于关系型数据库的表名
  172. * @param jsonList json格式的文档数据: List<json>
  173. * @return
  174. */
  175. public BulkResponse batchIndexDocsForJson(String index, String type, List<String> jsonList)
  176. throws Exception {
  177. if (jsonList.isEmpty()) {
  178. throw new Exception( "批量创建索引时,传入的参数'jsonList'为空!");
  179. }
  180. List<IndexRequest> requestList = new ArrayList<IndexRequest>(jsonList.size());
  181. for (String json : jsonList) {
  182. IndexRequest request = client.prepareIndex(index, type)
  183. .setSource(json)
  184. .request();
  185. requestList.add(request);
  186. }
  187. BulkRequestBuilder bulkRequest = client.prepareBulk();
  188. for (IndexRequest request : requestList) {
  189. bulkRequest.add(request);
  190. }
  191. BulkResponse response = bulkRequest
  192. .execute()
  193. .actionGet();
  194. return response;
  195. }
  196. /**
  197. * 为多份文档建立索引,采用自生成id
  198. *
  199. * @param index 索引名,相当于关系型数据库的库名
  200. * @param type 文档类型,相当于关系型数据库的表名
  201. * @param kvList 键值对形式的文档数据:List<Map<field, value>>
  202. * @return
  203. */
  204. public BulkResponse batchIndexDocsForMap(String index, String type, List<Map<String, Object>> kvList)
  205. throws Exception {
  206. if (kvList.isEmpty()) {
  207. throw new Exception( "批量创建索引时,传入的参数'kvList'为空!");
  208. }
  209. List<String> jsonList = new ArrayList<String>(kvList.size());
  210. for (Map<String, Object> kvMap : kvList) {
  211. jsonList.add(JSONObject.toJSONString(kvMap));
  212. }
  213. BulkResponse response = this.batchIndexDocsForJson(index, type, jsonList);
  214. jsonList.clear();
  215. return response;
  216. }
  217. /**
  218. * 为多份文档建立索引
  219. *
  220. * @param index 索引名,相当于关系型数据库的库名
  221. * @param type 文档类型,相当于关系型数据库的表名
  222. * @param idJsonMap id及json格式的文档数据: Map<id,json>
  223. * @return
  224. */
  225. public BulkResponse batchIndexDocsForJson(String index, String type, Map<String, String> idJsonMap)
  226. throws Exception {
  227. if (idJsonMap.isEmpty()) {
  228. throw new Exception( "批量创建索引时,传入的参数'idJsonMap'为空!");
  229. }
  230. List<IndexRequest> requestList = new ArrayList<IndexRequest>(idJsonMap.size());
  231. for (String id : idJsonMap.keySet()) {
  232. String json = idJsonMap.get(id);
  233. IndexRequest request = client.prepareIndex(index, type, id)
  234. .setSource(json)
  235. .request();
  236. requestList.add(request);
  237. }
  238. BulkRequestBuilder bulkRequest = client.prepareBulk();
  239. for (IndexRequest request : requestList) {
  240. bulkRequest.add(request);
  241. }
  242. BulkResponse response = bulkRequest
  243. .execute()
  244. .actionGet();
  245. return response;
  246. }
  247. /**
  248. * 为多份文档建立索引
  249. *
  250. * @param index 索引名,相当于关系型数据库的库名
  251. * @param type 文档类型,相当于关系型数据库的表名
  252. * @param idKvMap id及键值对形式的文档数据:Map<id,Map<field, value>>
  253. * @return
  254. */
  255. public BulkResponse batchIndexDocsForMap(String index, String type, Map<String, Map<String, Object>> idKvMap)
  256. throws Exception {
  257. if (idKvMap.isEmpty()) {
  258. throw new Exception( "批量创建索引时,传入的参数'idKvMap'为空!");
  259. }
  260. Map<String, String> idJsonMap = new HashMap<String, String>(idKvMap.size());
  261. for (String id : idKvMap.keySet()) {
  262. Map<String, Object> kvMap = idKvMap.get(id);
  263. idJsonMap.put(id, JSONObject.toJSONString(kvMap));
  264. }
  265. BulkResponse response = this.batchIndexDocsForJson(index, type, idJsonMap);
  266. idJsonMap.clear();
  267. return response;
  268. }
  269. /**
  270. * 更新一个doc, 若不存在则插入
  271. *
  272. * @param index
  273. * @param type
  274. * @param id
  275. * @param json
  276. * @param script
  277. * @throws java.util.concurrent.ExecutionException
  278. * @throws InterruptedException
  279. */
  280. // public UpdateResponse upsertDoc(String index, String type, String id, String json, String script) throws Exception {
  281. // IndexRequest indexRequest = new IndexRequest(index, type, id).source(json);
  282. // UpdateRequest updateRequest = new UpdateRequest(index, type, id);
  283. // //updateRequest.doc();
  284. // updateRequest.upsert(indexRequest);
  285. // updateRequest.script(script);
  286. //
  287. // UpdateResponse response = client.update(updateRequest).get();
  288. //
  289. // return response;
  290. // }
  291. public UpdateResponse upsertDoc(String index, String type, String id, String insertJson, String updateJson) throws Exception {
  292. IndexRequest indexRequest = new IndexRequest(index, type, id).source(insertJson);
  293. UpdateRequest updateRequest = new UpdateRequest(index, type, id);
  294. updateRequest.doc(updateJson);
  295. updateRequest.upsert(indexRequest);
  296. UpdateResponse response = client.update(updateRequest).get();
  297. return response;
  298. }
  299. /**
  300. * 根据条件 统计个数
  301. *
  302. * @param queryBuilder 查詢條件
  303. * @param index 索引库名 相當於 数据库名
  304. * @param type 索引类型 相當於 表名
  305. * @return
  306. */
  307. public long countQuery(String index, String type, QueryBuilder queryBuilder) {
  308. CountRequestBuilder crb = client.prepareCount(index).setTypes(type);
  309. if (queryBuilder != null) {
  310. crb.setQuery(queryBuilder);
  311. }
  312. CountResponse response = crb.execute().actionGet();
  313. return response.getCount();
  314. }
  315. public SearchResponse searchAgg(String index, String type, String searchType, QueryBuilder queryBuilder,
  316. AbstractAggregationBuilder aggBuilder) {
  317. SearchRequestBuilder builder = client.prepareSearch(index).setTypes(type);
  318. if (!StringUtils.isEmpty(searchType)) {
  319. builder.setSearchType(SearchType.valueOf(searchType));
  320. }
  321. if (queryBuilder != null) {
  322. builder = builder.setQuery(queryBuilder);
  323. }
  324. if (aggBuilder != null) {
  325. builder = builder.addAggregation(aggBuilder);
  326. }
  327. SearchResponse searchResponse = builder.execute().actionGet();
  328. return searchResponse;
  329. }
  330. /**
  331. * 删除一个文档
  332. *
  333. * @param index 索引名,相当于关系型数据库的库名
  334. * @param type 文档类型,相当于关系型数据库的表名
  335. * @param id 键值对形式的数据集
  336. * @return
  337. */
  338. public DeleteResponse deleteDoc(String index, String type, String id) throws InterruptedException {
  339. DeleteRequestBuilder builder = client.prepareDelete(index, type, id);
  340. DeleteResponse response = builder
  341. .execute()
  342. .actionGet();
  343. return response;
  344. }
  345. /**
  346. * 根据条件删除多个文档
  347. *
  348. * @param index 索引名,相当于关系型数据库的库名
  349. * @param type 文档类型,相当于关系型数据库的表名
  350. * @param queryBuilder 查询器
  351. * @return
  352. */
  353. public void deleteDocsByQuery(String index, String type, QueryBuilder queryBuilder) {
  354. client.prepareDeleteByQuery(index).setTypes(type).setQuery(queryBuilder)
  355. .execute()
  356. .actionGet();
  357. }
  358. /**
  359. * 指定id获取文档
  360. *
  361. * @param index 索引名,相当于关系型数据库的库名
  362. * @param type 文档类型,相当于关系型数据库的表名
  363. * @param id 文档id
  364. * @return
  365. */
  366. public Map<String, Object> getDoc(String index, String type, String id) {
  367. GetResponse response = client.prepareGet(index, type, id)
  368. .execute()
  369. .actionGet();
  370. Map<String, Object> retMap = response.getSourceAsMap();
  371. return retMap;
  372. }
  373. public List<Map<String, Object>> search(String index, String type, QueryBuilder queryBuilder, FilterBuilder filterBuilder) {
  374. SearchRequestBuilder builder = client.prepareSearch(index).setTypes(type);
  375. if (queryBuilder != null) {
  376. builder = builder.setQuery(queryBuilder);
  377. }
  378. if (filterBuilder != null) {
  379. builder = builder.setPostFilter(filterBuilder);
  380. }
  381. SearchResponse searchResponse = builder.execute().actionGet();
  382. SearchHits hits = searchResponse.getHits();
  383. log.info( "Es Hits count: " + hits.getTotalHits());
  384. List<Map<String, Object>> kvList = new ArrayList<Map<String, Object>>();
  385. SearchHit[] hitArray = hits.getHits();
  386. if (hitArray.length > 0) {
  387. for (SearchHit hit : hitArray) {
  388. Map<String, Object> kvMap = hit.getSource();
  389. kvMap.put( "version", hit.getVersion());
  390. kvMap.put( "_id", hit.getId());
  391. kvList.add(kvMap);
  392. }
  393. }
  394. return kvList;
  395. }
  396. }

10、Hbase处理工具

import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.filter.CompareFilter;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.util.Bytes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 操作Hbase的常用方法
 * <p/>
 * Created by huqingmiao on 2015/4/14.
 */
public class HbaseUtil {

    private static final Logger log = LoggerFactory.getLogger(HbaseUtil.class);

    private static Configuration conf = null;

    private static HConnection conn = null;

    private static String HADOOP_HOME = "C:/hadoop";

    static {

//        try {
//            String hadoopHome = System.getProperties().getProperty("hadoop.home.dir"); //Windows下的HOME目录, 在unix下部署不需要设置
//            if (hadoopHome == null || "".equals(hadoopHome.trim())) {
//                hadoopHome = HADOOP_HOME;
//            }
//
//            File hadoopBinDir = new File(hadoopHome, "bin");      //HOME目录下的bin目录
//            if (!hadoopBinDir.exists()) {
//                hadoopBinDir.mkdirs();
//            }
//            File winExeFile = new File(hadoopBinDir.getCanonicalPath() + File.separator + "winutils.exe");
//            if (!winExeFile.exists()) {
//                winExeFile.createNewFile();
//            }
//
//            //设置环境变量
//            System.getProperties().put("hadoop.home.dir", hadoopHome);
//
//        } catch (IOException e) {
//            log.error("create ./bin/winutils.exe error.", e);
//        }

        //默认从hbase-site.xml读取配置信息
        conf = HBaseConfiguration.create();
//        conf.set("hbase.zookeeper.property.clientPort", "2181");
//        conf.set("hbase.zookeeper.quorum", "10.75.201.125");
//        conf.set("hbase.master", "10.75.201.125:60010");
        //conf.set("hbase.zookeeper.quorum", "hmaster");
        //与hbase/conf/hbase-site.xml中hbase.zookeeper.property.clientPort配置的值相同
      //  conf.set("hbase.zookeeper.property.clientPort", "2181");
    }


    public HbaseUtil() {
        try {
            //预先创建了一个连接,以后的访问都共享该连接
        	//conf.addResource("hbase-site.xml");
            conn = HConnectionManager.createConnection(conf);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public void finalize() throws Throwable {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        super.finalize();
    }


    /**
     * 建表
     *
     * @param tableName     表名
     * @param columnFamilys 列簇名
     * @throws Exception
     */
    public void createTable(String tableName, String[] columnFamilys) throws Exception {
        HBaseAdmin hAdmin = null;
        try {
            hAdmin = new HBaseAdmin(conf);

            if (hAdmin.tableExists(tableName)) {
                log.info("已经存在要创建的表:" + tableName);

            } else {
                HTableDescriptor tableDesc = new HTableDescriptor(TableName.valueOf(tableName));

                //描述列族
                for (String columnFamily : columnFamilys) {
                    tableDesc.addFamily(new HColumnDescriptor(columnFamily));
                }

                //建表
                hAdmin.createTable(tableDesc);
                log.info("成功创建表:" + tableName);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (hAdmin != null) {
                    hAdmin.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 删除表
     *
     * @param tableName 表名
     * @throws Exception
     */
    public void deleteTable(String tableName) throws Exception {
        HBaseAdmin hAdmin = null;
        try {
            hAdmin = new HBaseAdmin(conf);

            if (hAdmin.tableExists(tableName)) {
                hAdmin.disableTable(tableName);//禁用表
                hAdmin.deleteTable(tableName);// 删除表
                log.info("成功删除表:" + tableName);

            } else {
                log.info("要删除的表不存在:" + tableName);
            }

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (hAdmin != null) {
                    hAdmin.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 向指定的行、列簇、列写入一项数据;如果该行不存在,则会插入一行。
     *
     * @param tableName 表名
     * @param rowkey    行键
     * @param colFamily 列簇名
     * @param column    列名
     * @param value     列值
     * @throws Exception
     */
    public void putData(String tableName, String rowkey,
                        String colFamily, String column, String value) throws Exception {

        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);
            Put put = new Put(Bytes.toBytes(rowkey));

            // 参数分别为:列族、列、值
            put.add(Bytes.toBytes(colFamily), Bytes.toBytes(column), Bytes.toBytes(value));

            table.put(put);
            log.info("成功写入1项数据到{}.", tableName);

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 向指定的行、列簇、列写入一项数据;如果该行不存在,则会插入一行。
     *
     * @param tableName 表名
     * @param hbCell    存放行键、列簇、列名、列值的数据单元
     * @throws Exception
     */
    public void putData(String tableName, HbaseCell hbCell) throws Exception {
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);
            Put put = new Put(convertToBytes(hbCell.getRowkey()));

            // 参数分别为:列族、列、值
            put.add(Bytes.toBytes(hbCell.getColFamily()), Bytes.toBytes(hbCell.getColName()), convertToBytes(hbCell.getColValue()));

            table.put(put);
            log.info("成功写入1项数据到{}.", tableName);

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 写入多行、多列数据
     *
     * @param tableName  表名
     * @param hbCellList 存放行键、列簇、列名、列值的数据单元.
     * @throws Exception
     */
    public void putData(String tableName, List<HbaseCell> hbCellList) throws Exception {
        if (hbCellList.isEmpty()) {
            return;
        }
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);

            List<Put> putList = new ArrayList<Put>();
            for (HbaseCell hbCell : hbCellList) {
                Put put = new Put(convertToBytes(hbCell.getRowkey()));
                put.add(Bytes.toBytes(hbCell.getColFamily()), Bytes.toBytes(hbCell.getColName()), convertToBytes(hbCell.getColValue()));

                putList.add(put);
            }

            table.put(putList);
            log.info("成功写入{}项数据到{}.", hbCellList.size(), tableName);

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 写入多行、多列数据
     *
     * @param tableName  表名
     * @param hbCellList 存放行键、列簇、列名、列值的数据单元.
     * @throws Exception
     */
    public void putDataForNotNull(String tableName, List<HbaseCell> hbCellList) throws Exception {
        if (hbCellList.isEmpty()) {
            return;
        }
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);

            List<Put> putList = new ArrayList<Put>();
            for (HbaseCell hbCell : hbCellList) {
                if (!StringUtils.isEmpty(hbCell.getColValue() + "")) {
                    Put put = new Put(convertToBytes(hbCell.getRowkey()));
                    put.add(Bytes.toBytes(hbCell.getColFamily()), Bytes.toBytes(hbCell.getColName()), convertToBytes(hbCell.getColValue()));
                    putList.add(put);
                }
            }
            table.put(putList);
            log.info("成功写入{}项数据到{}.", hbCellList.size(), tableName);

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 删除一行
     *
     * @param tableName 表名
     * @param rowkey    行键
     * @throws Exception
     */

    public void delRow(String tableName, String rowkey) throws Exception {
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);
            Delete del = new Delete(Bytes.toBytes(rowkey));

            table.delete(del);
            log.info("成功删除1行数据!");

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 删除多行
     *
     * @param tableName 表名
     * @param rowkeys   行键
     * @throws Exception
     */
    public void delMulitRows(String tableName, List<String> rowkeys) throws Exception {
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);

            List<Delete> delList = new ArrayList<Delete>();
            for (String rowkey : rowkeys) {
                Delete del = new Delete(Bytes.toBytes(rowkey));
                delList.add(del);
            }
            table.delete(delList);
            delList.clear();
            log.info("成功删除{}行数据.", delList.size());

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 获取指定行的所有数据项
     *
     * @param tableName 表名
     * @param rowkey    行键
     * @return
     * @throws Exception
     */
    public Result getRow(String tableName, String rowkey) throws Exception {
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);

            Get get = new Get(Bytes.toBytes(rowkey));
            Result rs = table.get(get);

//            for (Cell cell : result.rawCells()) {
//                System.out.print("Row Name: " + new String(CellUtil.cloneRow(cell)) + " ");
//                System.out.print("Timestamp: " + cell.getTimestamp() + " ");
//                System.out.print("column Family: " + new String(CellUtil.cloneFamily(cell)) + " ");
//                System.out.print("column Name:  " + new String(CellUtil.cloneQualifier(cell)) + " ");
//                System.out.println("Value: " + new String(CellUtil.cloneValue(cell)) + " ");
//            }

            return rs;

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 获取指定表的所有行的数据项
     *
     * @param tableName 表名
     * @return
     * @throws Exception
     */
    public List<Result> findAllRows(String tableName) throws Exception {
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);

            Scan scan = new Scan();
            ResultScanner results = table.getScanner(scan);

            List<Result> rsList = new ArrayList<Result>();
            for (Result rs : results) {
                rsList.add(rs);
            }
            return rsList;

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 通用查询
     *
     * @param tableName 表名
     * @param filter    查询过滤器。单一条件查询可传Filter对象,组合条件查询可传FilterList, FilterList是Filter的子类。
     */
    public List<Result> findRow(String tableName, Filter filter) throws Exception {
        HTableInterface table = null;
        try {
            //table = new HTable(conf, tableName);
            table = conn.getTable(tableName);

            Scan scan = new Scan();
            scan.setFilter(filter);
            ResultScanner results = table.getScanner(scan);

            List<Result> rsList = new ArrayList<Result>();
            for (Result rs : results) {
                rsList.add(rs);
            }
            return rsList;

        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw e;
        } finally {
            try {
                if (table != null) {
                    table.close();
                }
            } catch (IOException e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 打印、展示查询结果
     *
     * @param result
     */
    public void showData(Result result) {

        for (Cell cell : result.rawCells()) {
            log.info("Row: " + new String(CellUtil.cloneRow(cell)) + " ");
            log.info("Timestamp: " + cell.getTimestamp() + " ");
            log.info("Column Family: " + new String(CellUtil.cloneFamily(cell)) + " ");
            log.info("Column Name:  " + new String(CellUtil.cloneQualifier(cell)) + " ");
            log.info("Column Value: " + new String(CellUtil.cloneValue(cell)) + " ");
        }

    }

    /**
     * 打印、展示查询的各项列值
     *
     * @param rsList
     */
    public void showData(List<Result> rsList) {
        log.info(">>>总的数据条数:" + rsList.size());

        if (rsList.isEmpty()) {
            return;
        }
        for (Result rs : rsList) {
            Cell[] cells = rs.rawCells();
            for (Cell cell : rs.rawCells()) {
                log.info("Row: " + new String(CellUtil.cloneRow(cell)) + " ");
                log.info("Timestamp: " + cell.getTimestamp() + " ");
                log.info("Column Family: " + new String(CellUtil.cloneFamily(cell)) + " ");
                log.info("Column Name:  " + new String(CellUtil.cloneQualifier(cell)) + " ");
                log.info("Column Value: " + new String(CellUtil.cloneValue(cell)) + " ");
            }
        }
    }


    /**
     * 打印、展示查询的各项列值
     *
     * @param rsList
     */
    public void showRowkey(List<Result> rsList) {
        log.info(">>>总的数据条数:" + rsList.size());

        if (rsList.isEmpty()) {
            return;
        }
        for (Result rs : rsList) {
            log.info(new String(rs.getRow()));
        }
    }

    private byte[] convertToBytes(Object obj) throws Exception {
        if (obj == null) {
            return new byte[0];
        }
        if (obj instanceof String) {
            return Bytes.toBytes((String) obj);
        }
        if (obj instanceof Double) {
            return Bytes.toBytes((Double) obj);
        }
        if (obj instanceof Float) {
            return Bytes.toBytes((Float) obj);
        }
        if (obj instanceof Long) {
            return Bytes.toBytes((Long) obj);
        }
        if (obj instanceof Integer) {
            return Bytes.toBytes((Integer) obj);
        }
        if (obj instanceof Date) {
            return Bytes.toBytes(((Date) obj).getTime());
        }
        if (obj instanceof Timestamp) {
            return Bytes.toBytes(((Timestamp) obj).getTime());
        }
        if (obj instanceof BigDecimal) {
            return Bytes.toBytes((BigDecimal) obj);
        }
        throw new Exception("未能识别的数据类型: " + obj.getClass().getName());
    }


    // main
    public static void main(String[] args) {
        try {
        	HbaseUtil client = new HbaseUtil();

            String tableName = "testtable";

            // 创建数据库表:“studyinfo”
            String[] colFamilys = {"studyinfo", "course"};
            client.createTable(tableName, colFamilys);

            // 添加第一行数据
            client.putData(tableName, "ligan", "studyinfo", "age", "2333");
            client.putData(tableName, "ligan", "studyinfo", "sex", "boy");
            client.putData(tableName, "ligan", "course", "china", "97");
            client.putData(tableName, "ligan", "course", "math", "128");
            client.putData(tableName, "ligan", "course", "english", "85");

            // 添加第二行数据
            client.putData(tableName, "xiaoxue", "studyinfo", "age", "20");
            client.putData(tableName, "xiaoxue", "studyinfo", "sex", "boy");
            client.putData(tableName, "xiaoxue", "course", "china", "90");
            client.putData(tableName, "xiaoxue", "course", "math", "100");
            client.putData(tableName, "xiaoxue", "course", "english", "90");

            // 添加第三行数据,也可以这样写:
            HbaseCell hbCell1 = new HbaseCell("walker", "studyinfo", "age", "18");
            HbaseCell hbCell2 = new HbaseCell("walker", "studyinfo", "sex", "girl");
            HbaseCell hbCell3 = new HbaseCell("walker", "course", "math", "100");
            HbaseCell hbCell4 = new HbaseCell("walker", "course", "english", "30");
            List<HbaseCell> cellList = new ArrayList<HbaseCell>();
            cellList.add(hbCell1);
            cellList.add(hbCell2);
            cellList.add(hbCell3);
            cellList.add(hbCell4);
            client.putData(tableName, cellList);


            // 获取一条数据
            log.info("获取一条数据");
            Result rs = client.getRow(tableName, "ligan");
            client.showData(rs);


            //组合查询
            log.info("组合查询");
            List<Filter> filters = new ArrayList<Filter>();
            Filter filter1 = new SingleColumnValueFilter(Bytes
                    .toBytes("studyinfo"), Bytes.toBytes("age"), CompareFilter.CompareOp.GREATER, Bytes
                    .toBytes("18"));
            filters.add(filter1);

            Filter filter2 = new SingleColumnValueFilter(Bytes
                    .toBytes("course"), Bytes.toBytes("math"), CompareFilter.CompareOp.EQUAL, Bytes
                    .toBytes("100"));
            filters.add(filter2);

            FilterList filterList = new FilterList(filters);

            List<Result> rsList = client.findRow(tableName, filterList);
            log.info(">>>" + rsList.size());


            // 获取所有数据
            log.info("获取所有数据");
            rsList = client.findAllRows(tableName);
            log.info(">>>" + rsList.size());

            //删除一条数据
            log.info("删除一条数据");
            client.delRow(tableName, "tht");
            log.info(">>>" + rsList.size());

            //删除多条数据
            log.info("删除多条数据");
            List<String> rows = new ArrayList<String>();
            rows.add("xiaoxue");
            rows.add("walker");
            client.delMulitRows(tableName, rows);
            client.findAllRows(tableName);
            log.info(">>>" + rsList.size());


            //删除数据库
            log.info("删除表");
            client.deleteTable(tableName);


        } catch (Exception err) {
            err.printStackTrace();
        }
    }

}

11、mongodb处理工具

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.bson.Document;

import com.alibaba.fastjson.JSONObject;
import com.github.walker.mybatis.paginator.PageList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;


public class MongoManager {
	
	 
	    private static MongoClient  client = null;  
	  
	    private MongoManager() 
	    { 
	    	
	    }  
	  
	    static {  
	        initDBPrompties();  
	    }  
	  	  
	    /** 
	     * 初始化连接池 
	     */  
	    private static void initDBPrompties() {  	    	    		
	    	 String url=PropertyHolder.getProperty("mongodb.url");
	    	 String dbName=PropertyHolder.getProperty("mongodb.dbName"); 
	    	 String userName=PropertyHolder.getProperty("mongodb.userName");
	    	 String password=PropertyHolder.getProperty("mongodb.password");
	    	 int connectionsPerHost = Integer.valueOf(PropertyHolder.getProperty("mongodb.connectionsPerHost"));
	    	 int threads = Integer.valueOf(PropertyHolder.getProperty("mongodb.threads"));
	    	 int maxWaitTime=Integer.valueOf(PropertyHolder.getProperty("mongodb.maxWaitTime"));
	    	 int socketTimeout=Integer.valueOf(PropertyHolder.getProperty("mongodb.socketTimeout"));
	    	 int maxConnectionLifeTime=Integer.valueOf(PropertyHolder.getProperty("mongodb.maxConnectionLifeTime"));
	    	 int connectTimeout = Integer.valueOf(PropertyHolder.getProperty("mongodb.connectTimeout"));
	    	 
	    	 List<MongoCredential> credentials = new ArrayList<MongoCredential>();
	    	 ServerAddress address = new ServerAddress(url);
	    	 MongoCredential credential = MongoCredential.createCredential(userName,dbName,password.toCharArray());
			 credentials.add(credential);
	    	 
	    	 MongoClientOptions.Builder build = new MongoClientOptions.Builder();  	         
	         build.connectionsPerHost(connectionsPerHost);
	         build.maxWaitTime(maxWaitTime);
	         build.maxConnectionLifeTime(maxConnectionLifeTime);
	         build.connectTimeout(connectTimeout);
	         build.threadsAllowedToBlockForConnectionMultiplier(threads);
	         build.socketTimeout(socketTimeout);
	         MongoClientOptions options = build.build();  
	         client = new MongoClient(address, credentials, options);  
	    }  
	    
	    /**
	     * 获取数据库
	     * @param dbName 数据库
	     * @return
	     */
		public static MongoDatabase getDB(String dbName) {  
	        return client.getDatabase(dbName);
	    }
	    
	    /**
	     * 获取表
	     * @param dbName 数据库
	     * @param collectionName 集合
	     * @return
	     */
	    public static MongoCollection<Document>  getCollection(String dbName,String collectionName)
	    {
	    	 MongoCollection<Document>  collection = getDB(dbName).getCollection(collectionName);
	    	 return collection;
	    }
	    
	    /**
	     * 插入表数据
	     * @param dbName 数据库
	     * @param collectionName 集合
	     * @param json 待入库json
	     */
	    public static void insert(String dbName,String collectionName,String json)
	    {
	    	MongoCollection<Document> collection = getCollection(dbName, collectionName);
	        Document document = Document.parse(json);
	    	collection.insertOne(document);
	    }
	    
	    /**
	     * 分页查询用户操作日志
	     * @param dbName 数据库
	     * @param collectionName 集合
	     * @param acctNo 账户号
	     * @param start 
	     * @param pageSize
	     * @return
	     */
	    public static PageList<UserOpLog> findUserOpLog(String dbName,String collectionName,String acctNo,String tenantId,String keyWord,String startDate,String endDate,int start,int pageSize)
	    {   
	    	List<UserOpLog> logList = new ArrayList<UserOpLog>();
	    	MongoCollection<Document> collection = getCollection(dbName, collectionName);
	        BasicDBObject queryObject = new BasicDBObject();
	        BasicDBObject tmpObject = new BasicDBObject();
	        BasicDBObject dateObject = new BasicDBObject();	       
	        if(StringUtils.isNotEmpty(acctNo))
	        {   
	        	
	        	queryObject.put("acctNo", acctNo);		        
	        }
	        if(tenantId!=null)
	        {
	        	queryObject.put("tenantId", tenantId);		        
	        }
	        if(StringUtils.isNotEmpty(keyWord))
	        {   
	        	Pattern pattern = Pattern.compile("^.*"+keyWord+".*$", Pattern.CASE_INSENSITIVE);
	        	queryObject.put("opDesc", pattern);		        
	        }
	        
	        tmpObject.put("$gte", startDate); //大于
	        dateObject = tmpObject.append("$lte", endDate);	//小于      	               	        
	        queryObject.put("opTime", dateObject);	      
	        FindIterable<Document> iterator= collection.find(queryObject).sort((new BasicDBObject("opTime",-1)));		       
	        int count = 0;
	        MongoCursor<Document> cursor= iterator.iterator();
	        while(cursor.hasNext()) { 
	        	Document doc = cursor.next();
	        	if(count>=start && count<=pageSize+start-1)
	        	{	        		
	                UserOpLog userOpLog = new UserOpLog();
	                userOpLog.setAcctNo(doc.getString("acctNo"));
	                userOpLog.setClasz(doc.getString("clasz"));
	                userOpLog.setErrorMsg(doc.getString("errorMsg"));
	                userOpLog.setMethod(doc.getString("method"));
	                userOpLog.setName(doc.getString("name"));
	                userOpLog.setOpDesc(doc.getString("opDesc"));
	                userOpLog.setOpResult(doc.getInteger("opResult"));
	                userOpLog.setOpTime(doc.getString("opTime"));
	                userOpLog.setUri(doc.getString("uri"));
	                userOpLog.setTenantId(doc.getString("tenantId"));
	                logList.add(userOpLog);
	        	}
                count++;
            }  
	        cursor.close();
	        PageList<UserOpLog> pageList = new PageList<UserOpLog>(logList,count);
	        return pageList;	        
	    }
	    
	    /**
	     * 分页查询接口调用日志
	     * @param dbName 数据库
	     * @param collectionName 集合
	     * @param tenantId 商户ID
	     * @param appId 应用ID
	     * @param startDate 开始日期
	     * @param endDate 结束日期
	     * @param start
	     * @param pageSize
	     * @return
	     */
	    public static PageList<UserCallLog> findUserCallLog(String dbName,String collectionName,String tenantId,String appId,String startDate,String endDate,int start,int pageSize)
	    {   
	    	List<UserCallLog> logList = new ArrayList<UserCallLog>();
	    	MongoCollection<Document> collection = getCollection(dbName, collectionName);
	        BasicDBObject queryObject = new BasicDBObject();
	        BasicDBObject tmpObject = new BasicDBObject();
	        BasicDBObject dateObject = new BasicDBObject();	       
	        if(StringUtils.isNotEmpty(tenantId))
	        {
	        	queryObject.put("tenantId", tenantId);	
	        	
	        }
	        if(StringUtils.isNotEmpty(appId))
	        {
	        	queryObject.put("appId", appId);		        
	        }	       
	        
	        tmpObject.put("$gte", startDate); //大于
	        dateObject = tmpObject.append("$lte", endDate);	//小于      	               	        
	        queryObject.put("reqTime", dateObject);	      
	        FindIterable<Document> iterator= collection.find(queryObject) ;		       
	        int count = 0;
	        MongoCursor<Document> cursor= iterator.iterator();
	        while(cursor.hasNext()) { 
	        	Document doc = cursor.next();
	        	if(count>=start && count<=pageSize+start-1)
	        	{	        		
	        		UserCallLog userCallLog = new UserCallLog();
	        		userCallLog.setAppId(doc.getString("appId"));
	                userCallLog.setClientHost(doc.getString("clientHost"));
	                userCallLog.setClientIp(doc.getString("clientIp"));
	                userCallLog.setClientPort(doc.getInteger("clientPort"));
	                userCallLog.setErrorCode(doc.getString("errorCode"));
	                userCallLog.setErrorMsg(doc.getString("errorMsg"));
	                userCallLog.setFlowNo(doc.getString("flowNo"));
	                userCallLog.setInterfaceClasz(doc.getString("interfaceClasz"));
	                userCallLog.setInterfaceId(doc.getString("interfaceId"));
	                userCallLog.setMethodId(doc.getString("methodId"));
	                userCallLog.setMethodName(doc.getString("methodName"));
	                userCallLog.setReqBytes(doc.getInteger("reqBytes"));
	                userCallLog.setReqTime(doc.getString("reqTime"));
	                userCallLog.setResBytes(doc.getInteger("resBytes"));
	                userCallLog.setResTime(doc.getString("resTime"));
	                userCallLog.setSvcId(doc.getString("svcId"));
	                userCallLog.setSvcInterface(doc.getString("svcInterface"));
	                userCallLog.setTenantId(doc.getString("tenantId"));
	                userCallLog.setToken(doc.getString("token"));
	                userCallLog.setUri(doc.getString("uri"));
	                logList.add(userCallLog);
	        	}
                count++;
            }  
	        cursor.close();
	        PageList<UserCallLog> pageList = new PageList<UserCallLog>(logList,count);
	        return pageList;	        
	    }
	    
	   
}

12、redis处理工具

  1. import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import redis.clients.jedis.Jedis;
  5. import redis.clients.jedis.JedisPool;
  6. import java.util.Map;
  7. import java.util.Properties;
  8. import java.util.concurrent.Executors;
  9. import java.util.concurrent.ScheduledExecutorService;
  10. import java.util.concurrent.TimeUnit;
  11. public class QCloudJedis {
  12. private static final Logger log = LoggerFactory.getLogger(QCloudJedis.class);
  13. private static final Properties properties = ClassesConfigLoader.getProperties();
  14. private static final String host = properties.getProperty( "redis.host");
  15. private static final int port = Integer.valueOf(properties.getProperty( "redis.port"));
  16. private static final String instanceid = properties.getProperty( "redis.instanceid");
  17. private static final String password = properties.getProperty( "redis.password");
  18. private static final int timeout = Integer.valueOf(properties.getProperty( "redis.timeout", "2000"));
  19. private static final int maxTotal = Integer.valueOf(properties.getProperty( "redis.maxTotal", "1024"));
  20. private static final int maxIdle = Integer.valueOf(properties.getProperty( "redis.maxIdle", "10"));
  21. private static final int maxWaitMillis = Integer.valueOf(properties.getProperty( "redis.maxWaitMillis", "3000"));
  22. private static final boolean testOnIdle = Boolean.valueOf(properties.getProperty( "redis.testOnIdle", "true")); //是否checkIdle
  23. private static final int timeCheckIdle = Integer.valueOf(properties.getProperty( "redis.timeCheckIdle", "60000")); //每隔多少秒check一次
  24. private static final int idleTimeout = Integer.valueOf(properties.getProperty( "redis.idleTimeout", "300000")); //超时时间
  25. private static final int numTestsPerEvictionRun = Integer.valueOf(properties.getProperty( "redis.numTestsPerEvictionRun", "1024")); //一次驱逐过程中,最多驱逐对象的个数
  26. private static JedisPool pool = null;
  27. //private static Jedis jedis = null;
  28. private static Object lock = new Object();
  29. static {
  30. init();
  31. }
  32. private static void init() {
  33. if ( null == pool) {
  34. GenericObjectPoolConfig config = new GenericObjectPoolConfig();
  35. config.setMaxTotal(maxTotal);
  36. config.setMaxIdle(maxIdle);
  37. config.setMaxWaitMillis(maxWaitMillis);
  38. config.setTestWhileIdle(testOnIdle);
  39. config.setTimeBetweenEvictionRunsMillis(timeCheckIdle);
  40. config.setMinEvictableIdleTimeMillis(idleTimeout);
  41. config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
  42. synchronized (lock) {
  43. if ( null == pool) {
  44. try {
  45. pool = new JedisPool(config, host, port, timeout, instanceid + ":" + password);
  46. log.info( "init jedis pool successful!");
  47. } catch (Exception e) {
  48. log.error( "", e);
  49. }
  50. }
  51. }
  52. }
  53. }
  54. // public static Jedis getInstance() {
  55. // init();
  56. //
  57. // return jedis;
  58. // }
  59. /**
  60. * 获取一个jedis 对象
  61. *
  62. * @return
  63. */
  64. private static Jedis getJedis() {
  65. if (pool == null) {
  66. init();
  67. }
  68. return pool.getResource();
  69. }
  70. /**
  71. * 返还到连接池
  72. *
  73. * @param pool
  74. * @param redis
  75. */
  76. private static void returnResource(Jedis redis) {
  77. if (redis != null) {
  78. redis.close();
  79. }
  80. }
  81. // 删除key
  82. public static Long del(String key) {
  83. Jedis jedis = null;
  84. try {
  85. jedis = getJedis();
  86. return jedis.del(key);
  87. } catch (Exception e) {
  88. log.error( "操作Redis发生异常,异常详情:", e);
  89. return - 1L;
  90. } finally {
  91. // 返还到连接池
  92. returnResource(jedis);
  93. }
  94. }
  95. public static Boolean exists(String key) {
  96. Jedis jedis = null;
  97. Boolean flag = false;
  98. try {
  99. jedis = getJedis();
  100. flag = jedis.exists(key);
  101. } catch (Exception e) {
  102. log.error( "操作Redis发生异常,异常详情:", e);
  103. } finally {
  104. // 返还到连接池
  105. returnResource(jedis);
  106. }
  107. return flag;
  108. }
  109. /**
  110. * 获取数据
  111. *
  112. * @param key
  113. * @return
  114. */
  115. public static String get(String key) {
  116. String value = null;
  117. Jedis jedis = null;
  118. try {
  119. jedis = getJedis();
  120. value = jedis.get(key);
  121. } catch (Exception e) {
  122. log.error( "操作Redis发生异常,异常详情:", e);
  123. } finally {
  124. // 返还到连接池
  125. returnResource(jedis);
  126. }
  127. return value;
  128. }
  129. // 设置
  130. public static String set(String key, String value) {
  131. Jedis jedis = null;
  132. try {
  133. jedis = getJedis();
  134. return jedis.set(key, value);
  135. } catch (Exception e) {
  136. log.error( "操作Redis发生异常,异常详情:", e);
  137. return "";
  138. } finally {
  139. // 返还到连接池
  140. returnResource(jedis);
  141. }
  142. }
  143. // 获取Hash值
  144. public static String hget(String key, String field) {
  145. Jedis jedis = null;
  146. String value = null;
  147. try {
  148. jedis = getJedis();
  149. value = jedis.hget(key, field);
  150. } catch (Exception e) {
  151. log.error( "操作Redis发生异常,异常详情:", e);
  152. } finally {
  153. // 返还到连接池
  154. returnResource(jedis);
  155. }
  156. return value;
  157. }
  158. public static Map<String, String> hgetAll(String key) {
  159. Jedis jedis = null;
  160. Map<String, String> value = null;
  161. try {
  162. jedis = getJedis();
  163. value = jedis.hgetAll(key);
  164. } catch (Exception e) {
  165. log.error( "操作Redis发生异常,异常详情:", e);
  166. } finally {
  167. // 返还到连接池
  168. returnResource(jedis);
  169. }
  170. return value;
  171. }
  172. // 设置Hash值
  173. public static Long hset(String key, String field, String value) {
  174. Jedis jedis = null;
  175. try {
  176. jedis = getJedis();
  177. return jedis.hset(key, field, value);
  178. } catch (Exception e) {
  179. log.error( "操作Redis发生异常,异常详情:", e);
  180. return - 1L;
  181. } finally {
  182. // 返还到连接池
  183. returnResource(jedis);
  184. }
  185. }
  186. // 删除Hash值
  187. public static Long hdel(String key, String... fields) {
  188. Jedis jedis = null;
  189. try {
  190. jedis = getJedis();
  191. return jedis.hdel(key, fields);
  192. } catch (Exception e) {
  193. log.error( "操作Redis发生异常,异常详情:", e);
  194. return - 1L;
  195. } finally {
  196. // 返还到连接池
  197. returnResource(jedis);
  198. }
  199. }
  200. public static Long expire(String key, int seconds) {
  201. Jedis jedis = null;
  202. try {
  203. jedis = getJedis();
  204. return jedis.expire(key, seconds);
  205. } catch (Exception e) {
  206. log.error( "操作Redis发生异常,异常详情:", e);
  207. return - 1L;
  208. } finally {
  209. // 返还到连接池
  210. returnResource(jedis);
  211. }
  212. }
  213. public static void main(String[] args) {
  214. try {
  215. while ( true) {
  216. String key = "ftc-ump-mid";
  217. //System.out.println("before setting: " + jedis.hget(key, "attr"));
  218. System.out.println( ">>" + QCloudJedis.hset(key, "attr", "0"));
  219. QCloudJedis.expire(key, 5);
  220. System.out.println( "after setting: " + QCloudJedis.hget(key, "attr"));
  221. System.out.println( ">>" + QCloudJedis.hdel(key, "attr"));
  222. System.out.println( "after delete: " + QCloudJedis.hget(key, "attr"));
  223. Thread.sleep( 1000 * 10);
  224. }
  225. //关闭退出
  226. //jedis.quit();
  227. //jedis.close();
  228. } catch (Exception e) {
  229. e.printStackTrace();
  230. }
  231. }
  232. }



猜你喜欢

转载自blog.csdn.net/qq_28817739/article/details/80900481
今日推荐